concinnity-dev 0.19.16

The Concinnity dev tooling library: world authoring, the in-engine editor, the debug server, docs and packaging
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
// src/editor/lighting_panel.rs
//
// The Lighting panel's layout half: a floating panel of themed sections (see
// `lighting.rs` for the bindings) with a status line + Apply button in its
// header row. Each field row is a caption plus one control -- a text input, a
// checkbox, or a text input with a colour swatch -- backed by a per-binding
// control pool at reserved ids. Like the rest of the editor HUD it is plain
// `Sprite` / `TextLabel` / `TextInput` components driven each frame by the
// editor hook; the hook owns seeding, focus, and the commit path.

use super::form::{FieldKind, FormField};
use super::lighting::{self, Row};
use super::registry::{self, PanelKey};
use super::theme;
use super::widget::{self, place_rounded, point_in};
use crate::components::TextAlign;
use crate::ecs::World;
use crate::ecs::asset_id::AssetId;

const BASE: u32 = registry::base(PanelKey::Lighting);
pub(crate) const PANEL_BG: AssetId = AssetId(BASE);
pub(crate) const TITLE_LABEL: AssetId = AssetId(BASE + 2);
pub(crate) const CLOSE_BG: AssetId = AssetId(BASE + 3);
pub(crate) const CLOSE_LABEL: AssetId = AssetId(BASE + 4);
pub(crate) const APPLY_BG: AssetId = AssetId(BASE + 5);
pub(crate) const APPLY_LABEL: AssetId = AssetId(BASE + 6);
pub(crate) const STATUS_LABEL: AssetId = AssetId(BASE + 7);

// Per-row chrome (row index) and per-binding controls (global binding index);
// the sub-ranges stay disjoint for any plausible row / binding count.
pub(crate) fn row_bg(i: usize) -> AssetId {
    AssetId(BASE + 0x20 + i as u32)
}
pub(crate) fn row_label(i: usize) -> AssetId {
    AssetId(BASE + 0x40 + i as u32)
}
pub(crate) fn input(b: usize) -> AssetId {
    AssetId(BASE + 0x60 + b as u32)
}
pub(crate) fn check_bg(b: usize) -> AssetId {
    AssetId(BASE + 0x80 + b as u32)
}
pub(crate) fn swatch(b: usize) -> AssetId {
    AssetId(BASE + 0xA0 + b as u32)
}

// Geometry, in window pixels. Every rect derives from the panel origin `o` (the
// title bar's top-left), so dragging the title bar moves the whole panel.
// The default (and minimum) panel width; the user can widen it past this.
pub(crate) const LIGHT_W: f32 = 380.0;
const PAD: f32 = 10.0;
// The header row under the title bar: the status line and the Apply button.
const HEADER_H: f32 = 32.0;
const BTN_W: f32 = 70.0;
const ROW_H: f32 = 28.0;
const LABEL_COL: f32 = 160.0;
const CHECK_SIZE: f32 = 18.0;
const SWATCH_W: f32 = 24.0;
const GAP: f32 = 6.0;

const HEADER_ROW_TINT: [f32; 4] = [0.16, 0.17, 0.22, 1.0];
const ROW_TINT: [f32; 4] = [0.0, 0.0, 0.0, 0.0];
const ROW_TINT_HOVER: [f32; 4] = theme::HOVER_TINT;
const BTN_TINT: [f32; 4] = [0.22, 0.40, 0.56, 1.0];
const BTN_TINT_HOVER: [f32; 4] = [0.28, 0.48, 0.66, 1.0];
const CHECK_ON: [f32; 4] = [0.30, 0.66, 0.34, 1.0];
const CHECK_OFF: [f32; 4] = [0.30, 0.30, 0.34, 1.0];
const LABEL: [f32; 3] = [0.90, 0.90, 0.92];
const HEADER_LABEL: [f32; 3] = [0.70, 0.74, 0.84];
const ADD_LABEL: [f32; 3] = [0.55, 0.80, 0.60];
const ERROR_LABEL: [f32; 3] = [0.95, 0.55, 0.55];
const LABEL_TOP: f32 = ROW_H * 0.5 - theme::TEXT_HALF;

// The per-frame view the hook assembles: the row list, the per-binding derived
// fields (`None` while a section's asset is absent), the focused binding, and
// the status line from the last rejected Apply.
pub(crate) struct LightingView<'a> {
    pub rows: &'a [Row],
    pub fields: &'a [Option<FormField>],
    pub focus: Option<usize>,
    pub status: Option<&'a str>,
    // Typed-but-not-Applied field edits exist: the heading marks them.
    pub dirty: bool,
    pub mouse: [f32; 2],
}

// A resolved Lighting-panel click.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum LightingAction {
    // Give binding `b`'s text input keyboard focus.
    Focus(usize),
    // Flip binding `b`'s checkbox (committed immediately by the hook).
    Toggle(usize),
    // Add the missing singleton asset of section `s`.
    Add(usize),
    // Capture every text control, validate per asset, and commit.
    Apply,
    // A click elsewhere on the panel: swallowed so it cannot reach the world.
    Consume,
}

// Where the panel sits until the user drags it: the window's left edge, below
// the View panel's default anchor.
pub(crate) fn default_origin() -> [f32; 2] {
    let view = super::view::default_origin();
    [8.0, view[1] + super::view::size()[1] + 8.0]
}

// The panel footprint for `n_rows` rows, for the hook's drag clamp.
pub(crate) fn size(n_rows: usize) -> [f32; 2] {
    [
        LIGHT_W,
        widget::TITLE_H + HEADER_H + n_rows as f32 * ROW_H + PAD,
    ]
}

// The Apply button, pinned to the header row's right end.
pub(crate) fn apply_rect(o: [f32; 2], w: f32) -> [f32; 4] {
    [
        o[0] + w - PAD - BTN_W,
        o[1] + widget::TITLE_H + 4.0,
        BTN_W,
        HEADER_H - 8.0,
    ]
}

// Row `i`, stacked below the header row.
pub(crate) fn row_rect(o: [f32; 2], w: f32, i: usize) -> [f32; 4] {
    [
        o[0],
        o[1] + widget::TITLE_H + HEADER_H + i as f32 * ROW_H,
        w,
        ROW_H,
    ]
}

// The control area on a field row's right side; a colour field's input is
// narrowed to leave room for its swatch.
fn control_rect(row: [f32; 4], color: bool) -> [f32; 4] {
    let x = row[0] + LABEL_COL;
    let w = row[0] + row[2] - PAD - x - if color { SWATCH_W + GAP } else { 0.0 };
    [x, row[1] + 3.0, w, row[3] - 6.0]
}

fn swatch_rect(row: [f32; 4]) -> [f32; 4] {
    [
        row[0] + row[2] - PAD - SWATCH_W,
        row[1] + 4.0,
        SWATCH_W,
        row[3] - 8.0,
    ]
}

fn check_rect(row: [f32; 4]) -> [f32; 4] {
    [
        row[0] + LABEL_COL,
        row[1] + (ROW_H - CHECK_SIZE) * 0.5,
        CHECK_SIZE,
        CHECK_SIZE,
    ]
}

// A colour field's swatch tint, parsed from its comma-separated text (3 or 4
// components); an unparseable value shows white rather than stale colour.
fn parse_color(text: &str) -> [f32; 4] {
    let parts: Vec<f32> = text
        .split(|c: char| c == ',' || c.is_whitespace())
        .filter(|s| !s.is_empty())
        .filter_map(|s| s.parse().ok())
        .collect();
    match parts.len() {
        3 => [parts[0], parts[1], parts[2], 1.0],
        4 => [parts[0], parts[1], parts[2], parts[3]],
        _ => [1.0, 1.0, 1.0, 1.0],
    }
}

// Resolve a click at `(mx, my)` against the panel at origin `o`. `None` means
// the click missed the panel. Title-bar presses never reach this: the shared
// routing intercepts them first.
pub(crate) fn hit_test(
    view: &LightingView,
    mx: f32,
    my: f32,
    o: [f32; 2],
    s: [f32; 2],
) -> Option<LightingAction> {
    let w = s[0];
    if point_in(mx, my, apply_rect(o, w)) {
        return Some(LightingAction::Apply);
    }
    for (i, row) in view.rows.iter().enumerate() {
        if !point_in(mx, my, row_rect(o, w, i)) {
            continue;
        }
        return Some(match *row {
            Row::Header(_) => LightingAction::Consume,
            Row::Add(sec) => LightingAction::Add(sec),
            Row::Field(b) => match view.fields.get(b).and_then(|f| f.as_ref()) {
                Some(f) if f.kind == FieldKind::Bool => LightingAction::Toggle(b),
                Some(_) => LightingAction::Focus(b),
                None => LightingAction::Consume,
            },
        });
    }
    point_in(mx, my, widget::outer_rect(o, s)).then_some(LightingAction::Consume)
}

// Position + show the panel (`Some(view)`) at effective size `s`, or blank every
// element (`None`).
pub(crate) fn apply(world: &mut World, view: Option<&LightingView>, o: [f32; 2], s: [f32; 2]) {
    let Some(view) = view else {
        hide_all(world);
        return;
    };
    let w = s[0];
    let n = view.rows.len();
    widget::place_panel(world, PANEL_BG, widget::outer_rect(o, s));
    let title = widget::title_rect(o, w);
    let heading = if view.dirty { "Lighting *" } else { "Lighting" };
    widget::place_heading(world, TITLE_LABEL, title, heading);
    let close_hover = point_in(view.mouse[0], view.mouse[1], widget::close_rect(title));
    widget::place_close(world, CLOSE_BG, CLOSE_LABEL, title, close_hover);

    // Header row: the status line (only after a rejected Apply) + the button.
    let apply = apply_rect(o, w);
    let apply_hover = point_in(view.mouse[0], view.mouse[1], apply);
    let tint = if apply_hover {
        BTN_TINT_HOVER
    } else {
        BTN_TINT
    };
    place_rounded(world, APPLY_BG, apply, tint, theme::CONTROL_RADIUS, true);
    if let Some(l) = widget::label_mut(world, APPLY_LABEL) {
        l.x = apply[0] + apply[2] * 0.5;
        l.y = apply[1] + apply[3] * 0.5 - theme::TEXT_HALF;
        l.align = TextAlign::Center;
        l.color = [1.0, 1.0, 1.0];
        l.visible = true;
        l.content = "Apply".to_string();
    }
    // The status shares the header row with Apply, so it is one line into
    // whatever the button leaves it.
    let left = o[0] + PAD;
    widget::place_message(
        world,
        STATUS_LABEL,
        [
            left,
            o[1] + widget::TITLE_H + HEADER_H * 0.5 - theme::TEXT_HALF,
            (apply[0] - PAD - left).max(0.0),
            widget::LINE_H,
        ],
        view.status.unwrap_or(""),
        ERROR_LABEL,
        view.status.is_some(),
    );

    // Every pooled control starts hidden; the row pass below shows what this
    // frame's rows actually use (sections toggle between fields and an add row).
    for b in 0..lighting::binding_count() {
        widget::hide_field(world, input(b));
        widget::set_sprite_visible(world, check_bg(b), false);
        widget::set_sprite_visible(world, swatch(b), false);
    }

    for (i, row) in view.rows.iter().enumerate() {
        let r = row_rect(o, w, i);
        let hovered = point_in(view.mouse[0], view.mouse[1], r);
        let (bg, caption, color) = match *row {
            Row::Header(s) => (
                HEADER_ROW_TINT,
                lighting::SECTIONS[s].title.to_string(),
                HEADER_LABEL,
            ),
            Row::Add(s) => (
                if hovered { ROW_TINT_HOVER } else { ROW_TINT },
                format!("+ Add {}", lighting::SECTIONS[s].ty),
                ADD_LABEL,
            ),
            Row::Field(b) => {
                let caption = lighting::binding(b).2.to_string();
                (ROW_TINT, caption, LABEL)
            }
        };
        place_rounded(
            world,
            row_bg(i),
            theme::highlight_rect(r),
            bg,
            theme::CONTROL_RADIUS,
            true,
        );
        if let Some(l) = widget::label_mut(world, row_label(i)) {
            l.x = r[0] + PAD;
            l.y = r[1] + LABEL_TOP;
            l.align = TextAlign::Left;
            l.color = color;
            l.visible = true;
            l.content = caption;
        }
        let Row::Field(b) = *row else { continue };
        let Some(field) = view.fields.get(b).and_then(|f| f.as_ref()) else {
            continue;
        };
        match field.kind {
            FieldKind::Bool => {
                let tint = if field.boolval { CHECK_ON } else { CHECK_OFF };
                place_rounded(world, check_bg(b), check_rect(r), tint, 4.0, true);
            }
            FieldKind::Vec { color: true, .. } => {
                widget::show_field(
                    world,
                    input(b),
                    control_rect(r, true),
                    view.focus == Some(b),
                );
                place_rounded(
                    world,
                    swatch(b),
                    swatch_rect(r),
                    parse_color(&field.initial),
                    4.0,
                    true,
                );
            }
            _ => {
                widget::show_field(
                    world,
                    input(b),
                    control_rect(r, false),
                    view.focus == Some(b),
                );
            }
        }
    }

    // Blank any pooled row chrome past this frame's row count.
    for i in n..max_rows() {
        widget::set_sprite_visible(world, row_bg(i), false);
        widget::set_label_visible(world, row_label(i), false);
    }
}

// The largest row count the panel can show: every section header plus every
// binding (an absent section's add row never exceeds its field rows).
pub(crate) fn max_rows() -> usize {
    lighting::SECTIONS.len() + lighting::binding_count()
}

// Hide every panel element, blurring the typed fields so a hidden field cannot
// keep keyboard focus.
pub(crate) fn hide_all(world: &mut World) {
    widget::hide_all(world, &all_sprite_ids(), &all_label_ids(), &all_field_ids());
}

// Every panel sprite id, in draw (insertion) order: chrome first, then the row
// backgrounds, then the floating per-binding controls above them.
pub(crate) fn all_sprite_ids() -> Vec<AssetId> {
    let mut ids = vec![PANEL_BG, CLOSE_BG, APPLY_BG];
    ids.extend((0..max_rows()).map(row_bg));
    ids.extend((0..lighting::binding_count()).map(check_bg));
    ids.extend((0..lighting::binding_count()).map(swatch));
    ids
}

pub(crate) fn all_label_ids() -> Vec<AssetId> {
    let mut ids = vec![TITLE_LABEL, CLOSE_LABEL, APPLY_LABEL, STATUS_LABEL];
    ids.extend((0..max_rows()).map(row_label));
    ids
}

pub(crate) fn all_field_ids() -> Vec<AssetId> {
    (0..lighting::binding_count()).map(input).collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::components::{Sprite, TextInput, TextLabel};

    fn injected_world() -> World {
        let mut world = World::new();
        for id in all_sprite_ids() {
            world.add_component(Sprite {
                asset_id: id,
                ..Default::default()
            });
        }
        for id in all_label_ids() {
            world.add_component(TextLabel {
                asset_id: id,
                ..Default::default()
            });
        }
        for id in all_field_ids() {
            world.add_component(TextInput {
                asset_id: id,
                ..Default::default()
            });
        }
        world
    }

    fn all_present_view<'a>(
        rows: &'a [Row],
        fields: &'a [Option<super::FormField>],
    ) -> LightingView<'a> {
        LightingView {
            rows,
            fields,
            focus: None,
            status: None,
            dirty: false,
            mouse: [0.0, 0.0],
        }
    }

    fn derived_fields() -> Vec<Option<super::FormField>> {
        lighting::SECTIONS
            .iter()
            .flat_map(|s| lighting::section_fields(s, None).into_iter().map(Some))
            .collect()
    }

    #[test]
    fn hit_test_resolves_each_control() {
        let rows = lighting::rows(&[true, true, true, true]);
        let fields = derived_fields();
        let view = all_present_view(&rows, &fields);
        let o = [40.0, 40.0];
        let s = size(rows.len());
        let a = apply_rect(o, LIGHT_W);
        assert_eq!(
            hit_test(&view, a[0] + 5.0, a[1] + 5.0, o, s),
            Some(LightingAction::Apply)
        );
        // Row 0 is the Sun header; row 1 its first (float) field.
        let r0 = row_rect(o, LIGHT_W, 0);
        assert_eq!(
            hit_test(&view, r0[0] + 5.0, r0[1] + 5.0, o, s),
            Some(LightingAction::Consume)
        );
        let r1 = row_rect(o, LIGHT_W, 1);
        assert_eq!(
            hit_test(&view, r1[0] + 5.0, r1[1] + 5.0, o, s),
            Some(LightingAction::Focus(0))
        );
        // The fog `enabled` row toggles rather than focusing.
        let fog_enabled = lighting::section_base(1);
        let i = rows
            .iter()
            .position(|r| *r == Row::Field(fog_enabled))
            .unwrap();
        let rf = row_rect(o, LIGHT_W, i);
        assert_eq!(
            hit_test(&view, rf[0] + 5.0, rf[1] + 5.0, o, s),
            Some(LightingAction::Toggle(fog_enabled))
        );
        assert_eq!(hit_test(&view, 5000.0, 5000.0, o, s), None);
    }

    #[test]
    fn hit_test_add_row_targets_the_missing_section() {
        let rows = lighting::rows(&[true, false, true, true]);
        let fields = derived_fields();
        let view = all_present_view(&rows, &fields);
        let o = [0.0, 0.0];
        let s = size(rows.len());
        let i = rows.iter().position(|r| *r == Row::Add(1)).unwrap();
        let r = row_rect(o, LIGHT_W, i);
        assert_eq!(
            hit_test(&view, r[0] + 5.0, r[1] + 5.0, o, s),
            Some(LightingAction::Add(1))
        );
    }

    #[test]
    fn apply_draws_sections_controls_and_swatch() {
        let mut world = injected_world();
        let rows = lighting::rows(&[true, true, true, true]);
        let fields = derived_fields();
        let view = all_present_view(&rows, &fields);
        let o = [20.0, 20.0];
        apply(&mut world, Some(&view), o, size(rows.len()));
        let title = world
            .query::<TextLabel>()
            .find(|l| l.asset_id == TITLE_LABEL)
            .unwrap();
        assert!(title.visible && title.content == "Lighting");
        let header = world
            .query::<TextLabel>()
            .find(|l| l.asset_id == row_label(0))
            .unwrap();
        assert_eq!(header.content, "Sun");
        // The sun colour binding shows a swatch tinted by its current value; the
        // fog toggle shows a checkbox; the intensity field shows a text input.
        let sun_color = 3;
        assert!(
            world
                .query::<Sprite>()
                .find(|s| s.asset_id == swatch(sun_color))
                .unwrap()
                .visible
        );
        let fog_enabled = lighting::section_base(1);
        assert!(
            world
                .query::<Sprite>()
                .find(|s| s.asset_id == check_bg(fog_enabled))
                .unwrap()
                .visible
        );
        assert!(
            world
                .query::<TextInput>()
                .find(|t| t.asset_id == input(4))
                .unwrap()
                .visible,
            "sun intensity input shown"
        );
        assert!(
            !world
                .query::<TextInput>()
                .find(|t| t.asset_id == input(fog_enabled))
                .unwrap()
                .visible,
            "a bool binding has no text input"
        );
        // The status line is hidden until an Apply is rejected.
        assert!(
            !world
                .query::<TextLabel>()
                .find(|l| l.asset_id == STATUS_LABEL)
                .unwrap()
                .visible
        );
    }

    #[test]
    fn absent_section_hides_its_controls_and_shows_the_add_row() {
        let mut world = injected_world();
        let rows_all = lighting::rows(&[true, true, true, true]);
        let fields_all = derived_fields();
        apply(
            &mut world,
            Some(&all_present_view(&rows_all, &fields_all)),
            [20.0, 20.0],
            size(rows_all.len()),
        );
        // Re-draw with fog absent: its controls blank, its add row appears.
        let rows = lighting::rows(&[true, false, true, true]);
        let mut fields = derived_fields();
        let base = lighting::section_base(1);
        for b in base..base + lighting::SECTIONS[1].fields.len() {
            fields[b] = None;
        }
        apply(
            &mut world,
            Some(&all_present_view(&rows, &fields)),
            [20.0, 20.0],
            size(rows.len()),
        );
        let fog_enabled = lighting::section_base(1);
        assert!(
            !world
                .query::<Sprite>()
                .find(|s| s.asset_id == check_bg(fog_enabled))
                .unwrap()
                .visible
        );
        let i = rows.iter().position(|r| *r == Row::Add(1)).unwrap();
        let add = world
            .query::<TextLabel>()
            .find(|l| l.asset_id == row_label(i))
            .unwrap();
        assert_eq!(add.content, "+ Add VolumetricFog");
    }

    #[test]
    fn hide_all_blanks_every_element() {
        let mut world = injected_world();
        let rows = lighting::rows(&[true, true, true, true]);
        let fields = derived_fields();
        apply(
            &mut world,
            Some(&all_present_view(&rows, &fields)),
            [20.0, 20.0],
            size(rows.len()),
        );
        apply(&mut world, None, [0.0, 0.0], size(0));
        assert!(world.query::<Sprite>().all(|s| !s.visible));
        assert!(world.query::<TextLabel>().all(|l| !l.visible));
        assert!(world.query::<TextInput>().all(|t| !t.visible));
    }

    #[test]
    fn parse_color_reads_rgb_and_rgba() {
        assert_eq!(parse_color("1, 0.5, 0"), [1.0, 0.5, 0.0, 1.0]);
        assert_eq!(parse_color("0 0 0 0.5"), [0.0, 0.0, 0.0, 0.5]);
        assert_eq!(parse_color("nonsense"), [1.0, 1.0, 1.0, 1.0]);
    }
}