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
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
//! Machine-readable catalog of CLI operations, scene sections, and scene
//! components, printed by `rusting schema`.
//!
//! Defaults are not written by hand: they are the scene form of each
//! component's `Default`, read back through the same code that saves scenes.
//! Tests check that every documented field exists, every saved field is
//! documented, and every example loads through the scene parser and the
//! component registry.

use serde_json::{json, Map, Value};
use uuid::Uuid;

use crate::reflect::{EnumInfo, Hints, TypeInfo, TypeRegistry, VariantFields};
use crate::runtime::{
    add_registered_component, registered_component_names,
    registered_component_values, scene_document, Camera, Collider,
    CollisionLayers, DirectionalLight, GpuPhysicsWatch, Name, PhysicsBody,
    PhysicsSyncMode, PointLight, RigidBody, SceneComponentRegistry, SceneId,
    SpotLight, SCENE_FORMAT_VERSION,
};
use crate::{App, AssetPlugin, Transform};

/// Version of the catalog layout. Raise it when a key changes meaning.
/// Version 2 derives component fields from reflection, with `*` for map
/// keys, and adds `resources` and `asset_types`.
pub const SCHEMA_CATALOG_VERSION: u32 = 2;

/// One `rusting` command.
pub struct Operation {
    /// Words that select the command, as `rusting --help <topic>` takes them.
    pub name: &'static str,
    /// Arguments after `rusting`.
    pub usage: &'static str,
    pub summary: &'static str,
    /// Whether the command needs Vulkan, and what it reads back.
    pub gpu: &'static str,
    /// Flag defaults as `(flag, value)`.
    pub defaults: &'static [(&'static str, &'static str)],
    /// Arguments after `rusting`; relative paths name a project `my_game`
    /// in the current folder.
    pub example: &'static str,
}

const NO_GPU: &str = "none";

/// Operations that change nothing on disk; every other one is marked
/// mutating for tool clients (`rusting mcp`).
pub const READ_ONLY: &[&str] = &[
    "doctor",
    "project inspect",
    "scene inspect",
    "scene map",
    "scene query",
    "validate",
    "check",
    "inspect",
    "determinism",
    "asset list",
    "diff",
    "preset list",
    "effect list",
    "docs",
    "explain",
    "schema",
];

/// Operations that write project files (scenes, assets, sources, the
/// manifest). Build outputs and captures do not count.
pub const WRITES_PROJECT: &[&str] = &[
    "new",
    "scene patch",
    "fix",
    "asset import",
    "asset reimport",
    "asset generate",
    "add scenario",
    "add system",
    "preset apply",
    "effect apply",
    "cook",
];

/// What a finished command changed: `disk` for project files, `editor` and
/// `game` for a live editor buffer or running game. A command line tool
/// never writes either of those itself: an open editor picks up a disk
/// change on its next scene poll, and `rusting debug` reports `game`.
pub fn touched(args: &[String], ok: bool) -> serde_json::Value {
    let words: Vec<&str> = args
        .iter()
        .map(String::as_str)
        .filter(|arg| !arg.starts_with("--"))
        .collect();
    let dry_run = args.iter().any(|arg| arg == "--dry-run");
    let writes = WRITES_PROJECT.iter().any(|name| {
        let name: Vec<&str> = name.split(' ').collect();
        words.starts_with(&name)
    });
    serde_json::json!({"disk": ok && writes && !dry_run, "editor": false, "game": false})
}

pub const OPERATIONS: &[Operation] = &[
    Operation {
        name: "doctor",
        usage: "doctor [--probe] [--json]",
        summary: "Report engine, platform, build tools, and Vulkan device capability. No GPU is a valid result. --probe also opens the device a run would pick, runs a tiny GPU job on it and reports probe.selected_device, or probe.ok false with the error (15 s limit).",
        gpu: "optional: lists devices when a driver is present",
        defaults: &[],
        example: "doctor --json",
    },
    Operation {
        name: "new",
        usage: "new <parent-directory> <project-name> [--template 3d|first-person|third-person|sandbox|2d|starter] [--json]",
        summary: "Create a project from a template: 3d is the editor's lit cube; first-person and third-person a walkable room with a player controller; sandbox a pile of dynamic bodies that fall and settle; 2d a playable side-view level; starter the complete Coin Run game (collect five coins, then touch the flag). The parent must exist and the project folder must not.",
        gpu: NO_GPU,
        defaults: &[("--template", "3d")],
        example: "new . my_game --json",
    },
    Operation {
        name: "project inspect",
        usage: "project inspect [project-root] [--limit N] [--fields a,b] [--summary] [--json]",
        summary: "Inspect and validate project.json, Cargo.toml, the main scene path, and src/main.rs.",
        gpu: NO_GPU,
        defaults: &[("project-root", "the current folder")],
        example: "project inspect my_game --json",
    },
    Operation {
        name: "scene inspect",
        usage: "scene inspect <scene-path> [--limit N] [--fields a,b] [--summary] [--json]",
        summary: "Inspect a migrated scene: entities, cameras, classes, assets, and reference warnings.",
        gpu: NO_GPU,
        defaults: &[],
        example: "scene inspect my_game/scenes/main.rscene --json",
    },
    Operation {
        name: "scene map",
        usage: "scene map <scene-path> [--limit N] [--fields a,b] [--summary] [--json]",
        summary: "Draw every tile map as rows of characters with a legend. Entities that sit over a map's cells appear as letters, with their name, ID, column and row. A text view of a 2D layout for a model without vision.",
        gpu: NO_GPU,
        defaults: &[],
        example: "scene map my_game/scenes/main.rscene --json",
    },
    Operation {
        name: "scene query",
        usage: "scene query <scene-path> [--id ID | --name NAME | --class CLASS | --component COMPONENT] [--limit N] [--fields a,b] [--summary] [--json]",
        summary: "Find entities by one filter. Results are ordered by persistent UUID and include full component data.",
        gpu: NO_GPU,
        defaults: &[("filter", "all entities")],
        example: "scene query my_game/scenes/main.rscene --name Cube --json",
    },
    Operation {
        name: "scene patch",
        usage: "scene patch <scene-path> <patch.json> [--dry-run] [--json]",
        summary: "Apply a patch batch atomically: every operation succeeds and the scene validates, or nothing is written. Reports the revision and a per-field diff. expected_revision and per-field expected values report SCENE_CONFLICT instead of overwriting newer edits.",
        gpu: NO_GPU,
        defaults: &[("dry-run", "false")],
        example: "scene patch my_game/scenes/main.rscene patch.json --dry-run --json",
    },
    Operation {
        name: "scene add-model",
        usage: "scene add-model <scene-path> <model.glb|gltf> [--name NAME] [--dry-run] [--json]",
        summary: "Place a glTF or GLB model in a scene as one object (named after the file, or NAME) with a child per node and primitive, keeping its materials and textures. Import the model under assets/ first with `asset import`; move the object with a patch afterwards.",
        gpu: NO_GPU,
        defaults: &[("dry-run", "false")],
        example: "scene add-model my_game/scenes/main.rscene my_game/assets/models/tree.glb --name Tree --json",
    },
    Operation {
        name: "scene retarget",
        usage: "scene retarget <scene-path> <from-object> <clip> <to-object> [--dry-run] [--json]",
        summary: "Copy a clip from one character's skeleton to another's and save it on the target's rusting.animation (replacing a clip of the same name). Bones pair up by the objects' `humanoid` maps, or by bone name with rig prefixes such as mixamorig: dropped. Rotations keep their turn from the source's rest pose; only the hips keep position keys, scaled by hip height. Rest poses are the scene's transforms.",
        gpu: NO_GPU,
        defaults: &[("dry-run", "false")],
        example: "scene retarget my_game/scenes/main.rscene Mixamo walk Knight --dry-run --json",
    },
    Operation {
        name: "validate",
        usage: "validate [project-root] [--json]",
        summary: "Check project files, scene structure, referenced assets, and that every physics solver and custom shader in the main scene supports project.json `determinism` (Off | Local | CrossPlatform), without Vulkan or a window.",
        gpu: NO_GPU,
        defaults: &[("project-root", "the current folder")],
        example: "validate my_game --json",
    },
    Operation {
        name: "cook",
        usage: "cook [project-root] [--json]",
        summary: "Validate and cook the manifest's main scene to its configured cooked_scene path.",
        gpu: NO_GPU,
        defaults: &[("project-root", "the current folder")],
        example: "cook my_game --json",
    },
    Operation {
        name: "fix",
        usage: "fix [project-root] [--dry-run] [--json]",
        summary: "Apply every certain fix `validate` finds to the main scene: a misspelled key is renamed in place, so nothing else in the file changes. --dry-run lists the fixes without writing. Problems without a certain fix stay as diagnostics.",
        gpu: NO_GPU,
        defaults: &[("project-root", "the current folder")],
        example: "fix my_game --dry-run --json",
    },
    Operation {
        name: "check",
        usage: "check [project-root] [--json]",
        summary: "Validate the project, then compile its Rust code with a debug `cargo build`, the same build `run` and `test` reuse. The first build of a new project compiles the engine and takes minutes; later ones take seconds.",
        gpu: NO_GPU,
        defaults: &[("project-root", "the current folder")],
        example: "check my_game --json",
    },
    Operation {
        name: "run",
        usage: "run [project-root] [--release] [--ticks N] [--timeout SECONDS] [--record FILE | --replay FILE] [--json]",
        summary: "Cook, build, and run the game from the project folder. --ticks N runs N fixed ticks without a window, saves the end state to build/final.rscene for `scene query`, and exits. --timeout stops a game still running; reaching it is not a failure. --record FILE saves the windowed session's input, frame times and per-tick state hashes to FILE when the window closes; --replay FILE plays such a file back without a window and fails at the first tick whose state differs, so a recorded run is a regression test.",
        gpu: "required for a window; none with --ticks",
        defaults: &[("--release", "off (debug build)"), ("--ticks", "off (opens a window)"), ("--timeout", "none"), ("project-root", "the current folder")],
        example: "run my_game --ticks 120 --json",
    },
    Operation {
        name: "test",
        usage: "test [project-root] [scenario.json | folder] [--release] [--timeout SECONDS] [--update-golden] [--json]",
        summary: "Cook and build the game, then run a scenario file in it without a window: named actions at fixed ticks, checks on reflected scene state and events, and optional captures. Given a folder, runs every .json in it in name order and lists each result under `scenarios`; with neither argument, runs tests/. Fails with SCENARIO_FAILED and the first failing tick and step. --update-golden rewrites capture `golden` images instead of comparing them. The scenario format is under `scenario` in `rusting schema`.",
        gpu: "optional: only capture, expect_pixels and render-budget runs render; captures are skipped without Vulkan; one frame readback per capture or pixel check",
        defaults: &[("--release", "off (debug build)"), ("--timeout", "none"), ("project-root", "the current folder"), ("scenario", "every file in tests/")],
        example: "test my_game my_game/tests/falls.json --json",
    },
    Operation {
        name: "debug",
        usage: "debug [project-root]",
        summary: "Cook and build the game, then run it without a window as a debug session: the game's standard input and output carry one JSON request and one JSON reply per line. The game is paused between commands. Commands: `{\"cmd\": \"step\", \"ticks\": N}` (the only way time passes), `get` (`entity`, `path`), `set` (`entity`, `path`, `value`), `press` / `release` (`action`), `capture` (`path`, optional `size` [w, h]; needs Vulkan), `tick`, `quit`. A reply is `{\"id\", \"ok\", \"tick\", \"result\" or \"error\"}`. Build failures go to standard error as the usual result envelope.",
        gpu: "capture needs Vulkan; every other command does not",
        defaults: &[("project-root", "the current folder")],
        example: "debug my_game",
    },
    Operation {
        name: "serve",
        usage: "serve",
        summary: "Run as a local daemon: read one JSON-RPC 2.0 request per line from stdin and write one response per line to stdout, until `shutdown` or end of input. `method` is the command words (`scene query`), `params` the remaining arguments as an array of strings (or `{\"args\": [...]}`), and `result` the same envelope as `--json`. Every command is available except `serve`. Errors use the JSON-RPC codes -32700 (parse), -32600 (invalid request), -32601 (unknown method), -32602 (bad params) and -32603 (the operation panicked). Each request runs in the daemon process, so it costs no process start; builds, shaders and loaded scenes are not cached between requests yet.",
        gpu: NO_GPU,
        defaults: &[],
        example: "serve",
    },
    Operation {
        name: "mcp",
        usage: "mcp [root]",
        summary: "Run as a Model Context Protocol server over stdio (newline-delimited JSON-RPC), scoped to the project `root` (default: the current folder). Every command except `serve`, `debug` and `mcp` is a tool named with underscores (`scene_query`) taking `{\"args\": [...]}`, the arguments after the command words. Tools that change nothing carry `readOnlyHint: true`; the rest are mutating. A result is the `--json` envelope as text, with `isError` set when `ok` is false, so it matches the CLI. Arguments with an absolute path or `..` are refused.",
        gpu: NO_GPU,
        defaults: &[],
        example: "mcp my_game",
    },
    Operation {
        name: "inspect",
        usage: "inspect [project-root] --tick N [--entity NAME]... [--limit N] [--fields a,b] [--summary] [--json]",
        summary: "Cook and build the game, run it without a window to tick N, and report the scene form of each named entity after that tick's update: transform, components and counters. With no `--entity`, reports every named entity of the main scene. Entities that do not exist at that tick are null.",
        gpu: NO_GPU,
        defaults: &[("project-root", "the current folder"), ("--entity", "every named entity")],
        example: "inspect my_game --tick 120 --entity Player --json",
    },
    Operation {
        name: "determinism",
        usage: "determinism [project-root] [--ticks N | --scenario scenario.json | --gpu scenario.json] [--json]",
        summary: "Build the game in debug and release, run each headless for N ticks (release also pinned to one CPU when `taskset` exists), and compare every tick's world-state hash. Fails with DETERMINISM_DIVERGED naming the first divergent tick and entity. Hash reports go to build/determinism/<configuration>-<ticks>.json. With --scenario, it replays a scenario (its scripted input) in a debug and then a release build and compares the CPU world-state hash of every tick, and the GPU body hash of every tick both runs delivered (DETERMINISM_DIVERGED names the tick and data.divergence.state says CPU or GPU). GPU physics bodies do not simulate headless; for them use --gpu, which is --scenario that also fails with DETERMINISM_NO_GPU_STATE when the scenario hashed no GPU bodies (set \"gpu\": true in it). A failing expect step in the scenario does not stop the comparison; data.scenario_passed reports it. It catches order-dependent GPU code, not vendor differences.",
        gpu: NO_GPU,
        defaults: &[("--ticks", "600"), ("project-root", "the current folder")],
        example: "determinism my_game --ticks 300 --json",
    },
    Operation {
        name: "export",
        usage: "export <project-root> <parent-directory> [--target TRIPLE] [--json]",
        summary: "Cook, build a release, and package the game into a new folder under the parent. A native export is verified by running a copy for 60 headless ticks from a fresh temporary folder.",
        gpu: NO_GPU,
        defaults: &[("--target", "host")],
        example: "export my_game exports --json",
    },
    Operation {
        name: "capture",
        usage: "capture <scene-path> <output.png> [--camera ID|NAME] [--tick N] [--size WxH] [--pick X,Y]... [--pick-rect X,Y,W,H]... [--no-hud] [--json]",
        summary: "Render one camera of a scene offscreen to a PNG after N fixed ticks. --no-hud leaves the HUD out. Each --pick maps a pixel to the persistent ID of the object under it. Each --pick-rect lists every object covering a rectangle with its share of the rectangle (sampled, at most 64x64 points). Game code is not run. Without Vulkan, camera data and picks are still reported with a VULKAN_UNAVAILABLE error.",
        gpu: "required for the PNG: renders every tick through N and reads back one frame (width x height x 4 bytes)",
        defaults: &[("--camera", "the scene's active camera"), ("--tick", "0"), ("--size", "1280x720")],
        example: "capture my_game/scenes/main.rscene shot.png --tick 60 --pick 640,360 --json",
    },
    Operation {
        name: "asset import",
        usage: "asset import <project-root> <source-file> [--to FOLDER] [--author A] [--license L] [--url U] [--generator G] [--notes N] [--max-size PIXELS] [--dry-run] [--json]",
        summary: "Copy a png, jpeg, bmp, tga, gltf, glb, wav or ogg file (and a glTF's external buffers and images) into assets/FOLDER after loading it as the runtime would, and write <file>.rmeta with a new stable ID, settings, dependencies, content hash, and source/license provenance. Scenes reference it by the returned `reference` path (relative to the scene); sound clips (`rusting.sound_cue.clip`, `play_sound`) are relative to assets/ instead, e.g. `sounds/hit.wav`. Warns when no license is given. --dry-run runs every check on a staged copy and writes nothing (`dry_run: true` in the report).",
        gpu: NO_GPU,
        defaults: &[("--to", "assets/ itself"), ("--max-size", "none (images keep their size)")],
        example: "asset import my_game art/crate.png --to props --license CC0-1.0 --json",
    },
    Operation {
        name: "asset reimport",
        usage: "asset reimport <project-root> <asset-id-or-path> [--from FILE] [--author A] [--license L] [--url U] [--generator G] [--notes N] [--max-size PIXELS] [--dry-run] [--json]",
        summary: "Replace an imported asset and keep its ID: from --from, else the recorded original file if it still exists, else revalidate the asset in place. Given provenance flags and settings replace the recorded ones. Reports the scenes that use it; a running game or editor hot-reloads the file. --dry-run previews the replacement without writing.",
        gpu: NO_GPU,
        defaults: &[("--from", "the recorded original, else the asset itself")],
        example: "asset reimport my_game assets/props/crate.png --from art/crate_v2.png --json",
    },
    Operation {
        name: "asset generate",
        usage: "asset generate <project-root> <hook> <prompt> [--to FOLDER | --replace ASSET-ID-OR-PATH] [--dry-run] [--json]",
        summary: "Run the optional generator hook `generators.<hook>` from project.json ({\"command\": [program, args...], \"license\": L, \"settings\": {\"max_size\": N}}) with RUSTING_PROMPT and an empty RUSTING_OUTPUT_DIR. The hook writes a file there and prints a last line of JSON {\"file\": NAME, \"license\"?, \"author\"?, \"url\"?, \"generator\"?, \"notes\"?}. The file then goes through `asset import` (or `asset reimport` with --replace), so type, size, dependencies, and metadata are checked the same way; output without a license from the hook or its config is rejected. Projects work without any hook.",
        gpu: NO_GPU,
        defaults: &[("--to", "assets/ itself"), ("--replace", "none (imports a new asset)")],
        example: "asset generate my_game icons red_crate --to props --dry-run --json",
    },
    Operation {
        name: "asset list",
        usage: "asset list [project-root] [--limit N] [--fields a,b] [--summary] [--json]",
        summary: "List imported assets with ID, dependencies, provenance, settings, and referencing scenes. Fails on missing files or dependencies, invalid or duplicate metadata; warns on files changed since import, files without .rmeta, and assets without a license.",
        gpu: NO_GPU,
        defaults: &[("project-root", "the current folder")],
        example: "asset list my_game --json",
    },
    Operation {
        name: "add scenario",
        usage: "add scenario [project-root] <name> [--json]",
        summary: "Write tests/<name>.json with a check that fails until you name a real entity and value. Red scenario first, then make it pass.",
        gpu: NO_GPU,
        defaults: &[("project-root", "the current folder")],
        example: "add scenario my_game door_opens --json",
    },
    Operation {
        name: "add system",
        usage: "add system [project-root] <name> [--json]",
        summary: "Append a documented stub `fn <name>(_scene, _time)` to src/main.rs and write a failing scenario <name>.json. Call the function from `update`, replace the `todo!`, then make the scenario pass.",
        gpu: NO_GPU,
        defaults: &[("project-root", "the current folder")],
        example: "add system my_game spin_coins --json",
    },
    Operation {
        name: "diff",
        usage: "diff <scene-a> <scene-b> [--limit N] [--fields a,b] [--summary] [--json]",
        summary: "Compare two scene files by entity ID: entities added, removed and changed, with the JSON path, old value and new value of every changed field, plus changes to scene-level fields.",
        gpu: NO_GPU,
        defaults: &[],
        example: "diff old.rscene my_game/scenes/main.rscene --json",
    },
    Operation {
        name: "preset list",
        usage: "preset list [--limit N] [--fields a,b] [--summary] [--json]",
        summary: "List the starter art-direction presets and every value each one writes.",
        gpu: NO_GPU,
        defaults: &[],
        example: "preset list --json",
    },
    Operation {
        name: "preset apply",
        usage: "preset apply <scene-path> <preset> [--only lighting,camera,text] [--dry-run] [--json]",
        summary: "Apply an art-direction preset as one scene patch: sun, ambient and sky light, tone mapping, background color (scope `lighting`), perspective camera field of view (`camera`), and HUD text size and color (`text`). `--only` limits it to the named scopes; the result lists every changed field in `patch.changes`, so `--dry-run` previews them. Creates a Sun entity when the scene has no directional light. The values stay ordinary, editable scene data; reapplying edits the same entities.",
        gpu: NO_GPU,
        defaults: &[("--dry-run", "false"), ("--only", "every scope")],
        example: "preset apply my_game/scenes/main.rscene night --only lighting --dry-run --json",
    },
    Operation {
        name: "effect list",
        usage: "effect list [--limit N] [--fields a,b] [--summary] [--json]",
        summary: "List the particle effect presets (dust_motes, falling_leaves, snow, rain, sparks, smoke, fire, embers, fireflies, magic_sparkle, confetti) with a summary, a suggested height and the full `rusting.particle_emitter` each one writes.",
        gpu: NO_GPU,
        defaults: &[],
        example: "effect list --json",
    },
    Operation {
        name: "effect apply",
        usage: "effect apply <scene-path> <effect> [--on OBJECT | --name NAME --at X,Y,Z] [--dry-run] [--json]",
        summary: "Add a particle effect preset to a scene as one scene patch. `--on` sets the `rusting.particle_emitter` of an existing object (a torch, a chimney); otherwise a new object named after the effect is created at `--at`, or at the preset's suggested height above the origin. Every value stays ordinary, editable scene data.",
        gpu: NO_GPU,
        defaults: &[("--at", "0, the preset's height, 0"), ("--name", "the effect's name in title case, made unique"), ("--dry-run", "false")],
        example: "effect apply my_game/scenes/main.rscene fire --at 2,0,-3 --json",
    },
    Operation {
        name: "docs",
        usage: "docs [--brief] [--budget TOKENS] | docs search <words> [--limit N] | docs show <id> [--budget TOKENS] [--json]",
        summary: "Read the manual, tutorials, agent guides, every command and every diagnostic code offline, from the installed version. With no arguments, list the items. `--brief` prints a compact overview sized to `--budget` tokens. `search` needs every word, ranks title hits first, shows the best 10 (`--limit N` for more) and reports `total` and `omitted`. `api/GameScene` (and `api/GameObject`, ...) lists every method of a type; `sample/<name>` prints a sample game's README and code. `show` prints one item, cut at a line to fit `--budget`, and reports whether it was cut.",
        gpu: NO_GPU,
        defaults: &[("--budget", "2000 tokens (about four characters each)"), ("--limit", "10 search matches")],
        example: "docs search scene patch --json",
    },
    Operation {
        name: "explain",
        usage: "explain [CODE] [--limit N] [--fields a,b] [--summary] [--json]",
        summary: "Explain a diagnostic code: what it means, how to fix it, and an example. With no code, list every code the tools can emit.",
        gpu: NO_GPU,
        defaults: &[],
        example: "explain SCENE_CONFLICT --json",
    },
    Operation {
        name: "schema",
        usage: "schema [--json-schema] [--json]",
        summary: "Print this catalog: operations, scene sections and components with defaults, examples, units, ranges, and GPU cost. With --json-schema, print JSON Schema (draft 2020-12) for scene, scene_patch, scenario, project and asset_meta files instead.",
        gpu: NO_GPU,
        defaults: &[],
        example: "schema --json-schema",
    },
];

/// Documentation for one saved field. `path` is a JSON pointer relative to
/// the section; enum variants appear as keys, as they do in scene files.
struct Field {
    path: &'static str,
    unit: &'static str,
    range: &'static str,
    doc: &'static str,
}

const fn field(
    path: &'static str,
    unit: &'static str,
    range: &'static str,
    doc: &'static str,
) -> Field {
    Field {
        path,
        unit,
        range,
        doc,
    }
}

const RGB: &str = "linear RGB";
const METRES: &str = "m";
const RADIANS: &str = "rad";

/// A top-level entity key or a registered component.
struct Section {
    key: &'static str,
    summary: &'static str,
    gpu: &'static str,
    /// Scene form of an authored, non-default value.
    example: fn() -> Value,
    fields: &'static [Field],
}

/// A registered component. Its fields come from its reflected type.
struct ComponentSection {
    key: &'static str,
    summary: &'static str,
    gpu: &'static str,
    /// Scene form of an authored, non-default value.
    example: fn() -> Value,
}

const ENTITY_SECTIONS: &[Section] = &[
    Section {
        key: "id",
        summary: "Persistent object ID. Unique in the scene; keep it when editing so references and patches stay valid.",
        gpu: NO_GPU,
        example: || json!("6f1c1d6e-9a53-4a6d-8f59-2c3e1c0c5a10"),
        fields: &[field("", "UUID", "unique", "")],
    },
    Section {
        key: "parent",
        summary: "Parent object ID; the transform is relative to the parent.",
        gpu: NO_GPU,
        example: || Value::Null,
        fields: &[field("", "UUID", "an existing object; no cycles", "null for a root object")],
    },
    Section {
        key: "name",
        summary: "Object name. Unique in the scene, so scenarios and queries can find it.",
        gpu: NO_GPU,
        example: || json!("Crate"),
        fields: &[field("", "", "unique", "")],
    },
    Section {
        key: "classes",
        summary: "Reusable class names. One class selects any number of objects, for queries and GPU physics rules.",
        gpu: NO_GPU,
        example: || json!(["crates", "breakable"]),
        fields: &[field("", "", "non-empty, no repeats", "")],
    },
    Section {
        key: "visible",
        summary: "Whether the object and its children render.",
        gpu: NO_GPU,
        example: || json!(true),
        fields: &[field("", "", "", "null means visible")],
    },
    Section {
        key: "transform",
        summary: "Position, rotation, and scale relative to the parent.",
        gpu: NO_GPU,
        example: || json!({"position": [2.0, 0.5, -1.0], "rotation": [0.0, 0.785, 0.0], "scale": [1.0, 1.0, 1.0]}),
        fields: &[
            field("/position", METRES, "", "[x, y, z]; +Y is up and -Z is forward"),
            field("/rotation", RADIANS, "", "Euler angles around X, Y, and Z, applied X first, then Y, then Z (R = Rz·Ry·Rx); forward is -Z: (-sin y·cos x, sin x, -cos y·cos x) for z = 0"),
            field("/scale", "factor", "> 0 on each axis", ""),
        ],
    },
    Section {
        key: "mesh_renderer",
        summary: "Mesh and material to draw.",
        gpu: "one draw per mesh and material batch; mesh and texture memory",
        example: || json!({
            "mesh": {"BuiltinPrimitive": "Torus"},
            "material": {"Inline": {
                "name": "", "model": "Pbr", "alpha_mode": "Opaque",
                "base_color": [0.8, 0.5, 0.2, 1.0], "emissive": [0.0, 0.0, 0.0],
                "metallic": 0.0, "roughness": 0.6,
                "transmission": 0.0, "ior": 1.5, "thickness": 0.0,
                "uv_scale": [1.0, 1.0], "uv_offset": [0.0, 0.0],
                "base_color_texture": null, "normal_texture": null,
                "metallic_roughness_texture": null, "occlusion_texture": null,
                "emissive_texture": null
            }},
            "cast_shadows": true, "receive_shadows": true
        }),
        fields: &[
            field("/mesh/BuiltinPrimitive", "", "Cube, Sphere, Triangle, Plane, Tetrahedron, Octahedron, Dodecahedron, Icosahedron, Pyramid, Cylinder, Cone, Torus, Quad", "other variants: \"BuiltinCube\", \"BuiltinSphere\", {\"AssetPath\": \"assets/model.gltf\"}"),
            field("/material/Inline/name", "", "text", "label shown in the editor; may be empty"),
            field("/material/Inline/model", "", "Pbr | Unlit", "other variant: \"BuiltinError\""),
            field("/material/Inline/alpha_mode", "", "Opaque | {\"Mask\": {\"cutoff\": 0..1}} | Blend", ""),
            field("/material/Inline/base_color", "linear RGBA", "0..1", ""),
            field("/material/Inline/emissive", RGB, ">= 0", "HDR; values above 1 glow"),
            field("/material/Inline/metallic", "", "0..1", ""),
            field("/material/Inline/roughness", "", "0..1", ""),
            field("/material/Inline/transmission", "", "0..1", "optional, default 0; light passing through, tinted by base_color (glass)"),
            field("/material/Inline/ior", "", "1..3", "optional, default 1.5; index of refraction"),
            field("/material/Inline/thickness", "m", ">= 0", "optional, default 0; how far the refracted ray travels"),
            field("/material/Inline/uv_scale", "", "[u, v]", "optional, default [1, 1]; texture repeats per face, [8, 4] tiles a long floor"),
            field("/material/Inline/uv_offset", "", "[u, v]", "optional, default [0, 0]; texture shift in whole-texture units"),
            field("/material/Inline/base_color_texture", "path relative to the scene file", "", "a plain string such as \"../assets/textures/crate.png\", not {\"$asset\": ...}; null for none; same for the other texture slots"),
            field("/material/Inline/normal_texture", "path relative to the scene file", "", ""),
            field("/material/Inline/metallic_roughness_texture", "path relative to the scene file", "", "glTF layout: roughness in G, metallic in B"),
            field("/material/Inline/occlusion_texture", "path relative to the scene file", "", ""),
            field("/material/Inline/emissive_texture", "path relative to the scene file", "", ""),
            field("/cast_shadows", "", "", ""),
            field("/receive_shadows", "", "", ""),
        ],
    },
    Section {
        key: "camera",
        summary: "A view. Among active cameras without a viewport the highest priority fills the window; on a tie the one spawned first wins. Every active camera with a viewport then draws into its part of the window, lower priority first, so split screen is two active cameras with viewports. Game code switches with `scene.set_active_camera(name)`, which makes that camera the only active one, or `scene.set_camera(name, active, viewport)`.",
        gpu: "one scene render per drawn camera; inactive cameras cost nothing",
        example: || json!({"projection": {"Perspective": {"vertical_fov_radians": 1.0, "near": 0.1, "far": 500.0}}, "active": true, "priority": 1, "viewport": [0.0, 0.0, 0.5, 1.0]}),
        fields: &[
            field("/projection/Perspective/vertical_fov_radians", RADIANS, "0 < fov < 3.14", "other variant: {\"Orthographic\": {\"vertical_size\" (m), \"near\", \"far\"}}"),
            field("/projection/Perspective/near", METRES, "> 0", ""),
            field("/projection/Perspective/far", METRES, "> near", ""),
            field("/active", "", "", ""),
            field("/priority", "", "i32", "higher wins among active cameras"),
            field("/viewport", "fractions", "[x, y, width, height], each 0..1", "optional; part of the window from the top-left corner, e.g. [0, 0, 0.5, 1] is the left half"),
        ],
    },
    Section {
        key: "physics_body",
        summary: "Where the body simulates. Needs a collider to collide.",
        gpu: "Gpu: compute per fixed tick; nothing is read back unless rusting.physics_sync asks for state",
        example: || json!({"simulation": "Gpu", "solver": "Simplified", "custom_shader": null}),
        fields: &[
            field("/simulation", "", "None | Static | Cpu | Gpu", "Cpu bodies are readable by gameplay every tick"),
            field("/solver", "", "Full | Simplified | NoCollision | Custom | Space", "GPU compute profile; Custom needs custom_shader"),
            field("/custom_shader", "project path", "", "GLSL defining `void solve(inout PhysicsState body)`; null unless solver is Custom. See `rusting docs show guide/gpu-condition-shaders`, which also covers game-code condition shaders"),
        ],
    },
    Section {
        key: "rigid_body",
        summary: "Mass and motion of a simulated body.",
        gpu: NO_GPU,
        example: || json!({"kind": "Dynamic", "mass": 5.0, "linear_velocity": [0.0, 2.0, 0.0], "angular_velocity": [0.0, 0.0, 0.0], "gravity_scale": 1.0}),
        fields: &[
            field("/kind", "", "Dynamic | Kinematic | Fixed", ""),
            field("/mass", "kg", "> 0", ""),
            field("/linear_velocity", "m/s", "", "initial velocity"),
            field("/angular_velocity", "rad/s", "", "initial spin"),
            field("/gravity_scale", "factor", "", "0 disables gravity"),
        ],
    },
    Section {
        key: "collider",
        summary: "Collision shape in the body's local space.",
        gpu: NO_GPU,
        example: || json!({"shape": {"Box": {"half_extents": [0.5, 0.5, 0.5]}}, "friction": 0.6, "restitution": 0.2, "sensor": false}),
        fields: &[
            field("/shape/Box/half_extents", METRES, "> 0", "other variants: {\"Sphere\": {\"radius\"}}, {\"Capsule\": {\"half_height\", \"radius\"}}, \"ConvexMesh\", \"TriangleMesh\" (static only)"),
            field("/friction", "", ">= 0", ""),
            field("/restitution", "", "0..1", "bounciness"),
            field("/sensor", "", "", "reports overlaps without pushing"),
        ],
    },
    Section {
        key: "collision_layers",
        summary: "Which bodies may collide: both must list each other's membership in their filters.",
        gpu: NO_GPU,
        example: || json!({"memberships": 2, "filters": 1}),
        fields: &[
            field("/memberships", "bitmask", "u32", ""),
            field("/filters", "bitmask", "u32", ""),
        ],
    },
    Section {
        key: "gpu_physics_watch",
        summary: "GPU conditions that raise named gameplay events for this body.",
        gpu: "evaluated in GPU physics; only matching events are read back",
        example: || json!({"rules": []}),
        fields: &[field("/rules", "", "", "see GpuPhysicsRule: event, condition, mode, payload, cooldown_seconds")],
    },
    Section {
        key: "directional_light",
        summary: "Sun-like light from the object's forward direction.",
        gpu: "one shadow pass when shadows is true",
        example: || json!({"color": [1.0, 0.95, 0.9], "illuminance": 50000.0, "shadows": true}),
        fields: &[
            field("/color", RGB, "0..1", ""),
            field("/illuminance", "lux", ">= 0", "100000 is direct sunlight"),
            field("/shadows", "", "", ""),
        ],
    },
    Section {
        key: "point_light",
        summary: "Light radiating from the object's position.",
        gpu: "shading cost per lit pixel; up to 64 lights per frame (16 at Eco), the rest are dropped",
        example: || json!({"color": [1.0, 0.8, 0.6], "intensity": 800.0, "range": 8.0}),
        fields: &[
            field("/color", RGB, "0..1", ""),
            field("/intensity", "renderer units, not lumens", ">= 0", "1000 lights a white surface facing it, up close, as brightly as the 100000 lux sun; brightness falls off as (1 - distance/range)^2. A desk lamp in a dark room: 400-1500; a bright party light: 3000-8000"),
            field("/range", METRES, "> 0", "light reaches zero here"),
        ],
    },
    Section {
        key: "spot_light",
        summary: "Cone of light along the object's forward direction.",
        gpu: "as point_light",
        example: || json!({"color": [1.0, 1.0, 1.0], "intensity": 1200.0, "range": 12.0, "inner_angle": 0.3, "outer_angle": 0.5}),
        fields: &[
            field("/color", RGB, "0..1", ""),
            field("/intensity", "renderer units, not lumens", ">= 0", "as point_light: 1000 matches the 100000 lux sun up close"),
            field("/range", METRES, "> 0", "light reaches zero here"),
            field("/inner_angle", RADIANS, "0..outer_angle", "fully lit cone"),
            field("/outer_angle", RADIANS, "inner_angle..1.57", "light reaches zero here"),
        ],
    },
];

const COMPONENT_SECTIONS: &[ComponentSection] = &[
    ComponentSection {
        key: "rusting.ambient_light",
        summary: "Flat light added everywhere.",
        gpu: NO_GPU,
        example: || json!({"color": [0.8, 0.85, 1.0], "intensity": 0.2}),
    },
    ComponentSection {
        key: "rusting.sky_light",
        summary: "Hemisphere light: up-facing surfaces see sky_color, down-facing ones ground_color.",
        gpu: NO_GPU,
        example: || json!({"sky_color": [0.5, 0.7, 1.0], "ground_color": [0.3, 0.25, 0.2], "intensity": 0.4}),
    },
    ComponentSection {
        key: "rusting.tone_mapping",
        summary: "Exposure and the curve that maps HDR color to the display. The first one found is used.",
        gpu: NO_GPU,
        example: || json!({"mapper": "Aces", "exposure": 1.2}),
    },
    ComponentSection {
        key: "rusting.color_grading",
        summary: "Runs after tone mapping: contrast around mid grey, saturation (0 grey, 1 unchanged), shadows and highlights color tints, and vignette (0..1) darkening the corners. The first one found is used.",
        gpu: "a few instructions per pixel",
        example: || json!({"contrast": 1.1, "saturation": 0.9, "shadows": [0.92, 0.98, 1.1], "highlights": [1.08, 1.0, 0.9], "vignette": 0.3}),
    },
    ComponentSection {
        key: "rusting.camera_screen",
        summary: "On an object with a mesh: shows what the camera entity named camera sees, at size [w, h] pixels, in place of the material's base color and emissive maps. The camera may be inactive. Give each screen its own material.",
        gpu: "renders the scene once more per screen per frame",
        example: || json!({"camera": "Cam B", "size": [320, 180]}),
    },
    ComponentSection {
        key: "rusting.environment_map",
        summary: "Equirectangular (2:1) sky image under assets/ that surfaces reflect and are lit by, replacing the sky_light hemisphere. Rough surfaces see it blurred. The first one found is used.",
        gpu: NO_GPU,
        example: || json!({"texture": "sky.png", "intensity": 1.0}),
    },
    ComponentSection {
        key: "rusting.reflection_probe",
        summary: "Box of half size extents around the object's position. Surfaces inside reflect the scene as seen from that position, projected onto the box walls, in place of the environment map. Captured when added or changed; up to four are used.",
        gpu: "each probe renders the scene six times when captured",
        example: || json!({"extents": [5.0, 3.0, 5.0], "intensity": 1.0}),
    },
    ComponentSection {
        key: "rusting.fog",
        summary: "Exponential height fog: the scene fades into color with distance, thinning above height by height_falloff per metre. Brighter toward the sun by sun_scatter; sky_affect fades the background too. The first one found is used.",
        gpu: "a few instructions per pixel, plus one full-screen sky pass when sky_affect > 0",
        example: || json!({"color": [0.55, 0.65, 0.75], "density": 0.02, "height": 0.0, "height_falloff": 0.1, "sun_scatter": 0.3, "sky_affect": 1.0}),
    },
    ComponentSection {
        key: "rusting.bloom",
        summary: "Glow around pixels brighter than threshold (linear, before exposure), spread over the screen before tone mapping. The first one found is used.",
        gpu: "a half-resolution blur chain of about 12 compute passes",
        example: || json!({"intensity": 0.5, "threshold": 1.0, "spread": 0.7}),
    },
    ComponentSection {
        key: "rusting.ambient_occlusion",
        summary: "Screen-space ambient occlusion: darkens ambient, sky and environment light in creases within radius metres. Off on the Eco quality profile. The first one found is used.",
        gpu: "a depth prepass plus two full-screen compute passes",
        example: || json!({"radius": 1.0, "intensity": 1.0}),
    },
    ComponentSection {
        key: "rusting.background",
        summary: "Clear color behind the scene. The one on the entity with the lowest ID is used; without one the game keeps its render settings.",
        gpu: NO_GPU,
        example: || json!({"color": [0.5, 0.7, 0.9, 1.0]}),
    },
    ComponentSection {
        key: "rusting.render_bounds",
        summary: "Render-only visibility bounds in local space, separate from the collider.",
        gpu: "smaller bounds let culling skip more draws",
        example: || json!({"Sphere": {"center": [0.0, 0.5, 0.0], "radius": 1.0}}),
    },
    ComponentSection {
        key: "rusting.physics_sync",
        summary: "What a GPU body sends back to the CPU.",
        gpu: "SelectedState and FullState read back 144 bytes per body per fixed tick; Events reads back only fired events",
        example: || json!("SelectedState"),
    },
    ComponentSection {
        key: "rusting.auto_simulation",
        summary: "Lets the engine choose CPU or GPU simulation for the body.",
        gpu: NO_GPU,
        example: || json!({}),
    },
    ComponentSection {
        key: "rusting.player_controller",
        summary: "First- or third-person walking body. Reads the player.* actions; parent a camera to it at eye height. camera_distance above 0 orbits that camera behind the body. Ground steeper than max_slope is a wall; ledges up to max_step_height are stepped onto; push_bodies false keeps it from moving dynamic bodies. turn_speed (rad/s) turns its non-camera children toward the walking direction.",
        gpu: NO_GPU,
        example: || json!({"walk_speed": 5.0, "sprint_multiplier": 1.5, "jump_speed": 6.0, "gravity": 12.0, "look_sensitivity": 0.003, "mouse_look": true, "collision_mask": 1, "yaw": 1.57, "pitch": 0.0, "camera_distance": 4.0, "camera_height": 0.6, "camera_offset": [0.0, 0.0, 0.0], "max_slope": 0.78, "max_step_height": 0.3, "push_bodies": true, "turn_speed": 0.0}),
    },
    ComponentSection {
        key: "rusting.tween",
        summary: "Animates one Transform property from `from` to `to` on the fixed step.",
        gpu: NO_GPU,
        example: || json!({"property": "Scale", "from": [1.0, 1.0, 1.0], "to": [1.2, 1.2, 1.2], "duration": 0.4, "delay": 0.0, "easing": "BackOut", "repeat": "PingPong"}),
    },
    ComponentSection {
        key: "rusting.sound_cue",
        summary: "Sends a SoundEvent when the body starts touching something or game code calls trigger(). The windowed game plays the clip (path relative to assets/, not the scene-relative asset `reference`); headless runs and scenarios count it (scenario entity `audio:`).",
        gpu: NO_GPU,
        example: || json!({"clip": "sounds/hit.ogg", "volume": 0.8, "on_collision": true}),
    },
    ComponentSection {
        key: "rusting.burst_emitter",
        summary: "Spawns particles that fly out, fall, and shrink, when the body starts touching something or game code calls trigger(). rate above 0 emits that many particles per second with no trigger, starting anywhere in the area box (half extents); stretch makes particles taller, for rain. Particles copy the emitter's mesh.",
        gpu: NO_GPU,
        example: || json!({"count": 20, "speed": 4.0, "lifetime": 0.8, "particle_scale": 0.1, "gravity": 9.81, "on_collision": false, "rate": 0.0, "area": [0.0, 0.0, 0.0], "stretch": 1.0}),
    },
    ComponentSection {
        key: "rusting.particle_emitter",
        summary: "Particle effects: rate and bursts per cycle, an emission shape (Point, Box, Sphere, Cone, Circle), random [min, max] ranges for lifetime, speed, size, rotation and spin, gravity, drag, wind and turbulence, size and color keys over life, fades, World or Local space, Billboard or Velocity facing, Alpha or Additive blend. Particles are not entities; each emitter is one instanced draw. Random values come from the scene seed, the emitter's SceneId and the fixed tick. Game code calls play(), pause(), stop() or restart(). `rusting effect list` shows ready presets.",
        gpu: "one instanced draw of up to max_particles quads per emitter, rebuilt every frame",
        example: || json!({"autoplay": true, "rate": 20.0, "bursts": [], "max_particles": 500, "prewarm": false, "duration": 5.0, "looping": true, "on_collision": false, "shape": "Sphere", "shape_size": [0.5, 0.5, 0.5], "lifetime": [1.0, 2.0], "speed": [0.5, 1.5], "size": [0.05, 0.1], "rotation": [0.0, 0.0], "spin": [0.0, 0.0], "direction": [0.0, 1.0, 0.0], "spread": 0.5, "gravity": 0.0, "drag": 0.5, "wind": [0.0, 0.0, 0.0], "turbulence": 0.5, "turbulence_frequency": 1.0, "size_over_life": [{"t": 0.0, "value": 1.0}, {"t": 1.0, "value": 0.2}], "color_over_life": [{"t": 0.0, "color": [1.0, 0.8, 0.3, 1.0]}, {"t": 1.0, "color": [1.0, 0.2, 0.1, 1.0]}], "start_colors": [], "emissive": 3.0, "fade_in": 0.1, "fade_out": 0.4, "space": "World", "facing": "Billboard", "stretch": 0.1, "blend": "Additive", "sprite": "Soft"}),
    },
    ComponentSection {
        key: "rusting.animation",
        summary: "Keyframe animation: named clips of tracks keyed over time. A track writes Position, Rotation (radians), Scale, Color (RGBA), Emissive (RGB), Visible, Orientation (quaternion x,y,z,w, used by imported glTF clips), or a numeric Field of another registered component, on this entity or a child path such as Arm/Hand. Interpolation is Step, Linear or Smooth (Catmull-Rom); repeat is Once, Loop or PingPong; speed scales time. Markers in events reach game code as animation events. A clip with `blend` points is a 1D blend space: its clips are stretched to its length (1 s when 0) and the two around the `blend_parameter` value are mixed. With `blend_parameter_y` set it is a 2D blend space: each point also has `at_y`, and every point is weighted by gradient bands (a point plays alone on its spot). Transitions make a state machine: when the playing clip is `from` (empty: any) and the parameter test holds (Above, Below or Equal; at_end also waits for the clip to finish), it crossfades to `to`; the first match in list order wins. Layers play clips on top of the state on their own clocks: an override layer replaces, an additive one adds the clip's motion from its first frame, `weight` (or the `weight_parameter` value) scales it, and `mask` limits it to target paths and their children. `root_motion` (Off, InPlace, Transform, Velocity) keeps the `root_bone` Position track at its first-frame x and z and collects its horizontal motion: InPlace for game code (take_root_motion), Transform moves the object, Velocity sets its GPU body velocity through the physics command bridge. `humanoid` maps standard bone names (Hips, Spine, LeftUpperArm...) to this rig's bone paths for `rusting scene retarget`; empty matches bones by name without rig prefixes. Runs on the fixed tick, so playback is deterministic. Game code calls play_animation(), crossfade(), stop_animation(), is_playing() and set_animation_parameter().",
        gpu: NO_GPU,
        example: || json!({"clips": [{"name": "bob", "duration": 0.0, "repeat": "PingPong", "tracks": [{"target": "", "property": "Position", "interpolation": "Smooth", "keys": [{"time": 0.0, "value": [0.0, 0.0, 0.0]}, {"time": 1.0, "value": [0.0, 0.5, 0.0]}]}], "events": [{"time": 1.0, "name": "top"}], "blend": [], "blend_parameter": "", "blend_parameter_y": ""}], "autoplay": "bob", "speed": 1.0, "parameters": {}, "transitions": [{"from": "bob", "to": "run", "parameter": "speed", "compare": "Above", "value": 1.0, "at_end": false, "fade": 0.2}], "layers": [{"clip": "wave", "weight": 1.0, "weight_parameter": "", "additive": false, "mask": ["Body/Arm"]}], "root_motion": "Off", "root_bone": "", "humanoid": [{"bone": "Hips", "path": "Armature/Hips"}]}),
    },
    ComponentSection {
        key: "rusting.skin",
        summary: "Skinned mesh: joint paths from this object (child names joined by /, .. for the parent) and one column-major inverse bind matrix per joint. Vertex joints and weights come from the .rskin file the glTF importer cooks next to the mesh. glTF import and `scene add-model` fill it in; animate the joints with rusting.animation. The mesh is bent on the CPU each frame a joint moves.",
        gpu: "the bent mesh is uploaded again each frame a joint moves",
        example: || json!({"joints": ["../Armature/Root", "../Armature/Root/Tip"], "inverse_bind": [[[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]], [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, -1.0, 0.0, 1.0]]]}),
    },
    ComponentSection {
        key: "rusting.ik",
        summary: "Inverse kinematics on the end of a joint chain, solved each fixed step after the animation pose. kind LookAt turns this object so its local forward axis points at target. kind TwoBone bends this object's parent and grandparent (upper arm and forearm, thigh and shin) so this object's origin reaches target; the middle joint bends toward pole if set. kind Foot is TwoBone toward the ground under this object (no target): a ray from reach metres above the character's floor (nearest ancestor with rusting.animation) finds the CPU collider below, and the foot keeps its animated height above it, turns to the slope, and lowers the hips (the thigh's parent) when the ground is out of reach. weight 0 keeps the animated pose, 1 solves fully. A null target turns off LookAt and TwoBone. kind Chain bends the `joints` ancestors above this object (FABRIK, for tails, spines and tentacles) so it reaches target. Each tick starts from the clip pose, never last tick's IK.",
        gpu: NO_GPU,
        example: || json!({"kind": "TwoBone", "target": null, "pole": null, "weight": 1.0, "forward": [0.0, 0.0, -1.0], "reach": 0.5, "joints": 3}),
    },
    ComponentSection {
        key: "rusting.ragdoll",
        summary: "Hands a character's bones from animation to CPU physics and back. Going limp (game code `set_ragdoll(name, true)`, or a CPU body closing on the character's colliders at hit_speed m/s or faster; 0 only on command) spawns a capsule body per entry of bones (path from this object, length and radius in metres along the bone's local +Y, mass in kg) moving as the animation moved it, jointed to the nearest ancestor bone's body with `joint` (a rusting joint kind; X axis along the bone by default, set by frame). The character's own collider is taken off while limp. After recover_after seconds (0 waits for `set_ragdoll(name, false)`) the character moves under its hips, the bodies are removed, and bones blend back to the animation over blend_time seconds. Bones without an entry keep their animated local pose. muscle (Hz, 0 = passive) makes it an active ragdoll: the bodies exist from the start, each is turned toward its bone's animated pose relative to its parent body by a critically damped spring at that frequency, and the top body is held to the animated hips; hits push it and it springs back, a hit at hit_speed drops the muscles until recovery, after which they regain strength over blend_time. Set muscle to 0 to go limp and return to plain animation.",
        gpu: NO_GPU,
        example: || json!({"bones": [{"path": "Armature/Hips", "length": 0.25, "radius": 0.12, "mass": 10.0, "joint": {"ConeTwist": {"swing": 0.7, "twist": [-0.4, 0.4]}}, "frame": [0.0, 0.0, 1.5707964]}, {"path": "Armature/Hips/Spine", "length": 0.4, "radius": 0.12, "mass": 12.0, "joint": {"ConeTwist": {"swing": 0.5, "twist": [-0.3, 0.3]}}, "frame": [0.0, 0.0, 1.5707964]}], "hit_speed": 6.0, "recover_after": 2.0, "blend_time": 0.5, "muscle": 0.0}),
    },
    ComponentSection {
        key: "rusting.morph",
        summary: "Blend shape (morph target) weights for the object's mesh, one per shape, usually 0 to 1. The shape offsets come from the .rmorph file the glTF importer cooks next to the mesh. glTF import and `scene add-model` fill it in, and imported clips animate it with a Field track on /weights. Extra mesh parts of the object (its children without their own rusting.morph) use these weights too. The mesh is reshaped on the CPU each frame a weight changes.",
        gpu: "the reshaped mesh is uploaded again each frame a weight changes",
        example: || json!({"weights": [0.0, 1.0]}),
    },
    ComponentSection {
        key: "rusting.fluid_block",
        summary: "Particle fluid: a block of count_x by count_y by count_z particles resting on the floor of a box centered on the entity. It runs every fixed tick, floats and sinks dynamic bodies with sphere colliders, and draws a smooth water surface when visible (show_particles adds a sphere per particle). CPU only, deterministic; a few thousand particles at most.",
        gpu: NO_GPU,
        example: || json!({"spacing": 0.1, "count_x": 6, "count_y": 6, "count_z": 6, "container_half_extents": [0.5, 0.5, 0.5], "iterations": 4, "viscosity": 0.01, "visible": true, "show_particles": false}),
    },
    ComponentSection {
        key: "rusting.water",
        summary: "Water for seas, lakes and rivers: a size by size rectangle of animated waves centered on the entity (axis aligned, rotation and scale ignored). Dynamic bodies with sphere, box or capsule colliders float in it, and flow_speed carries them along flow_direction, which also turns the waves. Deterministic and cheap; a long thin rectangle with a flow_speed is a river. Put it on an empty object.",
        gpu: "one mesh of about resolution squared vertices, rewritten every fixed tick",
        example: || json!({"size": [20.0, 20.0], "resolution": 64, "wave_height": 0.25, "wave_length": 4.0, "wave_speed": 1.0, "flow_direction": 0.0, "flow_speed": 0.0, "color": [0.1, 0.4, 0.7, 0.7]}),
    },
    ComponentSection {
        key: "rusting.hud",
        summary: "Text label or button drawn over the game view. offset points inward from the anchor, in logical pixels, and the text is measured after {counter} values are filled in, so right and bottom anchors keep their margin. A clicked button sends HudButtonPressed.",
        gpu: "a few egui triangles",
        example: || json!({"text": "Score: 0", "anchor": "TopRight", "offset": [24.0, 24.0], "font_size": 24.0, "color": [1.0, 0.9, 0.4, 1.0], "button": false, "requires": null, "camera": null}),
    },
    ComponentSection {
        key: "rusting.input_action",
        summary: "Binds a named action to keys and mouse buttons, for game code (GameScene::pressed, held) and scenario press steps. Bindings add to the ActionMap; the player.* actions are already bound.",
        gpu: NO_GPU,
        example: || json!({"action": "fire", "inputs": ["MouseLeft", "KeyF"]}),
    },
    ComponentSection {
        key: "rusting.counter",
        summary: "Named integer. HUD text shows it as {name}; pickups add to it.",
        gpu: NO_GPU,
        example: || json!({"name": "coins", "value": 0, "target": 5}),
    },
    ComponentSection {
        key: "rusting.pickup",
        summary: "Collected once when a platformer or player body touches its collider (make it a sensor): adds value to the counter, hides the entity, and triggers its sound cue and burst emitter.",
        gpu: NO_GPU,
        example: || json!({"counter": "coins", "value": 1, "requires": null, "collected": false}),
    },
    ComponentSection {
        key: "rusting.tile_map",
        summary: "Grid of square tiles written as text rows, top row first; the Transform position is the top-left corner. Tiles spawn as unsaved Quad entities, and each run of solid tiles in a row gets one fixed box collider.",
        gpu: "one instanced Quad draw per tile kind",
        example: || json!({"tile_size": 0.5, "rows": ["....", "#..#", "####"], "tiles": {"#": {"color": [0.3, 0.6, 0.3, 1.0], "texture": null, "solid": true}}}),
    },
    ComponentSection {
        key: "rusting.platformer_controller",
        summary: "Side-view run and jump in the XY plane. Reads player.left, player.right and player.jump; parent an orthographic camera to follow.",
        gpu: NO_GPU,
        example: || json!({"run_speed": 6.0, "jump_speed": 9.0, "gravity": 25.0, "collision_mask": 1}),
    },
    ComponentSection {
        key: "rusting.scene_instance",
        summary: "Places another scene under this entity when the scene loads, as a prefab. The placed entities get stable IDs; the text scene stores only the link and each changed field (rusting.instance_overrides), and cooking includes them, so a game ships without the source scene. Nested instances work; a scene that contains itself fails to load.",
        gpu: NO_GPU,
        example: || json!({"source": "prefabs/coin.rscene"}),
    },
    ComponentSection {
        key: "rusting.connections",
        summary: "Signal connections of the object that emits them: each runs a Rust handler the game registered with App::add_signal_handler, with target as the receiver, when this object sends the handler's event or gains or loses its component. A game fails to load a scene that names an unregistered handler or a missing object.",
        gpu: NO_GPU,
        example: || json!({"list": [{"handler": "add_score", "target": "8d1f6f0e-3c43-4b0a-9a57-2f64a1b0c7d2"}]}),
    },
    ComponentSection {
        key: "rusting.joint",
        summary: "Joins this CPU body to target's (null: the world) at anchor and target_anchor. kind is Fixed, Hinge, Slider, BallSocket, ConeTwist, Distance, Spring, or Generic (per-axis Locked, Free, or Limited, each with an optional spring and motor). The frame's X axis is the hinge, slider, and twist axis. A break_force or break_torque above 0 removes the joint and sends JointBroken when a step's load passes it.",
        gpu: NO_GPU,
        example: || json!({"target": null, "kind": {"Hinge": {"limit": [-1.0, 1.0], "spring": {"target": 0.0, "stiffness": 20.0, "damping": 2.0}, "motor": {"speed": 2.0, "max_force": 50.0}}}, "anchor": [0.0, 1.0, 0.0], "frame": [0.0, 0.0, 1.5], "target_anchor": [0.0, 3.0, 0.0], "target_frame": [0.0, 0.0, 1.5], "collide_connected": false, "break_force": 500.0, "break_torque": 0.0}),
    },
    ComponentSection {
        key: "rusting.articulation",
        summary: "Makes this body the root of a reduced-coordinate joint tree. Fixed, Hinge, Slider, and BallSocket joints hanging from it, directly or through other links, are solved in joint space: they never drift apart and hinge and slider limits hold exactly. A dynamic root floats; a fixed or kinematic root is the base. Reduced joints do not break.",
        gpu: NO_GPU,
        example: || json!({}),
    },
];

/// The scene form of an entity holding every built-in section and every
/// registered component at its default value.
pub(crate) fn defaults() -> &'static (Map<String, Value>, Map<String, Value>) {
    static DEFAULTS: std::sync::OnceLock<(
        Map<String, Value>,
        Map<String, Value>,
    )> = std::sync::OnceLock::new();
    DEFAULTS.get_or_init(build_defaults)
}

fn build_defaults() -> (Map<String, Value>, Map<String, Value>) {
    let mut app = App::new();
    app.add_plugin(AssetPlugin)
        .expect("a new app accepts the asset plugin");
    let world = app.world_mut();
    // Built from the asset defaults, so the scene form cannot drift from them.
    let renderer = {
        let mut assets = world.resource_mut::<crate::assets::AssetServer>();
        let material = assets.materials.insert(Default::default());
        crate::runtime::MeshRenderer {
            mesh: assets.builtin_primitives
                [&crate::assets::PrimitiveShape::Cube],
            material,
            cast_shadows: true,
            receive_shadows: true,
        }
    };
    let entity = world
        .spawn((
            renderer,
            SceneId(Uuid::nil()),
            Name("Default".into()),
            Transform::default(),
            Camera::default(),
            PhysicsBody::default(),
            RigidBody::default(),
            Collider::default(),
            CollisionLayers::default(),
            GpuPhysicsWatch::default(),
            DirectionalLight::default(),
            PointLight::default(),
            SpotLight::default(),
        ))
        .id();
    for name in registered_component_names(world) {
        add_registered_component(world, entity, &name)
            .expect("registered components have defaults");
    }
    let components = registered_component_values(world, entity)
        .expect("defaults serialize")
        .into_iter()
        .map(|(name, text)| {
            (
                name,
                serde_json::from_str(&text).expect("registry writes JSON"),
            )
        })
        .collect();
    let document = scene_document(world, "defaults").expect("defaults save");
    let Ok(Value::Object(mut entity)) =
        serde_json::to_value(&document.entities[0])
    else {
        unreachable!("an entity saves as an object");
    };
    entity.remove("components");
    // The document writes a cube as "BuiltinCube"; the docs list the
    // primitive form.
    entity["mesh_renderer"]["mesh"] = json!({"BuiltinPrimitive": "Cube"});
    (entity, components)
}

fn section_value(section: &Section, default: Option<&Value>) -> Value {
    json!({
        "key": section.key,
        "summary": section.summary,
        "gpu_cost": section.gpu,
        "default": default,
        "example": (section.example)(),
        "fields": section.fields.iter().map(|field| json!({
            "path": field.path,
            "unit": field.unit,
            "range": field.range,
            "doc": field.doc,
        })).collect::<Vec<_>>(),
    })
}

/// Field documentation of a reflected type, in the layout of [`Field`].
/// Map keys show as `*`, enum payloads under their variant name, and
/// containers appear only when they carry a doc.
fn reflected_fields(info: &TypeInfo) -> Vec<Value> {
    let mut fields = Vec::new();
    describe(info, &Hints::default(), String::new(), &mut fields);
    fields
}

fn describe(
    info: &TypeInfo,
    hints: &Hints,
    path: String,
    out: &mut Vec<Value>,
) {
    let entry = |range: String| json!({"path": path, "unit": hints.unit, "range": range, "doc": hints.doc});
    match info {
        TypeInfo::Option(inner) => describe(inner, hints, path, out),
        TypeInfo::Struct(info) => {
            if !hints.doc.is_empty() {
                out.push(entry(String::new()));
            }
            for field in &info.fields {
                describe(
                    &field.ty,
                    &field.hints,
                    format!("{path}/{}", field.name),
                    out,
                );
            }
        }
        TypeInfo::Map(item) if matches!(**item, TypeInfo::Struct(_)) => {
            if !hints.doc.is_empty() {
                out.push(entry(String::new()));
            }
            describe(item, &Hints::default(), format!("{path}/*"), out);
        }
        TypeInfo::Enum(info) if !info.is_unit_only() => {
            out.push(entry(variant_names(info)));
            for variant in &info.variants {
                let at = format!("{path}/{}", variant.name);
                match &variant.fields {
                    VariantFields::Unit => {}
                    VariantFields::Tuple(items) if items.len() == 1 => {
                        describe(&items[0], &Hints::default(), at, out);
                    }
                    VariantFields::Tuple(items) => {
                        for (index, item) in items.iter().enumerate() {
                            describe(
                                item,
                                &Hints::default(),
                                format!("{at}/{index}"),
                                out,
                            );
                        }
                    }
                    VariantFields::Struct(fields) => {
                        for field in fields {
                            describe(
                                &field.ty,
                                &field.hints,
                                format!("{at}/{}", field.name),
                                out,
                            );
                        }
                    }
                }
            }
        }
        leaf => out.push(entry(range_text(leaf, hints))),
    }
}

fn variant_names(info: &EnumInfo) -> String {
    info.variants
        .iter()
        .map(|variant| variant.name)
        .collect::<Vec<_>>()
        .join(" | ")
}

fn range_text(info: &TypeInfo, hints: &Hints) -> String {
    match (hints.min, hints.max) {
        (Some(min), Some(max)) => return format!("{min}..{max}"),
        (Some(min), None) => return format!(">= {min}"),
        (None, Some(max)) => return format!("<= {max}"),
        (None, None) => {}
    }
    match info {
        TypeInfo::Int { name, .. } => (*name).to_owned(),
        TypeInfo::Enum(info) => variant_names(info),
        TypeInfo::Entity | TypeInfo::Handle(_) => info.kind_name().to_owned(),
        TypeInfo::Array(item, _)
        | TypeInfo::List(item)
        | TypeInfo::Map(item) => range_text(item, &Hints::default()),
        _ => String::new(),
    }
}

fn component_value(
    section: &ComponentSection,
    info: &TypeInfo,
    default: Option<&Value>,
) -> Value {
    json!({
        "key": section.key,
        "summary": section.summary,
        "gpu_cost": section.gpu,
        "default": default,
        "example": (section.example)(),
        "fields": reflected_fields(info),
    })
}

fn reflected_types<'a>(
    types: impl Iterator<Item = (&'a str, &'a TypeInfo)>,
) -> Vec<Value> {
    types
        .map(
            |(key, info)| json!({"key": key, "fields": reflected_fields(info)}),
        )
        .collect()
}

/// JSON Schema (draft 2020-12) for the files the engine reads, keyed by
/// `scene`, `scene_patch`, `scenario`, `project` and `asset_meta`, so generic
/// editors and validators can check them. Entity sections and registered
/// components come from the catalog tables; their values are not described
/// further (the catalog lists the fields).
#[must_use]
pub fn json_schemas() -> Value {
    let registry = SceneComponentRegistry::default();
    let mut entity: Map<String, Value> = ENTITY_SECTIONS
        .iter()
        .map(|section| {
            (
                section.key.to_owned(),
                json!({"description": section.summary}),
            )
        })
        .collect();
    let components: Map<String, Value> = COMPONENT_SECTIONS
        .iter()
        .filter_map(|section| {
            registry.info(section.key).map(|_| {
                (
                    section.key.to_owned(),
                    json!({"type": "string", "description": "component value as a JSON string"}),
                )
            })
        })
        .collect();
    entity.insert(
        "components".into(),
        json!({"type": "object", "properties": components}),
    );
    let entity_ref =
        json!({"type": "string", "description": "entity UUID or unique name"});
    let operation = |name: &str, required: &[&str], props: Value| {
        let mut properties = props;
        properties["op"] = json!({"const": name});
        let mut required = required.to_vec();
        required.push("op");
        json!({"type": "object", "properties": properties,
               "required": required, "additionalProperties": false})
    };
    let value = json!({"description": "any JSON value"});
    let path = json!({"type": "string", "description": "JSON pointer"});
    json!({
        "scene": {
            "$schema": JSON_SCHEMA_DRAFT,
            "title": "RustingEngine scene",
            "type": "object",
            "properties": {
                "format_version": {"type": "integer"},
                "name": {"type": "string"},
                "entities": {"type": "array", "items": {
                    "type": "object", "properties": entity}},
                "render": {"type": "object"},
                "simulation": {"type": "object"},
            },
            "required": ["name", "entities"],
        },
        "scene_patch": {
            "$schema": JSON_SCHEMA_DRAFT,
            "title": "RustingEngine scene patch",
            "type": "object",
            "properties": {
                "expected_revision": {"type": ["string", "null"]},
                "operations": {"type": "array", "items": {"oneOf": [
                    operation("create", &["entity"], json!({"entity": {"type": "object"}})),
                    operation("upsert", &["entity"], json!({"entity": {"type": "object"}, "merge": {"type": "boolean"}})),
                    operation("set", &["id", "path", "value"], json!({"id": entity_ref, "path": path, "value": value, "expected": value})),
                    operation("remove", &["id", "path"], json!({"id": entity_ref, "path": path, "expected": value})),
                    operation("reparent", &["id", "parent"], json!({"id": entity_ref, "parent": {"type": ["string", "null"]}})),
                    operation("duplicate", &["id"], json!({"id": entity_ref, "new_id": {"type": "string"}, "name": {"type": "string"}})),
                    operation("delete", &["id"], json!({"id": entity_ref, "missing_ok": {"type": "boolean"}})),
                    operation("set_scene", &["path", "value"], json!({"path": path, "value": value, "expected": value})),
                ]}},
            },
            "required": ["operations"],
            "additionalProperties": false,
        },
        "scenario": {
            "$schema": JSON_SCHEMA_DRAFT,
            "title": "RustingEngine scenario",
            "type": "object",
            "properties": {
                "name": {"type": "string"},
                "seed": {"type": "integer", "minimum": 0},
                "ticks": {"type": "integer", "minimum": 0},
                "capture_size": {"type": "array", "items": {"type": "integer", "minimum": 1},
                                 "minItems": 2, "maxItems": 2},
                "steps": {"type": "array", "items": {
                    "type": "object",
                    "properties": {"tick": {"type": "integer", "minimum": 0}},
                    "required": ["tick"]}},
                "keep_going": {"type": "boolean"},
                "annotate": {"type": "boolean"},
                "contact_sheet": {"type": "string"},
                "audio_out": {"type": "string"},
                "files": {"type": "object", "additionalProperties": {"type": "string"}},
                "gpu": {"type": "boolean"},
                "invariants": {"type": "array", "items": {
                    "type": "object",
                    "properties": {"entity": {"type": "string"}, "counter": {"type": "string"}}}},
                "budgets": {"type": "object", "properties": {
                    "max_tick_ms": {"type": "number"},
                    "mean_tick_ms": {"type": "number"},
                    "p95_tick_ms": {"type": "number"},
                    "max_draws": {"type": "integer", "minimum": 0},
                    "max_triangles": {"type": "integer", "minimum": 0}}},
            },
            "required": ["name", "ticks"],
        },
        "project": {
            "$schema": JSON_SCHEMA_DRAFT,
            "title": "RustingEngine project.json",
            "type": "object",
            "properties": {
                "format_version": {"type": "integer"},
                "name": {"type": "string"},
                "main_scene": {"type": "string"},
                "cooked_scene": {"type": "string"},
                "binary_name": {"type": "string"},
                "generators": {"type": "object"},
                "determinism": {"type": "string"},
            },
            "required": ["name", "main_scene", "cooked_scene"],
        },
        "asset_meta": {
            "$schema": JSON_SCHEMA_DRAFT,
            "title": "RustingEngine .rmeta asset sidecar",
            "type": "object",
            "properties": {
                "format_version": {"type": "integer"},
                "id": {"type": "string"},
                "kind": {"type": ["string", "object"]},
                "settings": {"type": "object"},
                "dependencies": {"type": "array", "items": {"type": "string"}},
                "content_hash": {"type": "string"},
                "source": {"type": "object"},
            },
            "required": ["format_version", "id", "kind", "content_hash"],
        },
    })
}

const JSON_SCHEMA_DRAFT: &str = "https://json-schema.org/draft/2020-12/schema";

/// The full catalog as JSON.
#[must_use]
pub fn catalog() -> Value {
    let (entity, components) = defaults();
    let registry = SceneComponentRegistry::default();
    let types = TypeRegistry::default();
    json!({
        "catalog_version": SCHEMA_CATALOG_VERSION,
        "engine_version": env!("CARGO_PKG_VERSION"),
        "scene_format_version": SCENE_FORMAT_VERSION,
        "operations": OPERATIONS.iter().map(|operation| json!({
            "name": operation.name,
            "usage": format!("rusting {}", operation.usage),
            "summary": operation.summary,
            "gpu_cost": operation.gpu,
            "defaults": operation.defaults.iter()
                .map(|(flag, value)| (flag.to_string(), json!(value)))
                .collect::<Map<_, _>>(),
            "example": format!("rusting {}", operation.example),
        })).collect::<Vec<_>>(),
        "scene": {
            "file": "JSON object with format_version, name, entities, and render {quality: Auto|Eco|Balanced|High, culling: Auto|Disabled|Frustum|FrustumAndOcclusion}",
            "entity_sections": ENTITY_SECTIONS.iter()
                .map(|section| section_value(section, entity.get(section.key)))
                .collect::<Vec<_>>(),
            "components_note": "Registered components are stored under `components` as JSON strings keyed by name. Scenario `expect` paths and this catalog show them parsed. Fields come from each type's reflection: `*` stands for any map key, enum payloads sit under the variant name, an entity reference saves as the target's object ID, an asset handle as {\"$asset\": path}, and a component with migrations saves \"$version\". Unknown fields fail the load; register a rename or remove migration instead.",
            "components": COMPONENT_SECTIONS.iter()
                .map(|section| {
                    let info = registry.info(section.key)
                        .expect("catalog components are registered");
                    component_value(section, info, components.get(section.key))
                })
                .collect::<Vec<_>>(),
        },
        "resources_note": "Resources are runtime state that game code sets (for example `scene.set_render_scale`). A scene file cannot set them: scene settings are `render` and `simulation` (set_scene `/render/...`).",
        "resources": reflected_types(types.resources()),
        "asset_types": reflected_types(types.assets()),
        "physics_sync_readback_bytes": PhysicsSyncMode::STATE_READBACK_BYTES,
        "scene_patch": {
            "file": "JSON object: expected_revision (optional, from scene inspect), operations",
            "ids": "id, parent and create's entity.parent take a UUID or the unique name of an entity",
            "paths": "JSON pointers into the entity's scene form with registered components parsed, as in scenario expect paths; /id cannot change",
            "operations": {
                "create": "{\"op\": \"create\", \"entity\": {\"name\": \"Crate\", \"parent\": null}}: a missing id gets a new UUID; fields left out of built-in sections take their defaults",
                "upsert": "{\"op\": \"upsert\", \"entity\": {\"name\": \"Crate\"}}: create, or replace the entity with the same id (else name) and keep its id; a patch of upserts can run again; \"merge\": true keeps fields left out (null removes one)",
                "set": "{\"op\": \"set\", \"id\": UUID, \"path\": \"/transform/position/1\", \"value\": 2.0, \"expected\": 1.0}: expected is optional",
                "remove": "{\"op\": \"remove\", \"id\": UUID, \"path\": \"/collider\"}",
                "reparent": "{\"op\": \"reparent\", \"id\": UUID, \"parent\": UUID or null}",
                "duplicate": "{\"op\": \"duplicate\", \"id\": UUID, \"new_id\": UUID, \"name\": \"Copy\"}: one entity, no children; unnamed unless name is given",
                "delete": "{\"op\": \"delete\", \"id\": UUID, \"missing_ok\": true}: also deletes descendants; missing_ok skips a missing entity",
                "set_scene": "{\"op\": \"set_scene\", \"path\": \"/render/quality\", \"value\": \"High\"}: scene fields (name, render, simulation); expected is optional",
            },
            "errors": "SCENE_CONFLICT (revision or expected value differs), PATCH_OPERATION, PATCH_INVALID",
        },
        "scenario": {
            "file": "JSON object: name, seed (u64, default 0), ticks (last tick run), capture_size ([w, h], default [1280, 720]; the headless screen size from tick 0), files, steps",
            "files": "{\"files\": {\"saves/1.json\": \"fixtures/save.json\"}}: top-level; copies fixtures (relative to the scenario file) into the run's empty user data folder, build/test-userdata/<scenario>/, before tick 0",
            "tick_order": "Scenario tick N is the game's fixed tick N: game code sees time.fixed_tick == N in that tick's update. Within one tick: set, press, release and pointer steps apply first; then the game's update and the fixed physics step run; then expect, expect_events, expect_screen, log and capture steps and the invariants see the result. So an expect on the same tick as a set sees the value after that tick's update, not the value before the set; check the old value one tick earlier.",
            "audio": "\"entity\": \"audio:\" in expect, log and invariants reads {\"requested\": n, \"clips\": {\"<clip path>\": n}}: every sound game code and sound cues asked for, played or not (headless runs have no device). Escape `/` in a clip path as `~1`: /clips/sfx~1hit.wav. From an offline mix of those sounds it also reads level [l, r] (RMS over the last tick), peak [l, r] (largest sample that tick; 1.0 is full scale), clipped (samples at or over full scale since tick 0; expect it to equal 0 to catch clipping) and playing.",
            "counter": "In expect, set, log and invariants, {\"counter\": \"score\"} replaces entity and path: it names the entity holding the `rusting.counter` called `score` and defaults the path to /components/rusting.counter/value. Counters made by game code (`set_counter` or `add_to_counter` on a new name) work too.",
            "steps": {
                "press": "{\"tick\": 5, \"press\": \"player.jump\"}: press every input bound to the action before the tick's update; \"at\": 0.4 (press and tap) lands the press 40% into the tick, so scene.press_tick gives 5.4",
                "release": "{\"tick\": 6, \"release\": \"player.jump\"}",
                "tap": "{\"tick\": 5, \"tap\": \"pause\"}: presses the action and releases it before the next tick; egui sees the keys too, so Tab and Enter navigate menus",
                "left_stick": "{\"tick\": 5, \"left_stick\": [0.0, 1.0]}: tilts the gamepad's left stick (each axis -1..1, [0, 1] fully up) until another step moves it; past half tilt it also presses PadLeftStickUp and the other directions. right_stick works the same",
                "click": "{\"tick\": 2, \"click\": \"New Game\"}: moves the cursor to the topmost text the last frame drew with this exact label (egui widgets, HUD buttons, painted text) and clicks the left mouse button; fails listing the texts on screen when none matches. Object form {\"click\": {\"text\": \"-\", \"index\": 2}} or {\"click\": {\"starts_with\": \"Slot 1\"}}: starts_with matches a prefix; index (0-based) picks the nth match in reading order, top to bottom then left to right",
                "restart": "{\"tick\": 20, \"restart\": true}: reloads the starting scene; the user data folder keeps its files",
                "expect_quit": "{\"tick\": 31, \"expect_quit\": true}: the game called scene.quit() by this tick; the run ends after the tick that quits and steps at later ticks fail",
                "expect_file": "{\"tick\": 41, \"expect_file\": {\"path\": \"settings.cfg\", \"contains\": \"volume=60\"}}: a file in the user data folder; exists (default true) false checks it is absent; unlike other checks it also runs after the game quits",
                "pointer": "{\"tick\": 10, \"pointer\": [0.5, 0.5]}: moves the mouse cursor to this point of the view, as fractions of its width and height from the top-left corner",
                "expect": "{\"tick\": 30, \"until\": 60, \"expect\": {\"entity\": \"Cube\", \"path\": \"/transform/position/1\", \"less_than\": 0.0}}: JSON pointer into the entity's scene form; equals (with tolerance), not_equals (fails when equal within tolerance), greater_than, less_than, or exists (false once an entity is despawned; empty path means the whole entity); until: an absolute tick; the check must hold every tick from `tick` through it; within: an absolute tick; passes on the first tick from `tick` through it that holds",
                "expect_events": "{\"tick\": 60, \"expect_events\": {\"kind\": \"collision\", \"entity\": \"Cube\", \"at_least\": 1}}: events gameplay saw from tick 0",
                "expect_screen": "{\"tick\": 30, \"expect_screen\": {\"entity\": \"Coin\", \"on_screen\": true, \"inside\": [0.0, 0.0, 0.5, 1.0], \"min_share\": 0.01}}: where a mesh entity is in the active camera's frame (capture_size): on_screen, occluded (all of its box is behind other objects), inside (its box within the fractions [left, top, right, bottom]), min_share (share of the frame it is the nearest hit for); bounds picking; until and within work too. \"camera\": \"Cam 2\" projects through that camera instead, and inside and min_share are then fractions of its viewport",
                "expect_pixels": "{\"tick\": 30, \"expect_pixels\": {\"region\": [0.5, 0.0, 1.0, 1.0], \"mean_min\": [0, 0, 80], \"mean_max\": [60, 60, 255], \"stddev_min\": 2.0}}: mean sRGB [r, g, b] (0..255) and brightness standard deviation of a region of the frame (HUD included); region is [left, top, right, bottom] fractions, the whole frame by default; \"camera\" makes region relative to that camera's viewport; until and within work too; fails without Vulkan",
                "capture": "{\"tick\": 30, \"capture\": \"shots/tick30.png\"} or {\"capture\": {\"path\": \"shots/a.png\", \"camera\": \"Cam 2\", \"hud\": false, \"golden\": \"golden/a.png\", \"tolerance\": 1.0}}: path relative to the scenario file; camera renders that camera over the whole frame without the HUD; golden compares with that image: it fails when the largest of the R, G and B mean differences (0..255) is over tolerance (default 1.0), and `rusting test --update-golden` rewrites it; skipped without Vulkan",
                "log": "{\"tick\": 10, \"until\": 40, \"log\": {\"counter\": \"score\"}}: records the value (entity and path, or counter) in the report every tick through until; never fails",
                "set": "{\"tick\": 0, \"set\": {\"entity\": \"Player\", \"path\": \"/transform/position\", \"value\": [0.0, 1.0, -12.0]}}: writes before the tick runs; path under /transform, /visible, /rigid_body, /collider, /physics_body, /collision_layers, /point_light, /spot_light, /directional_light (the entity must already have it) or /components/<name>, for example /components/rusting.counter/value or /collider/friction",
            },
            "gpu": "{\"gpu\": true}: top-level; opens the headless Vulkan device so GPU bodies simulate and GPU events arrive in `rusting test`. A scenario with a `capture` step does this too, but without either the GPU bodies stay where they spawned and GPU rules never fire. Fails with `gpu: no Vulkan device` when none opens; software Vulkan (lavapipe) works but is slow",
            "invariants": "{\"invariants\": [{\"entity\": \"Player\", \"path\": \"/transform/position\", \"finite\": true}, {\"entity\": \"Player\", \"path\": \"/transform/position/1\", \"greater_than\": -5.0}]}: top-level; same fields as `expect` plus `finite` (no NaN or infinite number). Checked after every tick; the first tick one fails is reported as `invariant N:`. A missing entity or path passes unless `exists` is set",
            "budgets": "{\"budgets\": {\"p95_tick_ms\": 8.0, \"max_draws\": 200}}: top-level; each limit exceeded fails the run with a `budget:` step. Timing is wall-clock and machine-dependent: set headroom and read `perf.environment` (engine version, OS, arch, debug or release, device) in `rusting test --json`. Draw and triangle limits need a capture step and Vulkan",
            "tick_length_seconds": 1.0 / 60.0,
        },
    })
}

#[cfg(test)]
mod tests {
    #[test]
    fn touched_reports_project_writes_but_not_reads_dry_runs_or_failures() {
        let words = |line: &str| -> Vec<String> {
            line.split(' ').map(str::to_owned).collect()
        };
        let disk =
            |line: &str, ok| super::touched(&words(line), ok)["disk"].as_bool();
        assert_eq!(disk("scene patch a.json p.json", true), Some(true));
        assert_eq!(
            disk("scene patch a.json --dry-run p.json", true),
            Some(false)
        );
        assert_eq!(disk("scene patch a.json p.json", false), Some(false));
        assert_eq!(disk("scene query a.json", true), Some(false));
        assert_eq!(disk("fix . --json", true), Some(true));
        let all = super::touched(&words("test ."), true);
        assert_eq!(
            (all["editor"].as_bool(), all["game"].as_bool()),
            (Some(false), Some(false))
        );
    }

    use std::collections::BTreeSet;

    use super::*;
    use crate::runtime::{
        load_scene_document, set_registered_component, SceneDocument,
        SceneLoadMode, CONNECTIONS_COMPONENT, SCENE_INSTANCE_COMPONENT,
    };

    fn schema_keys(schema: &Value) -> BTreeSet<String> {
        schema["properties"]
            .as_object()
            .unwrap()
            .keys()
            .cloned()
            .collect()
    }

    fn written_keys(value: &impl serde::Serialize) -> BTreeSet<String> {
        serde_json::to_value(value)
            .unwrap()
            .as_object()
            .unwrap()
            .keys()
            .cloned()
            .collect()
    }

    #[test]
    fn json_schemas_describe_every_key_the_engine_writes() {
        let schemas = json_schemas();
        // Every schema key must be known to serde; every written key must be
        // in the schema.
        let scene = SceneDocument {
            format_version: 0,
            name: String::new(),
            entities: Vec::new(),
            render: Default::default(),
            simulation: Default::default(),
        };
        assert_eq!(written_keys(&scene), schema_keys(&schemas["scene"]));
        let scenario: crate::scenario::Scenario =
            serde_json::from_value(json!({"name": "n", "ticks": 1})).unwrap();
        assert_eq!(written_keys(&scenario), schema_keys(&schemas["scenario"]));
        let patch = crate::scene_patch::ScenePatch::default();
        assert_eq!(written_keys(&patch), schema_keys(&schemas["scene_patch"]));
        let project = crate::project::ProjectManifest {
            format_version: 1,
            name: "n".into(),
            main_scene: "a".into(),
            cooked_scene: "b".into(),
            binary_name: String::new(),
            generators: Default::default(),
            determinism: Default::default(),
        };
        let mut keys = written_keys(&project);
        keys.extend(["generators".to_owned(), "determinism".to_owned()]);
        assert_eq!(keys, schema_keys(&schemas["project"]));
        for name in
            ["scene", "scene_patch", "scenario", "project", "asset_meta"]
        {
            assert_eq!(schemas[name]["$schema"], JSON_SCHEMA_DRAFT, "{name}");
        }
    }

    #[test]
    fn json_schema_patch_operations_match_the_parser() {
        let schemas = json_schemas();
        let ops = schemas["scene_patch"]["properties"]["operations"]["items"]
            ["oneOf"]
            .as_array()
            .unwrap();
        for op in ops {
            let name = op["properties"]["op"]["const"].as_str().unwrap();
            // A patch naming only `op` must fail for a missing field, not for
            // an unknown operation.
            let error = serde_json::from_value::<
                crate::scene_patch::PatchOperation,
            >(json!({"op": name}))
            .unwrap_err()
            .to_string();
            assert!(!error.contains("unknown variant"), "{name}: {error}");
        }
        assert_eq!(ops.len(), 8);
    }

    #[test]
    fn json_schema_entity_lists_every_section_and_component() {
        let schemas = json_schemas();
        let entity = &schemas["scene"]["properties"]["entities"]["items"];
        let keys = schema_keys(entity);
        for section in ENTITY_SECTIONS {
            assert!(keys.contains(section.key), "{}", section.key);
        }
        let components = schema_keys(&entity["properties"]["components"]);
        for section in COMPONENT_SECTIONS {
            assert!(components.contains(section.key), "{}", section.key);
        }
    }

    /// JSON pointers of every leaf. Arrays are leaves.
    fn leaves(value: &Value, prefix: String, out: &mut BTreeSet<String>) {
        match value {
            Value::Object(map) if !map.is_empty() => {
                for (key, value) in map {
                    leaves(value, format!("{prefix}/{key}"), out);
                }
            }
            _ => {
                out.insert(prefix);
            }
        }
    }

    /// Whether `path` is `pattern`, or under it when `prefix` is set, with
    /// `*` in the pattern matching any one segment.
    fn matches(pattern: &str, path: &str, prefix: bool) -> bool {
        let mut pattern = pattern.split('/');
        let mut path = path.split('/');
        loop {
            match (pattern.next(), path.next()) {
                (None, None) => return true,
                (None, Some(_)) => return prefix,
                (Some(_), None) => return false,
                (Some(wanted), Some(segment)) => {
                    if wanted != "*" && wanted != segment {
                        return false;
                    }
                }
            }
        }
    }

    /// Every saved leaf is documented, and every documented path has a
    /// saved leaf at or under it in the example or the default.
    fn check_fields(
        key: &str,
        documented: &[String],
        example: &Value,
        default: Option<&Value>,
    ) {
        let mut saved = BTreeSet::new();
        leaves(example, String::new(), &mut saved);
        if let Some(default) = default.filter(|value| !value.is_null()) {
            leaves(default, String::new(), &mut saved);
        }
        saved.remove("");
        for path in &saved {
            assert!(
                documented
                    .iter()
                    .any(|pattern| matches(pattern, path, false)),
                "{key}{path} is saved but not documented"
            );
        }
        // Fields of an enum variant the example does not use have no
        // saved parent, so only fields under a saved parent must be saved.
        let parent_saved = |pattern: &String| {
            pattern.rsplit_once('/').is_none_or(|(parent, _)| {
                parent.is_empty()
                    || saved.iter().any(|path| matches(parent, path, true))
            })
        };
        for pattern in documented
            .iter()
            .filter(|path| !path.is_empty() && parent_saved(path))
        {
            assert!(
                saved.iter().any(|path| matches(pattern, path, true)),
                "{key}{pattern} is documented but not saved"
            );
        }
    }

    fn documented(section: &Section) -> Vec<String> {
        section
            .fields
            .iter()
            .map(|field| field.path.to_owned())
            .collect()
    }

    #[test]
    fn every_saved_field_is_documented_and_every_section_is_listed() {
        let (entity, components) = defaults();
        let listed: BTreeSet<_> =
            ENTITY_SECTIONS.iter().map(|section| section.key).collect();
        let saved: BTreeSet<_> = entity.keys().map(String::as_str).collect();
        assert_eq!(listed, saved, "entity sections and saved keys differ");
        for section in ENTITY_SECTIONS {
            check_fields(
                section.key,
                &documented(section),
                &(section.example)(),
                entity.get(section.key),
            );
        }
        let mut app = App::new();
        app.add_plugin(AssetPlugin).unwrap();
        let registered = registered_component_names(app.world());
        let mut listed: Vec<_> = COMPONENT_SECTIONS
            .iter()
            .map(|section| section.key)
            .collect();
        listed.sort_unstable();
        assert_eq!(listed, registered, "catalog and component registry differ");
        let registry = SceneComponentRegistry::default();
        for section in COMPONENT_SECTIONS {
            let fields = reflected_fields(registry.info(section.key).unwrap());
            let paths: Vec<String> = fields
                .iter()
                .map(|field| field["path"].as_str().unwrap().to_owned())
                .collect();
            check_fields(
                section.key,
                &paths,
                &(section.example)(),
                components.get(section.key),
            );
        }
    }

    #[test]
    fn examples_load_through_the_scene_parser_and_registry_unchanged() {
        let mut entity: Map<String, Value> = ENTITY_SECTIONS
            .iter()
            .map(|section| (section.key.to_owned(), (section.example)()))
            .collect();
        // The instance example names a file that does not exist here, and
        // the connections example a handler and an object.
        let components: Map<String, Value> = COMPONENT_SECTIONS
            .iter()
            .filter(|section| {
                ![SCENE_INSTANCE_COMPONENT, CONNECTIONS_COMPONENT]
                    .contains(&section.key)
            })
            .map(|section| {
                let text = (section.example)().to_string();
                (section.key.to_owned(), Value::String(text))
            })
            .collect();
        entity.insert("components".into(), Value::Object(components));
        let document: SceneDocument = serde_json::from_value(json!({
            "format_version": SCENE_FORMAT_VERSION,
            "name": "examples",
            "entities": [entity],
        }))
        .expect("examples parse as a scene");

        let mut app = App::new();
        app.add_plugin(AssetPlugin).unwrap();
        let world = app.world_mut();
        load_scene_document(world, &document, SceneLoadMode::Replace)
            .expect("examples load");
        let saved = scene_document(world, "examples").unwrap();
        let mut saved = serde_json::to_value(&saved.entities[0]).unwrap();
        let mut expected = serde_json::to_value(&document.entities[0]).unwrap();
        // Compare components as values: field order may differ.
        for value in [&mut saved, &mut expected] {
            for component in
                value["components"].as_object_mut().unwrap().values_mut()
            {
                *component =
                    serde_json::from_str(component.as_str().unwrap()).unwrap();
            }
        }
        assert_eq!(saved, expected);

        // Each component example also restores alone through the registry.
        let entity = world.spawn(SceneId(Uuid::new_v4())).id();
        for section in COMPONENT_SECTIONS {
            set_registered_component(
                world,
                entity,
                section.key,
                &(section.example)().to_string(),
            )
            .unwrap_or_else(|error| panic!("{}: {error}", section.key));
        }
    }

    #[test]
    fn catalog_lists_every_operation_with_defaults_and_cost() {
        let catalog = catalog();
        let operations = catalog["operations"].as_array().unwrap();
        assert_eq!(operations.len(), OPERATIONS.len());
        for operation in operations {
            assert!(operation["gpu_cost"]
                .as_str()
                .is_some_and(|c| !c.is_empty()));
            assert!(operation["example"].as_str().unwrap().starts_with(
                &format!("rusting {}", operation["name"].as_str().unwrap())
            ));
        }
        let camera = &catalog["scene"]["entity_sections"]
            .as_array()
            .unwrap()
            .iter()
            .find(|section| section["key"] == "camera")
            .unwrap()["default"];
        assert_eq!(camera["active"], false);
        let player = catalog["scene"]["components"]
            .as_array()
            .unwrap()
            .iter()
            .find(|section| section["key"] == "rusting.player_controller")
            .unwrap();
        assert_eq!(player["default"]["walk_speed"], 4.0);
        let pitch = player["fields"]
            .as_array()
            .unwrap()
            .iter()
            .find(|field| field["path"] == "/pitch")
            .unwrap();
        assert_eq!(pitch["range"], "-1.55..1.55");
        assert_eq!(pitch["unit"], "rad");
        let tiles = catalog["scene"]["components"]
            .as_array()
            .unwrap()
            .iter()
            .find(|section| section["key"] == "rusting.tile_map")
            .unwrap();
        assert!(tiles["fields"]
            .as_array()
            .unwrap()
            .iter()
            .any(|field| field["path"] == "/tiles/*/solid"));
        let resources = catalog["resources"].as_array().unwrap();
        assert!(resources
            .iter()
            .any(|resource| resource["key"] == "rusting.render_settings"));
        let material = &catalog["asset_types"][0];
        assert_eq!(material["key"], "rusting.material");
        assert!(material["fields"]
            .as_array()
            .unwrap()
            .iter()
            .any(|field| field["path"] == "/alpha_mode/Mask/cutoff"));
    }
}