yog-cli 0.49.3

Yog build tool — `yog build` compiles a mod and packages it as .yog.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
//! Kinds of recipe for the recipe editor — the game's (`yog_registry`'s
//! built-in definitions) and the mod's own (`.ydef` `kind: "recipe_kind"`),
//! all described the same way: their slots (and the `.yrecipe` fields the
//! game's are written in), their values, and — the layout books show them
//! by (built in, or a `.yui` `recipe_layout`) — the picture (images, the
//! station, slot frames) with where slots, result and texts go on it.

use std::path::{Path, PathBuf};
use yog_ids::Format;

use std::borrow::Cow;
use yog_book::layout_picture::{Piece, pieces};
use yog_book::renderer::{BLOCK_PITCH, SLOT_YAW};
use yog_data::Schema;
use yog_formats::book::layout::{LayoutPart, RecipeLayout};
use yog_formats::def::{Def, RecipeKindDef};
use yog_gfx::{Color, Vec2};
use yog_registry::recipe_kinds::{self, fields};

use crate::design::{assets::Resources, gfx, images, raster};

/// How much bigger than GUI pixels the picture is drawn.
const SCALE: u32 = 3;

#[derive(Debug, yog_data::Schema)]
#[data(rename_all = "camelCase")]
pub struct Slot {
    pub name: String,
    /// What editors call it; `name` if none.
    pub label: Option<String>,
    pub description: Option<String>,
    pub max: u32,
    pub required: bool,
    /// The game's kinds: the `.yrecipe` field it's written in.
    pub field: Option<String>,
    /// Its places are a crafting grid's (`pattern` and `key`).
    pub grid: bool,
}

#[derive(Debug, yog_data::Schema)]
#[data(rename_all = "camelCase")]
pub struct ValueSpec {
    pub name: String,
    /// `number`, `text` or `bool` — the format's word for its type.
    pub kind: String,
    /// What it is when a recipe doesn't say.
    pub default: Option<f64>,
}

/// Something the editor puts on the picture, in GUI pixels.
#[derive(Debug, yog_data::Schema)]
#[data(rename_all = "camelCase", tag = "type")]
pub enum Spot {
    /// The `index`-th ingredient of `slot`.
    Slot {
        slot: String,
        index: usize,
        at: [f32; 2],
    },
    Result {
        at: [f32; 2],
    },
    Count {
        at: [f32; 2],
    },
    /// `{name}` is the recipe's value of that name.
    Text {
        text: String,
        at: [f32; 2],
    },
}

#[derive(Debug, yog_data::Schema)]
#[data(rename_all = "camelCase")]
pub struct Layout {
    /// The `.yui` it's laid out in; empty for a built-in layout.
    pub file: String,
    pub size: [f32; 2],
    /// The picture, `SCALE`× GUI pixels, `data:image/png;base64,…`.
    pub image: Option<String>,
    pub scale: u32,
    pub spots: Vec<Spot>,
}

#[derive(Debug, yog_data::Schema)]
#[data(rename_all = "camelCase")]
pub struct Kind {
    pub id: String,
    /// What editors call it; the id's path if none.
    pub label: Option<String>,
    /// The `.ydef` that declares it; empty for the game's.
    pub file: String,
    pub slots: Vec<Slot>,
    pub values: Vec<ValueSpec>,
    pub layout: Option<Layout>,
}

/// The fields every `.yrecipe` has, by the names the format gives them
/// (`yog_registry::recipe_kinds::fields`) — the editor reads and writes
/// recipes with these.
#[derive(Debug, yog_data::Schema)]
#[data(rename_all = "camelCase")]
pub struct Fields {
    #[data(rename = "type")]
    pub kind: Cow<'static, str>,
    pub result: Cow<'static, str>,
    pub count: Cow<'static, str>,
    pub slots: Cow<'static, str>,
    pub values: Cow<'static, str>,
    pub pattern: Cow<'static, str>,
    pub key: Cow<'static, str>,
    pub grid_side: usize,
}

/// Every kind the editor knows for the mod at `root`, and the fields.
#[derive(Debug, yog_data::Schema)]
pub struct Kinds {
    pub game: Vec<Kind>,
    pub own: Vec<Kind>,
    pub fields: Fields,
}

pub const FIELDS: Fields = Fields {
    kind: Cow::Borrowed(fields::TYPE),
    result: Cow::Borrowed(fields::RESULT),
    count: Cow::Borrowed(fields::COUNT),
    slots: Cow::Borrowed(fields::SLOTS),
    values: Cow::Borrowed(fields::VALUES),
    pattern: Cow::Borrowed(fields::PATTERN),
    key: Cow::Borrowed(fields::KEY),
    grid_side: recipe_kinds::GRID_SIDE,
};

/// The kinds for the mod at `root` (none of the mod's without one).
pub fn all(root: Option<&Path>) -> Kinds {
    Kinds {
        game: root.map(game_kinds).unwrap_or_default(),
        own: root.map(kinds).unwrap_or_default(),
        fields: FIELDS,
    }
}

/// The game's kinds, as books show them: their built-in layouts, or the
/// mod's own `recipe_layout` for one.
pub fn game_kinds(root: &Path) -> Vec<Kind> {
    let layouts = crate::design::mod_ui::recipe_layouts(root);
    recipe_kinds::GAME
        .iter()
        .map(|k| describe(root, k, k.id.clone(), String::new(), &layouts))
        .collect()
}

/// The kinds the mod at `root` declares, by id.
pub fn kinds(root: &Path) -> Vec<Kind> {
    let ns = crate::design::project::mod_id(root).unwrap_or_default();
    let files = crate::files::of(&root.join(yog_ids::project::CONTENT), Format::Def);
    let layouts = crate::design::mod_ui::recipe_layouts(root);
    let mut out: Vec<Kind> = files
        .iter()
        .filter_map(|file| {
            let text = crate::files::read_source(file).ok()?;
            let Def::RecipeKind(k) = yog_data::from_text::<Def>(&text).ok()?.value else {
                return None;
            };
            let id = if k.id.contains(':') {
                k.id.clone()
            } else {
                format!("{ns}:{}", k.id)
            };
            Some(describe(
                root,
                &k,
                id,
                file.to_string_lossy().into_owned(),
                &layouts,
            ))
        })
        .collect();
    out.sort_by(|a, b| a.id.cmp(&b.id));
    out
}

/// Kind `k` (as `id`, declared in `file`) for the editor: the mod's layout
/// for it, else a built-in one.
fn describe(
    root: &Path,
    k: &RecipeKindDef,
    id: String,
    file: String,
    layouts: &[(PathBuf, RecipeLayout)],
) -> Kind {
    let own: Vec<RecipeLayout> = layouts.iter().map(|(_, l)| l.clone()).collect();
    let layout_file = layouts
        .iter()
        .find(|(_, l)| l.kinds.contains(&id))
        .map(|(f, _)| f.clone())
        .unwrap_or_default();
    Kind {
        label: k.name.clone(),
        file,
        slots: k
            .slots
            .0
            .iter()
            .map(|(name, s)| Slot {
                name: name.clone(),
                label: s.name.clone(),
                description: s.description.clone(),
                max: s.max,
                required: s.required,
                field: s.field.clone(),
                grid: s.grid,
            })
            .collect(),
        values: k
            .values
            .0
            .iter()
            .map(|(name, t)| ValueSpec {
                name: name.clone(),
                kind: t.write().as_str().unwrap_or_default().to_string(),
                default: k.default_of(name),
            })
            .collect(),
        layout: yog_formats::book::layout::find(&own, &id).map(|l| layout(root, &layout_file, l)),
        id,
    }
}

/// The picture of `layout` (what doesn't change with the recipe) and the spots.
fn layout(root: &Path, file: &Path, layout: &RecipeLayout) -> Layout {
    let size = layout.size;
    let mut spots = Vec::new();
    for p in &layout.parts {
        match p {
            LayoutPart::Slots { slot, at, .. } => {
                spots.extend(at.iter().enumerate().map(|(index, at)| Spot::Slot {
                    slot: slot.clone(),
                    index,
                    at: *at,
                }));
            }
            LayoutPart::Result { at, .. } => spots.push(Spot::Result { at: *at }),
            LayoutPart::Count { at } => spots.push(Spot::Count { at: *at }),
            LayoutPart::Text { text, at } => spots.push(Spot::Text {
                text: text.clone(),
                at: *at,
            }),
            LayoutPart::Image { .. } | LayoutPart::Item { .. } | LayoutPart::Block { .. } => {}
        }
    }
    let (w, h) = (
        size[0].ceil().max(1.0) as u32,
        size[1].ceil().max(1.0) as u32,
    );
    let ops = gfx::record(w as i32, h as i32, |ctx| {
        let d = ctx.draw2d();
        for piece in pieces(layout) {
            match piece {
                Piece::Image { source, uv, at } => {
                    d.image_region(source, at, Some(uv), Color::WHITE)
                }
                Piece::Item { item, at } => d.item(item, Vec2::new(at.x, at.y), at.w),
                Piece::Block { block, at } => {
                    d.blocks(&[((0, 0, 0), block)], at, SLOT_YAW, BLOCK_PITCH)
                }
            }
        }
    });
    images::set_document(Some(root));
    let res = Resources::for_mod(Some(root));
    let image = raster::rasterize(&ops, w, h, SCALE, &res).png_url();
    Layout {
        file: file.to_string_lossy().into_owned(),
        size,
        image,
        scale: SCALE,
        spots,
    }
}

/// Where a new kind's layout goes, under the mod's sources, and what its name ends with.
const LAYOUT_DIR: &str = "ui";
const LAYOUT_SUFFIX: &str = "_layout";

/// Makes a new kind of recipe in the mod of `file` — `content/<name>.ydef`
/// (its slots and values) and `src/ui/<name>_layout.yui` (how it's shown);
/// the layout's path, to open in the designer.
pub fn create(file: &Path, name: &str) -> Result<PathBuf, String> {
    let root = super::mod_root(file).ok_or("not inside a mod")?;
    let name = name.trim();
    if !yog_ids::valid_name(name) {
        return Err("a kind's name: a-z, 0-9 and _".into());
    }
    let def = root
        .join(yog_ids::project::CONTENT)
        .join(Format::Def.file(name));
    let layout = root
        .join(yog_ids::project::SRC)
        .join(LAYOUT_DIR)
        .join(Format::Ui.file(&format!("{name}{LAYOUT_SUFFIX}")));
    if let Some(taken) = [&def, &layout].into_iter().find(|f| f.exists()) {
        return Err(format!("{} exists", taken.display()));
    }
    for (f, text) in [(&def, template(name)), (&layout, layout_template(name))] {
        if let Some(dir) = f.parent() {
            std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
        }
        if yog_ids::Format::of_path(f).is_some_and(|f| f.is_data()) {
            crate::files::write_source(f, &text)?;
        } else {
            std::fs::write(f, text).map_err(|e| e.to_string())?;
        }
    }
    Ok(layout)
}

/// A new kind's `.ydef`: two slots and a value to start from.
pub fn template(id: &str) -> String {
    format!(
        r#"{{
  kind: "recipe_kind",
  id: "{id}",
  // Named slots: how many ingredients each takes.
  slots: {{
    input: {{ required: true }},
    extra: {{ max: 2 }},
  }},
  // Named values a recipe of the kind gives (number, text, bool).
  values: {{ time: "number" }},
}}
"#
    )
}

/// A new kind's layout (`src/ui/<id>_layout.yui`), for the screen designer:
/// the template's slots framed, the result, its time.
pub fn layout_template(id: &str) -> String {
    // What the designer shows in them: the game's ore and its ingot.
    let (input, result) = (yog_ids::qualify("iron_ore"), yog_ids::qualify("iron_ingot"));
    format!(
        r#"<!-- How recipes of {id} are shown: in books and in the recipe editor. -->
<Component recipe_layout="{id}" width="100" height="40">
    <RecipeSlot slot="input" x="4" y="12" frame="true" d:item="{input}"/>
    <RecipeSlot slot="extra" x="30" y="4" frame="true"/>
    <RecipeSlot slot="extra" x="30" y="22" frame="true"/>
    <RecipeResult x="78" y="12" frame="true" d:item="{result}"/>
    <Label text="{{x:Bind time}} ticks" x="50" y="32"/>
</Component>
"#
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn reads_the_mods_kinds_and_lays_them_out() {
        let dir = std::env::temp_dir().join(format!("yog-idle-kinds-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(dir.join("content/machines")).unwrap();
        std::fs::write(dir.join("yog.toml"), "[mod]\nid = \"mymod\"\n").unwrap();
        std::fs::write(
            dir.join("content/machines/crusher.ydef"),
            template("crusher"),
        )
        .unwrap();
        std::fs::create_dir_all(dir.join("src/ui")).unwrap();
        std::fs::write(
            dir.join("src/ui/crusher_layout.yui"),
            layout_template("crusher"),
        )
        .unwrap();
        std::fs::write(
            dir.join("content/other.ydef"),
            r#"{ kind: "sound_group", id: "x" }"#,
        )
        .unwrap();
        let ks = kinds(&dir);
        assert_eq!(ks.len(), 1);
        let k = &ks[0];
        assert_eq!(k.id, "mymod:crusher");
        assert_eq!(
            k.slots
                .iter()
                .map(|s| (s.name.as_str(), s.max, s.required))
                .collect::<Vec<_>>(),
            [("input", 1, true), ("extra", 2, false)]
        );
        assert_eq!(k.values[0].kind, "number");
        let l = k.layout.as_ref().unwrap();
        assert!(
            l.image
                .as_deref()
                .is_some_and(|i| i.starts_with("data:image/png"))
        );
        assert_eq!(
            l.spots
                .iter()
                .filter(|s| matches!(s, Spot::Slot { .. }))
                .count(),
            3
        );
        assert!(
            l.spots
                .iter()
                .any(|s| matches!(s, Spot::Text { text, .. } if text == "{time} ticks"))
        );
        assert!(l.file.ends_with("crusher_layout.yui"));
        let game = game_kinds(&dir);
        assert_eq!(
            game.iter().map(|k| k.id.as_str()).collect::<Vec<_>>(),
            recipe_kinds::ids::ALL,
            "the registry's kinds, in its order"
        );
        let shaped = game[0].layout.as_ref().unwrap();
        assert_eq!(
            shaped
                .spots
                .iter()
                .filter(|s| matches!(s, Spot::Slot { slot, .. } if slot == "grid"))
                .count(),
            9,
            "the crafting table's own picture"
        );
        let smithing = game
            .iter()
            .find(|k| k.id == recipe_kinds::ids::SMITHING)
            .unwrap()
            .layout
            .as_ref()
            .unwrap();
        let parts: Vec<&str> = smithing
            .spots
            .iter()
            .filter_map(|s| {
                if let Spot::Slot { slot, .. } = s {
                    Some(slot.as_str())
                } else {
                    None
                }
            })
            .collect();
        assert_eq!(
            parts,
            ["base", "addition", "template"],
            "Patchouli's smithing strip"
        );
        assert!(
            smithing
                .spots
                .iter()
                .any(|s| matches!(s, Spot::Result { .. }))
        );
        assert!(smithing.image.is_some());
        let brewing = game
            .iter()
            .find(|k| k.id == recipe_kinds::ids::BREWING)
            .unwrap();
        assert_eq!(
            brewing
                .slots
                .iter()
                .map(|s| s.field.as_deref())
                .collect::<Vec<_>>(),
            [Some("from"), Some("ingredient")]
        );
        assert!(
            brewing.layout.as_ref().is_some_and(|l| l.image.is_some()),
            "Yog's own brewing strip"
        );
        // What the recipe editor reads (recipeModel.ts `RecipeKind`).
        let spots = yog_data::Schema::write(&l.spots);
        let types: Vec<&str> = spots
            .as_list()
            .unwrap()
            .iter()
            .map(|s| s.get("type").and_then(yog_data::Value::as_str).unwrap())
            .collect();
        assert_eq!(types, ["slot", "slot", "slot", "result", "text"]);
        let _ = std::fs::remove_dir_all(&dir);
    }
}