Skip to main content

yog_cli/yres/
mod.rs

1//! `.yres` resource files — a mod's texts, images, sounds, files, colors,
2//! numbers and flags, like a C# project's `Resources/*.resx`. See
3//! Yog-IDLE's `docs/yres.md` for the format.
4//!
5//! `yog build` reads `resources/**/*.yres`: `<Set>.yres` is the neutral
6//! (en_us) file of resource set `<Set>`, `<Set>.<locale>.yres` its culture
7//! variants (texts only). It
8//!
9//! - writes the texts into `assets/<mod id>/lang/<locale>.json` (merged with
10//!   a hand-written one), `{name}`/`{0}` placeholders turned into `%1$s`;
11//! - bundles image/file/sound entries' files under `assets/<mod id>/...`,
12//!   plus a `sounds.json` for the sounds;
13//! - generates `.yog-build/generated/resources/<Set>.g.rs` — a type per
14//!   set with a typed accessor per entry — and `resources.g.rs` including
15//!   them, pulled in as `crate::res` by `yog_api::resources!();`;
16//! - resolves `@<Set>.<name>` references for `.yui` screens and `yog.toml`.
17
18mod accessors;
19mod compile;
20mod load;
21mod names;
22mod outputs;
23mod placeholders;
24
25pub use compile::compile;
26pub use load::{ResFile, Set};
27pub use names::{
28    accessor_name, default_key, name_problem, valid_locale, valid_name, valid_set_name,
29};
30pub use outputs::write_sources;
31
32use std::collections::{BTreeMap, HashMap};
33use std::path::{Path, PathBuf};
34
35/// The locale of the neutral `<Set>.yres` files.
36pub const NEUTRAL_LOCALE: &str = "en_us";
37/// Where resource files live, under the mod root.
38pub const RESOURCES_DIR: &str = yog_ids::project::RESOURCES;
39/// Where the generated accessors go, under the mod root.
40/// The file `yog_api::resources!()` includes; it includes one
41/// `resources/<Set>.g.rs` per set (shown under its `.yres` in Yog-IDLE).
42pub const GENERATED_FILE: &str = ".yog-build/generated/resources.g.rs";
43/// Where the per-set `<Set>.g.rs` files go.
44pub const GENERATED_DIR: &str = ".yog-build/generated/resources";
45
46/// A generated file: path inside the `.yog` and its bytes.
47pub type Output = (String, Vec<u8>);
48
49pub use yog_formats::yres::{Entry, EntryObject, Kind, Value, parse, write};
50
51/// What `.yui` screens and `yog.toml` can refer to as `@<Set>.<name>`.
52#[derive(Debug, Clone, Default)]
53pub struct Refs {
54    /// `Set.name` → (translation key, neutral text).
55    pub texts: HashMap<String, (String, String)>,
56    /// `Set.name` → image source (`<mod id>:<texture>`).
57    pub images: HashMap<String, String>,
58    /// `Set.name` → color (`0xAARRGGBB`).
59    pub colors: HashMap<String, u32>,
60    /// `Set.name` → an image's picture, as the build writes it.
61    pub pictures: HashMap<String, Picture>,
62}
63
64impl Refs {
65    /// Text `r`: its translation key and neutral words.
66    pub fn text(&self, r: &yog_data::Res) -> Result<&(String, String), String> {
67        self.texts
68            .get(&r.name())
69            .ok_or_else(|| format!("`{r}`: no text `{}` in resources/*.yres", r.name()))
70    }
71
72    /// Color `r` (`0xAARRGGBB`).
73    pub fn color(&self, r: &yog_data::Res) -> Result<u32, String> {
74        self.colors
75            .get(&r.name())
76            .copied()
77            .ok_or_else(|| format!("`{r}`: no color `{}` in resources/*.yres", r.name()))
78    }
79
80    /// Image `r`'s source.
81    pub fn image(&self, r: &yog_data::Res) -> Result<&str, String> {
82        self.images
83            .get(&r.name())
84            .map(String::as_str)
85            .ok_or_else(|| format!("`{r}`: no image `{}` in resources/*.yres", r.name()))
86    }
87
88    /// The translation key text `t` names — `@lang:key`, a thing's name, a
89    /// `.yres` text; none for words, which aren't one.
90    pub fn key_of(&self, t: &yog_data::Text) -> Result<Option<String>, String> {
91        use yog_data::Text;
92        Ok(match t {
93            Text::Literal(_) => None,
94            Text::Lang(k) => Some(k.clone()),
95            Text::NameOf(r) => Some(yog_ids::lang_key(
96                &r.kind,
97                yog_formats::book::refs::bare(&r.id),
98            )),
99            Text::Res(r) => Some(self.text(r)?.0.clone()),
100        })
101    }
102}
103
104/// An image's picture: its PNG and the file the build writes it to — which
105/// a texture packed into an atlas takes the place of.
106#[derive(Debug, Clone, Default, PartialEq)]
107pub struct Picture {
108    pub png: Vec<u8>,
109    pub output: String,
110}
111
112/// Everything `yog build` makes of a mod's resources.
113#[derive(Debug, Default)]
114pub struct Compiled {
115    /// Files to add to the `.yog` (lang JSON, images, sounds, sounds.json) —
116    /// they replace a hand-written asset at the same path (merged into them).
117    pub outputs: Vec<Output>,
118    /// `<Set>` → generated Rust source.
119    pub sources: BTreeMap<String, String>,
120    pub refs: Refs,
121    pub warnings: Vec<String>,
122    /// Number of `.yres` files read.
123    pub files: usize,
124}
125
126/// Every `resources/**/*.yres` of the mod at `root`, sorted.
127pub fn find(root: &Path) -> Vec<PathBuf> {
128    crate::files::under(&root.join(RESOURCES_DIR), &|p| yog_ids::Format::Res.is(p))
129}
130
131/// What's wrong with `e`'s value for its type, if anything — the build's
132/// rule, which editors show too.
133pub fn value_problem(e: &Entry) -> Option<String> {
134    let media = |what: &str| format!("{:?}: {what} are bytes (`@bytes:…`)", e.name);
135    match (e.kind, &e.value) {
136        (Kind::Image | Kind::File | Kind::Sound, Value::Bytes(_))
137            if !yog_ids::valid_path(&e.name.replace('.', yog_ids::sep::PATH)) =>
138        {
139            Some(format!(
140                "{:?}: Minecraft resource paths are lower case — only a-z, 0-9, `_`, `-`, `.`",
141                e.name
142            ))
143        }
144        (Kind::Sound, Value::Bytes(b)) if !b.starts_with(yog_formats::yres::OGG_MAGIC) => {
145            Some(format!("{:?}: sounds are Ogg Vorbis", e.name))
146        }
147        (Kind::Image | Kind::File | Kind::Sound, Value::Bytes(_)) => None,
148        (Kind::Image, _) => Some(media("images")),
149        (Kind::File, _) => Some(media("files")),
150        (Kind::Sound, _) => Some(media("sounds")),
151        (Kind::Color, _) => parse_color(e.text()).is_none().then(|| {
152            format!(
153                "{:?}: `{}` isn't a color — #RRGGBB or #AARRGGBB",
154                e.name,
155                e.text()
156            )
157        }),
158        (Kind::Number, Value::Num(_))
159        | (Kind::Bool, Value::Bool(_))
160        | (Kind::String, Value::Str(_)) => None,
161        (Kind::Number, _) => Some(format!("{:?}: a number", e.name)),
162        (Kind::Bool, _) => Some(format!("{:?}: true or false", e.name)),
163        (Kind::String, _) => Some(format!("{:?}: a text", e.name)),
164    }
165}
166
167/// A color entry's value as ARGB, when it is one.
168pub fn color_of(e: &Entry) -> Option<u32> {
169    (e.kind == Kind::Color)
170        .then(|| parse_color(e.text()))
171        .flatten()
172}
173
174/// `#RRGGBB` / `#AARRGGBB`: a `.yres` color is written with its `#`.
175fn parse_color(s: &str) -> Option<u32> {
176    crate::yui::color(s).filter(|_| s.trim().starts_with(crate::yui::HEX_MARK))
177}
178
179/// Resolves a `yog.toml` value: `@<Set>.<name>` of a text → (neutral text,
180/// Some(key)); anything else as is. Errors on an unknown reference.
181pub fn resolve_text(refs: &Refs, value: &str) -> Result<(String, Option<String>), String> {
182    match value.strip_prefix('@') {
183        Some(rest) if rest.starts_with('@') => Ok((rest.to_string(), None)),
184        Some(rest) => match refs.texts.get(rest) {
185            Some((key, text)) => Ok((text.clone(), Some(key.clone()))),
186            None => Err(format!("`{value}`: no text `{rest}` in resources/*.yres")),
187        },
188        None => Ok((value.to_string(), None)),
189    }
190}
191
192/// Resolves a `yog.toml` image value: `@<Set>.<name>` → its image source.
193pub fn resolve_image(refs: &Refs, value: &str) -> Result<String, String> {
194    match value.strip_prefix('@') {
195        Some(rest) => refs
196            .images
197            .get(rest)
198            .cloned()
199            .ok_or_else(|| format!("`{value}`: no image `{rest}` in resources/*.yres")),
200        None => Ok(value.to_string()),
201    }
202}
203
204#[cfg(test)]
205mod tests;