concinnity-dev 0.19.23

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
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
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
// src/debug/hot_reload/tests.rs
//
// Unit tests for the hot-reload machinery (moved here from the single-file
// module). Pull each submodule's items in explicitly.

use super::decode::*;
use super::passes::*;
use super::state::*;
use super::watcher::*;
use crate::gfx::graphics_system::hot_reload_sources::*;
use notify::{Event, EventKind};
use std::path::PathBuf;

#[test]
fn empty_map_round_trips() {
    let m = TextureSourceMap::new();
    assert!(m.is_empty());
    assert_eq!(m.len(), 0);
    assert!(m.watch_dirs().is_empty());
}

#[test]
fn pushes_and_collects_unique_parent_dirs() {
    let mut m = TextureSourceMap::new();
    m.push_texture("assets/a.png".to_string(), 0, 0);
    m.push_texture("assets/b.png".to_string(), 0, 1);
    m.push_texture("textures/nm.png".to_string(), 0, 1);
    assert_eq!(m.entries.len(), 3);
    let dirs = m.watch_dirs();
    assert_eq!(dirs.len(), 2);
    assert!(dirs.iter().any(|p| p.ends_with("assets")));
    assert!(dirs.iter().any(|p| p.ends_with("textures")));
}

#[test]
fn bare_filenames_skip_watch_dir() {
    // A source with no parent directory has nowhere to watch; the watcher
    // would otherwise try to subscribe to "" which notify rejects.
    let mut m = TextureSourceMap::new();
    m.push_texture("standalone.png".to_string(), 0, 0);
    assert!(m.watch_dirs().is_empty());
}

#[test]
fn glb_extension_is_an_asset_event() {
    let evt = Event::new(EventKind::Modify(notify::event::ModifyKind::Any))
        .add_path(PathBuf::from("/tmp/model.glb"));
    assert!(is_asset_event(&evt));
}

#[test]
fn cube_extension_is_an_asset_event() {
    // ColorLut sources travel through the same watcher; `.cube` must pass.
    let evt = Event::new(EventKind::Modify(notify::event::ModifyKind::Any))
        .add_path(PathBuf::from("/tmp/grade.cube"));
    assert!(is_asset_event(&evt));
}

#[test]
fn hdr_extension_is_an_asset_event() {
    // EnvironmentMap sources travel through the same watcher; `.hdr` must pass.
    let evt = Event::new(EventKind::Modify(notify::event::ModifyKind::Any))
        .add_path(PathBuf::from("/tmp/studio.hdr"));
    assert!(is_asset_event(&evt));
}

#[test]
fn hdr_extension_matches_case_insensitively() {
    let evt = Event::new(EventKind::Modify(notify::event::ModifyKind::Any))
        .add_path(PathBuf::from("/tmp/STUDIO.HDR"));
    assert!(is_asset_event(&evt));
}

#[test]
fn unrelated_extension_is_not_an_asset_event() {
    // `.jsonl` (the world file) is now a recognised asset event; pick an
    // extension nothing in the engine cares about as the negative case.
    let evt = Event::new(EventKind::Modify(notify::event::ModifyKind::Any))
        .add_path(PathBuf::from("/tmp/world.txt"));
    assert!(!is_asset_event(&evt));
}

#[test]
fn state_with_only_environment_map_still_spawns_a_watcher() {
    // With no textures and no LUT but an EnvironmentMap, the watcher must
    // still be set up so `.hdr` saves trigger reloads. The state stores the
    // EnvironmentMapSource verbatim for the reload helper to consult.
    let env_map = EnvironmentMapSource {
        resolved_path: concinnity_host::scratch::path("asset_hot_reload_envmap_only.hdr")
            .to_string_lossy()
            .into_owned(),
        prefilter_face_size: 64,
        irradiance_face_size: 16,
        prefilter_samples: 64,
        prefilter_clamp: 12.0,
    };
    // Parent dir (temp dir) exists, so the watcher should subscribe.
    let state = AssetHotReloadState::from_sources(HotReloadSources {
        environment_map: Some(env_map.clone()),
        ..Default::default()
    });
    assert!(state.environment_map.is_some());
    let captured = state.environment_map.as_ref().unwrap();
    assert_eq!(captured.prefilter_face_size, env_map.prefilter_face_size);
    assert_eq!(captured.irradiance_face_size, env_map.irradiance_face_size);
    assert_eq!(captured.prefilter_samples, env_map.prefilter_samples);
}

#[test]
fn fully_empty_state_skips_watcher_creation() {
    // No textures, no LUT, no EnvironmentMap, no meshes, no skinned, no
    // world path → nothing to watch.
    let state = AssetHotReloadState::from_sources(HotReloadSources::default());
    assert!(state.environment_map.is_none());
    assert!(state.color_lut.is_none());
    assert!(state.map.is_empty());
    assert!(state.meshes.is_empty());
    assert!(state.skinned_meshes.is_empty());
}

#[test]
fn mesh_source_map_collects_unique_parent_dirs() {
    let mut m = MeshSourceMap::new();
    m.entries.push(MeshSourceEntry {
        source: "assets/models/a.glb".to_string(),
        primitive_index: 0,
        lod_levels: 1,
        lod_distances: Vec::new(),
        draw_indices: vec![0, 1],
    });
    m.entries.push(MeshSourceEntry {
        source: "assets/models/a.glb".to_string(),
        primitive_index: 1,
        lod_levels: 1,
        lod_distances: Vec::new(),
        draw_indices: vec![2],
    });
    m.entries.push(MeshSourceEntry {
        source: "assets/hdri/b.glb".to_string(),
        primitive_index: 0,
        lod_levels: 1,
        lod_distances: Vec::new(),
        draw_indices: vec![3],
    });
    let dirs = m.watch_dirs();
    assert_eq!(dirs.len(), 2);
    assert!(dirs.iter().any(|p| p.ends_with("assets/models")));
    assert!(dirs.iter().any(|p| p.ends_with("assets/hdri")));
}

#[test]
fn mesh_source_map_skips_bare_filenames_in_watch_dirs() {
    // A bare filename has no parent directory; the watcher would otherwise
    // try to subscribe to "" which notify rejects. The debug-WS
    // `reload-assets` command path still works for these.
    let mut m = MeshSourceMap::new();
    m.entries.push(MeshSourceEntry {
        source: "standalone.glb".to_string(),
        primitive_index: 0,
        lod_levels: 1,
        lod_distances: Vec::new(),
        draw_indices: vec![0],
    });
    assert!(m.watch_dirs().is_empty());
}

#[test]
fn state_with_only_meshes_still_spawns_a_watcher() {
    let mut meshes = MeshSourceMap::new();
    meshes.entries.push(MeshSourceEntry {
        source: concinnity_host::scratch::path("dummy.glb")
            .to_string_lossy()
            .into_owned(),
        primitive_index: 0,
        lod_levels: 1,
        lod_distances: Vec::new(),
        draw_indices: vec![0],
    });
    let state = AssetHotReloadState::from_sources(HotReloadSources {
        meshes,
        ..Default::default()
    });
    assert_eq!(state.meshes.len(), 1);
    assert_eq!(state.meshes.entries[0].draw_indices, vec![0]);
}

#[test]
fn skinned_mesh_source_map_collects_unique_parent_dirs() {
    let mut m = SkinnedMeshSourceMap::new();
    m.entries.push(SkinnedMeshSourceEntry {
        source: "assets/models/a.glb".to_string(),
        skin_index: 0,
        skinned_index: 0,
        vertex_base: 0,
        vertex_count: 100,
        index_count: 300,
        joint_count: 24,
    });
    m.entries.push(SkinnedMeshSourceEntry {
        source: "assets/models/b.glb".to_string(),
        skin_index: 0,
        skinned_index: 1,
        vertex_base: 100,
        vertex_count: 50,
        index_count: 150,
        joint_count: 5,
    });
    let dirs = m.watch_dirs();
    assert_eq!(dirs.len(), 1);
    assert!(dirs[0].ends_with("assets/models"));
}

#[test]
fn state_with_only_skinned_still_spawns_a_watcher() {
    let mut skinned = SkinnedMeshSourceMap::new();
    skinned.entries.push(SkinnedMeshSourceEntry {
        source: concinnity_host::scratch::path("skinned.glb")
            .to_string_lossy()
            .into_owned(),
        skin_index: 0,
        skinned_index: 0,
        vertex_base: 0,
        vertex_count: 8,
        index_count: 24,
        joint_count: 2,
    });
    let state = AssetHotReloadState::from_sources(HotReloadSources {
        skinned_meshes: skinned,
        ..Default::default()
    });
    assert_eq!(state.skinned_meshes.len(), 1);
    assert_eq!(state.skinned_meshes.entries[0].joint_count, 2);
}

#[test]
fn state_with_only_world_jsonl_still_spawns_a_watcher() {
    // World-only worlds (no Texture/LUT/EnvMap/Mesh/Skinned) still want
    // their world.jsonl watched so Prop transform edits propagate.
    let world_path = concinnity_host::scratch::path("world_only.jsonl")
        .to_string_lossy()
        .into_owned();
    let state = AssetHotReloadState::from_sources(HotReloadSources {
        world_jsonl_path: Some(world_path.clone()),
        ..Default::default()
    });
    assert_eq!(state.world_jsonl_path.as_deref(), Some(world_path.as_str()));
}

#[test]
fn jsonl_extension_is_an_asset_event() {
    let evt = Event::new(EventKind::Modify(notify::event::ModifyKind::Any))
        .add_path(PathBuf::from("/tmp/world.jsonl"));
    assert!(is_asset_event(&evt));
}

#[test]
fn md_extension_is_an_asset_event() {
    // StoryImport sources travel through the same watcher; the closure
    // routes `.md` saves to the story re-expansion flag.
    let evt = Event::new(EventKind::Modify(notify::event::ModifyKind::Any))
        .add_path(PathBuf::from("/tmp/story.md"));
    assert!(is_asset_event(&evt));
}

#[test]
fn reload_stories_re_expands_and_dedupes_by_snapshot() {
    let tree = concinnity_testing::TempTree::new();
    let dir = tree.path();
    let md = tree.write(
        "tale.md",
        "---\ntitle: Tale\ncharacters:\n  a: Ana\n---\n\n# start\n\nHello there.\n",
    );
    let world = dir.join("world.jsonl");
    std::fs::write(
        &world,
        format!(
            "{}\n",
            serde_json::json!({
                "name": "tale", "type": "StoryImport",
                "args": {"source": md.to_str().unwrap()}
            })
        ),
    )
    .unwrap();

    let mut snapshots = std::collections::HashMap::new();
    let stories = reload_stories(world.to_str().unwrap(), &mut snapshots);
    assert_eq!(stories.len(), 1);
    assert_eq!(stories[0].title, "Tale");
    assert_eq!(stories[0].nodes[0].pages[0].text, "Hello there.");
    assert!(stories[0].scaffold.screen.is_some());

    // Unchanged source: the snapshot filters it out.
    let unchanged = reload_stories(world.to_str().unwrap(), &mut snapshots);
    assert!(unchanged.is_empty());

    // Edited dialogue comes back exactly once.
    std::fs::write(
        &md,
        "---\ntitle: Tale\ncharacters:\n  a: Ana\n---\n\n# start\n\nHello again.\n",
    )
    .unwrap();
    let edited = reload_stories(world.to_str().unwrap(), &mut snapshots);
    assert_eq!(edited.len(), 1);
    assert_eq!(edited[0].nodes[0].pages[0].text, "Hello again.");

    // A broken edit keeps the running story (and the snapshot state).
    std::fs::write(&md, "---\ntitle: Broken\n").unwrap();
    let broken = reload_stories(world.to_str().unwrap(), &mut snapshots);
    assert!(broken.is_empty());
}

#[test]
fn fresh_state_has_no_envmap_in_flight() {
    // The off-thread envmap convolution slot must start empty; a
    // non-`None` value at construction would skip the very first reload
    // request a `reload_assets` pass made.
    let state = AssetHotReloadState::from_sources(HotReloadSources::default());
    let slot = state.env_map_inflight.lock().expect("lock");
    assert!(slot.is_none());
}

#[test]
fn fresh_state_has_no_asset_batch_in_flight() {
    // Same invariant as the envmap slot: a non-`None` value at
    // construction would make the very first `reload_assets` think a
    // worker was already running and skip the spawn.
    let state = AssetHotReloadState::from_sources(HotReloadSources::default());
    let slot = state.asset_batch_inflight.lock().expect("lock");
    assert!(slot.is_none());
}

#[test]
fn decode_asset_batch_with_empty_inputs_returns_empty_batch() {
    // The worker body must handle the no-sources case cleanly so an
    // accidentally-spawned worker on a world without any file-backed
    // assets exits quickly with nothing to apply.
    let batch = decode_asset_batch(Vec::new(), None, Vec::new(), Vec::new());
    assert!(batch.textures.is_empty());
    assert!(batch.color_lut.is_none());
    assert!(batch.meshes.is_empty());
    assert!(batch.skinned_meshes.is_empty());
    assert_eq!(batch.decode_failures, 0);
}

#[test]
fn apply_skinned_layouts_refreshes_every_matching_entry() {
    // After a size-changing skinned rebuild, every source-map entry
    // whose `skinned_index` appears in the returned layouts should pick
    // up the new vertex_base / vertex_count / index_count so subsequent
    // in-place reloads write to the correct shared-buffer regions.
    let mut entries = vec![
        SkinnedMeshSourceEntry {
            source: "a.glb".to_string(),
            skin_index: 0,
            skinned_index: 0,
            vertex_base: 0,
            vertex_count: 10,
            index_count: 30,
            joint_count: 4,
        },
        SkinnedMeshSourceEntry {
            source: "b.glb".to_string(),
            skin_index: 0,
            skinned_index: 1,
            vertex_base: 10,
            vertex_count: 20,
            index_count: 60,
            joint_count: 6,
        },
    ];
    let layouts = vec![
        crate::gfx::backend::SkinnedSlotLayout {
            skinned_index: 0,
            vertex_base: 0,
            vertex_count: 15,
            index_count: 45,
        },
        crate::gfx::backend::SkinnedSlotLayout {
            skinned_index: 1,
            vertex_base: 15,
            vertex_count: 20,
            index_count: 60,
        },
    ];
    apply_skinned_layouts_to_entries(&mut entries, &layouts);
    assert_eq!(entries[0].vertex_base, 0);
    assert_eq!(entries[0].vertex_count, 15);
    assert_eq!(entries[0].index_count, 45);
    // Unchanged slot 1 was still re-packed (vertex_base shifted from 10
    // → 15 because slot 0's vertex_count grew from 10 → 15).
    assert_eq!(entries[1].vertex_base, 15);
    assert_eq!(entries[1].vertex_count, 20);
    assert_eq!(entries[1].index_count, 60);
    // joint_count is untouched: that lives outside the rebuild's scope.
    assert_eq!(entries[0].joint_count, 4);
    assert_eq!(entries[1].joint_count, 6);
}

#[test]
fn drain_pending_skeleton_updates_clears_the_queue() {
    // The render thread polls + drains in one step; a second drain on
    // the same frame must return nothing so a successful apply does not
    // double-write the SkeletonPose components.
    let mut state = AssetHotReloadState::from_sources(HotReloadSources::default());
    state.pending_skeleton_updates.push(PendingSkeletonUpdate {
        skinned_index: 0,
        new_skeleton: crate::gfx::skeleton::Skeleton::new(Vec::new()),
    });
    state.pending_skeleton_updates.push(PendingSkeletonUpdate {
        skinned_index: 3,
        new_skeleton: crate::gfx::skeleton::Skeleton::new(Vec::new()),
    });
    let drained = state.drain_pending_skeleton_updates();
    assert_eq!(drained.len(), 2);
    assert_eq!(drained[0].skinned_index, 0);
    assert_eq!(drained[1].skinned_index, 3);
    // Second drain returns empty.
    assert!(state.drain_pending_skeleton_updates().is_empty());
}

#[test]
fn procedural_mesh_source_map_round_trips_empty() {
    let m = ProceduralMeshSourceMap::new();
    assert!(m.is_empty());
    assert_eq!(m.len(), 0);
}

#[test]
fn procedural_mesh_args_normalise_via_round_trip() {
    // The init pipeline captures args as `serde_json::to_value(component)`;
    // the reload pipeline normalises new on-disk args through
    // `ProceduralMesh::deserialize → serialize`. Same input must produce
    // the same JSON value on both sides, otherwise an unchanged JSONL
    // would still trigger a spurious regen.
    let user_args = serde_json::json!({
        "generator": "box",
        "half_extents": [0.5, 0.5, 0.5],
    });

    // Init-side: parse + re-serialize (mirroring what `serde_json::to_value`
    // on the deserialised component yields).
    let init_component: crate::components::ProceduralMesh =
        serde_json::from_value(user_args.clone()).unwrap();
    let init_norm = serde_json::to_value(&init_component).unwrap();

    // Reload-side: parse user args → component → re-serialize.
    let reload_component: crate::components::ProceduralMesh =
        serde_json::from_value(user_args.clone()).unwrap();
    let reload_norm = serde_json::to_value(&reload_component).unwrap();

    assert_eq!(init_norm, reload_norm);
}

#[test]
fn procedural_mesh_args_diff_detects_real_changes() {
    // A meaningful arg change must produce a distinct normalised value so
    // the diff fires.
    let v1: crate::components::ProceduralMesh = serde_json::from_value(serde_json::json!({
        "generator": "box",
        "half_extents": [0.5, 0.5, 0.5],
    }))
    .unwrap();
    let v2: crate::components::ProceduralMesh = serde_json::from_value(serde_json::json!({
        "generator": "box",
        "half_extents": [1.0, 1.0, 1.0],
    }))
    .unwrap();
    let n1 = serde_json::to_value(&v1).unwrap();
    let n2 = serde_json::to_value(&v2).unwrap();
    assert_ne!(n1, n2);
}

#[test]
fn procedural_mesh_reload_result_default_is_all_zero() {
    let r = ProceduralMeshReloadResult::default();
    assert_eq!(r.regenerated, 0);
    assert_eq!(r.unchanged, 0);
    assert_eq!(r.failed, 0);
}

#[test]
fn state_with_only_procedural_meshes_still_spawns_a_watcher() {
    // ProceduralMesh entries on their own (no textures, no LUTs, no meshes)
    // need to keep the watcher alive: their trigger is the `PENDING_WORLD`
    // flag flipped from the world.jsonl watcher. Without a world_jsonl_path
    // there is nothing to subscribe to, so we declare one here.
    let world_path = concinnity_host::scratch::path("asset_hot_reload_proc_only_world.jsonl")
        .to_string_lossy()
        .into_owned();
    let mut proc = ProceduralMeshSourceMap::new();
    proc.entries.push(ProceduralMeshSourceEntry {
        name: "box_mesh".to_string(),
        args: serde_json::from_value(serde_json::json!({"generator": "box"})).unwrap(),
        draw_indices: vec![0],
    });
    let state = AssetHotReloadState::from_sources(HotReloadSources {
        procedural_meshes: proc,
        world_jsonl_path: Some(world_path),
        ..Default::default()
    });
    assert_eq!(state.procedural_meshes.len(), 1);
    assert_eq!(state.procedural_meshes.entries[0].name, "box_mesh");
}

#[test]
fn shader_stage_source_map_round_trips_empty() {
    let m = ShaderStageSourceMap::new();
    assert!(m.is_empty());
    assert_eq!(m.len(), 0);
    assert!(m.watch_dirs().is_empty());
}

#[test]
fn shader_stage_source_map_collects_unique_parent_dirs() {
    use crate::components::ShaderStage;
    let mut m = ShaderStageSourceMap::new();
    m.entries.push(ShaderStageSourceEntry {
        stage: ShaderStage::Vertex,
        resolved_path: "assets/shaders/sway.slang".to_string(),
    });
    m.entries.push(ShaderStageSourceEntry {
        stage: ShaderStage::Fragment,
        resolved_path: "assets/other/custom.slang".to_string(),
    });
    let dirs = m.watch_dirs();
    assert_eq!(dirs.len(), 2);
    assert!(dirs.iter().any(|p| p.ends_with("assets/shaders")));
    assert!(dirs.iter().any(|p| p.ends_with("assets/other")));
}

#[test]
fn shader_stage_source_map_skips_bare_filenames_in_watch_dirs() {
    // A bare filename has no parent directory; the watcher would try to
    // subscribe to "" which notify rejects. The debug-WS `reload-assets`
    // command still works for these.
    use crate::components::ShaderStage;
    let mut m = ShaderStageSourceMap::new();
    m.entries.push(ShaderStageSourceEntry {
        stage: ShaderStage::Vertex,
        resolved_path: "standalone.slang".to_string(),
    });
    assert!(m.watch_dirs().is_empty());
}

#[test]
fn slang_extension_is_an_asset_event() {
    // The world Shader's files travel through the same watcher as the texture
    // / mesh paths; the closure routes them to the shader-stage flag rather
    // than the texture-decode batch.
    let evt = Event::new(EventKind::Modify(notify::event::ModifyKind::Any))
        .add_path(PathBuf::from("/tmp/scene.slang"));
    assert!(is_asset_event(&evt));
}

#[test]
fn shader_extension_matches_case_insensitively() {
    assert!(is_shader_extension("slang"));
    assert!(is_shader_extension("Slang"));
    assert!(is_shader_extension("SLANG"));
    assert!(!is_shader_extension("metal"));
    assert!(!is_shader_extension("png"));
    assert!(!is_shader_extension("glb"));
}

fn modified(path: &str) -> Event {
    Event::new(EventKind::Modify(notify::event::ModifyKind::Any)).add_path(PathBuf::from(path))
}

// Each source kind routes to the narrowest pass that can serve it, so a
// dialogue save never pays for a texture decode and a shader save never
// re-reads the world.
#[test]
fn each_extension_routes_to_its_reload_pass() {
    for (path, expected) in [
        ("/tmp/lit.slang", ReloadKind::ShaderStages),
        ("/tmp/LIT.SLANG", ReloadKind::ShaderStages),
        ("/tmp/world.jsonl", ReloadKind::World),
        ("/tmp/WORLD.JSONL", ReloadKind::World),
        ("/tmp/intro.md", ReloadKind::Stories),
        ("/tmp/INTRO.MD", ReloadKind::Stories),
        ("/tmp/model.glb", ReloadKind::Assets),
        ("/tmp/albedo.png", ReloadKind::Assets),
        ("/tmp/studio.hdr", ReloadKind::Assets),
        ("/tmp/grade.cube", ReloadKind::Assets),
        ("/tmp/buffer.bin", ReloadKind::Assets),
    ] {
        assert_eq!(
            classify_event(&modified(path)),
            Some(expected),
            "{path} routes to {expected:?}"
        );
    }
}

// A change nothing is sourced from kicks no pass at all -- neither does an
// access event on a file that would otherwise be relevant.
#[test]
fn an_irrelevant_change_routes_nowhere() {
    assert_eq!(classify_event(&modified("/tmp/notes.txt")), None);
    let accessed = Event::new(EventKind::Access(notify::event::AccessKind::Read))
        .add_path(PathBuf::from("/tmp/model.glb"));
    assert_eq!(classify_event(&accessed), None);
}

// notify reports renames and temp sidecars as multi-path events; the shader
// pass wins over the broader asset pass whichever slot the shader lands in, so
// an editor's atomic save still recompiles rather than re-decoding textures.
#[test]
fn a_shader_among_several_paths_still_routes_to_the_shader_pass() {
    let leading = Event::new(EventKind::Modify(notify::event::ModifyKind::Any))
        .add_path(PathBuf::from("/tmp/lit.slang"))
        .add_path(PathBuf::from("/tmp/albedo.png"));
    let trailing = Event::new(EventKind::Modify(notify::event::ModifyKind::Any))
        .add_path(PathBuf::from("/tmp/albedo.png"))
        .add_path(PathBuf::from("/tmp/lit.slang"));
    assert_eq!(classify_event(&leading), Some(ReloadKind::ShaderStages));
    assert_eq!(classify_event(&trailing), Some(ReloadKind::ShaderStages));
}

// A create or a remove is as much a reload trigger as a modify: an asset added
// or deleted beside its siblings changes what the world resolves to.
#[test]
fn creates_and_removes_route_like_modifies() {
    for kind in [
        EventKind::Create(notify::event::CreateKind::File),
        EventKind::Remove(notify::event::RemoveKind::File),
    ] {
        let evt = Event::new(kind).add_path(PathBuf::from("/tmp/model.glb"));
        assert_eq!(classify_event(&evt), Some(ReloadKind::Assets), "{kind:?}");
    }
}

#[test]
fn state_with_only_shader_stages_still_spawns_a_watcher() {
    // World loaded only via shader-stage edits (no textures, no
    // meshes, no LUTs, no IBL, no world.jsonl) still want the watcher
    // alive so `.slang` saves trigger the recompile pass.
    use crate::components::ShaderStage;
    let mut stages = ShaderStageSourceMap::new();
    stages.entries.push(ShaderStageSourceEntry {
        stage: ShaderStage::Vertex,
        resolved_path: concinnity_host::scratch::path("asset_hot_reload_shader_only.slang")
            .to_string_lossy()
            .into_owned(),
    });
    let state = AssetHotReloadState::from_sources(HotReloadSources {
        shader_stages: stages,
        ..Default::default()
    });
    assert_eq!(state.shader_stages.len(), 1);
    assert_eq!(state.shader_stages.entries[0].stage, ShaderStage::Vertex);
}

#[test]
fn shader_stage_reload_result_default_is_all_zero() {
    let r = ShaderStageReloadResult::default();
    assert_eq!(r.recompiled, 0);
    assert_eq!(r.failed, 0);
    assert!(!r.pipelines_rebuilt);
}

#[test]
fn reload_shader_stages_on_empty_map_is_a_no_op() {
    // The helper must short-circuit before touching the backend on a
    // world with no captured Shader sources (e.g. the GLSL-only
    // path on Vulkan, or a world that pre-dated the capture). The
    // default backend trait impl errors on
    // `update_world_shader_pipelines`; an empty map must not hit it.
    struct DummyBackend;
    impl crate::gfx::scene_flow::SceneControl for DummyBackend {
        fn update_visibility(&mut self, _: usize, _: bool) {}
        fn set_fade(&mut self, _: f32) {}
    }
    impl crate::gfx::backend::RenderBackend for DummyBackend {
        fn window_closed(&mut self) -> bool {
            false
        }
        fn capture_cursor(&mut self) {}
        fn take_input(&mut self) -> crate::gfx::input::RenderInput {
            crate::gfx::input::RenderInput::default()
        }
        fn wait_idle(&self) {}
        fn draw_frame(
            &mut self,
            _: crate::gfx::backend::FrameParams<'_>,
        ) -> crate::gfx::error::RenderResult<()> {
            Ok(())
        }
        fn update_view(&mut self, _: [[f32; 4]; 4]) {}
        fn update_models(&mut self, _: &[(u32, [[f32; 4]; 4])]) {}
        fn retire_draw_object(&mut self, _: usize) {}
        fn upload_skinned(
            &mut self,
            _: &[crate::gfx::mesh_payload::SkinnedVertex],
            _: &[u32],
            _: Vec<crate::gfx::render_types::SkinnedDrawObject>,
        ) -> crate::gfx::error::RenderResult<()> {
            Ok(())
        }
        fn update_skinned_pose(&mut self, _: usize, _: &[[[f32; 4]; 4]]) {}
        fn evict_texture_slot(&mut self, _: usize) -> Result<(), String> {
            Ok(())
        }
        fn update_texture_slot(
            &mut self,
            _: usize,
            _: &concinnity_core::bake::texture::TextureImage,
        ) -> crate::gfx::error::RenderResult<()> {
            Ok(())
        }
        fn evict_mesh(&mut self, _: usize, _: u64) -> Result<(), String> {
            Ok(())
        }
        fn upload_mesh(
            &mut self,
            _: usize,
            _: &[crate::gfx::mesh_payload::Vertex],
            _: &[u16],
            _: u64,
        ) -> crate::gfx::error::RenderResult<()> {
            Ok(())
        }
        fn setup_chunk_streaming(
            &mut self,
            _: usize,
            _: usize,
        ) -> crate::gfx::error::RenderResult<()> {
            Ok(())
        }
        fn add_chunk_mesh(
            &mut self,
            _: crate::gfx::backend::ChunkMesh<'_>,
            _: crate::gfx::draw_slot::SlotAlloc,
        ) -> crate::gfx::error::RenderResult<()> {
            Ok(())
        }
        fn remove_chunk_mesh(&mut self, _: usize, _: u64) -> Result<(), String> {
            Ok(())
        }
        fn set_chunk_model(&mut self, _: usize, _: [[f32; 4]; 4]) -> Result<(), String> {
            Ok(())
        }
    }

    let map = ShaderStageSourceMap::new();
    let mut backend = DummyBackend;
    let r = reload_shader_stages(&map, &mut backend);
    assert_eq!(r.recompiled, 0);
    assert_eq!(r.failed, 0);
    assert!(!r.pipelines_rebuilt);
}

#[test]
fn apply_skinned_layouts_leaves_entries_without_a_matching_layout_alone() {
    // A backend that returned layouts for only a subset of slots (e.g.
    // a future partial-rebuild path) should still leave the other
    // entries' captured state untouched. The Metal `rebuild_skinned_geometry`
    // returns a layout for every slot, but this guard keeps the
    // contract robust to backend variation.
    let mut entries = vec![SkinnedMeshSourceEntry {
        source: "a.glb".to_string(),
        skin_index: 0,
        skinned_index: 7,
        vertex_base: 42,
        vertex_count: 12,
        index_count: 36,
        joint_count: 2,
    }];
    let layouts = vec![crate::gfx::backend::SkinnedSlotLayout {
        skinned_index: 0,
        vertex_base: 0,
        vertex_count: 99,
        index_count: 99,
    }];
    apply_skinned_layouts_to_entries(&mut entries, &layouts);
    assert_eq!(entries[0].vertex_base, 42);
    assert_eq!(entries[0].vertex_count, 12);
    assert_eq!(entries[0].index_count, 36);
}

// Shared fixtures for the decode / poll / pass tests below.

// A minimal RenderBackend that records every hot-reload dispatch so tests can
// assert which trait calls a pass made. Failure toggles let the error branches
// fire without a real GPU.
#[derive(Default)]
struct RecordingBackend {
    texture_updates: Vec<(usize, u32, u32)>,
    lut_updates: Vec<u32>,
    mesh_updates: Vec<usize>,
    static_rebuild_change_counts: Vec<usize>,
    skinned_updates: Vec<usize>,
    skinned_rebuild_change_counts: Vec<usize>,
    skeleton_updates: Vec<(usize, usize)>,
    env_updates: usize,
    fog_updates: usize,
    // Overrides for `draw_geometry_size`; absent draws report `None` like the
    // trait default.
    geometry_sizes: std::collections::HashMap<usize, (usize, usize)>,
    // Overrides for `draw_lod_index_counts`; absent draws report `None` like
    // the trait default.
    lod_counts: std::collections::HashMap<usize, Vec<usize>>,
    // Layouts `rebuild_skinned_geometry` hands back on success, stored as
    // (skinned_index, vertex_base, vertex_count, index_count).
    skinned_layouts: Vec<(usize, u32, usize, usize)>,
    fail_texture_updates: bool,
    fail_lut_updates: bool,
    fail_mesh_updates: bool,
    fail_static_rebuild: bool,
    fail_skinned_updates: bool,
    fail_skinned_rebuild: bool,
    fail_skeleton_update: bool,
    fail_env_updates: bool,
}

impl crate::gfx::scene_flow::SceneControl for RecordingBackend {
    fn update_visibility(&mut self, _: usize, _: bool) {}
    fn set_fade(&mut self, _: f32) {}
}

impl crate::gfx::backend::RenderBackend for RecordingBackend {
    fn window_closed(&mut self) -> bool {
        false
    }
    fn capture_cursor(&mut self) {}
    fn take_input(&mut self) -> crate::gfx::input::RenderInput {
        crate::gfx::input::RenderInput::default()
    }
    fn wait_idle(&self) {}
    fn draw_frame(
        &mut self,
        _: crate::gfx::backend::FrameParams<'_>,
    ) -> crate::gfx::error::RenderResult<()> {
        Ok(())
    }
    fn update_view(&mut self, _: [[f32; 4]; 4]) {}
    fn update_models(&mut self, _: &[(u32, [[f32; 4]; 4])]) {}
    fn retire_draw_object(&mut self, _: usize) {}
    fn upload_skinned(
        &mut self,
        _: &[crate::gfx::mesh_payload::SkinnedVertex],
        _: &[u32],
        _: Vec<crate::gfx::render_types::SkinnedDrawObject>,
    ) -> crate::gfx::error::RenderResult<()> {
        Ok(())
    }
    fn update_skinned_pose(&mut self, _: usize, _: &[[[f32; 4]; 4]]) {}
    fn evict_texture_slot(&mut self, _: usize) -> Result<(), String> {
        Ok(())
    }
    fn update_texture_slot(
        &mut self,
        slot: usize,
        image: &concinnity_core::bake::texture::TextureImage,
    ) -> crate::gfx::error::RenderResult<()> {
        self.texture_updates
            .push((slot, image.width(), image.height()));
        if self.fail_texture_updates {
            return Err("texture update rejected".into());
        }
        Ok(())
    }
    fn evict_mesh(&mut self, _: usize, _: u64) -> Result<(), String> {
        Ok(())
    }
    fn upload_mesh(
        &mut self,
        _: usize,
        _: &[crate::gfx::mesh_payload::Vertex],
        _: &[u16],
        _: u64,
    ) -> crate::gfx::error::RenderResult<()> {
        Ok(())
    }
    fn setup_chunk_streaming(&mut self, _: usize, _: usize) -> crate::gfx::error::RenderResult<()> {
        Ok(())
    }
    fn add_chunk_mesh(
        &mut self,
        _: crate::gfx::backend::ChunkMesh<'_>,
        _: crate::gfx::draw_slot::SlotAlloc,
    ) -> crate::gfx::error::RenderResult<()> {
        Ok(())
    }
    fn remove_chunk_mesh(&mut self, _: usize, _: u64) -> Result<(), String> {
        Ok(())
    }
    fn set_chunk_model(&mut self, _: usize, _: [[f32; 4]; 4]) -> Result<(), String> {
        Ok(())
    }

    fn update_color_lut(&mut self, size: u32, _: &[u8]) -> Result<(), String> {
        self.lut_updates.push(size);
        if self.fail_lut_updates {
            return Err("lut update rejected".to_string());
        }
        Ok(())
    }
    fn draw_geometry_size(&self, draw_idx: usize) -> Option<(usize, usize)> {
        self.geometry_sizes.get(&draw_idx).copied()
    }
    fn draw_lod_index_counts(&self, draw_idx: usize) -> Option<Vec<usize>> {
        self.lod_counts.get(&draw_idx).cloned()
    }
    fn update_mesh_geometry(
        &mut self,
        draw_idx: usize,
        _: &[crate::gfx::mesh_payload::Vertex],
        _: &[u16],
        _: &[(f32, Vec<u16>)],
    ) -> Result<(), String> {
        self.mesh_updates.push(draw_idx);
        if self.fail_mesh_updates {
            return Err("mesh update rejected".to_string());
        }
        Ok(())
    }
    fn rebuild_static_geometry(
        &mut self,
        changes: Vec<crate::gfx::backend::DrawGeometryUpdate>,
    ) -> crate::gfx::error::RenderResult<()> {
        self.static_rebuild_change_counts.push(changes.len());
        if self.fail_static_rebuild {
            return Err("static rebuild rejected".into());
        }
        Ok(())
    }
    fn update_skinned_mesh_geometry(
        &mut self,
        skinned_index: usize,
        _: u32,
        _: &[crate::gfx::mesh_payload::SkinnedVertex],
        _: &[u16],
    ) -> Result<(), String> {
        self.skinned_updates.push(skinned_index);
        if self.fail_skinned_updates {
            return Err("skinned update rejected".to_string());
        }
        Ok(())
    }
    fn rebuild_skinned_geometry(
        &mut self,
        changes: Vec<crate::gfx::backend::SkinnedDrawGeometryUpdate>,
    ) -> Result<Vec<crate::gfx::backend::SkinnedSlotLayout>, String> {
        self.skinned_rebuild_change_counts.push(changes.len());
        if self.fail_skinned_rebuild {
            return Err("skinned rebuild rejected".to_string());
        }
        Ok(self
            .skinned_layouts
            .iter()
            .map(|&(skinned_index, vertex_base, vertex_count, index_count)| {
                crate::gfx::backend::SkinnedSlotLayout {
                    skinned_index,
                    vertex_base,
                    vertex_count,
                    index_count,
                }
            })
            .collect())
    }
    fn update_skinned_skeleton(
        &mut self,
        skinned_index: usize,
        new_joint_count: usize,
    ) -> Result<(), String> {
        self.skeleton_updates.push((skinned_index, new_joint_count));
        if self.fail_skeleton_update {
            return Err("skeleton update rejected".to_string());
        }
        Ok(())
    }
    fn update_environment_map(&mut self, _: &[u8]) -> crate::gfx::error::RenderResult<()> {
        self.env_updates += 1;
        if self.fail_env_updates {
            return Err("environment map update rejected".into());
        }
        Ok(())
    }
    fn update_fog_settings(&mut self, _: Option<crate::gfx::volumetric_fog::FogSettings>) {
        self.fog_updates += 1;
    }
}

// A valid 1x1 RGBA8 PNG, so the texture-decode path has a real file to chew on.
fn write_tiny_png(path: &std::path::Path) {
    std::fs::write(path, concinnity_testing::fixtures::png::one_pixel()).unwrap();
}

// Write a 2x2x2 identity-ish Adobe Cube LUT (8 data lines).
fn write_tiny_cube(path: &std::path::Path) {
    let text = "LUT_3D_SIZE 2\n\
                0 0 0\n1 0 0\n0 1 0\n1 1 0\n0 0 1\n1 0 1\n0 1 1\n1 1 1\n";
    std::fs::write(path, text).unwrap();
}

fn zero_vertex() -> crate::gfx::mesh_payload::Vertex {
    crate::gfx::mesh_payload::Vertex {
        pos: [0.0; 3],
        normal: [0.0; 3],
        tangent: [0.0; 3],
        color: [0.0; 3],
        uv: [0.0; 2],
    }
}

fn zero_skinned_vertex() -> crate::gfx::mesh_payload::SkinnedVertex {
    crate::gfx::mesh_payload::SkinnedVertex {
        pos: [0.0; 3],
        normal: [0.0; 3],
        tangent: [0.0; 3],
        color: [0.0; 3],
        uv: [0.0; 2],
        joints: [0; 4],
        weights: [0.0; 4],
    }
}

fn joint_def(name: &str) -> crate::components::SkeletonJoint {
    crate::components::SkeletonJoint {
        name: name.to_string(),
        parent: -1,
        translation: [0.0; 3],
        rotation_deg: [0.0; 3],
        scale: [1.0; 3],
    }
}

// Push a ready-made decode batch into the state's in-flight slot as if a
// worker had just finished, so `poll_pending_assets` has something to drain.
fn inject_batch(state: &AssetHotReloadState, batch: DecodedAssetBatch) {
    let (tx, rx) = std::sync::mpsc::channel();
    tx.send(batch).unwrap();
    *state.asset_batch_inflight.lock().unwrap() = Some(rx);
}

// decode_asset_batch

#[test]
fn decode_asset_batch_decodes_a_png_texture() {
    let dir = tempfile::tempdir().unwrap();
    let png = dir.path().join("albedo.png");
    write_tiny_png(&png);
    let entry = TextureSourceEntry {
        source: png.to_string_lossy().into_owned(),
        image_index: 0,
        slot: 3,
    };
    let batch = decode_asset_batch(vec![entry], None, Vec::new(), Vec::new());
    assert_eq!(batch.decode_failures, 0);
    assert_eq!(batch.textures.len(), 1);
    let tex = &batch.textures[0];
    assert_eq!(tex.slot, 3);
    assert_eq!((tex.width, tex.height), (1, 1));
    assert_eq!(tex.pixels, vec![10, 20, 30, 255]);
}

#[test]
fn decode_asset_batch_counts_a_missing_texture_as_a_failure() {
    let dir = tempfile::tempdir().unwrap();
    let entry = TextureSourceEntry {
        source: dir
            .path()
            .join("never_written.png")
            .to_string_lossy()
            .into_owned(),
        image_index: 0,
        slot: 0,
    };
    let batch = decode_asset_batch(vec![entry], None, Vec::new(), Vec::new());
    assert!(batch.textures.is_empty());
    assert_eq!(batch.decode_failures, 1);
}

#[test]
fn decode_asset_batch_mixes_successes_and_failures() {
    let dir = tempfile::tempdir().unwrap();
    let png = dir.path().join("ok.png");
    write_tiny_png(&png);
    let good = TextureSourceEntry {
        source: png.to_string_lossy().into_owned(),
        image_index: 0,
        slot: 1,
    };
    let bad = TextureSourceEntry {
        source: dir.path().join("gone.png").to_string_lossy().into_owned(),
        image_index: 0,
        slot: 2,
    };
    let batch = decode_asset_batch(vec![good, bad], None, Vec::new(), Vec::new());
    assert_eq!(batch.textures.len(), 1);
    assert_eq!(batch.decode_failures, 1);
}

#[test]
fn decode_asset_batch_counts_an_unparseable_glb_texture_as_a_failure() {
    // A `.glb`-suffixed source routes through the shared parse cache; garbage
    // bytes must fail the parse and count, not panic.
    let dir = tempfile::tempdir().unwrap();
    let glb = dir.path().join("broken.glb");
    std::fs::write(&glb, b"not a glb at all").unwrap();
    let entry = TextureSourceEntry {
        source: glb.to_string_lossy().into_owned(),
        image_index: 0,
        slot: 0,
    };
    let batch = decode_asset_batch(vec![entry], None, Vec::new(), Vec::new());
    assert!(batch.textures.is_empty());
    assert_eq!(batch.decode_failures, 1);
}

#[test]
fn decode_asset_batch_decodes_a_cube_lut() {
    let dir = tempfile::tempdir().unwrap();
    let cube = dir.path().join("grade.cube");
    write_tiny_cube(&cube);
    let lut = ColorLutSource {
        resolved_path: cube.to_string_lossy().into_owned(),
    };
    let batch = decode_asset_batch(Vec::new(), Some(lut), Vec::new(), Vec::new());
    assert_eq!(batch.decode_failures, 0);
    let lut = batch.color_lut.expect("decoded lut");
    assert_eq!(lut.size, 2);
    assert_eq!(lut.data.len(), 2 * 2 * 2 * 4);
}

#[test]
fn decode_asset_batch_counts_a_missing_lut_as_a_failure() {
    let dir = tempfile::tempdir().unwrap();
    let lut = ColorLutSource {
        resolved_path: dir.path().join("gone.cube").to_string_lossy().into_owned(),
    };
    let batch = decode_asset_batch(Vec::new(), Some(lut), Vec::new(), Vec::new());
    assert!(batch.color_lut.is_none());
    assert_eq!(batch.decode_failures, 1);
}

#[test]
fn decode_asset_batch_counts_a_missing_mesh_source_as_a_failure() {
    let dir = tempfile::tempdir().unwrap();
    let entry = MeshSourceEntry {
        source: dir.path().join("gone.glb").to_string_lossy().into_owned(),
        primitive_index: 0,
        lod_levels: 1,
        lod_distances: Vec::new(),
        draw_indices: vec![0],
    };
    let batch = decode_asset_batch(Vec::new(), None, vec![entry], Vec::new());
    assert!(batch.meshes.is_empty());
    assert_eq!(batch.decode_failures, 1);
}

#[test]
fn decode_asset_batch_counts_a_missing_skinned_source_as_a_failure() {
    let dir = tempfile::tempdir().unwrap();
    let entry = SkinnedMeshSourceEntry {
        source: dir.path().join("gone.glb").to_string_lossy().into_owned(),
        skin_index: 0,
        skinned_index: 0,
        vertex_base: 0,
        vertex_count: 8,
        index_count: 24,
        joint_count: 2,
    };
    let batch = decode_asset_batch(Vec::new(), None, Vec::new(), vec![entry]);
    assert!(batch.skinned_meshes.is_empty());
    assert_eq!(batch.decode_failures, 1);
}

// reload_assets (worker spawn plumbing)

#[test]
fn reload_assets_with_no_sources_spawns_nothing() {
    let state = AssetHotReloadState::from_sources(HotReloadSources::default());
    reload_assets(&state);
    assert!(state.asset_batch_inflight.lock().unwrap().is_none());
    assert!(state.env_map_inflight.lock().unwrap().is_none());
}

#[test]
fn reload_assets_skips_the_spawn_while_a_batch_is_in_flight() {
    let mut map = TextureSourceMap::new();
    map.push_texture("standalone.png".to_string(), 0, 0);
    let state = AssetHotReloadState::from_sources(HotReloadSources {
        map,
        ..Default::default()
    });
    // Simulate a still-running worker: a receiver with a live sender and no
    // payload yet.
    let (_tx, rx) = std::sync::mpsc::channel::<DecodedAssetBatch>();
    *state.asset_batch_inflight.lock().unwrap() = Some(rx);
    reload_assets(&state);
    // Our receiver is still in the slot (a fresh spawn would have replaced it
    // with one whose worker sends a decode-failure batch).
    let slot = state.asset_batch_inflight.lock().unwrap();
    assert!(matches!(
        slot.as_ref().unwrap().try_recv(),
        Err(std::sync::mpsc::TryRecvError::Empty)
    ));
}

#[test]
fn reload_assets_spawns_a_decode_worker_for_a_lut_source() {
    let dir = tempfile::tempdir().unwrap();
    let cube = dir.path().join("grade.cube");
    write_tiny_cube(&cube);
    let state = AssetHotReloadState::from_sources(HotReloadSources {
        color_lut: Some(ColorLutSource {
            resolved_path: cube.to_string_lossy().into_owned(),
        }),
        ..Default::default()
    });
    reload_assets(&state);
    let rx = state
        .asset_batch_inflight
        .lock()
        .unwrap()
        .take()
        .expect("worker scheduled");
    // The worker terminates after decoding the single small LUT, so a
    // blocking receive completes without wall-clock timing assumptions.
    let batch = rx.recv().expect("worker sent a batch");
    assert_eq!(batch.color_lut.expect("decoded lut").size, 2);
    // No EnvironmentMap declared: the envmap slot stays untouched.
    assert!(state.env_map_inflight.lock().unwrap().is_none());
}

// poll_pending_assets

#[test]
fn poll_pending_assets_with_nothing_in_flight_returns_false() {
    let mut state = AssetHotReloadState::from_sources(HotReloadSources::default());
    let mut backend = RecordingBackend::default();
    assert!(!poll_pending_assets(&mut state, &mut backend));
}

#[test]
fn poll_pending_assets_keeps_waiting_while_the_worker_runs() {
    let mut state = AssetHotReloadState::from_sources(HotReloadSources::default());
    let (_tx, rx) = std::sync::mpsc::channel::<DecodedAssetBatch>();
    *state.asset_batch_inflight.lock().unwrap() = Some(rx);
    let mut backend = RecordingBackend::default();
    assert!(!poll_pending_assets(&mut state, &mut backend));
    // Still parked for the next frame.
    assert!(state.asset_batch_inflight.lock().unwrap().is_some());
}

#[test]
fn poll_pending_assets_clears_the_slot_when_the_worker_disconnects() {
    let mut state = AssetHotReloadState::from_sources(HotReloadSources::default());
    let (tx, rx) = std::sync::mpsc::channel::<DecodedAssetBatch>();
    drop(tx);
    *state.asset_batch_inflight.lock().unwrap() = Some(rx);
    let mut backend = RecordingBackend::default();
    assert!(poll_pending_assets(&mut state, &mut backend));
    assert!(state.asset_batch_inflight.lock().unwrap().is_none());
}

#[test]
fn poll_pending_assets_reloads_every_texture_through_the_shared_pool() {
    let mut state = AssetHotReloadState::from_sources(HotReloadSources::default());
    // Albedo and normal maps share one pool, so both reload through
    // `update_texture_slot` at their own pool slot (no separate normal path).
    let batch = DecodedAssetBatch {
        textures: vec![
            DecodedTexture {
                slot: 2,
                width: 4,
                height: 4,
                pixels: vec![0; 64],
                source: "a.png".to_string(),
            },
            DecodedTexture {
                slot: 5,
                width: 8,
                height: 8,
                pixels: vec![0; 256],
                source: "n.png".to_string(),
            },
        ],
        ..Default::default()
    };
    inject_batch(&state, batch);
    let mut backend = RecordingBackend::default();
    assert!(poll_pending_assets(&mut state, &mut backend));
    assert_eq!(backend.texture_updates, vec![(2, 4, 4), (5, 8, 8)]);
    assert!(state.asset_batch_inflight.lock().unwrap().is_none());
}

#[test]
fn poll_pending_assets_survives_a_backend_texture_rejection() {
    let mut state = AssetHotReloadState::from_sources(HotReloadSources::default());
    let batch = DecodedAssetBatch {
        textures: vec![DecodedTexture {
            slot: 0,
            width: 1,
            height: 1,
            pixels: vec![0; 4],
            source: "a.png".to_string(),
        }],
        ..Default::default()
    };
    inject_batch(&state, batch);
    let mut backend = RecordingBackend {
        fail_texture_updates: true,
        ..Default::default()
    };
    // The failure is tallied and logged; the poll still reports consumption.
    assert!(poll_pending_assets(&mut state, &mut backend));
    assert_eq!(backend.texture_updates.len(), 1);
}

#[test]
fn poll_pending_assets_applies_a_color_lut() {
    let mut state = AssetHotReloadState::from_sources(HotReloadSources::default());
    let batch = DecodedAssetBatch {
        color_lut: Some(DecodedColorLut {
            size: 2,
            data: vec![0; 32],
            source: "grade.cube".to_string(),
        }),
        ..Default::default()
    };
    inject_batch(&state, batch);
    let mut backend = RecordingBackend::default();
    assert!(poll_pending_assets(&mut state, &mut backend));
    assert_eq!(backend.lut_updates, vec![2]);
}

fn one_mesh_state(draw_indices: Vec<usize>) -> AssetHotReloadState {
    let mut meshes = MeshSourceMap::new();
    meshes.entries.push(MeshSourceEntry {
        source: "model.glb".to_string(),
        primitive_index: 0,
        lod_levels: 1,
        lod_distances: Vec::new(),
        draw_indices,
    });
    AssetHotReloadState::from_sources(HotReloadSources {
        meshes,
        ..Default::default()
    })
}

fn decoded_mesh(entry_idx: usize, vertex_count: usize) -> DecodedMesh {
    DecodedMesh {
        entry_idx,
        vertices: vec![zero_vertex(); vertex_count],
        indices: vec![0; vertex_count * 3],
        lod_alternates: Vec::new(),
    }
}

#[test]
fn poll_pending_assets_updates_meshes_in_place_per_draw_slot() {
    let mut state = one_mesh_state(vec![2, 5]);
    let batch = DecodedAssetBatch {
        meshes: vec![decoded_mesh(0, 3)],
        ..Default::default()
    };
    inject_batch(&state, batch);
    // Default draw_geometry_size (None) means no size change is detectable:
    // the in-place path fires for every draw slot of the entry.
    let mut backend = RecordingBackend::default();
    assert!(poll_pending_assets(&mut state, &mut backend));
    assert_eq!(backend.mesh_updates, vec![2, 5]);
    assert!(backend.static_rebuild_change_counts.is_empty());
}

#[test]
fn poll_pending_assets_rebuilds_a_size_changed_mesh() {
    let mut state = one_mesh_state(vec![2, 5]);
    let batch = DecodedAssetBatch {
        meshes: vec![decoded_mesh(0, 3)],
        ..Default::default()
    };
    inject_batch(&state, batch);
    let mut backend = RecordingBackend::default();
    // The backend reports different init-time counts for draw 2, so the
    // whole entry (both slots) is queued into one rebuild call.
    backend.geometry_sizes.insert(2, (999, 999));
    assert!(poll_pending_assets(&mut state, &mut backend));
    assert!(backend.mesh_updates.is_empty());
    assert_eq!(backend.static_rebuild_change_counts, vec![2]);
}

#[test]
fn poll_pending_assets_skips_an_out_of_range_mesh_entry() {
    let mut state = AssetHotReloadState::from_sources(HotReloadSources::default());
    let batch = DecodedAssetBatch {
        meshes: vec![decoded_mesh(7, 3)],
        ..Default::default()
    };
    inject_batch(&state, batch);
    let mut backend = RecordingBackend::default();
    assert!(poll_pending_assets(&mut state, &mut backend));
    assert!(backend.mesh_updates.is_empty());
    assert!(backend.static_rebuild_change_counts.is_empty());
}

fn one_skinned_state(entry: SkinnedMeshSourceEntry) -> AssetHotReloadState {
    let mut skinned = SkinnedMeshSourceMap::new();
    skinned.entries.push(entry);
    AssetHotReloadState::from_sources(HotReloadSources {
        skinned_meshes: skinned,
        ..Default::default()
    })
}

fn skinned_entry() -> SkinnedMeshSourceEntry {
    SkinnedMeshSourceEntry {
        source: "rig.glb".to_string(),
        skin_index: 0,
        skinned_index: 4,
        vertex_base: 0,
        vertex_count: 2,
        index_count: 3,
        joint_count: 2,
    }
}

fn decoded_skinned(entry_idx: usize, vertex_count: usize, joints: usize) -> DecodedSkinnedMesh {
    DecodedSkinnedMesh {
        entry_idx,
        vertices: vec![zero_skinned_vertex(); vertex_count],
        indices: vec![0; 3],
        skeleton: (0..joints).map(|i| joint_def(&format!("j{i}"))).collect(),
    }
}

#[test]
fn poll_pending_assets_updates_skinned_meshes_in_place() {
    let mut state = one_skinned_state(skinned_entry());
    let batch = DecodedAssetBatch {
        skinned_meshes: vec![decoded_skinned(0, 2, 2)],
        ..Default::default()
    };
    inject_batch(&state, batch);
    let mut backend = RecordingBackend::default();
    assert!(poll_pending_assets(&mut state, &mut backend));
    assert_eq!(backend.skinned_updates, vec![4]);
    assert!(backend.skinned_rebuild_change_counts.is_empty());
    assert!(state.pending_skeleton_updates.is_empty());
}

#[test]
fn poll_pending_assets_rebuilds_size_changed_skinned_and_refreshes_the_layout() {
    let mut state = one_skinned_state(skinned_entry());
    let batch = DecodedAssetBatch {
        skinned_meshes: vec![decoded_skinned(0, 5, 2)],
        ..Default::default()
    };
    inject_batch(&state, batch);
    let mut backend = RecordingBackend::default();
    backend.skinned_layouts.push((4, 7, 5, 3));
    assert!(poll_pending_assets(&mut state, &mut backend));
    assert!(backend.skinned_updates.is_empty());
    assert_eq!(backend.skinned_rebuild_change_counts, vec![1]);
    let entry = &state.skinned_meshes.entries[0];
    assert_eq!(entry.vertex_base, 7);
    assert_eq!(entry.vertex_count, 5);
    assert_eq!(entry.index_count, 3);
}

#[test]
fn poll_pending_assets_queues_a_skeleton_update_on_joint_count_change() {
    let mut state = one_skinned_state(skinned_entry());
    let batch = DecodedAssetBatch {
        skinned_meshes: vec![decoded_skinned(0, 2, 3)],
        ..Default::default()
    };
    inject_batch(&state, batch);
    let mut backend = RecordingBackend::default();
    assert!(poll_pending_assets(&mut state, &mut backend));
    assert_eq!(backend.skeleton_updates, vec![(4, 3)]);
    assert_eq!(state.skinned_meshes.entries[0].joint_count, 3);
    let drained = state.drain_pending_skeleton_updates();
    assert_eq!(drained.len(), 1);
    assert_eq!(drained[0].skinned_index, 4);
}

#[test]
fn poll_pending_assets_failed_skinned_rebuild_drops_queued_skeleton_updates() {
    let mut state = one_skinned_state(skinned_entry());
    // Both the joint count and the vertex count changed, so the rebuild path
    // fires with a skeleton update queued behind it.
    let batch = DecodedAssetBatch {
        skinned_meshes: vec![decoded_skinned(0, 5, 3)],
        ..Default::default()
    };
    inject_batch(&state, batch);
    let mut backend = RecordingBackend {
        fail_skinned_rebuild: true,
        ..Default::default()
    };
    assert!(poll_pending_assets(&mut state, &mut backend));
    // The geometry kept its old shape, so the SkeletonPose refresh and the
    // joint-count write must both be discarded.
    assert!(state.pending_skeleton_updates.is_empty());
    assert!(backend.skeleton_updates.is_empty());
    assert_eq!(state.skinned_meshes.entries[0].joint_count, 2);
}

#[test]
fn poll_pending_assets_failed_joint_resize_keeps_the_old_count() {
    let mut state = one_skinned_state(skinned_entry());
    let batch = DecodedAssetBatch {
        skinned_meshes: vec![decoded_skinned(0, 2, 3)],
        ..Default::default()
    };
    inject_batch(&state, batch);
    let mut backend = RecordingBackend {
        fail_skeleton_update: true,
        ..Default::default()
    };
    assert!(poll_pending_assets(&mut state, &mut backend));
    assert_eq!(state.skinned_meshes.entries[0].joint_count, 2);
    // The queued SkeletonPose update is pruned so it cannot desync from the
    // unchanged backend joint buffers.
    assert!(state.pending_skeleton_updates.is_empty());
}

// poll_pending_envmap

#[test]
fn poll_pending_envmap_with_nothing_in_flight_returns_false() {
    let state = AssetHotReloadState::from_sources(HotReloadSources::default());
    let mut backend = RecordingBackend::default();
    assert!(!poll_pending_envmap(&state, &mut backend));
    assert_eq!(backend.env_updates, 0);
}

#[test]
fn poll_pending_envmap_keeps_waiting_while_the_worker_runs() {
    let state = AssetHotReloadState::from_sources(HotReloadSources::default());
    let (_tx, rx) = std::sync::mpsc::channel::<Result<Vec<u8>, String>>();
    *state.env_map_inflight.lock().unwrap() = Some(rx);
    let mut backend = RecordingBackend::default();
    assert!(!poll_pending_envmap(&state, &mut backend));
    assert!(state.env_map_inflight.lock().unwrap().is_some());
}

#[test]
fn poll_pending_envmap_applies_a_successful_payload() {
    let state = AssetHotReloadState::from_sources(HotReloadSources::default());
    let (tx, rx) = std::sync::mpsc::channel();
    tx.send(Ok(vec![1u8, 2, 3])).unwrap();
    *state.env_map_inflight.lock().unwrap() = Some(rx);
    let mut backend = RecordingBackend::default();
    assert!(poll_pending_envmap(&state, &mut backend));
    assert_eq!(backend.env_updates, 1);
    assert!(state.env_map_inflight.lock().unwrap().is_none());
}

#[test]
fn poll_pending_envmap_consumes_a_failed_convolution_without_a_backend_call() {
    let state = AssetHotReloadState::from_sources(HotReloadSources::default());
    let (tx, rx) = std::sync::mpsc::channel();
    tx.send(Err("bad hdr".to_string())).unwrap();
    *state.env_map_inflight.lock().unwrap() = Some(rx);
    let mut backend = RecordingBackend::default();
    assert!(poll_pending_envmap(&state, &mut backend));
    assert_eq!(backend.env_updates, 0);
    assert!(state.env_map_inflight.lock().unwrap().is_none());
}

#[test]
fn poll_pending_envmap_clears_the_slot_when_the_worker_disconnects() {
    let state = AssetHotReloadState::from_sources(HotReloadSources::default());
    let (tx, rx) = std::sync::mpsc::channel::<Result<Vec<u8>, String>>();
    drop(tx);
    *state.env_map_inflight.lock().unwrap() = Some(rx);
    let mut backend = RecordingBackend::default();
    assert!(poll_pending_envmap(&state, &mut backend));
    assert_eq!(backend.env_updates, 0);
    assert!(state.env_map_inflight.lock().unwrap().is_none());
}

#[test]
fn poll_pending_envmap_survives_a_backend_rejection() {
    let state = AssetHotReloadState::from_sources(HotReloadSources::default());
    let (tx, rx) = std::sync::mpsc::channel();
    tx.send(Ok(vec![9u8; 4])).unwrap();
    *state.env_map_inflight.lock().unwrap() = Some(rx);
    let mut backend = RecordingBackend {
        fail_env_updates: true,
        ..Default::default()
    };
    // The backend rejected the payload; the poll still reports consumption and
    // clears the slot rather than retrying the same failed convolution.
    assert!(poll_pending_envmap(&state, &mut backend));
    assert_eq!(backend.env_updates, 1);
    assert!(state.env_map_inflight.lock().unwrap().is_none());
}

#[test]
fn reload_assets_spawns_an_envmap_worker() {
    let dir = tempfile::tempdir().unwrap();
    // A path that does not resolve to a valid HDR: the worker still spawns and
    // parks a receiver, then reports a decode failure on its own thread.
    let hdr = dir.path().join("sky.hdr");
    let state = AssetHotReloadState::from_sources(HotReloadSources {
        environment_map: Some(EnvironmentMapSource {
            resolved_path: hdr.to_string_lossy().into_owned(),
            prefilter_face_size: 8,
            irradiance_face_size: 8,
            prefilter_samples: 4,
            prefilter_clamp: 4.0,
        }),
        ..Default::default()
    });
    reload_assets(&state);
    // The convolution worker was scheduled onto its own slot. Drain the parked
    // receiver so the worker thread completes before the test ends.
    let rx = state
        .env_map_inflight
        .lock()
        .unwrap()
        .take()
        .expect("envmap worker scheduled");
    let _ = rx.recv();
}

// poll_pending_assets: remaining apply branches

#[test]
fn poll_pending_assets_survives_a_color_lut_rejection() {
    let mut state = AssetHotReloadState::from_sources(HotReloadSources::default());
    let batch = DecodedAssetBatch {
        color_lut: Some(DecodedColorLut {
            size: 2,
            data: vec![0; 32],
            source: "grade.cube".to_string(),
        }),
        ..Default::default()
    };
    inject_batch(&state, batch);
    let mut backend = RecordingBackend {
        fail_lut_updates: true,
        ..Default::default()
    };
    // The failure is tallied and logged; the poll still reports consumption.
    assert!(poll_pending_assets(&mut state, &mut backend));
    assert_eq!(backend.lut_updates, vec![2]);
}

#[test]
fn poll_pending_assets_rebuilds_on_a_changed_lod_breakdown() {
    let mut state = one_mesh_state(vec![0]);
    let batch = DecodedAssetBatch {
        meshes: vec![DecodedMesh {
            entry_idx: 0,
            vertices: vec![zero_vertex(); 3],
            indices: vec![0; 9],
            lod_alternates: vec![(10.0, vec![0u16; 6])],
        }],
        ..Default::default()
    };
    inject_batch(&state, batch);
    let mut backend = RecordingBackend::default();
    // The slot's live LOD1 carries 3 indices; the reload's carries 6, so the
    // entry is queued for a rebuild rather than an in-place update even though
    // the base geometry size is unchanged.
    backend.lod_counts.insert(0, vec![3]);
    assert!(poll_pending_assets(&mut state, &mut backend));
    assert!(backend.mesh_updates.is_empty());
    assert_eq!(backend.static_rebuild_change_counts, vec![1]);
}

#[test]
fn poll_pending_assets_skips_an_out_of_range_skinned_entry() {
    let mut state = one_skinned_state(skinned_entry());
    let batch = DecodedAssetBatch {
        skinned_meshes: vec![decoded_skinned(9, 2, 2)],
        ..Default::default()
    };
    inject_batch(&state, batch);
    let mut backend = RecordingBackend::default();
    assert!(poll_pending_assets(&mut state, &mut backend));
    assert!(backend.skinned_updates.is_empty());
    assert!(backend.skinned_rebuild_change_counts.is_empty());
}

#[test]
fn poll_pending_assets_survives_a_skinned_in_place_rejection() {
    let mut state = one_skinned_state(skinned_entry());
    // Same vertex / index / joint counts as the entry: the in-place update path
    // fires, and the backend rejects it.
    let batch = DecodedAssetBatch {
        skinned_meshes: vec![decoded_skinned(0, 2, 2)],
        ..Default::default()
    };
    inject_batch(&state, batch);
    let mut backend = RecordingBackend {
        fail_skinned_updates: true,
        ..Default::default()
    };
    assert!(poll_pending_assets(&mut state, &mut backend));
    assert_eq!(backend.skinned_updates, vec![4]);
    assert!(backend.skinned_rebuild_change_counts.is_empty());
}

// reload_volumetric_fog

fn write_world_line(dir: &std::path::Path, line: &str) -> String {
    let path = dir.join("world.jsonl");
    std::fs::write(&path, format!("{line}\n")).unwrap();
    path.to_string_lossy().into_owned()
}

#[test]
fn reload_volumetric_fog_missing_file_is_a_no_op() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("gone.jsonl");
    let mut last = None;
    let mut backend = RecordingBackend::default();
    let r = reload_volumetric_fog(path.to_str().unwrap(), &mut last, &mut backend);
    assert!(!r.updated);
    assert!(last.is_none());
    assert_eq!(backend.fog_updates, 0);
}

#[test]
fn reload_volumetric_fog_invalid_jsonl_is_a_no_op() {
    let dir = tempfile::tempdir().unwrap();
    let path = write_world_line(dir.path(), "{ this is not json");
    let mut last = None;
    let mut backend = RecordingBackend::default();
    let r = reload_volumetric_fog(&path, &mut last, &mut backend);
    assert!(!r.updated);
    assert_eq!(backend.fog_updates, 0);
}

#[test]
fn reload_volumetric_fog_pushes_an_enabled_fog_once() {
    let dir = tempfile::tempdir().unwrap();
    let path = write_world_line(
        dir.path(),
        r#"{"name":"fog","type":"VolumetricFog","args":{"enabled":true,"density":0.5}}"#,
    );
    let mut last = None;
    let mut backend = RecordingBackend::default();
    let r = reload_volumetric_fog(&path, &mut last, &mut backend);
    assert!(r.updated);
    assert!(last.is_some());
    assert_eq!(backend.fog_updates, 1);

    // Unchanged file: the dedupe swallows the second pass.
    let r = reload_volumetric_fog(&path, &mut last, &mut backend);
    assert!(!r.updated);
    assert_eq!(backend.fog_updates, 1);
}

#[test]
fn reload_volumetric_fog_disabling_pushes_none() {
    let dir = tempfile::tempdir().unwrap();
    let path = write_world_line(
        dir.path(),
        r#"{"name":"fog","type":"VolumetricFog","args":{"enabled":true}}"#,
    );
    let mut last = None;
    let mut backend = RecordingBackend::default();
    assert!(reload_volumetric_fog(&path, &mut last, &mut backend).updated);
    assert!(last.is_some());

    let path = write_world_line(
        dir.path(),
        r#"{"name":"fog","type":"VolumetricFog","args":{"enabled":false}}"#,
    );
    assert!(reload_volumetric_fog(&path, &mut last, &mut backend).updated);
    assert!(last.is_none());
    assert_eq!(backend.fog_updates, 2);
}

#[test]
fn reload_volumetric_fog_removed_asset_pushes_none() {
    let dir = tempfile::tempdir().unwrap();
    let path = write_world_line(
        dir.path(),
        r#"{"name":"fog","type":"VolumetricFog","args":{"enabled":true}}"#,
    );
    let mut last = None;
    let mut backend = RecordingBackend::default();
    assert!(reload_volumetric_fog(&path, &mut last, &mut backend).updated);

    // The fog line disappears from the world entirely.
    let path = write_world_line(
        dir.path(),
        r#"{"name":"gfx","type":"GraphicsConfig","args":{}}"#,
    );
    assert!(reload_volumetric_fog(&path, &mut last, &mut backend).updated);
    assert!(last.is_none());
}

#[test]
fn reload_volumetric_fog_bad_args_keep_the_previous_state() {
    let dir = tempfile::tempdir().unwrap();
    let path = write_world_line(
        dir.path(),
        r#"{"name":"fog","type":"VolumetricFog","args":{"density":"oops"}}"#,
    );
    let mut last = None;
    let mut backend = RecordingBackend::default();
    let r = reload_volumetric_fog(&path, &mut last, &mut backend);
    assert!(!r.updated);
    assert!(last.is_none());
    assert_eq!(backend.fog_updates, 0);
}

// reload_procedural_meshes

fn normalised_box_args(half: f32) -> crate::components::ProceduralMesh {
    serde_json::from_value(serde_json::json!({
        "generator": "box",
        "half_extents": [half, half, half],
    }))
    .unwrap()
}

fn one_proc_mesh_map(
    name: &str,
    args: crate::components::ProceduralMesh,
) -> ProceduralMeshSourceMap {
    let mut map = ProceduralMeshSourceMap::new();
    map.entries.push(ProceduralMeshSourceEntry {
        name: name.to_string(),
        args,
        draw_indices: vec![0, 1],
    });
    map
}

fn box_world_line(name: &str, half: f32) -> String {
    format!(
        r#"{{"name":"{name}","type":"ProceduralMesh","args":{{"generator":"box","half_extents":[{half},{half},{half}]}}}}"#,
    )
}

#[test]
fn reload_procedural_meshes_with_an_empty_map_short_circuits() {
    let mut map = ProceduralMeshSourceMap::new();
    let mut backend = RecordingBackend::default();
    let r = reload_procedural_meshes("does_not_matter.jsonl", &mut map, &mut backend);
    assert_eq!((r.regenerated, r.unchanged, r.failed), (0, 0, 0));
}

#[test]
fn reload_procedural_meshes_missing_file_regenerates_nothing() {
    let dir = tempfile::tempdir().unwrap();
    let mut map = one_proc_mesh_map("box_mesh", normalised_box_args(0.5));
    let mut backend = RecordingBackend::default();
    let r = reload_procedural_meshes(
        dir.path().join("gone.jsonl").to_str().unwrap(),
        &mut map,
        &mut backend,
    );
    assert_eq!((r.regenerated, r.unchanged, r.failed), (0, 0, 0));
    assert!(backend.mesh_updates.is_empty());
}

#[test]
fn reload_procedural_meshes_skips_unchanged_args() {
    let dir = tempfile::tempdir().unwrap();
    let path = write_world_line(dir.path(), &box_world_line("box_mesh", 0.5));
    let mut map = one_proc_mesh_map("box_mesh", normalised_box_args(0.5));
    let mut backend = RecordingBackend::default();
    let r = reload_procedural_meshes(&path, &mut map, &mut backend);
    assert_eq!((r.regenerated, r.unchanged, r.failed), (0, 1, 0));
    assert!(backend.mesh_updates.is_empty());
}

#[test]
fn reload_procedural_meshes_treats_a_missing_jsonl_entry_as_unchanged() {
    let dir = tempfile::tempdir().unwrap();
    let path = write_world_line(
        dir.path(),
        r#"{"name":"gfx","type":"GraphicsConfig","args":{}}"#,
    );
    let mut map = one_proc_mesh_map("box_mesh", normalised_box_args(0.5));
    let mut backend = RecordingBackend::default();
    let r = reload_procedural_meshes(&path, &mut map, &mut backend);
    assert_eq!((r.regenerated, r.unchanged, r.failed), (0, 1, 0));
}

#[test]
fn reload_procedural_meshes_treats_unparseable_args_as_unchanged() {
    // A live-edited entry with args the generator cannot parse never reaches
    // the regen; the entry falls out of the new-args map and reads as
    // missing-from-jsonl.
    let dir = tempfile::tempdir().unwrap();
    let path = write_world_line(
        dir.path(),
        r#"{"name":"box_mesh","type":"ProceduralMesh","args":{"generator":42}}"#,
    );
    let mut map = one_proc_mesh_map("box_mesh", normalised_box_args(0.5));
    let mut backend = RecordingBackend::default();
    let r = reload_procedural_meshes(&path, &mut map, &mut backend);
    assert_eq!((r.regenerated, r.unchanged, r.failed), (0, 1, 0));
}

#[test]
fn reload_procedural_meshes_regenerates_changed_args_in_place() {
    let dir = tempfile::tempdir().unwrap();
    let path = write_world_line(dir.path(), &box_world_line("box_mesh", 1.0));
    let mut map = one_proc_mesh_map("box_mesh", normalised_box_args(0.5));
    let mut backend = RecordingBackend::default();
    let r = reload_procedural_meshes(&path, &mut map, &mut backend);
    assert_eq!((r.regenerated, r.unchanged, r.failed), (1, 0, 0));
    // In-place path (the default backend reports no size data): one update
    // per draw slot, and the captured args advance to the new snapshot.
    assert_eq!(backend.mesh_updates, vec![0, 1]);
    assert!(backend.static_rebuild_change_counts.is_empty());
    assert_eq!(map.entries[0].args, normalised_box_args(1.0));
}

#[test]
fn reload_procedural_meshes_keeps_args_when_the_backend_rejects_the_update() {
    let dir = tempfile::tempdir().unwrap();
    let path = write_world_line(dir.path(), &box_world_line("box_mesh", 1.0));
    let mut map = one_proc_mesh_map("box_mesh", normalised_box_args(0.5));
    let mut backend = RecordingBackend {
        fail_mesh_updates: true,
        ..Default::default()
    };
    let r = reload_procedural_meshes(&path, &mut map, &mut backend);
    assert_eq!((r.regenerated, r.unchanged, r.failed), (0, 0, 1));
    // The captured args stay at the pre-edit snapshot so the next reload
    // still sees the pending change.
    assert_eq!(map.entries[0].args, normalised_box_args(0.5));
}

#[test]
fn reload_procedural_meshes_rebuilds_on_size_change() {
    let dir = tempfile::tempdir().unwrap();
    let path = write_world_line(dir.path(), &box_world_line("box_mesh", 1.0));
    let mut map = one_proc_mesh_map("box_mesh", normalised_box_args(0.5));
    let mut backend = RecordingBackend::default();
    backend.geometry_sizes.insert(0, (1, 1));
    let r = reload_procedural_meshes(&path, &mut map, &mut backend);
    assert_eq!((r.regenerated, r.unchanged, r.failed), (1, 0, 0));
    assert!(backend.mesh_updates.is_empty());
    assert_eq!(backend.static_rebuild_change_counts, vec![2]);
    assert_eq!(map.entries[0].args, normalised_box_args(1.0));
}

#[test]
fn reload_procedural_meshes_failed_rebuild_keeps_captured_args() {
    let dir = tempfile::tempdir().unwrap();
    let path = write_world_line(dir.path(), &box_world_line("box_mesh", 1.0));
    let mut map = one_proc_mesh_map("box_mesh", normalised_box_args(0.5));
    let mut backend = RecordingBackend {
        fail_static_rebuild: true,
        ..Default::default()
    };
    backend.geometry_sizes.insert(0, (1, 1));
    let r = reload_procedural_meshes(&path, &mut map, &mut backend);
    assert_eq!((r.regenerated, r.unchanged, r.failed), (0, 0, 1));
    assert_eq!(map.entries[0].args, normalised_box_args(0.5));
}

// reload_stories (edge cases beyond the round-trip test above)

#[test]
fn reload_stories_missing_world_file_returns_nothing() {
    let dir = tempfile::tempdir().unwrap();
    let mut snapshots = std::collections::HashMap::new();
    let stories = reload_stories(
        dir.path().join("gone.jsonl").to_str().unwrap(),
        &mut snapshots,
    );
    assert!(stories.is_empty());
    assert!(snapshots.is_empty());
}

#[test]
fn reload_stories_ignores_worlds_without_stories() {
    let dir = tempfile::tempdir().unwrap();
    let path = write_world_line(
        dir.path(),
        r#"{"name":"gfx","type":"GraphicsConfig","args":{}}"#,
    );
    let mut snapshots = std::collections::HashMap::new();
    assert!(reload_stories(&path, &mut snapshots).is_empty());
    assert!(snapshots.is_empty());
}

// reload_shader_stages

#[test]
fn reload_shader_stages_missing_source_counts_as_failed_without_a_rebuild() {
    use crate::components::ShaderStage;
    let dir = tempfile::tempdir().unwrap();
    let mut map = ShaderStageSourceMap::new();
    map.entries.push(ShaderStageSourceEntry {
        stage: ShaderStage::Vertex,
        resolved_path: dir
            .path()
            .join("zz_never_written_stage.slang")
            .to_string_lossy()
            .into_owned(),
    });
    // The RecordingBackend would record a pipeline rebuild; a compile failure
    // must abort the pass before the backend is touched.
    let mut backend = RecordingBackend::default();
    let r = reload_shader_stages(&map, &mut backend);
    assert_eq!(r.recompiled, 0);
    assert_eq!(r.failed, 1);
    assert!(!r.pipelines_rebuilt);
}

// AssetHotReloadState

#[test]
fn state_reload_flag_round_trips() {
    let state = AssetHotReloadState::from_sources(HotReloadSources::default());
    assert!(!state.reload_requested());
    state
        .pending
        .store(true, std::sync::atomic::Ordering::SeqCst);
    assert!(state.reload_requested());
    state.clear_flag();
    assert!(!state.reload_requested());
}

#[test]
fn state_debug_format_summarises_the_catalogue() {
    let mut map = TextureSourceMap::new();
    map.push_texture("standalone.png".to_string(), 0, 0);
    let state = AssetHotReloadState::from_sources(HotReloadSources {
        map,
        ..Default::default()
    });
    let dump = format!("{state:?}");
    assert!(dump.contains("AssetHotReloadState"));
    assert!(dump.contains("entries: 1"));
    assert!(dump.contains("pending: false"));
    assert!(dump.contains("env_map_inflight: false"));
    assert!(dump.contains("asset_batch_inflight: false"));
}

#[test]
fn fresh_state_starts_with_empty_story_snapshots() {
    let state = AssetHotReloadState::from_sources(HotReloadSources::default());
    assert!(state.story_snapshots.is_empty());
    assert!(state.world_jsonl_path.is_none());
}

// watcher helpers

#[test]
fn access_events_are_not_asset_events() {
    let evt = Event::new(EventKind::Access(notify::event::AccessKind::Any))
        .add_path(PathBuf::from("/tmp/a.png"));
    assert!(!is_asset_event(&evt));
}

#[test]
fn events_without_paths_are_not_asset_events() {
    let evt = Event::new(EventKind::Modify(notify::event::ModifyKind::Any));
    assert!(!is_asset_event(&evt));
}

#[test]
fn extensionless_paths_are_not_asset_events() {
    let evt = Event::new(EventKind::Modify(notify::event::ModifyKind::Any))
        .add_path(PathBuf::from("/tmp/Makefile"));
    assert!(!is_asset_event(&evt));
}

#[test]
fn create_and_remove_events_count_as_asset_events() {
    let create = Event::new(EventKind::Create(notify::event::CreateKind::Any))
        .add_path(PathBuf::from("/tmp/a.png"));
    assert!(is_asset_event(&create));
    let remove = Event::new(EventKind::Remove(notify::event::RemoveKind::Any))
        .add_path(PathBuf::from("/tmp/a.png"));
    assert!(is_asset_event(&remove));
}

#[test]
fn uppercase_texture_extension_still_matches() {
    let evt = Event::new(EventKind::Modify(notify::event::ModifyKind::Any))
        .add_path(PathBuf::from("/tmp/ALBEDO.PNG"));
    assert!(is_asset_event(&evt));
}

#[test]
fn spawn_watcher_returns_none_when_no_directory_is_watchable() {
    let dir = tempfile::tempdir().unwrap();
    let mut meshes = MeshSourceMap::new();
    meshes.entries.push(MeshSourceEntry {
        source: dir
            .path()
            .join("no_such_subdir")
            .join("model.glb")
            .to_string_lossy()
            .into_owned(),
        primitive_index: 0,
        lod_levels: 1,
        lod_distances: Vec::new(),
        draw_indices: vec![0],
    });
    let sources = HotReloadSources {
        meshes,
        ..Default::default()
    };
    let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
    assert!(spawn_watcher(&sources, flag).is_none());
}

#[test]
fn spawn_watcher_subscribes_to_an_existing_source_directory() {
    let dir = tempfile::tempdir().unwrap();
    let mut map = TextureSourceMap::new();
    map.push_texture(
        dir.path().join("albedo.png").to_string_lossy().into_owned(),
        0,
        0,
    );
    let sources = HotReloadSources {
        map,
        ..Default::default()
    };
    let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
    // No file is ever written into the watched directory, so the closure
    // never fires and the process-global pending flags stay untouched.
    assert!(spawn_watcher(&sources, flag).is_some());
}

#[test]
fn story_source_dirs_collects_unique_parents_from_story_imports() {
    let dir = tempfile::tempdir().unwrap();
    let world = dir.path().join("world.jsonl");
    let lines = [
        r#"{"name":"s1","type":"StoryImport","args":{"source":"stories/tale.md"}}"#,
        r#"{"name":"s2","type":"StoryImport","args":{"source":"bare.md"}}"#,
        r#"{"name":"s3","type":"StoryImport","args":{"source":"stories/other.md"}}"#,
        r#"{"name":"gfx","type":"GraphicsConfig","args":{}}"#,
        r#"{"name":"s4","type":"StoryImport","args":{}}"#,
        "not json at all",
    ];
    std::fs::write(&world, lines.join("\n")).unwrap();
    let dirs = story_source_dirs(world.to_str().unwrap());
    assert_eq!(dirs.len(), 2);
    assert!(dirs.contains(&PathBuf::from(".")));
    assert!(dirs.contains(&PathBuf::from("stories")));
}

#[test]
fn story_source_dirs_of_a_missing_world_is_empty() {
    let dir = tempfile::tempdir().unwrap();
    let dirs = story_source_dirs(dir.path().join("gone.jsonl").to_str().unwrap());
    assert!(dirs.is_empty());
}

// decode backend-rejection sub-branches (poll_pending_assets)
//
// The static-mesh in-place and rebuild error paths are driven purely by the
// RecordingBackend's failure toggles, so no real model file is needed. The
// ColorLut and in-place skinned rejection paths have no matching toggle on the
// shared RecordingBackend and are left uncovered here.

#[test]
fn poll_pending_assets_survives_an_in_place_mesh_rejection() {
    // Default draw_geometry_size (None) keeps the in-place path; the backend
    // rejects every update but the poll must tally the failure and still report
    // the batch consumed rather than panic.
    let mut state = one_mesh_state(vec![2, 5]);
    let batch = DecodedAssetBatch {
        meshes: vec![decoded_mesh(0, 3)],
        ..Default::default()
    };
    inject_batch(&state, batch);
    let mut backend = RecordingBackend {
        fail_mesh_updates: true,
        ..Default::default()
    };
    assert!(poll_pending_assets(&mut state, &mut backend));
    // Both draw slots were attempted before the rejection was recorded.
    assert_eq!(backend.mesh_updates, vec![2, 5]);
    assert!(backend.static_rebuild_change_counts.is_empty());
    assert!(state.asset_batch_inflight.lock().unwrap().is_none());
}

#[test]
fn poll_pending_assets_survives_a_failed_static_rebuild() {
    // A reported size change routes the whole entry into rebuild_static_geometry,
    // which the backend rejects. The poll tallies the failure and clears the
    // in-flight slot without touching the in-place path.
    let mut state = one_mesh_state(vec![2, 5]);
    let batch = DecodedAssetBatch {
        meshes: vec![decoded_mesh(0, 3)],
        ..Default::default()
    };
    inject_batch(&state, batch);
    let mut backend = RecordingBackend {
        fail_static_rebuild: true,
        ..Default::default()
    };
    backend.geometry_sizes.insert(2, (999, 999));
    assert!(poll_pending_assets(&mut state, &mut backend));
    assert!(backend.mesh_updates.is_empty());
    assert_eq!(backend.static_rebuild_change_counts, vec![2]);
    assert!(state.asset_batch_inflight.lock().unwrap().is_none());
}

// spawn_envmap_worker in-flight skip (via reload_assets)

#[test]
fn reload_assets_skips_the_envmap_spawn_while_a_convolution_is_in_flight() {
    // With only an EnvironmentMap declared, reload_assets spawns no asset-decode
    // worker (no textures / LUT / meshes) and must leave an already-running
    // envmap convolution untouched so the user re-triggers after it lands.
    let dir = tempfile::tempdir().unwrap();
    let env_map = EnvironmentMapSource {
        resolved_path: dir.path().join("studio.hdr").to_string_lossy().into_owned(),
        prefilter_face_size: 64,
        irradiance_face_size: 16,
        prefilter_samples: 64,
        prefilter_clamp: 12.0,
    };
    let state = AssetHotReloadState::from_sources(HotReloadSources {
        environment_map: Some(env_map),
        ..Default::default()
    });
    // Simulate a still-running convolution: a receiver whose sender is alive and
    // has sent nothing yet.
    let (_tx, rx) = std::sync::mpsc::channel::<Result<Vec<u8>, String>>();
    *state.env_map_inflight.lock().unwrap() = Some(rx);
    reload_assets(&state);
    // Our receiver is still parked (a fresh spawn would have replaced it), and
    // no asset-decode batch was scheduled.
    let slot = state.env_map_inflight.lock().unwrap();
    assert!(matches!(
        slot.as_ref().unwrap().try_recv(),
        Err(std::sync::mpsc::TryRecvError::Empty)
    ));
    assert!(state.asset_batch_inflight.lock().unwrap().is_none());
}

// run_frame (the per-frame reload entry, driven over a RecordingBackend)

// Reset the process-global reload flags so a run_frame test starts from a known
// state regardless of what ran before it. Callers hold `test_support::lock()`
// for the whole test so this is race-free.
fn clear_pending_flags() {
    super::pending::take_pending_world();
    super::pending::take_pending_shader_stages();
    super::pending::take_pending_stories();
}

// Drive one `run_frame` over a fresh RecordingBackend with an empty
// WorldReloadState and fog bookkeeping, returning the effects, the backend (so
// callers can assert which dispatches fired), and the fog bookkeeping the
// world.jsonl pass may have updated.
fn drive_run_frame(
    state: &mut AssetHotReloadState,
) -> (
    FrameHotReloadEffects,
    RecordingBackend,
    Option<crate::gfx::volumetric_fog::FogSettings>,
) {
    let mut backend = RecordingBackend::default();
    let world_reload: Option<crate::gfx::graphics_system::WorldReloadState> = None;
    let mut last_fog: Option<crate::gfx::volumetric_fog::FogSettings> = None;
    let effects = {
        let mut apply = crate::gfx::graphics_system::HotReloadApplyParts {
            backend: &mut backend,
            world_reload: &world_reload,
            last_fog_settings: &mut last_fog,
        };
        run_frame(state, &mut apply, None)
    };
    (effects, backend, last_fog)
}

#[test]
fn run_frame_with_no_pending_flags_returns_empty_effects() {
    let _guard = crate::test_support::lock();
    clear_pending_flags();
    let mut state = AssetHotReloadState::from_sources(HotReloadSources::default());
    let (effects, backend, last_fog) = drive_run_frame(&mut state);
    assert!(effects.skeleton_updates.is_empty());
    assert!(effects.story_updates.is_empty());
    assert!(last_fog.is_none());
    assert_eq!(backend.fog_updates, 0);
    assert!(backend.mesh_updates.is_empty());
    assert!(backend.texture_updates.is_empty());
}

#[test]
fn run_frame_consumes_the_state_reload_flag_without_spawning_on_an_empty_catalogue() {
    let _guard = crate::test_support::lock();
    clear_pending_flags();
    let mut state = AssetHotReloadState::from_sources(HotReloadSources::default());
    state
        .pending
        .store(true, std::sync::atomic::Ordering::SeqCst);
    let (effects, _backend, _last_fog) = drive_run_frame(&mut state);
    // The flag was consumed and, with no file-backed sources, no worker spawned.
    assert!(!state.reload_requested());
    assert!(state.asset_batch_inflight.lock().unwrap().is_none());
    assert!(state.env_map_inflight.lock().unwrap().is_none());
    assert!(effects.story_updates.is_empty());
}

#[test]
fn run_frame_consumes_the_shader_stage_flag() {
    let _guard = crate::test_support::lock();
    clear_pending_flags();
    let mut state = AssetHotReloadState::from_sources(HotReloadSources::default());
    super::pending::set_pending_shader_stages();
    let _ = drive_run_frame(&mut state);
    // run_frame swallowed the flag; the empty Shader map made the pass a
    // no-op, but the flag consumption is the observable that it fired.
    assert!(!super::pending::take_pending_shader_stages());
}

#[test]
fn run_frame_reloads_stories_when_the_story_flag_is_set() {
    let _guard = crate::test_support::lock();
    clear_pending_flags();
    let dir = tempfile::tempdir().unwrap();
    let md = dir.path().join("tale.md");
    std::fs::write(
        &md,
        "---\ntitle: Tale\ncharacters:\n  a: Ana\n---\n\n# start\n\nHello there.\n",
    )
    .unwrap();
    let world = dir.path().join("world.jsonl");
    std::fs::write(
        &world,
        format!(
            "{}\n",
            serde_json::json!({
                "name": "tale", "type": "StoryImport",
                "args": {"source": md.to_str().unwrap()}
            })
        ),
    )
    .unwrap();
    let mut state = AssetHotReloadState::from_sources(HotReloadSources {
        world_jsonl_path: Some(world.to_string_lossy().into_owned()),
        ..Default::default()
    });
    super::pending::set_pending_stories();
    let (effects, _backend, _last_fog) = drive_run_frame(&mut state);
    assert_eq!(effects.story_updates.len(), 1);
    assert_eq!(effects.story_updates[0].title, "Tale");
    // The flag was consumed by the pass.
    assert!(!super::pending::take_pending_stories());
}

#[test]
fn run_frame_reloads_world_assets_when_the_world_flag_is_set() {
    let _guard = crate::test_support::lock();
    clear_pending_flags();
    let dir = tempfile::tempdir().unwrap();
    let world = write_world_line(
        dir.path(),
        r#"{"name":"fog","type":"VolumetricFog","args":{"enabled":true,"density":0.5}}"#,
    );
    let mut state = AssetHotReloadState::from_sources(HotReloadSources {
        world_jsonl_path: Some(world),
        ..Default::default()
    });
    super::pending::set_pending_world();
    let (_effects, backend, last_fog) = drive_run_frame(&mut state);
    // The world.jsonl pass applied the enabled fog exactly once and recorded it
    // into the caller's dedupe bookkeeping.
    assert_eq!(backend.fog_updates, 1);
    assert!(last_fog.is_some());
    assert!(!super::pending::take_pending_world());
}

// -- driver -------------------------------------------------------------

use super::driver::{HotReloadDriver, apply_effects};

#[test]
fn driver_on_a_world_without_graphics_stays_unarmed() {
    let mut driver = HotReloadDriver::new();
    let mut world = crate::ecs::World::new();
    driver.drive(&mut world);
    assert!(driver.pending().is_none());
}

#[test]
fn driver_rearm_swaps_the_pending_flag() {
    // A world rebuild re-captures sources; arming again must hand out a fresh
    // flag (the server refreshes its shared copy every tick for this reason).
    let mut driver = HotReloadDriver::new();
    driver.arm(HotReloadSources::default());
    let first = driver.pending().expect("armed driver exposes a flag");
    driver.arm(HotReloadSources::default());
    let second = driver.pending().expect("re-armed driver exposes a flag");
    assert!(!std::sync::Arc::ptr_eq(&first, &second));
}

#[test]
fn armed_driver_survives_a_drive_over_an_empty_world() {
    // A backendless world (headless test, or a frame before init finishes)
    // must not panic or drop the armed state.
    let mut driver = HotReloadDriver::new();
    driver.arm(HotReloadSources::default());
    let mut world = crate::ecs::World::new();
    driver.drive(&mut world);
    assert!(driver.pending().is_some());
}

#[test]
fn apply_effects_splices_the_matching_skeleton_pose_only() {
    use crate::components::SkeletonPose;
    use crate::gfx::skeleton::{Joint, JointPose, Skeleton};

    let mut world = crate::ecs::World::new();
    world.add_component(SkeletonPose::new(
        Default::default(),
        0,
        Skeleton::new(Vec::new()),
    ));
    world.add_component(SkeletonPose::new(
        Default::default(),
        1,
        Skeleton::new(Vec::new()),
    ));

    let new_skeleton = Skeleton::new(vec![Joint {
        name: String::new(),
        parent: None,
        bind: JointPose::default(),
    }]);
    apply_effects(
        &mut world,
        FrameHotReloadEffects {
            skeleton_updates: vec![PendingSkeletonUpdate {
                skinned_index: 1,
                new_skeleton,
            }],
            story_updates: Vec::new(),
        },
    );

    let joints_of = |idx: usize| {
        world
            .query::<SkeletonPose>()
            .find(|p| p.skinned_index == idx)
            .map(|p| (p.skeleton.len(), p.joint_matrices.len()))
            .unwrap()
    };
    // The targeted pose carries the new 1-joint hierarchy with matching
    // matrices; the other pose keeps its empty skeleton (its seed matrices,
    // padded to a 1-identity minimum, are untouched too).
    assert_eq!(joints_of(1), (1, 1));
    assert_eq!(joints_of(0).0, 0);
}

#[test]
fn apply_effects_sends_a_story_reload_event() {
    let mut world = crate::ecs::World::new();
    let story = crate::components::Story {
        asset_id: Default::default(),
        title: "Tale".to_string(),
        nodes: Vec::new(),
        text_speed: 0.0,
        scaffold: Default::default(),
        save_key: String::new(),
    };
    apply_effects(
        &mut world,
        FrameHotReloadEffects {
            skeleton_updates: Vec::new(),
            story_updates: vec![story],
        },
    );

    let mut cursor = crate::ecs::EventCursor::default();
    let events = world
        .events::<crate::components::StoryReload>()
        .expect("a StoryReload event queue exists after apply");
    let received: Vec<_> = events.read(&mut cursor).collect();
    assert_eq!(received.len(), 1);
    assert_eq!(received[0].story.title, "Tale");
}