aboutsummaryrefslogtreecommitdiff
path: root/games/rstnode/rst-core/src/loader.rs
diff options
context:
space:
mode:
Diffstat (limited to 'games/rstnode/rst-core/src/loader.rs')
-rw-r--r--games/rstnode/rst-core/src/loader.rs82
1 files changed, 82 insertions, 0 deletions
diff --git a/games/rstnode/rst-core/src/loader.rs b/games/rstnode/rst-core/src/loader.rs
new file mode 100644
index 000000000000..13cb3773fbf6
--- /dev/null
+++ b/games/rstnode/rst-core/src/loader.rs
@@ -0,0 +1,82 @@
+//! An adaptation of the assets loader from rst-client, but only for
+//! maps and unit definitions
+
+use crate::config::MapCfg;
+use serde_yaml;
+use std::{
+ collections::BTreeMap,
+ fs::{self, File, OpenOptions},
+ io::{Read, Write},
+ path::PathBuf,
+};
+
+/// A unique resource identifier
+#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
+pub struct Uri(String, String);
+
+impl From<&'static str> for Uri {
+ fn from(s: &'static str) -> Self {
+ let mut v: Vec<_> = s.split("/").collect();
+ Self(v.remove(0).into(), v.remove(0).into())
+ }
+}
+
+impl From<String> for Uri {
+ fn from(s: String) -> Self {
+ let mut v: Vec<_> = s.split("/").collect();
+ Self(v.remove(0).into(), v.remove(0).into())
+ }
+}
+
+/// A loader for maps
+pub struct MapLoader {
+ root: PathBuf,
+ inner: BTreeMap<String, MapCfg>,
+}
+
+impl MapLoader {
+ pub fn load_path(path: PathBuf) -> Self {
+ Self {
+ root: path.clone(),
+ inner: fs::read_dir(&path)
+ .unwrap()
+ .filter_map(|map| {
+ let map = map.unwrap();
+ let name = map.file_name().into_string().unwrap();
+
+ if map.path().is_dir() {
+ warn!("Directories in map path will be ignored: {}!", name);
+ None
+ } else {
+ let np = map.path().with_extension("");
+ let name = np.file_name().unwrap().to_str().unwrap();
+
+ debug!("Loading map {}", name);
+ let mut c = String::new();
+ let mut f = File::open(map.path()).unwrap();
+ f.read_to_string(&mut c).unwrap();
+
+ Some((name.into(), serde_yaml::from_str(&c).unwrap()))
+ }
+ })
+ .collect(),
+ }
+ }
+
+ /// Save all maps that are present currently
+ pub fn save_all(&self) {
+ self.inner.iter().for_each(|(name, map)| {
+ let path = self.root.join(format!("{}.rstmap", name));
+ let mut f = OpenOptions::new()
+ .truncate(true)
+ .create(true)
+ .write(true)
+ .open(path.clone())
+ .unwrap();
+
+ debug!("Writing map configuration {}", path.to_str().unwrap());
+ let buf = serde_yaml::to_string(&map).unwrap();
+ f.write_all(buf.as_bytes()).unwrap();
+ });
+ }
+}