rusting_engine 2.0.3

Vulkan 3D game engine with GPU-accelerated physics for massive physics-heavy scenes
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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
//! Inspector rows for registered components, drawn from their reflected
//! types: each field gets the widget its type and hints call for, with
//! ranges, units, and variant lists from the description.

use std::path::Path;

use bevy_ecs::prelude::World;
use egui::{ecolor, DragValue, Ui};
use serde_json::{json, Value};

use super::widgets;
use crate::assets::{read_data_file, AssetServer, TextureAsset};
use crate::editor::gui_elements::{self, TextActionProps};
use crate::reflect::{
    variant_zero, AssetKind, FieldInfo, Hints, ReflectAsset, TypeInfo,
    VariantFields, ASSET_KEY, DATA_KEY,
};
use crate::runtime::{Name, SceneId};

/// Draws a component's fields and returns true when the user changed one.
/// `value` is the component's scene form; `world` supplies the objects and
/// assets that references can pick.
pub fn edit_component(
    ui: &mut Ui,
    world: &World,
    info: &TypeInfo,
    value: &mut Value,
) -> bool {
    match (info, value) {
        (TypeInfo::Struct(info), Value::Object(map)) => {
            edit_fields(ui, world, &info.fields, map)
        }
        (info, value) => {
            edit_value(ui, world, "Value", info, &Hints::default(), value)
        }
    }
}

fn edit_fields(
    ui: &mut Ui,
    world: &World,
    fields: &[FieldInfo],
    map: &mut serde_json::Map<String, Value>,
) -> bool {
    let mut changed = false;
    for field in fields {
        let Some(value) = map.get_mut(field.name) else {
            continue;
        };
        ui.push_id(field.name, |ui| {
            if !field.hints.doc.is_empty() {
                widgets::describe_next_row(ui, field.hints.doc);
            }
            changed |= edit_value(
                ui,
                world,
                &field_label(field.name),
                &field.ty,
                &field.hints,
                value,
            );
        });
    }
    changed
}

fn edit_value(
    ui: &mut Ui,
    world: &World,
    label: &str,
    info: &TypeInfo,
    hints: &Hints,
    value: &mut Value,
) -> bool {
    match (info, value) {
        (TypeInfo::Bool, Value::Bool(value)) => {
            widgets::checkbox(ui, label, value)
        }
        (TypeInfo::Int { min, max, .. }, Value::Number(number)) => {
            let Some(mut integer) = number.as_i64() else {
                widgets::value(ui, label, &number.to_string());
                return false;
            };
            let low =
                hints.min.map_or(*min, |low| (low.ceil() as i128).max(*min));
            let high = hints
                .max
                .map_or(*max, |high| (high.floor() as i128).min(*max));
            let clamp = |bound: i128| {
                bound.clamp(i64::MIN.into(), i64::MAX.into()) as i64
            };
            // A saved value outside the hint range stays until the user
            // drags it; clamping on draw would edit the scene unasked.
            let drag = DragValue::new(&mut integer)
                .range(clamp(low)..=clamp(high))
                .clamp_existing_to_range(false);
            let changed = widgets::drag(ui, label, with_unit(drag, hints));
            if changed {
                *number = integer.into();
            }
            changed
        }
        (TypeInfo::Float, Value::Number(number)) => {
            let mut float = number.as_f64().unwrap_or_default();
            let drag = DragValue::new(&mut float)
                .speed(0.01)
                .range(
                    hints.min.unwrap_or(f64::NEG_INFINITY)
                        ..=hints.max.unwrap_or(f64::INFINITY),
                )
                .clamp_existing_to_range(false);
            let changed = widgets::drag(ui, label, with_unit(drag, hints));
            if let Some(edited) = changed
                .then(|| serde_json::Number::from_f64(float))
                .flatten()
            {
                *number = edited;
            }
            changed
        }
        (TypeInfo::Path, value @ Value::String(_))
            if hints.unit == "asset path" =>
        {
            edit_asset_path(ui, world, label, value)
        }
        (TypeInfo::String | TypeInfo::Path, Value::String(text)) => {
            widgets::text(ui, label, text)
        }
        (TypeInfo::Entity, value) => {
            let objects = scene_objects(world);
            pick(ui, label, value, &objects)
        }
        (TypeInfo::Handle(kind), value) => {
            edit_handle(ui, world, label, kind, value)
        }
        (TypeInfo::Array(item, len), Value::Array(items)) => {
            edit_array(ui, world, label, item, *len, hints, items)
        }
        (TypeInfo::List(item), Value::Array(items)) => {
            nested(ui, label, |ui| {
                let mut changed = false;
                let mut removed = None;
                for (index, value) in items.iter_mut().enumerate() {
                    ui.push_id(index, |ui| {
                        ui.horizontal(|ui| {
                            if ui
                                .small_button("−")
                                .on_hover_text("Remove")
                                .clicked()
                            {
                                removed = Some(index);
                            }
                            ui.vertical(|ui| {
                                changed |= edit_value(
                                    ui,
                                    world,
                                    &format!("[{index}]"),
                                    item,
                                    &Hints::default(),
                                    value,
                                );
                            });
                        });
                    });
                }
                if let Some(index) = removed {
                    items.remove(index);
                    changed = true;
                }
                let initial = initial_value(world, item);
                let addable = !(initial.is_null() && is_reference(item));
                if ui
                    .add_enabled(addable, egui::Button::new("+").small())
                    .on_hover_text("Add item")
                    .on_disabled_hover_text("Nothing to reference yet")
                    .clicked()
                {
                    items.push(initial);
                    changed = true;
                }
                changed
            })
        }
        (TypeInfo::Map(item), Value::Object(map)) => {
            nested(ui, label, |ui| edit_map(ui, world, item, map))
        }
        (TypeInfo::Option(inner), value) => {
            let mut present = !value.is_null();
            let mut changed = widgets::checkbox(ui, label, &mut present);
            if changed {
                *value = if present {
                    initial_value(world, inner)
                } else {
                    Value::Null
                };
                if present && value.is_null() {
                    // Nothing to reference yet: the option stays empty.
                    present = false;
                    changed = false;
                }
            }
            if present {
                ui.indent(label, |ui| {
                    changed |=
                        edit_value(ui, world, "Value", inner, hints, value);
                });
            }
            changed
        }
        (TypeInfo::Struct(info), Value::Object(map)) => {
            nested(ui, label, |ui| edit_fields(ui, world, &info.fields, map))
        }
        (TypeInfo::Enum(info), value) => {
            let current = match &*value {
                Value::String(name) => name.clone(),
                Value::Object(map) if map.len() == 1 => {
                    map.keys().next().cloned().unwrap_or_default()
                }
                other => return mismatch(ui, label, other),
            };
            let Some(variant) = info.variant(&current) else {
                return mismatch(ui, label, value);
            };
            let options: Vec<(&'static str, &str)> = info
                .variants
                .iter()
                .map(|variant| (variant.name, variant.name))
                .collect();
            let mut selected = variant.name;
            if widgets::choice(ui, label, &mut selected, &options) {
                let chosen = info.variant(selected).expect("listed variant");
                *value = variant_zero(chosen);
                return true;
            }
            let Value::Object(map) = value else {
                return false;
            };
            let Some(payload) = map.get_mut(variant.name) else {
                return false;
            };
            let mut changed = false;
            ui.indent(label, |ui| {
                changed = match (&variant.fields, payload) {
                    (VariantFields::Struct(fields), Value::Object(map)) => {
                        edit_fields(ui, world, fields, map)
                    }
                    (VariantFields::Tuple(items), payload)
                        if items.len() == 1 =>
                    {
                        edit_value(
                            ui,
                            world,
                            "Value",
                            &items[0],
                            &Hints::default(),
                            payload,
                        )
                    }
                    (VariantFields::Tuple(items), Value::Array(values)) => {
                        let mut changed = false;
                        for (index, (item, value)) in
                            items.iter().zip(values).enumerate()
                        {
                            ui.push_id(index, |ui| {
                                changed |= edit_value(
                                    ui,
                                    world,
                                    &format!("[{index}]"),
                                    item,
                                    &Hints::default(),
                                    value,
                                );
                            });
                        }
                        changed
                    }
                    (_, other) => mismatch(ui, "Value", other),
                };
            });
            changed
        }
        (_, other) => mismatch(ui, label, other),
    }
}

/// Scene objects a reference can point at, as (scene form, caption),
/// sorted by caption.
fn scene_objects(world: &World) -> Vec<(Value, String)> {
    let Some(mut query) = world.try_query::<(&SceneId, Option<&Name>)>() else {
        return Vec::new();
    };
    let mut objects: Vec<_> = query
        .iter(world)
        .map(|(id, name)| {
            let caption = name.map_or_else(
                || id.0.to_string()[..8].to_owned(),
                |name| name.0.clone(),
            );
            (Value::String(id.0.to_string()), caption)
        })
        .collect();
    objects.sort_by(|a, b| (&a.1, a.0.as_str()).cmp(&(&b.1, b.0.as_str())));
    objects
}

/// Loaded assets of `kind`, as (scene form, caption).
// ponytail: only assets something already loaded are listed; drag from the
// Assets panel or a file browser would reach the rest.
fn loaded_assets(world: &World, kind: AssetKind) -> Vec<(Value, String)> {
    world
        .get_resource::<AssetServer>()
        .map(|assets| kind.loaded_paths(assets))
        .unwrap_or_default()
        .into_iter()
        .map(|path| {
            let caption = path.display().to_string();
            (json!({ ASSET_KEY: path }), caption)
        })
        .collect()
}

/// A typed path plus a drop-down of loaded textures that fills it in.
// ponytail: every "asset path" `PathBuf` field is an image today (the
// environment map); key the list off a hint when a mesh path appears.
fn edit_asset_path(
    ui: &mut Ui,
    world: &World,
    label: &str,
    value: &mut Value,
) -> bool {
    let mut changed =
        value.as_str().map(str::to_owned).is_some_and(|mut text| {
            let edited = widgets::text(ui, label, &mut text);
            *value = Value::String(text);
            edited
        });
    let choices: Vec<(Value, String)> =
        loaded_assets(world, TextureAsset::KIND)
            .into_iter()
            .map(|(_, caption)| (Value::String(caption.clone()), caption))
            .collect();
    if !choices.is_empty() {
        changed |= pick(ui, "Loaded", value, &choices);
    }
    changed
}

/// Caption of the choice that keeps a data asset's values in the object.
const UNIQUE: &str = "Unique (saved with this object)";

/// A drop-down of loaded files. Data asset handles also offer `Unique`,
/// which keeps a private copy in the object, like Godot's Make Unique, and
/// edit that copy's fields right here.
fn edit_handle(
    ui: &mut Ui,
    world: &World,
    label: &str,
    kind: &AssetKind,
    value: &mut Value,
) -> bool {
    let mut choices = loaded_assets(world, *kind);
    let Some(embedded) = kind.embedded else {
        return pick(ui, label, value, &choices);
    };
    // Switching a file reference to Unique starts from the file's values.
    let unique = if value.get(DATA_KEY).is_some() {
        value.clone()
    } else {
        let file = value
            .get(ASSET_KEY)
            .and_then(Value::as_str)
            .and_then(|path| read_data_file(Path::new(path)).ok());
        json!({ DATA_KEY: file.map_or_else(embedded.default, |(_, data)| data) })
    };
    choices.push((unique, UNIQUE.to_owned()));
    let mut changed = pick(ui, label, value, &choices);
    if let Some(data) = value.get_mut(DATA_KEY) {
        ui.indent(label, |ui| {
            changed |= edit_component(ui, world, &(embedded.info)(), data);
        });
    }
    changed
}

/// The value a new list item or a switched-on option starts with: the
/// first object or asset for references, or the type's zero value.
fn initial_value(world: &World, info: &TypeInfo) -> Value {
    let first = |choices: Vec<(Value, String)>| {
        choices
            .into_iter()
            .next()
            .map_or(Value::Null, |(value, _)| value)
    };
    match info {
        TypeInfo::Entity => first(scene_objects(world)),
        TypeInfo::Handle(kind) => {
            match (loaded_assets(world, *kind), kind.embedded) {
                (assets, Some(embedded)) if assets.is_empty() => {
                    json!({ DATA_KEY: (embedded.default)() })
                }
                (assets, _) => first(assets),
            }
        }
        other => other.zero_value(),
    }
}

/// A drop-down over `choices`. It commits only on selection, so a
/// reference never holds a half-typed ID or path.
fn pick(
    ui: &mut Ui,
    label: &str,
    value: &mut Value,
    choices: &[(Value, String)],
) -> bool {
    const CURRENT: usize = usize::MAX;
    let mut options: Vec<(usize, &str)> = choices
        .iter()
        .enumerate()
        .map(|(index, (_, caption))| (index, caption.as_str()))
        .collect();
    let mut selected = choices
        .iter()
        .position(|(choice, _)| choice == value)
        .unwrap_or(CURRENT);
    let current = match &*value {
        Value::Null => "None".to_owned(),
        Value::String(text) => format!("{text} (missing)"),
        other if other.get(DATA_KEY).is_some() => UNIQUE.to_owned(),
        other => other.get(ASSET_KEY).and_then(Value::as_str).map_or_else(
            || other.to_string(),
            |path| format!("{path} (missing)"),
        ),
    };
    if selected == CURRENT {
        options.push((CURRENT, &current));
    }
    if widgets::choice(ui, label, &mut selected, &options)
        && selected != CURRENT
    {
        *value = choices[selected].0.clone();
        return true;
    }
    false
}

fn edit_array(
    ui: &mut Ui,
    world: &World,
    label: &str,
    item: &TypeInfo,
    len: usize,
    hints: &Hints,
    items: &mut Vec<Value>,
) -> bool {
    let floats = |items: &[Value]| -> Option<Vec<f64>> {
        items.iter().map(Value::as_f64).collect()
    };
    // egui's color buttons edit linear values; sRGB fields convert around
    // them. Alpha is linear either way.
    let srgb = hints.unit.starts_with("sRGB");
    let to_linear = |channel: f64| {
        let channel = channel as f32;
        if srgb {
            ecolor::linear_from_gamma(channel)
        } else {
            channel
        }
    };
    let from_linear = |channel: f32| {
        f64::from(if srgb {
            ecolor::gamma_from_linear(channel)
        } else {
            channel
        })
    };
    match (item, len, floats(items)) {
        (TypeInfo::Float, 3, Some(values)) if hints.color => {
            let mut rgb = [0, 1, 2].map(|index| to_linear(values[index]));
            let changed = widgets::color(ui, label, &mut rgb);
            if changed {
                *items = rgb
                    .iter()
                    .map(|&channel| from_linear(channel).into())
                    .collect();
            }
            changed
        }
        (TypeInfo::Float, 4, Some(values)) if hints.color => {
            let mut rgba = [
                to_linear(values[0]),
                to_linear(values[1]),
                to_linear(values[2]),
                values[3] as f32,
            ];
            let changed = widgets::color4(ui, label, &mut rgba);
            if changed {
                *items = vec![
                    from_linear(rgba[0]).into(),
                    from_linear(rgba[1]).into(),
                    from_linear(rgba[2]).into(),
                    f64::from(rgba[3]).into(),
                ];
            }
            changed
        }
        (TypeInfo::Float, 3, Some(values)) => {
            let mut values = [values[0], values[1], values[2]];
            let changed = widgets::vec3(ui, label, &mut values, 0.01);
            if changed {
                *items = values.iter().map(|&value| value.into()).collect();
            }
            changed
        }
        (TypeInfo::Int { .. }, 3, _) if items.iter().all(Value::is_i64) => {
            let mut values = [0, 1, 2]
                .map(|index| items[index].as_i64().unwrap_or_default());
            let changed = widgets::vec3(ui, label, &mut values, 1.0);
            if changed {
                *items = values.iter().map(|&value| value.into()).collect();
            }
            changed
        }
        _ => nested(ui, label, |ui| {
            let mut changed = false;
            for (index, value) in items.iter_mut().enumerate() {
                ui.push_id(index, |ui| {
                    changed |= edit_value(
                        ui,
                        world,
                        &format!("[{index}]"),
                        item,
                        &Hints::default(),
                        value,
                    );
                });
            }
            changed
        }),
    }
}

/// String-keyed map entries with remove buttons, and a key field that adds
/// an entry.
// ponytail: renaming a key is remove and add; add an inline key editor if
// maps with large values need it.
fn edit_map(
    ui: &mut Ui,
    world: &World,
    item: &TypeInfo,
    map: &mut serde_json::Map<String, Value>,
) -> bool {
    let mut changed = false;
    let mut removed = None;
    for (key, value) in map.iter_mut() {
        ui.push_id(key.as_str(), |ui| {
            ui.horizontal(|ui| {
                if ui.small_button("−").on_hover_text("Remove").clicked() {
                    removed = Some(key.clone());
                }
                ui.vertical(|ui| {
                    changed |= edit_value(
                        ui,
                        world,
                        key,
                        item,
                        &Hints::default(),
                        value,
                    );
                });
            });
        });
    }
    if let Some(key) = removed {
        map.remove(&key);
        changed = true;
    }
    let draft_id = ui.id().with("new_map_key");
    let mut draft: String =
        ui.data_mut(|data| data.get_temp(draft_id).unwrap_or_default());
    let add = gui_elements::text_action(
        ui,
        &mut draft,
        TextActionProps {
            tooltip: Some("Add an entry with this key"),
            ..TextActionProps::new("Add")
        },
    );
    let key = draft.trim().to_owned();
    if add.clicked() && !key.is_empty() && !map.contains_key(&key) {
        let initial = initial_value(world, item);
        if !(initial.is_null() && is_reference(item)) {
            map.insert(key, initial);
            draft.clear();
            changed = true;
        }
    }
    ui.data_mut(|data| data.insert_temp(draft_id, draft));
    changed
}

/// References start empty, so a list or map cannot add one when there is
/// nothing to point at yet.
fn is_reference(item: &TypeInfo) -> bool {
    matches!(item, TypeInfo::Entity | TypeInfo::Handle(_))
}

fn with_unit<'a>(drag: DragValue<'a>, hints: &Hints) -> DragValue<'a> {
    // Long units ("logical pixels") do not fit the field; the schema has them.
    if hints.unit.is_empty() || hints.unit.chars().count() > 5 {
        drag
    } else {
        drag.suffix(format!(" {}", hints.unit))
    }
}

/// A value that does not have its type's shape, shown read-only.
fn mismatch(ui: &mut Ui, label: &str, value: &Value) -> bool {
    widgets::value(ui, label, &value.to_string());
    false
}

fn nested(
    ui: &mut Ui,
    label: &str,
    body: impl FnOnce(&mut Ui) -> bool,
) -> bool {
    let doc = widgets::take_row_doc(ui);
    let section = egui::CollapsingHeader::new(label)
        .id_salt(ui.id().with(label))
        .default_open(true)
        .show(ui, body);
    if let Some(doc) = doc {
        section.header_response.on_hover_text(doc);
    }
    section.body_returned.unwrap_or(false)
}

/// `move_speed` -> `Move Speed`, matching Godot's property captions.
fn field_label(name: &str) -> String {
    name.split('_')
        .filter(|word| !word.is_empty())
        .map(|word| {
            let mut chars = word.chars();
            chars.next().map_or_else(String::new, |first| {
                first.to_uppercase().chain(chars).collect()
            })
        })
        .collect::<Vec<_>>()
        .join(" ")
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;
    use std::path::PathBuf;

    use bevy_ecs::entity::Entity;
    use serde_json::json;

    use super::*;
    use crate::assets::{Handle, TextureAsset};
    use crate::reflect::Reflect;

    #[allow(dead_code)]
    enum Shape {
        Point,
        Circle { radius: f32 },
        Named(String),
    }

    #[allow(dead_code)]
    struct Everything {
        speed: f32,
        lives: u8,
        alive: bool,
        tag: String,
        file: PathBuf,
        spawn: [f32; 3],
        cells: [i32; 3],
        tint: [f32; 4],
        waypoints: Vec<[f32; 2]>,
        stats: BTreeMap<String, i32>,
        target: Option<Entity>,
        texture: Option<Handle<TextureAsset>>,
        shape: Shape,
        other: Shape,
    }

    crate::reflect! {
        enum Shape { Point, Circle { radius: f32 { min: 0.0 } }, Named(String) }
    }

    crate::reflect! {
        struct Everything {
            speed: f32 { unit: "m/s", min: 0.0 },
            lives: u8,
            alive: bool,
            tag: String,
            file: PathBuf,
            spawn: [f32; 3],
            cells: [i32; 3],
            tint: [f32; 4] { color: true },
            waypoints: Vec<[f32; 2]>,
            stats: BTreeMap<String, i32>,
            target: Option<Entity>,
            texture: Option<Handle<TextureAsset>>,
            shape: Shape,
            other: Shape,
        }
    }

    #[test]
    fn references_start_at_the_first_object_or_stay_empty() {
        let mut world = World::new();
        assert_eq!(initial_value(&world, &TypeInfo::Entity), Value::Null);
        let id = uuid::Uuid::new_v4();
        // Captions sort, so "Alarm" comes first whatever the spawn order.
        world.spawn((SceneId(uuid::Uuid::new_v4()), Name("Switch".into())));
        world.spawn((SceneId(id), Name("Alarm".into())));
        assert_eq!(
            initial_value(&world, &TypeInfo::Entity),
            Value::String(id.to_string())
        );
        assert_eq!(
            initial_value(&world, &Handle::<TextureAsset>::type_info()),
            Value::Null
        );
        assert_eq!(initial_value(&world, &TypeInfo::Float), json!(0.0));
    }

    #[test]
    fn a_described_section_shows_its_doc_on_the_header() {
        let context = egui::Context::default();
        context.style_mut(|style| style.interaction.tooltip_delay = 0.0);
        let mut texts = Vec::new();
        for frame in 0..4 {
            let input = egui::RawInput {
                events: vec![egui::Event::PointerMoved(egui::pos2(40.0, 16.0))],
                time: Some(f64::from(frame)),
                ..Default::default()
            };
            let output = context.run(input, |context| {
                egui::CentralPanel::default().show(context, |ui| {
                    widgets::describe_next_row(ui, "Where the wave starts");
                    nested(ui, "Spawn", |ui| {
                        ui.label("Radius");
                        false
                    });
                });
            });
            texts = output
                .shapes
                .iter()
                .filter_map(|clipped| match &clipped.shape {
                    egui::Shape::Text(text) => {
                        Some(text.galley.text().to_owned())
                    }
                    _ => None,
                })
                .collect();
        }
        assert!(
            texts.iter().any(|text| text == "Where the wave starts"),
            "{texts:?}"
        );
    }

    #[test]
    fn field_names_become_captions() {
        assert_eq!(field_label("move_speed"), "Move Speed");
        assert_eq!(field_label("hp"), "Hp");
    }

    #[test]
    fn drawing_without_input_leaves_the_value_unchanged() {
        // Speed is below its hint minimum: drawing must not clamp it.
        let original = json!({
            "speed": -2.5,
            "lives": 3,
            "alive": true,
            "tag": "player",
            "file": "levels/one.json",
            "spawn": [0.0, 1.0, 2.0],
            "cells": [1, 2, 3],
            "tint": [1.0, 0.5, 0.25, 1.0],
            "waypoints": [[0.0, 1.0], [2.0, 3.0]],
            "stats": {"armor": 4},
            "target": "5a3f0c1e-7a2b-4c1d-9e8f-0123456789ab",
            "texture": {"$asset": "textures/crate.png"},
            "shape": {"Circle": {"radius": 1.5}},
            "other": "Point",
            "$version": 2
        });
        let mut value = original.clone();
        let context = egui::Context::default();
        let mut changed = true;
        let _ = context.run(egui::RawInput::default(), |context| {
            egui::CentralPanel::default().show(context, |ui| {
                changed = edit_component(
                    ui,
                    &World::new(),
                    &Everything::type_info(),
                    &mut value,
                );
            });
        });
        assert!(!changed);
        assert_eq!(value, original);
    }

    /// Draws `map` as an `i32` map with `draft` typed in the new-key field,
    /// clicking at `click`; returns whether it changed and each text's
    /// center.
    fn draw_map(
        context: &egui::Context,
        map: &mut serde_json::Map<String, Value>,
        draft: &str,
        click: Option<egui::Pos2>,
    ) -> (bool, Vec<(String, egui::Pos2)>) {
        let mut changed = false;
        let mut events = Vec::new();
        if let Some(pos) = click {
            events.push(egui::Event::PointerMoved(pos));
            for pressed in [true, false] {
                events.push(egui::Event::PointerButton {
                    pos,
                    button: egui::PointerButton::Primary,
                    pressed,
                    modifiers: egui::Modifiers::default(),
                });
            }
        }
        let output = context.run(
            egui::RawInput {
                events,
                ..Default::default()
            },
            |context| {
                egui::CentralPanel::default().show(context, |ui| {
                    let id = ui.id().with("new_map_key");
                    ui.data_mut(|data| {
                        data.insert_temp(id, draft.to_owned());
                    });
                    let item = i32::type_info();
                    changed = edit_map(ui, &World::new(), &item, map);
                });
            },
        );
        let texts = output
            .shapes
            .iter()
            .filter_map(|clipped| match &clipped.shape {
                egui::Shape::Text(text) => Some((
                    text.galley.text().to_owned(),
                    text.pos + text.galley.rect.center().to_vec2(),
                )),
                _ => None,
            })
            .collect();
        (changed, texts)
    }

    #[test]
    fn map_entries_can_be_added_by_key_and_removed() {
        let context = egui::Context::default();
        let mut map = json!({"#": 1}).as_object().unwrap().clone();
        let (_, texts) = draw_map(&context, &mut map, "*", None);
        let at = |label: &str| {
            texts
                .iter()
                .find(|(text, _)| text == label)
                .map(|(_, pos)| *pos)
                .unwrap_or_else(|| panic!("no {label:?} in {texts:?}"))
        };
        let (add, remove) = (at("Add"), at("−"));

        // An empty or existing key adds nothing.
        assert!(!draw_map(&context, &mut map, " ", Some(add)).0);
        assert!(!draw_map(&context, &mut map, "#", Some(add)).0);
        assert_eq!(map.len(), 1);

        assert!(draw_map(&context, &mut map, " * ", Some(add)).0);
        assert_eq!(map.get("*"), Some(&json!(0)));

        // "#" sorts before "*", so the first remove button is its row.
        assert!(draw_map(&context, &mut map, "", Some(remove)).0);
        assert_eq!(map.keys().collect::<Vec<_>>(), ["*"]);
    }
}