concinnity-cook 0.19.16

Authored world model, validation, and the asset cook pipeline that bakes a Concinnity world into a blob
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
// Build-time expansion of an OptionSelect settings row. A setting with more than
// two options expands to a dropdown (name + current value + a downward chevron
// under one click region firing "setting:<key>:open", which opens a floating
// option list at runtime); a setting with two options (an Off/On toggle) expands
// to a `<`/`>` stepper (name + `<` + value + `>` over two regions firing
// "setting:<key>:prev" / ":next"). The option count is read from the shared
// registry in `concinnity_core::gfx::settings`, so the row form always matches
// the setting the engine will apply.
//
// The value label shows a placeholder here; the runtime corrects it to the live
// value on the first frame. Names are prefixed with the OptionSelect's own name
// so generated elements stay scoped to its Screen via the build pipeline's
// `<screen>_*` rule and never collide with hand-authored assets.

use super::expand::{asset_name, type_norm};
use super::ui_spec::{font_sizes, label_value};
use crate::authoring::registry::build_only::OptionSelect;
use crate::authoring::spec::{asset, spec_to_value};

// Whether a setting row expands to a dropdown (more than two options, or a
// runtime-enumerated option list like `resolution`) rather than a `<`/`>`
// stepper. An unknown key (no registered options) falls back to the stepper
// form.
fn is_dropdown(setting: &str) -> bool {
    concinnity_core::gfx::settings::options(setting).is_some_and(|o| o.len() > 2)
        || concinnity_core::gfx::settings::is_dynamic_dropdown(setting)
}

// Where the control group (the `<` button + value + `>`) starts, as a fraction
// of the row width. The name occupies the left part, the control the right.
const CONTROL_FRAC: f32 = 0.42;
// The control group is capped to this fixed width, anchored to the right of the
// row, so on a wide row the control stays a compact column that lines up across
// rows (a narrow row falls back to `CONTROL_FRAC`). Mirrors `world/slider.rs`
// and the settings menu; keep in sync so all rows align.
const MAX_CONTROL_WIDTH: f32 = 360.0;
// Average glyph advance as a fraction of the font pixel size, for placing the
// single-character `<` / `>` glyphs (the built-in font is proportional, so this
// is approximate).
const AVG_ADVANCE_RATIO: f32 = 0.5;
// Padding around the `<` / `>` glyphs and the value, in pixels.
const GLYPH_PAD: f32 = 8.0;
// Placeholder shown until the runtime sets the live value on the first frame.
const VALUE_PLACEHOLDER: &str = "--";

// Replace every OptionSelect asset with the concrete UI assets it expands to.
pub(crate) fn expand_option_selects(assets: &mut Vec<serde_json::Value>) -> Result<(), String> {
    if !assets.iter().any(|v| type_norm(v) == "optionselect") {
        return Ok(());
    }

    let font_px_by_name = font_sizes(assets);

    let mut result: Vec<serde_json::Value> = Vec::new();
    for value in assets.drain(..) {
        if type_norm(&value) != "optionselect" {
            result.push(value);
            continue;
        }

        let name = asset_name(&value);
        if name.is_empty() {
            return Err("OptionSelect: missing `name`".to_string());
        }
        let args = value
            .get("args")
            .cloned()
            .unwrap_or_else(|| serde_json::json!({}));
        let select: OptionSelect = serde_json::from_value(args)
            .map_err(|e| format!("OptionSelect '{}': invalid args: {}", name, e))?;

        let default_px = select.font_px;
        let font_px = if select.font.is_empty() {
            default_px
        } else {
            *font_px_by_name.get(&select.font).unwrap_or(&default_px)
        };

        result.extend(expand_one(&name, &select, font_px));
    }

    *assets = result;
    Ok(())
}

// The Sprite/TextLabel child names an OptionSelect named `base` (for `setting`)
// expands to (the elements a scroll panel reflows + clips with its row). The
// HitRegions are excluded: they have no asset id and are reflowed by position.
// The child set depends on the row form (dropdown vs stepper), so it takes the
// setting key too. Locked to the expansion output by
// `element_names_match_expansion`.
pub(crate) fn element_names(base: &str, setting: &str) -> Vec<String> {
    if is_dropdown(setting) {
        vec![
            format!("{base}_label"),
            format!("{base}_value"),
            format!("{base}_chevron"),
        ]
    } else {
        vec![
            format!("{base}_label"),
            format!("{base}_prev_glyph"),
            format!("{base}_value"),
            format!("{base}_next_glyph"),
        ]
    }
}

fn expand_one(name: &str, s: &OptionSelect, font_px: f32) -> Vec<serde_json::Value> {
    let line_h = font_px * s.text_scale;
    let text_y = s.y + (s.height - line_h) / 2.0;
    let value_name = format!("{}_value", name);

    let glyph_w = font_px * AVG_ADVANCE_RATIO * s.text_scale;
    let ctrl_x = (s.x + s.width * CONTROL_FRAC).max(s.x + s.width - MAX_CONTROL_WIDTH);
    let right = s.x + s.width;

    // A setting with more than two options expands to a dropdown: the name, the
    // current value left-aligned in the control column, and a downward chevron
    // at the far right, all under one region that opens the floating list. The
    // chevron is an ASCII `v` (the built-in font atlas is ASCII-only).
    if is_dropdown(&s.setting) {
        return vec![
            // Name (left).
            label_value(
                &format!("{}_label", name),
                &s.label,
                &s.font,
                s.x,
                text_y,
                s.text_color,
                s.text_scale,
            ),
            // Current value, left-aligned at the start of the control column.
            label_value(
                &value_name,
                VALUE_PLACEHOLDER,
                &s.font,
                ctrl_x + GLYPH_PAD,
                text_y,
                s.value_color,
                s.text_scale,
            ),
            // Downward chevron flush to the right edge (mirrors the stepper `>`).
            label_value(
                &format!("{}_chevron", name),
                "v",
                &s.font,
                right - glyph_w,
                text_y,
                s.value_color,
                s.text_scale,
            ),
            // One click region over the whole control column opens the list.
            region(
                &format!("{}_open", name),
                Rect {
                    x: ctrl_x,
                    y: s.y,
                    width: right - ctrl_x,
                    height: s.height,
                },
                &value_name,
                s,
                &format!("setting:{}:open", s.setting),
            ),
        ];
    }

    // Two options: a `<`/`>` stepper. Layout, left to right: the name fills the
    // left part; then a `<` button, the value (left-aligned and display-only),
    // and a `>` at the far right. Two non-overlapping click regions only -- `<`
    // cycles to the previous option, and everything to its right (value + `>`)
    // cycles to the next. Overlapping regions must be avoided: UiInputSystem
    // keeps scanning after a setting action fires (it returns no StepResult), so
    // two regions hit by one click would both fire and cancel out.
    let sw = s.stepper_width;
    let next_x = ctrl_x + sw;

    vec![
        // Name (left).
        label_value(
            &format!("{}_label", name),
            &s.label,
            &s.font,
            s.x,
            text_y,
            s.text_color,
            s.text_scale,
        ),
        // `<` glyph, centered in the prev button.
        label_value(
            &format!("{}_prev_glyph", name),
            "<",
            &s.font,
            ctrl_x + (sw - glyph_w) / 2.0,
            text_y,
            s.value_color,
            s.text_scale,
        ),
        // Value (display only), left-aligned just past the `<` button.
        label_value(
            &value_name,
            VALUE_PLACEHOLDER,
            &s.font,
            next_x + GLYPH_PAD,
            text_y,
            s.value_color,
            s.text_scale,
        ),
        // `>` glyph, flush to the right edge of the row, so it mirrors the
        // left-aligned name and the row's left/right padding stays symmetric.
        label_value(
            &format!("{}_next_glyph", name),
            ">",
            &s.font,
            right - glyph_w,
            text_y,
            s.value_color,
            s.text_scale,
        ),
        // Prev click region (the `<` button).
        region(
            &format!("{}_prev", name),
            Rect {
                x: ctrl_x,
                y: s.y,
                width: sw,
                height: s.height,
            },
            &value_name,
            s,
            &format!("setting:{}:prev", s.setting),
        ),
        // Next click region (value + `>`).
        region(
            &format!("{}_next", name),
            Rect {
                x: next_x,
                y: s.y,
                width: right - next_x,
                height: s.height,
            },
            &value_name,
            s,
            &format!("setting:{}:next", s.setting),
        ),
    ]
}

// A settings-row rectangle in overlay coordinates.
#[derive(Clone, Copy)]
struct Rect {
    x: f32,
    y: f32,
    width: f32,
    height: f32,
}

// Build a HitRegion value scoped to a settings row.
fn region(
    name: &str,
    rect: Rect,
    value_label: &str,
    s: &OptionSelect,
    action: &str,
) -> serde_json::Value {
    spec_to_value(
        &asset::hit_region(name, [rect.x, rect.y, rect.width, rect.height], action)
            .set("label", value_label)
            .set("hover_color", s.hover_color)
            .set("hover_scale", s.hover_scale),
    )
}

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

    fn by_name<'a>(assets: &'a [serde_json::Value], name: &str) -> &'a serde_json::Value {
        assets
            .iter()
            .find(|v| asset_name(v) == name)
            .unwrap_or_else(|| panic!("no asset named {name}"))
    }

    #[test]
    fn passes_through_without_selects() {
        let mut assets = vec![serde_json::json!({"name":"x","type":"Window","args":{}})];
        expand_option_selects(&mut assets).unwrap();
        assert_eq!(assets.len(), 1);
    }

    #[test]
    fn expands_to_name_value_glyphs_and_two_stepper_regions() {
        let mut assets = vec![serde_json::json!({
            "name": "opt_vsync",
            "type": "OptionSelect",
            "args": {
                "setting": "vsync", "label": "Vsync",
                "x": 100.0, "y": 200.0, "width": 300.0, "stepper_width": 40.0
            }
        })];
        expand_option_selects(&mut assets).unwrap();

        assert!(!assets.iter().any(|v| type_norm(v) == "optionselect"));

        let lbl = by_name(&assets, "opt_vsync_label");
        assert_eq!(lbl["type"], "TextLabel");
        assert_eq!(lbl["args"]["content"], "Vsync");
        assert_eq!(lbl["args"]["centered"], false);
        assert_eq!(lbl["args"]["x"], 100.0);

        let val = by_name(&assets, "opt_vsync_value");
        assert_eq!(val["args"]["content"], VALUE_PLACEHOLDER);

        // ASCII glyphs (the built-in font atlas is ASCII-only).
        assert_eq!(
            by_name(&assets, "opt_vsync_prev_glyph")["args"]["content"],
            "<"
        );
        assert_eq!(
            by_name(&assets, "opt_vsync_next_glyph")["args"]["content"],
            ">"
        );

        // Two non-overlapping click regions. The row is narrow enough that the
        // fraction wins over the right-anchored cap: ctrl_x =
        // max(100 + 300*0.42, 100 + 300 - 360) = max(226, 40) = 226.
        let prev = by_name(&assets, "opt_vsync_prev");
        assert_eq!(prev["type"], "HitRegion");
        assert_eq!(prev["args"]["action"], "setting:vsync:prev");
        assert_eq!(prev["args"]["label"], "opt_vsync_value");
        assert_eq!(prev["args"]["x"], 226.0);
        assert_eq!(prev["args"]["width"], 40.0);

        let next = by_name(&assets, "opt_vsync_next");
        assert_eq!(next["args"]["action"], "setting:vsync:next");
        assert_eq!(next["args"]["label"], "opt_vsync_value");
        // next starts where prev ends (ctrl_x + stepper_width = 266) -> no overlap.
        assert_eq!(next["args"]["x"], 266.0);
        assert_eq!(next["args"]["width"], 134.0);
    }

    #[test]
    fn missing_name_is_an_error() {
        let mut assets = vec![serde_json::json!({"type":"OptionSelect","args":{}})];
        assert!(expand_option_selects(&mut assets).is_err());
    }

    #[test]
    fn invalid_args_name_the_select() {
        let mut assets = vec![serde_json::json!({
            "name": "opt", "type": "OptionSelect", "args": {"width": "wide"}
        })];
        let err = expand_option_selects(&mut assets).unwrap_err();
        assert!(err.contains("OptionSelect 'opt'"), "{err}");
        assert!(err.contains("invalid args"), "{err}");
    }

    // A row with no args at all is the fully defaulted row, not an error.
    #[test]
    fn select_without_args_uses_type_defaults() {
        let mut assets = vec![serde_json::json!({"name":"opt","type":"OptionSelect"})];
        expand_option_selects(&mut assets).unwrap();
        let defaults = OptionSelect::default();
        assert_eq!(by_name(&assets, "opt_label")["args"]["x"], defaults.x);
        assert_eq!(
            by_name(&assets, "opt_label")["args"]["content"],
            defaults.label
        );
    }

    // A setting with more than two options (window_mode has three) expands to a
    // dropdown: name + value + chevron under a single open region, no `<`/`>`.
    #[test]
    fn expands_to_dropdown_with_open_region() {
        let mut assets = vec![serde_json::json!({
            "name": "opt_wm",
            "type": "OptionSelect",
            "args": {
                "setting": "window_mode", "label": "Window Mode",
                "x": 100.0, "y": 200.0, "width": 300.0
            }
        })];
        expand_option_selects(&mut assets).unwrap();

        assert_eq!(
            by_name(&assets, "opt_wm_label")["args"]["content"],
            "Window Mode"
        );
        assert_eq!(
            by_name(&assets, "opt_wm_value")["args"]["content"],
            VALUE_PLACEHOLDER
        );
        // ASCII chevron (the built-in atlas is ASCII-only), and no stepper glyphs.
        assert_eq!(by_name(&assets, "opt_wm_chevron")["args"]["content"], "v");
        assert!(!assets.iter().any(|v| asset_name(v) == "opt_wm_prev_glyph"));
        assert!(!assets.iter().any(|v| asset_name(v) == "opt_wm_next_glyph"));

        // A single click region opens the floating list; no prev/next regions.
        let open = by_name(&assets, "opt_wm_open");
        assert_eq!(open["type"], "HitRegion");
        assert_eq!(open["args"]["action"], "setting:window_mode:open");
        assert_eq!(open["args"]["label"], "opt_wm_value");
        assert!(!assets.iter().any(|v| asset_name(v) == "opt_wm_prev"));
        assert!(!assets.iter().any(|v| asset_name(v) == "opt_wm_next"));
    }

    // A runtime-enumerated setting (resolution) has no static option table but
    // still expands to a dropdown; the runtime seeds the list from the display.
    #[test]
    fn dynamic_setting_expands_to_dropdown() {
        let mut assets = vec![serde_json::json!({
            "name": "opt_res",
            "type": "OptionSelect",
            "args": {
                "setting": "resolution", "label": "Resolution",
                "x": 100.0, "y": 200.0, "width": 300.0
            }
        })];
        expand_option_selects(&mut assets).unwrap();
        let open = by_name(&assets, "opt_res_open");
        assert_eq!(open["args"]["action"], "setting:resolution:open");
        assert_eq!(by_name(&assets, "opt_res_chevron")["args"]["content"], "v");
        assert!(!assets.iter().any(|v| asset_name(v) == "opt_res_prev"));
    }

    // `element_names` must list exactly the Sprite/TextLabel children the
    // expansion emits (a scroll panel relies on these to reflow + clip the row),
    // for both the stepper (vsync, two options) and dropdown (window_mode, three)
    // forms.
    #[test]
    fn element_names_match_expansion() {
        for (setting, label) in [("vsync", "Vsync"), ("window_mode", "Window Mode")] {
            let mut assets = vec![serde_json::json!({
                "name": "opt", "type": "OptionSelect",
                "args": { "setting": setting, "label": label }
            })];
            expand_option_selects(&mut assets).unwrap();
            let emitted: std::collections::HashSet<String> = assets
                .iter()
                .filter(|v| matches!(type_norm(v).as_str(), "textlabel" | "sprite"))
                .map(asset_name)
                .collect();
            let listed: std::collections::HashSet<String> =
                element_names("opt", setting).into_iter().collect();
            assert_eq!(listed, emitted, "element_names drifted for '{setting}'");
        }
    }
}