concinnity-dev 0.19.53

The Concinnity dev tooling library: world authoring, the in-engine editor, the debug server, docs and packaging
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
//! Runtime decal / emitter / screenshot spawn queue + dispatch (`cn debug`
//! only). Both halves live here so the engine never compiles them:
//!
//!   queue     a process-wide command queue the debug tool calls push onto
//!             (`enqueue`) and the per-frame debug drive drains (`drain`).
//!   dispatch  `dispatch_runtime_spawn` applies a `BackendCommand` against the live
//!             backend + the init-captured texture-name table, and
//!             `dispatch_world_command` applies a `WorldCommand` against the ECS,
//!             both run by `DebugServer::drive_runtime_commands`.
//!
//! The debug endpoint pushes commands off the engine thread; the drive applies them
//! at frame start on the main thread. Each command carries a reply channel so
//! the tool call can hand the new stable slot index back to its client
//! synchronously: the wait is bounded by one frame (~16 ms at 60 Hz). `cn run`
//! has no debug hook and never reaches any of this.

use concinnity_core::components::Camera3D;
use concinnity_core::components::DespawnRequest;
use concinnity_core::components::InputKey;
use concinnity_core::components::ReparentRequest;
use concinnity_core::components::SettingCommand;
use concinnity_core::components::SettingOp;
use concinnity_core::components::SpawnRequest;
use concinnity_core::components::StoryCommand;
use concinnity_core::components::Transform;
use concinnity_core::ecs::World;
use concinnity_core::ecs::asset_id::AssetId;
use concinnity_core::gfx::camera;
use concinnity_core::input::keymap::Bindable;
use concinnity_core::render::backend;
use concinnity_core::render::decal;
use concinnity_core::render::particles;
use concinnity_core::settings::SettingKey;
use concinnity_engine::controller::camera::Camera3DSystem;
use concinnity_engine::gfx::system::parked::TextureNameSlots;
use concinnity_host::thread::asset_id;
use std::sync::Mutex;

// A runtime decal-spawn request. `texture` is the world.jsonl name of the
// Texture asset to project; `None` (or an unresolvable name) falls back to
// the renderer's white slot 0 so the tint still stamps. Geometry is the
// same TRS triple the [`concinnity_core::components::Decal`] component carries.
#[derive(Debug, Clone)]
pub(crate) struct DecalSpawnArgs {
    pub texture: Option<String>,
    pub position: [f32; 3],
    pub rotation_deg: [f32; 3],
    pub size: [f32; 3],
    pub tint: [f32; 4],
}

impl Default for DecalSpawnArgs {
    fn default() -> Self {
        Self {
            texture: None,
            position: [0.0, 0.0, 0.0],
            rotation_deg: [0.0, 0.0, 0.0],
            size: [1.0, 1.0, 1.0],
            tint: [1.0, 1.0, 1.0, 1.0],
        }
    }
}

// A runtime emitter-spawn request. Same field shape as the
// [`concinnity_core::components::ParticleEmitter`] asset; the engine clamps + normalizes
// via [`concinnity_core::render::particles::build_particle_records`].
#[derive(Debug, Clone)]
pub(crate) struct EmitterSpawnArgs {
    pub texture: Option<String>,
    pub position: [f32; 3],
    pub direction: [f32; 3],
    pub spread_deg: f32,
    pub speed_min: f32,
    pub speed_max: f32,
    pub lifetime_min: f32,
    pub lifetime_max: f32,
    pub gravity: [f32; 3],
    pub spawn_rate: f32,
    pub max_particles: u32,
    pub size_start: f32,
    pub size_end: f32,
    pub color_start: [f32; 4],
    pub color_end: [f32; 4],
}

impl Default for EmitterSpawnArgs {
    fn default() -> Self {
        Self {
            texture: None,
            position: [0.0, 0.0, 0.0],
            direction: [0.0, 1.0, 0.0],
            spread_deg: 15.0,
            speed_min: 1.0,
            speed_max: 2.0,
            lifetime_min: 1.0,
            lifetime_max: 2.0,
            gravity: [0.0, -9.8, 0.0],
            spawn_rate: 32.0,
            max_particles: 256,
            size_start: 0.2,
            size_end: 0.05,
            color_start: [1.0, 1.0, 1.0, 1.0],
            color_end: [1.0, 1.0, 1.0, 0.0],
        }
    }
}

// A runtime camera-set request: a new pose for the active `Camera3D`. `yaw` /
// `pitch` are radians (the controller's own convention); `fov_y_degrees` is
// `None` to leave the field untouched. Applied against the live ECS, not the
// backend, so it carries no texture/slot fields.
#[derive(Debug, Clone)]
pub(crate) struct CameraSetArgs {
    pub position: [f32; 3],
    pub yaw: f32,
    pub pitch: f32,
    pub fov_y_degrees: Option<f32>,
}

impl Default for CameraSetArgs {
    fn default() -> Self {
        Self {
            position: [0.0, 0.0, 0.0],
            yaw: 0.0,
            pitch: 0.0,
            fov_y_degrees: None,
        }
    }
}

// A runtime camera-move request: a per-frame pose delta applied to the active
// `Camera3D` for a span of frames, so the renderer sees sustained motion (TAA
// ghosting, SSGI temporal noise, motion blur) that a one-shot `camera-set`
// teleport never produces. `forward` / `right` / `up` are per-frame position
// offsets (world units) along the free-fly look basis; `yaw` / `pitch` are
// per-frame radian deltas. `frames == 0` holds the motion indefinitely until a
// `camera-stop` command clears it; `frames > 0` applies it for exactly that
// many frames then auto-stops.
#[derive(Debug, Clone)]
pub(crate) struct CameraMoveArgs {
    pub forward: f32,
    pub right: f32,
    pub up: f32,
    pub yaw: f32,
    pub pitch: f32,
    pub frames: u32,
}

impl Default for CameraMoveArgs {
    fn default() -> Self {
        Self {
            forward: 0.0,
            right: 0.0,
            up: 0.0,
            yaw: 0.0,
            pitch: 0.0,
            frames: 0,
        }
    }
}

// An in-progress camera-move the per-frame debug drive applies to the active
// `Camera3D` each tick. Built from [`CameraMoveArgs`] when a `camera-move`
// command is drained; held on the `DebugServer` (main-thread only) and
// advanced once per frame until exhausted or a `camera-stop` clears it.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct CameraMotion {
    pub forward: f32,
    pub right: f32,
    pub up: f32,
    pub yaw: f32,
    pub pitch: f32,
    // Frames still to apply. `None` is an indefinite hold (cleared only by
    // `camera-stop`); `Some(n)` counts down to the auto-stop.
    pub frames_left: Option<u32>,
}

impl CameraMotion {
    // Build a motion from a drained `camera-move` request. `frames == 0` maps
    // to an indefinite hold.
    pub(crate) fn from_args(args: &CameraMoveArgs) -> Self {
        Self {
            forward: args.forward,
            right: args.right,
            up: args.up,
            yaw: args.yaw,
            pitch: args.pitch,
            frames_left: if args.frames == 0 {
                None
            } else {
                Some(args.frames)
            },
        }
    }

    // The motion to apply next frame, after one step has just been applied: a
    // finite countdown decremented by one (returning `None` once exhausted),
    // an indefinite hold returning itself unchanged.
    pub(crate) fn advanced(self) -> Option<Self> {
        match self.frames_left {
            None => Some(self),
            Some(n) if n > 1 => Some(Self {
                frames_left: Some(n - 1),
                ..self
            }),
            Some(_) => None,
        }
    }
}

// Compute the pose after applying one camera-move step to a free-fly camera at
// the given pose. `forward` / `right` follow the look-direction basis (matching
// `Camera3DSystem`'s free-fly mode); `up` is world up. Pitch is clamped to the
// same near-vertical limit the controller uses so a sustained pitch delta can
// not flip the camera over.
pub(crate) fn advance_pose(
    position: [f32; 3],
    yaw: f32,
    pitch: f32,
    motion: &CameraMotion,
) -> ([f32; 3], f32, f32) {
    let cp = pitch.cos();
    let fwd = [-yaw.sin() * cp, pitch.sin(), -yaw.cos() * cp];
    let right = [yaw.cos(), 0.0, -yaw.sin()];
    let new_pos = [
        position[0] + fwd[0] * motion.forward + right[0] * motion.right,
        position[1] + fwd[1] * motion.forward + motion.up,
        position[2] + fwd[2] * motion.forward + right[2] * motion.right,
    ];
    let new_yaw = yaw + motion.yaw;
    let new_pitch = (pitch + motion.pitch).clamp(
        -std::f32::consts::FRAC_PI_2 + 0.01,
        std::f32::consts::FRAC_PI_2 - 0.01,
    );
    (new_pos, new_yaw, new_pitch)
}

// A runtime command applied against the live backend. Each variant carries a
// `std::sync::mpsc::SyncSender` reply channel so the tool call can block (with
// timeout) on the result and hand a JSON reply back to its client.
pub(crate) enum BackendCommand {
    DecalAdd {
        args: DecalSpawnArgs,
        reply: std::sync::mpsc::SyncSender<Result<usize, String>>,
    },
    DecalRemove {
        id: usize,
        reply: std::sync::mpsc::SyncSender<Result<(), String>>,
    },
    EmitterAdd {
        args: EmitterSpawnArgs,
        reply: std::sync::mpsc::SyncSender<Result<usize, String>>,
    },
    EmitterRemove {
        id: usize,
        reply: std::sync::mpsc::SyncSender<Result<(), String>>,
    },
    // Capture the last presented frame to a PNG at `path`; replies the saved path.
    Screenshot {
        path: String,
        reply: std::sync::mpsc::SyncSender<Result<String, String>>,
    },
    // Read back one `CullStatus` value per live GPU cull record.
    CullStatus {
        reply: std::sync::mpsc::SyncSender<Result<Vec<u32>, String>>,
    },
}

// A runtime command applied against the ECS, or the debug server's camera-motion
// slot, once the per-frame drive has released the systems borrow. Replies like
// [`BackendCommand`].
pub(crate) enum WorldCommand {
    // Teleport the active `Camera3D` to a new pose.
    CameraSet {
        args: CameraSetArgs,
        reply: std::sync::mpsc::SyncSender<Result<(), String>>,
    },
    // Install a sustained camera motion; replies on acceptance, not completion.
    CameraMove {
        args: CameraMoveArgs,
        reply: std::sync::mpsc::SyncSender<Result<(), String>>,
    },
    // Clear any in-progress camera motion.
    CameraStop {
        reply: std::sync::mpsc::SyncSender<Result<(), String>>,
    },
    // Step a Quality-group graphics setting through the settings menu's command.
    QualitySet {
        setting: SettingKey,
        op: SettingOp,
        reply: std::sync::mpsc::SyncSender<Result<(), String>>,
    },
    // Bind a movement action to a key.
    Rebind {
        action: Bindable,
        key: InputKey,
        reply: std::sync::mpsc::SyncSender<Result<(), String>>,
    },
    // Despawn an authored placement and its descendants by name.
    Despawn {
        name: String,
        reply: std::sync::mpsc::SyncSender<Result<(), String>>,
    },
    // Re-parent an authored placement by name; a `None` parent detaches it.
    Reparent {
        child: String,
        parent: Option<String>,
        reply: std::sync::mpsc::SyncSender<Result<(), String>>,
    },
    // Spawn a copy of `template` under `name`, auto-despawning after `lifetime`.
    Spawn {
        template: String,
        name: String,
        position: [f32; 3],
        rotation_deg: [f32; 3],
        scale: [f32; 3],
        lifetime: Option<f32>,
        reply: std::sync::mpsc::SyncSender<Result<(), String>>,
    },
    // Fire the `StoryCommand` a stage click or key press would.
    Story {
        command: StoryCommand,
        reply: std::sync::mpsc::SyncSender<Result<(), String>>,
    },
}

// One queued runtime command, split by what the per-frame drive applies it to.
pub(crate) enum RuntimeCommand {
    Backend(BackendCommand),
    World(WorldCommand),
}

impl From<BackendCommand> for RuntimeCommand {
    fn from(cmd: BackendCommand) -> Self {
        Self::Backend(cmd)
    }
}

impl From<WorldCommand> for RuntimeCommand {
    fn from(cmd: WorldCommand) -> Self {
        Self::World(cmd)
    }
}

static QUEUE: Mutex<Vec<RuntimeCommand>> = Mutex::new(Vec::new());

// Push a command onto the runtime-spawn queue. Returns immediately; the
// caller blocks on its own reply receiver to get the result. A poisoned
// mutex is recovered and used regardless (an unrelated panic in another
// thread must not silently drop spawn commands).
pub(crate) fn enqueue(cmd: impl Into<RuntimeCommand>) {
    let mut q = match QUEUE.lock() {
        Ok(g) => g,
        Err(poisoned) => poisoned.into_inner(),
    };
    q.push(cmd.into());
}

// Take every queued command. Called by the `cn debug` drive
// (`DebugHook::tick`) at frame start. The returned `Vec` is the live list:
// the queue is reset to empty.
pub(crate) fn drain() -> Vec<RuntimeCommand> {
    let mut q = match QUEUE.lock() {
        Ok(g) => g,
        Err(poisoned) => poisoned.into_inner(),
    };
    std::mem::take(&mut *q)
}

// Process one runtime-spawn command (drained from the debug command queue)
// against the live backend. Resolves texture-name strings via the init-time
// interner snapshot + the parked `TextureNameSlots` before building
// the backend record, and sends the result back via the command's reply
// channel. Reply-channel send failures are silently dropped: the connection thread
// may have already given up waiting (e.g. its client disconnected), and
// that is not a renderer error.
pub(crate) fn dispatch_runtime_spawn(
    cmd: BackendCommand,
    texture_slots: Option<&TextureNameSlots>,
    backend: &mut dyn backend::RenderBackend,
) {
    match cmd {
        BackendCommand::DecalAdd { args, reply } => {
            let result = resolve_texture_slot(args.texture.as_deref(), texture_slots)
                .and_then(|slot| {
                    let model =
                        decal::decal_model_matrix(args.position, args.rotation_deg, args.size);
                    let inv_model = decal::invert_decal_model(model)
                        .ok_or_else(|| "decal-add: degenerate size".to_string())?;
                    Ok(decal::DecalRecord {
                        model,
                        inv_model,
                        texture_slot: slot,
                        tint: args.tint,
                    })
                })
                .and_then(|rec| backend.add_decal(rec).map_err(|e| e.to_string()));
            let _ = reply.send(result);
        }
        BackendCommand::DecalRemove { id, reply } => {
            let _ = reply.send(backend.remove_decal(id).map_err(|e| e.to_string()));
        }
        BackendCommand::EmitterAdd { args, reply } => {
            let result = resolve_texture_slot(args.texture.as_deref(), texture_slots)
                .map(|slot| {
                    // Mirror the clamp / normalize rules used by
                    // `build_particle_records` so a tool-call-spawned emitter and
                    // an authored one behave identically. We do not call
                    // that helper directly because it takes a
                    // `&[&ParticleEmitter]` and a texture-id-keyed map;
                    // here we already have a resolved slot.
                    let dir = {
                        let d = args.direction;
                        let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
                        if !len.is_finite() || len < 1e-6 {
                            [0.0, 1.0, 0.0]
                        } else {
                            [d[0] / len, d[1] / len, d[2] / len]
                        }
                    };
                    let spread_cos = args.spread_deg.clamp(0.0, 180.0).to_radians().cos();
                    let lifetime_min = args.lifetime_min.max(0.001);
                    let lifetime_max = args.lifetime_max.max(lifetime_min);
                    let speed_min = args.speed_min.max(0.0);
                    let speed_max = args.speed_max.max(speed_min);
                    let max_particles = args
                        .max_particles
                        .clamp(1, particles::MAX_PARTICLES_PER_EMITTER);
                    particles::ParticleEmitterRecord {
                        texture_slot: slot,
                        position: args.position,
                        direction: dir,
                        spread_cos,
                        speed_min,
                        speed_max,
                        lifetime_min,
                        lifetime_max,
                        gravity: args.gravity,
                        spawn_rate: args.spawn_rate.max(0.0),
                        max_particles,
                        size_start: args.size_start.max(0.0),
                        size_end: args.size_end.max(0.0),
                        color_start: args.color_start,
                        color_end: args.color_end,
                    }
                })
                .and_then(|rec| backend.add_emitter(rec).map_err(|e| e.to_string()));
            let _ = reply.send(result);
        }
        BackendCommand::EmitterRemove { id, reply } => {
            let _ = reply.send(backend.remove_emitter(id).map_err(|e| e.to_string()));
        }
        BackendCommand::Screenshot { path, reply } => {
            let _ = reply.send(backend.screenshot(&path).map_err(|e| e.to_string()));
        }
        BackendCommand::CullStatus { reply } => {
            let _ = reply.send(backend.read_cull_status().map_err(|e| e.to_string()));
        }
    }
}

// Apply a drained world command and reply. The setting, despawn, reparent,
// spawn and story commands send the same events the settings menu and gameplay
// systems emit, so the next world step applies them through the real paths; the
// reply fires once the event is queued, and an unknown name is a clean error.
// camera-move and camera-stop install or clear `motion`, which the debug drive
// advances once per frame.
pub(crate) fn dispatch_world_command(
    cmd: WorldCommand,
    world: &mut World,
    motion: &mut Option<CameraMotion>,
) {
    match cmd {
        WorldCommand::CameraSet { args, reply } => {
            let _ = reply.send(apply_camera_set(&args, world));
        }
        WorldCommand::CameraMove { args, reply } => {
            let result = if world.query::<Camera3D>().next().is_some() {
                *motion = Some(CameraMotion::from_args(&args));
                Ok(())
            } else {
                Err("camera-move: no Camera3D in world".to_string())
            };
            let _ = reply.send(result);
        }
        WorldCommand::CameraStop { reply } => {
            *motion = None;
            let _ = reply.send(Ok(()));
        }
        WorldCommand::QualitySet { setting, op, reply } => {
            send_setting(world, setting, op);
            let _ = reply.send(Ok(()));
        }
        WorldCommand::Rebind { action, key, reply } => {
            send_setting(world, SettingKey::KeyRebind(action), SettingOp::Rebind(key));
            let _ = reply.send(Ok(()));
        }
        WorldCommand::Despawn { name, reply } => {
            let result = asset_id::lookup(&name)
                .ok_or_else(|| format!("despawn: name '{name}' not found"))
                .map(|id| {
                    world
                        .events_mut::<DespawnRequest>()
                        .send(DespawnRequest { target: id.into() });
                });
            let _ = reply.send(result);
        }
        WorldCommand::Reparent {
            child,
            parent,
            reply,
        } => {
            let _ = reply.send(reparent_by_name(world, &child, parent.as_deref()));
        }
        WorldCommand::Spawn {
            template,
            name,
            position,
            rotation_deg,
            scale,
            lifetime,
            reply,
        } => {
            let result = spawn_ids(&template, &name).map(|template_id| {
                // A zero scale (the array default when the request omits it)
                // would make the instance invisible; treat it as unit scale.
                let scale = if scale == [0.0; 3] { [1.0; 3] } else { scale };
                world.events_mut::<SpawnRequest>().send(SpawnRequest {
                    template: template_id,
                    name: Some(asset_id::intern(&name)),
                    transform: Transform {
                        position,
                        rotation_deg,
                        scale,
                    },
                    lifetime_secs: lifetime,
                });
            });
            let _ = reply.send(result);
        }
        WorldCommand::Story { command, reply } => {
            world.events_mut::<StoryCommand>().send(command);
            let _ = reply.send(Ok(()));
        }
    }
}

// Resolve a spawn's template to its id, refusing a new-instance name some
// asset is already known by: interning it would hand back that asset's id.
fn spawn_ids(template: &str, name: &str) -> Result<AssetId, String> {
    let template_id = asset_id::lookup(template)
        .ok_or_else(|| format!("spawn: template '{template}' not found"))?;
    if asset_id::lookup(name).is_some() {
        return Err(format!("spawn: '{name}' already names an asset"));
    }
    Ok(template_id)
}

// Send the `SettingCommand` the settings menu emits. `GraphicsSystem` applies it
// live on its next step and refreshes the value label itself.
fn send_setting(world: &mut World, setting: SettingKey, op: SettingOp) {
    world.events_mut::<SettingCommand>().send(SettingCommand {
        setting,
        op,
        value_label: None,
        persist: true,
    });
}

// Resolve the child and optional parent names and queue a `ReparentRequest`.
fn reparent_by_name(world: &mut World, child: &str, parent: Option<&str>) -> Result<(), String> {
    let child_id =
        asset_id::lookup(child).ok_or_else(|| format!("reparent: child '{child}' not found"))?;
    let parent_id = parent
        .map(|p| asset_id::lookup(p).ok_or_else(|| format!("reparent: parent '{p}' not found")))
        .transpose()?;
    world.events_mut::<ReparentRequest>().send(ReparentRequest {
        child: child_id.into(),
        parent: parent_id.map(Into::into),
    });
    Ok(())
}

// Write a new pose onto the active `Camera3D` and zero the controller velocity.
// The free-fly controller integrates a smoothed velocity onto the camera
// position every step, so a leftover velocity (or held key) would drift the
// teleport away on the next step; zeroing it makes the new pose hold. The
// debug tick runs before the world step, so the controller sees the new pose
// the same frame, and with velocity zeroed (and no input in an unfocused
// window) it leaves it untouched.
pub(crate) fn apply_camera_set(args: &CameraSetArgs, world: &mut World) -> Result<(), String> {
    let Some(camera) = world.query_mut::<Camera3D>().next() else {
        return Err("camera-set: no Camera3D in world".to_string());
    };
    camera.position = args.position;
    camera.yaw = args.yaw;
    camera.pitch = args.pitch;
    if let Some(fov) = args.fov_y_degrees {
        camera.fov_y_degrees = fov;
    }
    camera.view_matrix = camera::view_matrix(camera.position, camera.yaw, camera.pitch);

    for system in world.systems_mut() {
        if let Some(c) = system.downcast_mut::<Camera3DSystem>() {
            c.reset_velocity();
        }
    }
    Ok(())
}

// Apply one camera-move step against the live ECS: advance the active
// `Camera3D`'s pose by the motion deltas, refresh its view matrix, and zero the
// controller velocity (same reason as `apply_camera_set`: keep free-fly from
// fighting the externally driven pose). Returns `false` when the world has no
// `Camera3D`, so the caller drops the motion instead of spinning forever.
pub(crate) fn apply_camera_move_step(motion: &CameraMotion, world: &mut World) -> bool {
    let Some(camera) = world.query_mut::<Camera3D>().next() else {
        return false;
    };
    let (pos, yaw, pitch) = advance_pose(camera.position, camera.yaw, camera.pitch, motion);
    camera.position = pos;
    camera.yaw = yaw;
    camera.pitch = pitch;
    camera.view_matrix = camera::view_matrix(pos, yaw, pitch);

    for system in world.systems_mut() {
        if let Some(c) = system.downcast_mut::<Camera3DSystem>() {
            c.reset_velocity();
        }
    }
    true
}

// Resolve an optional Texture asset name to its pool slot index. `None` (no
// texture authored on the spawn request) maps to slot 0 (the renderer's
// white fallback) so the tint / color gradient still stamps. An unknown
// name returns `Err`; the MCP client gets a clear error rather than a
// silent fallback. Texture-name resolution leans on the init-parked
// `TextureNameSlots` snapshot, so it only succeeds under
// `cn debug` worlds: that matches the current runtime-spawn use case
// (debug tool calls, headless tests).
fn resolve_texture_slot(
    texture: Option<&str>,
    texture_slots: Option<&TextureNameSlots>,
) -> Result<usize, String> {
    let Some(name) = texture else {
        return Ok(0);
    };
    let id = asset_id::lookup(name)
        .ok_or_else(|| format!("texture '{}' not found in interner", name))?;
    let slots = texture_slots.ok_or_else(|| {
        "texture-name resolution requires cn debug (texture-name slots not captured)".to_string()
    })?;
    slots
        .0
        .get(&id)
        .copied()
        .ok_or_else(|| format!("texture '{}' is not in the live texture pool", name))
}

#[cfg(test)]
mod tests {

    // A spawn resolves its template by handle, labels included, and refuses a
    // new name that an asset is already known by.
    #[test]
    fn spawn_ids_resolve_the_template_and_refuse_a_taken_name() {
        asset_id::reset_interner();
        asset_id::prime_name_table(&[(0, "crate".to_string()), (1, "Prop#0".to_string())]);
        assert_eq!(spawn_ids("Prop#0", "crate_copy"), Ok(AssetId(1)));
        assert!(spawn_ids("ghost", "x").unwrap_err().contains("not found"));
        assert!(
            spawn_ids("crate", "Prop#0")
                .unwrap_err()
                .contains("already names")
        );
    }

    use super::*;
    use crate::debug::test_backend::StubBackend;
    use crate::test_support;
    use concinnity_core::components::Camera3D;
    use concinnity_core::ecs::EventCursor;
    use concinnity_core::ecs::asset_id::AssetId;

    #[test]
    fn enqueue_drain_round_trip() {
        // The command queue is a process-global static; serialize against the
        // other queue tests so a concurrent drain cannot steal our commands.
        let _guard = test_support::lock();
        // Drain any leftovers from a panicked earlier test in this process.
        let _ = drain();
        let (tx, _rx) = std::sync::mpsc::sync_channel(1);
        enqueue(BackendCommand::DecalRemove { id: 7, reply: tx });
        let cmds = drain();
        assert_eq!(cmds.len(), 1);
        match cmds.into_iter().next().unwrap() {
            RuntimeCommand::Backend(BackendCommand::DecalRemove { id, .. }) => assert_eq!(id, 7),
            _ => panic!("wrong variant"),
        }
        // Second drain is empty.
        assert!(drain().is_empty());
    }

    #[test]
    fn despawn_enqueue_drain_round_trip() {
        let _guard = test_support::lock();
        let _ = drain();
        let (tx, _rx) = std::sync::mpsc::sync_channel(1);
        enqueue(WorldCommand::Despawn {
            name: "crate_a".to_string(),
            reply: tx,
        });
        let cmds = drain();
        assert_eq!(cmds.len(), 1);
        match cmds.into_iter().next().unwrap() {
            RuntimeCommand::World(WorldCommand::Despawn { name, .. }) => {
                assert_eq!(name, "crate_a")
            }
            _ => panic!("wrong variant"),
        }
        assert!(drain().is_empty());
    }

    #[test]
    fn reparent_enqueue_drain_round_trip() {
        let _guard = test_support::lock();
        let _ = drain();
        let (tx, _rx) = std::sync::mpsc::sync_channel(1);
        enqueue(WorldCommand::Reparent {
            child: "box_a".to_string(),
            parent: Some("frame".to_string()),
            reply: tx,
        });
        let cmds = drain();
        assert_eq!(cmds.len(), 1);
        match cmds.into_iter().next().unwrap() {
            RuntimeCommand::World(WorldCommand::Reparent { child, parent, .. }) => {
                assert_eq!(child, "box_a");
                assert_eq!(parent.as_deref(), Some("frame"));
            }
            _ => panic!("wrong variant"),
        }
        assert!(drain().is_empty());
    }

    #[test]
    fn decal_spawn_args_defaults() {
        let a = DecalSpawnArgs::default();
        assert_eq!(a.size, [1.0, 1.0, 1.0]);
        assert_eq!(a.tint, [1.0, 1.0, 1.0, 1.0]);
        assert!(a.texture.is_none());
    }

    #[test]
    fn emitter_spawn_args_defaults() {
        let a = EmitterSpawnArgs::default();
        assert_eq!(a.direction, [0.0, 1.0, 0.0]);
        assert_eq!(a.max_particles, 256);
        assert!((a.spread_deg - 15.0).abs() < 1e-6);
    }

    #[test]
    fn camera_set_args_defaults() {
        let a = CameraSetArgs::default();
        assert_eq!(a.position, [0.0, 0.0, 0.0]);
        assert_eq!(a.yaw, 0.0);
        assert_eq!(a.pitch, 0.0);
        assert!(a.fov_y_degrees.is_none());
    }

    #[test]
    fn camera_set_enqueue_drain_round_trip() {
        let _guard = test_support::lock();
        let _ = drain();
        let (tx, _rx) = std::sync::mpsc::sync_channel(1);
        enqueue(WorldCommand::CameraSet {
            args: CameraSetArgs {
                position: [1.0, 2.0, 3.0],
                yaw: 0.5,
                pitch: -0.25,
                fov_y_degrees: Some(60.0),
            },
            reply: tx,
        });
        let cmds = drain();
        assert_eq!(cmds.len(), 1);
        match cmds.into_iter().next().unwrap() {
            RuntimeCommand::World(WorldCommand::CameraSet { args, .. }) => {
                assert_eq!(args.position, [1.0, 2.0, 3.0]);
                assert_eq!(args.fov_y_degrees, Some(60.0));
            }
            _ => panic!("wrong variant"),
        }
        assert!(drain().is_empty());
    }

    // A world with a controlled Camera3D builds a Camera3DSystem at `start`;
    // `apply_camera_set` must write the pose, refresh the view matrix, and
    // succeed (the velocity reset runs over the constructed system).
    #[test]
    fn apply_camera_set_writes_active_camera() {
        use concinnity_core::components::{Camera3D, CameraController};
        use concinnity_core::ecs::World;

        let mut world = World::new();
        world.add_component(Camera3D {
            fov_y_degrees: 75.0,
            near: 0.05,
            far: 200.0,
            view_matrix: [[0.0; 4]; 4],
            position: [0.0; 3],
            yaw: 0.0,
            pitch: 0.0,
            desired_move: [0.0; 3],
            jump_requested: false,
            interact_requested: false,
            controller: Some(CameraController::default()),
        });
        world.start(concinnity_engine::ecs::SYSTEMS).unwrap();

        let args = CameraSetArgs {
            position: [10.0, 20.0, 30.0],
            yaw: 1.0,
            pitch: -0.5,
            fov_y_degrees: Some(50.0),
        };
        assert!(apply_camera_set(&args, &mut world).is_ok());

        let cam = world.query::<Camera3D>().next().expect("camera present");
        assert_eq!(cam.position, [10.0, 20.0, 30.0]);
        assert_eq!(cam.yaw, 1.0);
        assert_eq!(cam.pitch, -0.5);
        assert_eq!(cam.fov_y_degrees, 50.0);
        // view_matrix was refreshed from the new pose, no longer all-zero.
        assert_ne!(cam.view_matrix, [[0.0; 4]; 4]);
    }

    // `fov_y_degrees: None` leaves the existing field untouched.
    #[test]
    fn apply_camera_set_keeps_fov_when_none() {
        use concinnity_core::components::{Camera3D, CameraController};
        use concinnity_core::ecs::World;

        let mut world = World::new();
        world.add_component(Camera3D {
            fov_y_degrees: 75.0,
            near: 0.05,
            far: 200.0,
            view_matrix: [[0.0; 4]; 4],
            position: [0.0; 3],
            yaw: 0.0,
            pitch: 0.0,
            desired_move: [0.0; 3],
            jump_requested: false,
            interact_requested: false,
            controller: Some(CameraController::default()),
        });
        world.start(concinnity_engine::ecs::SYSTEMS).unwrap();

        let args = CameraSetArgs {
            position: [1.0, 1.0, 1.0],
            yaw: 0.0,
            pitch: 0.0,
            fov_y_degrees: None,
        };
        assert!(apply_camera_set(&args, &mut world).is_ok());
        let cam = world.query::<Camera3D>().next().expect("camera present");
        assert_eq!(cam.fov_y_degrees, 75.0);
    }

    // No Camera3D in the world is a clean error, not a panic.
    #[test]
    fn apply_camera_set_errors_without_camera() {
        let mut world = World::new();
        let args = CameraSetArgs::default();
        assert!(apply_camera_set(&args, &mut world).is_err());
    }

    #[test]
    fn camera_move_args_defaults_are_zero_hold() {
        let a = CameraMoveArgs::default();
        assert_eq!(a.forward, 0.0);
        assert_eq!(a.right, 0.0);
        assert_eq!(a.up, 0.0);
        assert_eq!(a.yaw, 0.0);
        assert_eq!(a.pitch, 0.0);
        // frames == 0 is the indefinite-hold sentinel.
        assert_eq!(a.frames, 0);
    }

    #[test]
    fn camera_motion_from_args_maps_zero_frames_to_indefinite_hold() {
        let hold = CameraMotion::from_args(&CameraMoveArgs {
            forward: 1.0,
            frames: 0,
            ..CameraMoveArgs::default()
        });
        assert_eq!(hold.frames_left, None);
        let finite = CameraMotion::from_args(&CameraMoveArgs {
            forward: 1.0,
            frames: 5,
            ..CameraMoveArgs::default()
        });
        assert_eq!(finite.frames_left, Some(5));
    }

    #[test]
    fn camera_motion_advanced_counts_down_then_stops() {
        let m = CameraMotion {
            forward: 1.0,
            right: 0.0,
            up: 0.0,
            yaw: 0.0,
            pitch: 0.0,
            frames_left: Some(3),
        };
        // Three frames remain: countdown 3 -> 2 -> 1 -> exhausted.
        let m = m.advanced().expect("2 frames remain");
        assert_eq!(m.frames_left, Some(2));
        let m = m.advanced().expect("1 frame remains");
        assert_eq!(m.frames_left, Some(1));
        assert!(m.advanced().is_none(), "last frame exhausts the motion");
    }

    #[test]
    fn camera_motion_advanced_holds_indefinitely() {
        let m = CameraMotion {
            forward: 0.0,
            right: 0.0,
            up: 0.0,
            yaw: 0.1,
            pitch: 0.0,
            frames_left: None,
        };
        // An indefinite hold returns itself unchanged forever.
        let next = m.clone().advanced().expect("hold never exhausts");
        assert_eq!(next, m);
    }

    #[test]
    fn advance_pose_moves_along_look_basis() {
        // yaw = 0, pitch = 0 looks down -Z; forward delta moves -Z, right moves
        // +X, up moves +Y.
        let motion = CameraMotion {
            forward: 2.0,
            right: 3.0,
            up: 4.0,
            yaw: 0.0,
            pitch: 0.0,
            frames_left: Some(1),
        };
        let (pos, yaw, pitch) = advance_pose([0.0, 0.0, 0.0], 0.0, 0.0, &motion);
        assert!((pos[0] - 3.0).abs() < 1e-5, "right -> +X");
        assert!((pos[1] - 4.0).abs() < 1e-5, "up -> +Y");
        assert!((pos[2] + 2.0).abs() < 1e-5, "forward -> -Z");
        assert_eq!(yaw, 0.0);
        assert_eq!(pitch, 0.0);
    }

    #[test]
    fn advance_pose_accumulates_yaw_and_clamps_pitch() {
        let motion = CameraMotion {
            forward: 0.0,
            right: 0.0,
            up: 0.0,
            yaw: 0.5,
            // A huge pitch delta must clamp, not flip the camera over.
            pitch: 100.0,
            frames_left: Some(1),
        };
        let (_, yaw, pitch) = advance_pose([0.0, 0.0, 0.0], 1.0, 0.0, &motion);
        assert!((yaw - 1.5).abs() < 1e-6);
        let limit = std::f32::consts::FRAC_PI_2 - 0.01;
        assert!(
            (pitch - limit).abs() < 1e-5,
            "pitch clamps to near-vertical"
        );
    }

    #[test]
    fn camera_move_enqueue_drain_round_trip() {
        let _guard = test_support::lock();
        let _ = drain();
        let (tx, _rx) = std::sync::mpsc::sync_channel(1);
        enqueue(WorldCommand::CameraMove {
            args: CameraMoveArgs {
                forward: 1.5,
                frames: 30,
                ..CameraMoveArgs::default()
            },
            reply: tx,
        });
        let (stx, _srx) = std::sync::mpsc::sync_channel(1);
        enqueue(WorldCommand::CameraStop { reply: stx });
        let cmds = drain();
        assert_eq!(cmds.len(), 2);
        let mut it = cmds.into_iter();
        match it.next().unwrap() {
            RuntimeCommand::World(WorldCommand::CameraMove { args, .. }) => {
                assert_eq!(args.forward, 1.5);
                assert_eq!(args.frames, 30);
            }
            _ => panic!("wrong variant"),
        }
        assert!(matches!(
            it.next().unwrap(),
            RuntimeCommand::World(WorldCommand::CameraStop { .. })
        ));
        assert!(drain().is_empty());
    }

    // apply_camera_move_step advances the active camera and refreshes its view
    // matrix; a sequence of steps accumulates displacement (sustained motion).
    #[test]
    fn apply_camera_move_step_advances_active_camera() {
        use concinnity_core::components::{Camera3D, CameraController};
        use concinnity_core::ecs::World;

        let mut world = World::new();
        world.add_component(Camera3D {
            fov_y_degrees: 75.0,
            near: 0.05,
            far: 200.0,
            view_matrix: [[0.0; 4]; 4],
            position: [0.0; 3],
            yaw: 0.0,
            pitch: 0.0,
            desired_move: [0.0; 3],
            jump_requested: false,
            interact_requested: false,
            controller: Some(CameraController::default()),
        });
        world.start(concinnity_engine::ecs::SYSTEMS).unwrap();

        let motion = CameraMotion {
            forward: 1.0,
            right: 0.0,
            up: 0.0,
            yaw: 0.0,
            pitch: 0.0,
            frames_left: Some(2),
        };
        assert!(apply_camera_move_step(&motion, &mut world));
        assert!(apply_camera_move_step(&motion, &mut world));

        let cam = world.query::<Camera3D>().next().expect("camera present");
        // Two forward steps of 1.0 along -Z accumulate to -2.0.
        assert!((cam.position[2] + 2.0).abs() < 1e-5);
        assert_ne!(cam.view_matrix, [[0.0; 4]; 4]);
    }

    // No Camera3D: the step is a clean `false`, not a panic, so the drive drops
    // the motion.
    #[test]
    fn apply_camera_move_step_false_without_camera() {
        let mut world = World::new();
        let motion = CameraMotion {
            forward: 1.0,
            right: 0.0,
            up: 0.0,
            yaw: 0.0,
            pitch: 0.0,
            frames_left: None,
        };
        assert!(!apply_camera_move_step(&motion, &mut world));
    }

    // DecalAdd with no texture resolves to the white slot and, with a
    // non-degenerate size, builds the DecalRecord before handing it to the
    // backend, whose default `add_decal` reports the feature is unimplemented.
    #[test]
    fn backend_dispatch_decal_add_builds_record_then_surfaces_backend_err() {
        let (tx, rx) = std::sync::mpsc::sync_channel(1);
        let mut backend = StubBackend;
        dispatch_runtime_spawn(
            BackendCommand::DecalAdd {
                args: DecalSpawnArgs::default(),
                reply: tx,
            },
            None,
            &mut backend,
        );
        let err = rx.recv().unwrap().unwrap_err();
        assert!(err.contains("add_decal"), "got: {err}");
    }

    // A zero size makes the decal model matrix non-invertible, caught before the
    // backend is touched.
    #[test]
    fn backend_dispatch_decal_add_rejects_degenerate_size() {
        let (tx, rx) = std::sync::mpsc::sync_channel(1);
        let mut backend = StubBackend;
        dispatch_runtime_spawn(
            BackendCommand::DecalAdd {
                args: DecalSpawnArgs {
                    size: [0.0, 0.0, 0.0],
                    ..DecalSpawnArgs::default()
                },
                reply: tx,
            },
            None,
            &mut backend,
        );
        let err = rx.recv().unwrap().unwrap_err();
        assert!(err.contains("degenerate size"), "got: {err}");
    }

    #[test]
    fn backend_dispatch_decal_remove_surfaces_backend_err() {
        let (tx, rx) = std::sync::mpsc::sync_channel(1);
        let mut backend = StubBackend;
        dispatch_runtime_spawn(
            BackendCommand::DecalRemove { id: 3, reply: tx },
            None,
            &mut backend,
        );
        let err = rx.recv().unwrap().unwrap_err();
        assert!(err.contains("remove_decal"), "got: {err}");
    }

    // EmitterAdd normalizes / clamps the request into a ParticleEmitterRecord
    // before the backend's default `add_emitter` reports it unimplemented. The
    // two configs cover both the normalize branch (unit direction) and the
    // degenerate-direction fallback plus every out-of-range clamp.
    #[test]
    fn backend_dispatch_emitter_add_normalizes_then_surfaces_backend_err() {
        let configs = [
            EmitterSpawnArgs::default(),
            EmitterSpawnArgs {
                direction: [0.0, 0.0, 0.0],
                spread_deg: 500.0,
                speed_min: -5.0,
                speed_max: -10.0,
                lifetime_min: -1.0,
                lifetime_max: -2.0,
                max_particles: 0,
                spawn_rate: -1.0,
                size_start: -1.0,
                size_end: -1.0,
                ..EmitterSpawnArgs::default()
            },
        ];
        for args in configs {
            let (tx, rx) = std::sync::mpsc::sync_channel(1);
            let mut backend = StubBackend;
            dispatch_runtime_spawn(
                BackendCommand::EmitterAdd { args, reply: tx },
                None,
                &mut backend,
            );
            let err = rx.recv().unwrap().unwrap_err();
            assert!(err.contains("add_emitter"), "got: {err}");
        }
    }

    #[test]
    fn backend_dispatch_emitter_remove_surfaces_backend_err() {
        let (tx, rx) = std::sync::mpsc::sync_channel(1);
        let mut backend = StubBackend;
        dispatch_runtime_spawn(
            BackendCommand::EmitterRemove { id: 5, reply: tx },
            None,
            &mut backend,
        );
        let err = rx.recv().unwrap().unwrap_err();
        assert!(err.contains("remove_emitter"), "got: {err}");
    }

    #[test]
    fn backend_dispatch_screenshot_surfaces_backend_err() {
        let (tx, rx) = std::sync::mpsc::sync_channel(1);
        let mut backend = StubBackend;
        dispatch_runtime_spawn(
            BackendCommand::Screenshot {
                path: "shot.png".to_string(),
                reply: tx,
            },
            None,
            &mut backend,
        );
        let err = rx.recv().unwrap().unwrap_err();
        assert!(err.contains("screenshot: not supported"), "got: {err}");
    }

    #[test]
    fn backend_dispatch_cull_status_surfaces_backend_err() {
        let (tx, rx) = std::sync::mpsc::sync_channel(1);
        let mut backend = StubBackend;
        dispatch_runtime_spawn(BackendCommand::CullStatus { reply: tx }, None, &mut backend);
        let err = rx.recv().unwrap().unwrap_err();
        assert!(
            err.contains("read_cull_status: not supported"),
            "got: {err}"
        );
    }

    // resolve_texture_slot: the no-texture fallback, the three failure cases,
    // and the live-pool hit. Touches the thread-local interner, so it takes the
    // shared lock and resets the interner first, like the queue tests.
    #[test]
    fn resolve_texture_slot_covers_every_case() {
        let _guard = test_support::lock();
        asset_id::reset_interner();

        // None -> the renderer's white fallback slot, no interner or reload.
        assert_eq!(resolve_texture_slot(None, None).unwrap(), 0);

        // A name absent from the interner is a clear error.
        let err = resolve_texture_slot(Some("ghost"), None).unwrap_err();
        assert!(err.contains("not found in interner"), "got: {err}");

        // Interned name but no parked map (not `cn debug`): unavailable.
        asset_id::intern_all(&["grid"]);
        let err = resolve_texture_slot(Some("grid"), None).unwrap_err();
        assert!(err.contains("slots not captured"), "got: {err}");

        // Interned name, map parked, but the name is not in the pool.
        let empty = TextureNameSlots::default();
        let err = resolve_texture_slot(Some("grid"), Some(&empty)).unwrap_err();
        assert!(err.contains("not in the live texture pool"), "got: {err}");

        // Interned name present in the pool map -> its resolved slot.
        let slots = TextureNameSlots([(AssetId(0), 5usize)].into());
        assert_eq!(resolve_texture_slot(Some("grid"), Some(&slots)).unwrap(), 5);
    }

    fn controlled_camera() -> Camera3D {
        use concinnity_core::components::{Camera3D, CameraController};
        Camera3D {
            fov_y_degrees: 75.0,
            near: 0.05,
            far: 200.0,
            view_matrix: [[0.0; 4]; 4],
            position: [0.0; 3],
            yaw: 0.0,
            pitch: 0.0,
            desired_move: [0.0; 3],
            jump_requested: false,
            interact_requested: false,
            controller: Some(CameraController::default()),
        }
    }

    // The CameraSet wrapper applies the pose against the live ECS and replies Ok.
    #[test]
    fn world_command_camera_set_applies_pose_and_replies_ok() {
        use concinnity_core::components::Camera3D;
        use concinnity_core::ecs::World;

        let mut world = World::new();
        world.add_component(controlled_camera());
        world.start(concinnity_engine::ecs::SYSTEMS).unwrap();

        let (tx, rx) = std::sync::mpsc::sync_channel(1);
        dispatch_world_command(
            WorldCommand::CameraSet {
                args: CameraSetArgs {
                    position: [1.0, 2.0, 3.0],
                    yaw: 0.5,
                    pitch: -0.25,
                    fov_y_degrees: Some(50.0),
                },
                reply: tx,
            },
            &mut world,
            &mut None,
        );
        assert!(rx.recv().unwrap().is_ok());
        let cam = world.query::<Camera3D>().next().expect("camera present");
        assert_eq!(cam.position, [1.0, 2.0, 3.0]);
        assert_eq!(cam.fov_y_degrees, 50.0);
    }

    #[test]
    fn world_command_quality_set_sends_setting_command() {
        let mut world = World::new();
        let (tx, rx) = std::sync::mpsc::sync_channel(1);
        dispatch_world_command(
            WorldCommand::QualitySet {
                setting: SettingKey::Ssao,
                op: SettingOp::Next,
                reply: tx,
            },
            &mut world,
            &mut None,
        );
        assert!(rx.recv().unwrap().is_ok());

        let events = world
            .events::<SettingCommand>()
            .expect("setting command queued");
        let mut cursor = EventCursor::default();
        let seen: Vec<_> = events.read(&mut cursor).collect();
        assert_eq!(seen.len(), 1);
        assert_eq!(seen[0].setting, SettingKey::Ssao);
        assert_eq!(seen[0].op, SettingOp::Next);
        assert!(seen[0].persist);
        assert!(seen[0].value_label.is_none());
    }

    #[test]
    fn world_command_rebind_sends_rebind_setting_command() {
        let mut world = World::new();
        let (tx, rx) = std::sync::mpsc::sync_channel(1);
        dispatch_world_command(
            WorldCommand::Rebind {
                action: Bindable::Forward,
                key: InputKey::Space,
                reply: tx,
            },
            &mut world,
            &mut None,
        );
        assert!(rx.recv().unwrap().is_ok());

        let events = world
            .events::<SettingCommand>()
            .expect("setting command queued");
        let mut cursor = EventCursor::default();
        let seen: Vec<_> = events.read(&mut cursor).collect();
        assert_eq!(seen.len(), 1);
        assert_eq!(seen[0].setting, SettingKey::KeyRebind(Bindable::Forward));
        assert_eq!(seen[0].op, SettingOp::Rebind(InputKey::Space));
    }

    #[test]
    fn world_command_story_forwards_the_command() {
        let mut world = World::new();
        let (tx, rx) = std::sync::mpsc::sync_channel(1);
        dispatch_world_command(
            WorldCommand::Story {
                command: StoryCommand::Choose(2),
                reply: tx,
            },
            &mut world,
            &mut None,
        );
        assert!(rx.recv().unwrap().is_ok());

        let events = world
            .events::<StoryCommand>()
            .expect("story command queued");
        let mut cursor = EventCursor::default();
        let seen: Vec<_> = events.read(&mut cursor).collect();
        assert_eq!(seen.len(), 1);
        assert_eq!(*seen[0], StoryCommand::Choose(2));
    }

    #[test]
    fn world_command_despawn_resolves_name_and_reports_unknown() {
        let _guard = test_support::lock();
        asset_id::reset_interner();
        asset_id::intern_all(&["crate_a", "crate_b"]);
        let mut world = World::new();

        let (tx, rx) = std::sync::mpsc::sync_channel(1);
        dispatch_world_command(
            WorldCommand::Despawn {
                name: "crate_b".to_string(),
                reply: tx,
            },
            &mut world,
            &mut None,
        );
        assert!(rx.recv().unwrap().is_ok());
        let events = world
            .events::<DespawnRequest>()
            .expect("despawn request queued");
        let mut cursor = EventCursor::default();
        let seen: Vec<_> = events.read(&mut cursor).collect();
        assert_eq!(seen.len(), 1);
        assert_eq!(seen[0].target.name().unwrap(), AssetId(1));

        // An unknown name is a clean error.
        let (tx, rx) = std::sync::mpsc::sync_channel(1);
        dispatch_world_command(
            WorldCommand::Despawn {
                name: "ghost".to_string(),
                reply: tx,
            },
            &mut world,
            &mut None,
        );
        let err = rx.recv().unwrap().unwrap_err();
        assert!(err.contains("'ghost' not found"), "got: {err}");
    }

    #[test]
    fn world_command_reparent_resolves_names_and_reports_errors() {
        let _guard = test_support::lock();
        asset_id::reset_interner();
        asset_id::intern_all(&["box_a", "frame"]);
        let mut world = World::new();
        let mut cursor = EventCursor::default();

        // Both names known -> queued with both ids.
        let (tx, rx) = std::sync::mpsc::sync_channel(1);
        dispatch_world_command(
            WorldCommand::Reparent {
                child: "box_a".to_string(),
                parent: Some("frame".to_string()),
                reply: tx,
            },
            &mut world,
            &mut None,
        );
        assert!(rx.recv().unwrap().is_ok());
        {
            let events = world
                .events::<ReparentRequest>()
                .expect("reparent request queued");
            let seen: Vec<_> = events.read(&mut cursor).collect();
            assert_eq!(seen.len(), 1);
            assert_eq!(seen[0].child.name().unwrap(), AssetId(0));
            assert_eq!(seen[0].parent.and_then(|p| p.name()), Some(AssetId(1)));
        }

        // A None parent detaches the child to a root.
        let (tx, rx) = std::sync::mpsc::sync_channel(1);
        dispatch_world_command(
            WorldCommand::Reparent {
                child: "box_a".to_string(),
                parent: None,
                reply: tx,
            },
            &mut world,
            &mut None,
        );
        assert!(rx.recv().unwrap().is_ok());
        {
            let events = world.events::<ReparentRequest>().unwrap();
            let seen: Vec<_> = events.read(&mut cursor).collect();
            assert_eq!(seen.len(), 1);
            assert!(seen[0].parent.is_none());
        }

        // Unknown child.
        let (tx, rx) = std::sync::mpsc::sync_channel(1);
        dispatch_world_command(
            WorldCommand::Reparent {
                child: "ghost".to_string(),
                parent: Some("frame".to_string()),
                reply: tx,
            },
            &mut world,
            &mut None,
        );
        let err = rx.recv().unwrap().unwrap_err();
        assert!(err.contains("child 'ghost' not found"), "got: {err}");

        // Known child, unknown parent.
        let (tx, rx) = std::sync::mpsc::sync_channel(1);
        dispatch_world_command(
            WorldCommand::Reparent {
                child: "box_a".to_string(),
                parent: Some("void".to_string()),
                reply: tx,
            },
            &mut world,
            &mut None,
        );
        let err = rx.recv().unwrap().unwrap_err();
        assert!(err.contains("parent 'void' not found"), "got: {err}");
    }

    #[test]
    fn world_command_spawn_resolves_template_interns_name_and_defaults_scale() {
        let _guard = test_support::lock();
        asset_id::reset_interner();
        asset_id::intern_all(&["template_a"]);
        let mut world = World::new();
        let mut cursor = EventCursor::default();

        let (tx, rx) = std::sync::mpsc::sync_channel(1);
        dispatch_world_command(
            WorldCommand::Spawn {
                template: "template_a".to_string(),
                name: "instance_1".to_string(),
                position: [1.0, 2.0, 3.0],
                rotation_deg: [0.0, 90.0, 0.0],
                scale: [2.0, 2.0, 2.0],
                lifetime: Some(5.0),
                reply: tx,
            },
            &mut world,
            &mut None,
        );
        assert!(rx.recv().unwrap().is_ok());
        {
            let events = world
                .events::<SpawnRequest>()
                .expect("spawn request queued");
            let seen: Vec<_> = events.read(&mut cursor).collect();
            assert_eq!(seen.len(), 1);
            assert_eq!(seen[0].template, AssetId(0));
            // The new instance name was interned to the next id.
            assert_eq!(seen[0].name, Some(AssetId(1)));
            assert_eq!(seen[0].transform.position, [1.0, 2.0, 3.0]);
            assert_eq!(seen[0].transform.scale, [2.0, 2.0, 2.0]);
            assert_eq!(seen[0].lifetime_secs, Some(5.0));
        }

        // A zero scale (the array default when omitted) is treated as unit scale
        // so the spawned copy is visible.
        let (tx, rx) = std::sync::mpsc::sync_channel(1);
        dispatch_world_command(
            WorldCommand::Spawn {
                template: "template_a".to_string(),
                name: "instance_2".to_string(),
                position: [0.0; 3],
                rotation_deg: [0.0; 3],
                scale: [0.0; 3],
                lifetime: None,
                reply: tx,
            },
            &mut world,
            &mut None,
        );
        assert!(rx.recv().unwrap().is_ok());
        {
            let events = world.events::<SpawnRequest>().unwrap();
            let seen: Vec<_> = events.read(&mut cursor).collect();
            assert_eq!(seen.len(), 1);
            assert_eq!(seen[0].transform.scale, [1.0, 1.0, 1.0]);
        }

        // An unknown template is a clean error.
        let (tx, rx) = std::sync::mpsc::sync_channel(1);
        dispatch_world_command(
            WorldCommand::Spawn {
                template: "missing".to_string(),
                name: "instance_3".to_string(),
                position: [0.0; 3],
                rotation_deg: [0.0; 3],
                scale: [1.0; 3],
                lifetime: None,
                reply: tx,
            },
            &mut world,
            &mut None,
        );
        let err = rx.recv().unwrap().unwrap_err();
        assert!(err.contains("template 'missing' not found"), "got: {err}");
    }

    // camera-move in a camera-less world is a clean error and installs nothing.
    #[test]
    fn world_command_camera_move_without_a_camera_errs_and_installs_no_motion() {
        let mut world = World::new();
        let mut motion = None;
        let (tx, rx) = std::sync::mpsc::sync_channel(1);
        dispatch_world_command(
            WorldCommand::CameraMove {
                args: CameraMoveArgs {
                    forward: 1.0,
                    ..CameraMoveArgs::default()
                },
                reply: tx,
            },
            &mut world,
            &mut motion,
        );
        let err = rx.recv().unwrap().unwrap_err();
        assert!(err.contains("no Camera3D"), "got: {err}");
        assert!(motion.is_none());
    }

    #[test]
    fn world_command_camera_move_installs_the_motion_when_a_camera_exists() {
        let mut world = World::new();
        world.add_component(controlled_camera());
        let mut motion = None;
        let (tx, rx) = std::sync::mpsc::sync_channel(1);
        dispatch_world_command(
            WorldCommand::CameraMove {
                args: CameraMoveArgs {
                    forward: 1.0,
                    frames: 4,
                    ..CameraMoveArgs::default()
                },
                reply: tx,
            },
            &mut world,
            &mut motion,
        );
        assert!(rx.recv().unwrap().is_ok());
        assert_eq!(motion.map(|m| m.frames_left), Some(Some(4)));
    }

    #[test]
    fn world_command_camera_stop_clears_the_motion_and_replies_ok() {
        let mut world = World::new();
        let mut motion = Some(CameraMotion::from_args(&CameraMoveArgs::default()));
        let (tx, rx) = std::sync::mpsc::sync_channel(1);
        dispatch_world_command(
            WorldCommand::CameraStop { reply: tx },
            &mut world,
            &mut motion,
        );
        assert!(rx.recv().unwrap().is_ok());
        assert!(motion.is_none());
    }
}