From 7919442d3d424f35f8d7f482fbfc19d6221af7af Mon Sep 17 00:00:00 2001 From: scorpion9979 Date: Tue, 4 Jun 2019 01:11:27 +0300 Subject: [PATCH] Implemented asset system for caching json data --- {common/assets => assets/common}/npc_names.json | 0 common/src/assets/mod.rs | 11 +++++++++++ common/src/npc.rs | 14 ++++++++------ 3 files changed, 19 insertions(+), 6 deletions(-) rename {common/assets => assets/common}/npc_names.json (100%) diff --git a/common/assets/npc_names.json b/assets/common/npc_names.json similarity index 100% rename from common/assets/npc_names.json rename to assets/common/npc_names.json diff --git a/common/src/assets/mod.rs b/common/src/assets/mod.rs index f691f296fe..3146368749 100644 --- a/common/src/assets/mod.rs +++ b/common/src/assets/mod.rs @@ -1,6 +1,7 @@ use dot_vox::DotVoxData; use image::DynamicImage; use lazy_static::lazy_static; +use serde_json::Value; use std::{ any::Any, collections::HashMap, @@ -106,6 +107,16 @@ impl Asset for DotVoxData { } } +impl Asset for Value { + fn load(specifier: &str) -> Result { + let file = + File::open(specifier).expect(&format!("opening {} in read-only mode", specifier)); + let json: serde_json::Value = serde_json::from_reader(file) + .expect(&format!("reading json contents from {}", specifier)); + Ok(json) + } +} + // TODO: System to load file from specifiers (e.g.: "core.ui.backgrounds.city"). fn try_open_with_path(name: &str) -> Option { debug!("Trying to access \"{}\"", name); diff --git a/common/src/npc.rs b/common/src/npc.rs index 381e664fbf..49108438b9 100644 --- a/common/src/npc.rs +++ b/common/src/npc.rs @@ -1,7 +1,10 @@ +use crate::assets; +use lazy_static::lazy_static; use rand::seq::SliceRandom; use serde_json; use std::fs::File; use std::io::Error; +use std::sync::Arc; pub enum NpcKind { Wolf, @@ -17,14 +20,13 @@ impl NpcKind { } } -const npc_names_dir: &str = "common/assets/npc_names.json"; +lazy_static! { + static ref NPC_NAMES_JSON: Arc = + assets::load_expect("assets/common/npc_names.json"); +} pub fn get_npc_name(npc_type: NpcKind) -> String { - let npc_names_file = - File::open(npc_names_dir).expect(&format!("opening {} in read-only mode", npc_names_dir)); - let npc_names_json: serde_json::Value = serde_json::from_reader(npc_names_file) - .expect(&format!("reading json contents from {}", npc_names_dir)); - let npc_names = npc_names_json + let npc_names = NPC_NAMES_JSON .get(npc_type.as_str()) .expect("accessing json using NPC type provided as key") .as_array()