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//!   (sounds as Ogg Vorbis: `.ysound` events name them);
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(crate) use names::{accessor_name, default_key, name_problem};
27pub use outputs::write_sources;
28
29use crate::diagnostics::Diagnostic;
30use std::collections::{BTreeMap, HashMap};
31use std::path::{Path, PathBuf};
32
33/// The locale of the neutral `<Set>.yres` files.
34pub const NEUTRAL_LOCALE: &str = "en_us";
35/// Where resource files live, under the mod root.
36pub(crate) const RESOURCES_DIR: &str = yog_ids::project::RESOURCES;
37/// Where the generated accessors go, under the mod root.
38/// The file `yog_api::resources!()` includes; it includes one
39/// `resources/<Set>.g.rs` per set (shown under its `.yres` in Yog-IDLE).
40pub const GENERATED_FILE: &str = ".yog-build/generated/resources.g.rs";
41/// Where the per-set `<Set>.g.rs` files go.
42pub const GENERATED_DIR: &str = ".yog-build/generated/resources";
43
44/// A generated file: path inside the `.yog` and its bytes.
45pub(crate) type Output = (String, Vec<u8>);
46
47pub use yog_formats::yres::{Entry, Kind, Value, parse, write};
48
49/// What `.yui` screens and `yog.toml` can refer to as `@<Set>.<name>`.
50#[derive(Debug, Clone, Default)]
51pub struct Refs {
52    /// `Set.name` → (translation key, neutral text).
53    pub(crate) texts: HashMap<String, (String, String)>,
54    /// `Set.name` → image source (`<mod id>:<texture>`).
55    pub(crate) images: HashMap<String, String>,
56    /// `Set.name` → color (`0xAARRGGBB`).
57    pub(crate) colors: HashMap<String, u32>,
58    /// `Set.name` → an image's picture, as the build writes it.
59    pub(crate) pictures: HashMap<String, Picture>,
60    /// `Set.name` → a sound's file as `sounds.json` names it (`<mod id>:<path>`).
61    pub(crate) sounds: HashMap<String, String>,
62}
63
64impl Refs {
65    /// Text `r`: its translation key and neutral words.
66    pub(crate) 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    /// Sound `r`: its file as `sounds.json` names it.
73    pub(crate) fn sound(&self, r: &yog_data::Res) -> Result<&str, String> {
74        self.sounds
75            .get(&r.name())
76            .map(String::as_str)
77            .ok_or_else(|| format!("`{r}`: no sound `{}` in resources/*.yres", r.name()))
78    }
79
80    /// Color `r` (`0xAARRGGBB`).
81    pub fn color(&self, r: &yog_data::Res) -> Result<u32, String> {
82        self.colors
83            .get(&r.name())
84            .copied()
85            .ok_or_else(|| format!("`{r}`: no color `{}` 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(crate) 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(crate) struct Picture {
108    pub(crate) png: Vec<u8>,
109    pub(crate) 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    /// The files it made: `(path in the .yog, bytes)`.
118    pub outputs: Vec<Output>,
119    /// `<Set>` → generated Rust source.
120    pub sources: BTreeMap<String, String>,
121    /// What screens and `yog.toml` can refer to (`@<Set>.<name>`).
122    pub refs: Refs,
123    /// What to warn of.
124    pub warnings: Vec<Diagnostic>,
125    /// Number of `.yres` files read.
126    pub files: usize,
127}
128
129/// Every `resources/**/*.yres` of the mod at `root`, sorted.
130pub(crate) fn find(root: &Path) -> Vec<PathBuf> {
131    crate::files::under(&root.join(RESOURCES_DIR), &|p| yog_ids::Format::Res.is(p))
132}
133
134/// What's wrong with `e`'s value for its type, if anything — the build's
135/// rule, which editors show too.
136pub(crate) fn value_problem(e: &Entry) -> Option<String> {
137    let media = |what: &str| format!("{:?}: {what} are bytes (`@bytes:…`)", e.name);
138    match (e.kind, &e.value) {
139        (Kind::Image | Kind::File | Kind::Sound, Value::Bytes(_))
140            if !yog_ids::valid_path(&e.name.replace('.', yog_ids::sep::PATH)) =>
141        {
142            Some(format!(
143                "{:?}: Minecraft resource paths are lower case — only a-z, 0-9, `_`, `-`, `.`",
144                e.name
145            ))
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(crate) 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;
206
207/// A resources error (`YB0003`), where it is to be said by the caller.
208pub(crate) fn problem(msg: impl std::fmt::Display) -> crate::diagnostics::Diagnostic {
209    crate::diagnostics::Diagnostic::error(yog_ids::build_problem::RESOURCES, msg)
210}
211
212/// A resources warning (`YB0003`).
213pub(crate) fn caveat(msg: impl std::fmt::Display) -> crate::diagnostics::Diagnostic {
214    crate::diagnostics::Diagnostic::warning(yog_ids::build_problem::RESOURCES, msg)
215}