nsi-intermediate 0.1.0

Renderer-agnostic intermediate representation for the Nodal Scene Interface – ɴsɪ.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
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
//! Tests for [`super`].
//!
//! Separate file per the workspace rule: source files do not grow
//! inline `#[cfg(test)]` modules.

use super::*;
use crate::OwnedData;
use nsi_trait::Type;

/// An ɴsɪ `"strength"` connection argument.
fn strength(value: i32) -> OwnedArgument {
    OwnedArgument {
        name: "strength".to_string(),
        ..priority(value)
    }
}

/// An ɴsɪ `"priority"` connection argument.
fn priority(value: i32) -> OwnedArgument {
    OwnedArgument {
        name: "priority".to_string(),
        type_tag: Type::I32,
        array_length: 1,
        flags: 0,
        data: OwnedData::I32(vec![value]),
    }
}

fn arg(name: &str, value: f32) -> OwnedArgument {
    OwnedArgument {
        name: name.to_string(),
        type_tag: Type::F32,
        array_length: 1,
        flags: 0,
        data: OwnedData::F32(vec![value]),
    }
}

#[test]
fn creates_and_finds_a_node() {
    let mut scene = Scene::default();
    scene.create("cam", "perspectivecamera").unwrap();
    assert_eq!(scene.node("cam").unwrap().node_type(), "perspectivecamera");
}

#[test]
fn set_attribute_overwrites_by_name() {
    let mut scene = Scene::default();
    scene.create("cam", "perspectivecamera").unwrap();
    scene.set_attribute("cam", vec![arg("fov", 45.0)]).unwrap();
    scene.set_attribute("cam", vec![arg("fov", 60.0)]).unwrap();
    assert_eq!(scene.node("cam").unwrap().attributes().count(), 1);
    assert_eq!(
        scene.node("cam").unwrap().attribute("fov").unwrap().data,
        OwnedData::F32(vec![60.0])
    );
}

#[test]
fn time_samples_are_kept_separately_and_sorted() {
    let mut scene = Scene::default();
    scene.create("xf", "transform").unwrap();
    scene
        .set_attribute_at_time("xf", 1.0, vec![arg("t", 1.0)])
        .unwrap();
    scene
        .set_attribute_at_time("xf", 0.0, vec![arg("t", 0.0)])
        .unwrap();
    assert_eq!(
        scene.attribute_times("xf", "t").unwrap(),
        vec![0.0, 1.0],
        "recorded later-time-first and reported in time order",
    );
    assert_eq!(
        scene
            .node("xf")
            .unwrap()
            .sample_calls("t")
            .unwrap()
            .iter()
            .map(|(time, _)| *time)
            .collect::<Vec<_>>(),
        vec![1.0, 0.0],
        "while the log keeps the order they were set in",
    );
    assert_eq!(scene.node("xf").unwrap().attributes().count(), 0);
}

#[test]
fn delete_removes_the_node_and_its_edges() {
    let mut scene = Scene::default();
    scene.create("xf", "transform").unwrap();
    scene.create("mesh", "mesh").unwrap();
    scene
        .connect("mesh", None, "xf", "objects")
        .expect("known attribute");
    scene.delete("xf").unwrap();
    assert!(scene.node("xf").is_none());
    assert!(scene.edges.is_empty());
}

#[test]
fn delete_attribute_removes_one_key() {
    let mut scene = Scene::default();
    scene.create("cam", "perspectivecamera").unwrap();
    scene
        .set_attribute("cam", vec![arg("fov", 45.0), arg("fs", 1.0)])
        .unwrap();
    scene.delete_attribute("cam", "fov");
    assert!(scene.node("cam").unwrap().attribute("fov").is_none());
    assert!(scene.node("cam").unwrap().attribute("fs").is_some());
}

/// Node order is insertion order. The `.nsi` stream diff against
/// 3Delight is meaningless if replay reorders nodes.
#[test]
fn node_order_is_insertion_order() {
    let mut scene = Scene::default();
    for handle in ["z", "a", "m"] {
        scene.create(handle, "transform").unwrap();
    }
    let order: Vec<&str> = scene.nodes().map(|(handle, _)| handle).collect();
    assert_eq!(order, vec!["z", "a", "m"]);
}

/// An unmapped destination must propagate, not be swallowed.
#[test]
fn connect_carries_an_unlisted_destination() {
    let mut scene = Scene::default();
    scene.create("a", "transform").unwrap();
    scene.create("b", "transform").unwrap();
    scene.connect("a", None, "b", "nonsense").unwrap();
    assert_eq!(
        scene.edges[0].kind,
        EdgeKind::Other {
            to_attribute: "nonsense".to_string()
        }
    );
}

/// `delete_attribute` walks the motion samples too. Only the static
/// path was proven before, and the two are separate tables.
#[test]
fn delete_attribute_removes_from_every_time_sample() {
    let mut scene = Scene::default();
    scene.create("xf", "transform").unwrap();
    scene.set_attribute("xf", vec![arg("t", 9.0)]).unwrap();
    scene
        .set_attribute_at_time("xf", 0.0, vec![arg("t", 0.0)])
        .unwrap();
    scene
        .set_attribute_at_time("xf", 1.0, vec![arg("t", 1.0), arg("keep", 2.0)])
        .unwrap();

    scene.delete_attribute("xf", "t");

    let node = &scene.node("xf").unwrap();
    assert!(node.attribute("t").is_none(), "static copy removed");
    assert!(node.sample_calls("t").is_none(), "every sample of it too");
    assert!(node.sample_calls("keep").is_some());
}

/// `disconnect` removes the edge it names and leaves the others.
#[test]
fn disconnect_removes_only_the_named_edge() {
    let mut scene = Scene::default();
    for handle in ["a", "b"] {
        scene.create(handle, "transform").unwrap();
        scene.connect(handle, None, ".root", "objects").unwrap();
    }

    scene.disconnect("a", None, ".root", "objects").unwrap();

    assert_eq!(scene.edges.len(), 1);
    assert_eq!(scene.edges[0].from, "b");
}

/// Classification is how `disconnect` identifies the edge, so an
/// unlisted destination removes exactly the edge that carries it.
#[test]
fn disconnect_removes_an_unlisted_destination() {
    let mut scene = Scene::default();
    scene.create("a", "transform").unwrap();
    scene.create("b", "transform").unwrap();
    scene.connect("a", None, "b", "nonsense").unwrap();
    scene.disconnect("a", None, "b", "nonsense").unwrap();
    assert!(scene.edges.is_empty());
}

/// ɴsɪ: `NSISetAttribute` "replaces any value previously set by
/// NSISetAttribute or NSISetAttributeAtTime". Leaving the samples behind
/// makes a node that was set static after being sampled look
/// motion-blurred to the resolver forever.
#[test]
fn a_static_set_clears_the_motion_samples_of_that_name() {
    let mut scene = Scene::default();
    scene.create("xf", "transform").unwrap();
    scene
        .set_attribute_at_time("xf", 0.0, vec![arg("t", 0.0)])
        .unwrap();
    scene
        .set_attribute_at_time("xf", 1.0, vec![arg("t", 1.0), arg("keep", 9.0)])
        .unwrap();

    scene.set_attribute("xf", vec![arg("t", 5.0)]).unwrap();

    let node = &scene.node("xf").unwrap();
    assert_eq!(node.attribute("t").unwrap().data, OwnedData::F32(vec![5.0]));
    assert!(node.sample_calls("t").is_none(), "its samples went with it");
    assert!(
        node.sample_calls("keep").is_some(),
        "an unrelated sampled attribute is untouched"
    );
}

/// And the other direction: `NSISetAttributeAtTime` "replaces any
/// value previously set by NSISetAttribute".
#[test]
fn a_sampled_set_clears_the_static_value_of_that_name() {
    let mut scene = Scene::default();
    scene.create("xf", "transform").unwrap();
    scene
        .set_attribute("xf", vec![arg("t", 5.0), arg("keep", 9.0)])
        .unwrap();

    scene
        .set_attribute_at_time("xf", 0.0, vec![arg("t", 0.0)])
        .unwrap();

    let node = &scene.node("xf").unwrap();
    assert!(node.attribute("t").is_none(), "static value replaced");
    assert!(node.attribute("keep").is_some(), "others untouched");
}

/// ɴsɪ: "It is not an error to create a connection which already
/// exists." Recording it twice would make the node look like it had
/// two parents, failing resolution for it and everything beneath it.
#[test]
fn a_repeated_connect_updates_rather_than_duplicates() {
    let mut scene = Scene::default();
    scene.create("grp", "transform").unwrap();
    scene.connect("grp", None, ".root", "objects").unwrap();
    scene
        .connect_with_arguments(
            "grp",
            None,
            ".root",
            "objects",
            vec![priority(4)],
        )
        .unwrap();

    assert_eq!(scene.edges.len(), 1, "one edge, not two parents");
    assert_eq!(scene.edges[0].priority(), 4, "arguments updated");
}

/// ɴsɪ: "the handle for either node, as well as any or all of the
/// attributes, may be the special value `.all`". The documented
/// example is disconnecting everything from the scene root.
#[test]
fn disconnect_all_matches_every_source() {
    let mut scene = Scene::default();
    for handle in ["a", "b", "c", "other"] {
        scene.create(handle, "transform").unwrap();
    }
    scene.connect("a", None, ".root", "objects").unwrap();
    scene.connect("b", None, ".root", "objects").unwrap();
    scene.connect("c", None, "other", "objects").unwrap();

    scene
        .disconnect(crate::ALL, None, ".root", "objects")
        .unwrap();

    assert_eq!(scene.edges.len(), 1);
    assert_eq!(scene.edges[0].to, "other");
}

/// `.all` in the destination handle, and in the attribute name.
#[test]
fn disconnect_all_matches_destinations_and_attributes() {
    let mut scene = Scene::default();
    for handle in ["a", "b", "x", "y", "z"] {
        scene.create(handle, "transform").unwrap();
    }
    scene.connect("a", None, "x", "objects").unwrap();
    scene.connect("a", None, "y", "geometryattributes").unwrap();
    scene.connect("b", None, "z", "objects").unwrap();

    // Every attribute of `a`, whatever it connects to.
    scene.disconnect("a", None, crate::ALL, crate::ALL).unwrap();

    assert_eq!(scene.edges.len(), 1);
    assert_eq!(scene.edges[0].from, "b");
}

/// `.all` as `to_attribute` must not be classified -- it names no single
/// class -- and must not error.
#[test]
fn disconnect_with_an_all_attribute_is_not_a_classify_error() {
    let mut scene = Scene::default();
    scene.create("a", "screen").unwrap();
    scene.create("x", "perspectivecamera").unwrap();
    scene.connect("a", None, "x", "screens").unwrap();
    assert!(scene.disconnect("a", None, "x", crate::ALL).is_ok());
    assert!(scene.edges.is_empty());
}

/// 3Delight answers `set_attribute` on an unknown handle with
/// "unknown node handle". Fabricating one is worse than rejecting
/// it: the node joins the scene, satisfies later `connect` calls --
/// defeating the check those do -- and replays as a `Create` the
/// renderer never wrote. The stream gate cannot see it, because a
/// call log records the call either way.
#[test]
fn setting_an_attribute_on_an_uncreated_handle_is_an_error() {
    let mut scene = Scene::default();

    assert_eq!(
        scene.set_attribute("ghost", vec![arg("fov", 45.0)]),
        Err(RecordError::UnknownHandle {
            handle: "ghost".to_string()
        })
    );
    assert_eq!(
        scene.set_attribute_at_time("ghost", 0.0, vec![arg("t", 1.0)]),
        Err(RecordError::UnknownHandle {
            handle: "ghost".to_string()
        })
    );
    assert!(scene.node("ghost").is_none(), "nothing fabricated");

    // And so the connection check cannot be walked around.
    scene.create("real", "transform").unwrap();
    assert!(scene.connect("real", None, "ghost", "objects").is_err());
}

/// The reserved handles are the exception: ɴsɪ says they "don't need
/// to be created", and every scene sets `.global`.
#[test]
fn the_reserved_handles_take_attributes_without_a_create() {
    let mut scene = Scene::default();
    assert!(
        scene
            .set_attribute(crate::GLOBAL, vec![arg("quality", 1.0)])
            .is_ok()
    );
    assert!(scene.node(crate::GLOBAL).is_some());
}

/// ɴsɪ: a recursive delete removes "nodes which connect to the
/// specified node", which is what makes deleting a whole shader
/// network one call.
#[test]
fn a_recursive_delete_takes_the_network_with_it() {
    let mut scene = Scene::default();
    for handle in ["attr", "surface", "texture"] {
        scene.create(handle, "shader").unwrap();
    }
    scene.create("mesh", "mesh").unwrap();
    scene.connect("mesh", None, ".root", "objects").unwrap();
    scene
        .connect("attr", None, "mesh", "geometryattributes")
        .unwrap();
    scene
        .connect("surface", None, "attr", "surfaceshader")
        .unwrap();
    scene
        .connect("texture", Some("out"), "surface", "color")
        .unwrap();

    scene.delete_recursive("attr").unwrap();

    assert!(scene.node("attr").is_none());
    assert!(scene.node("surface").is_none(), "network followed");
    assert!(scene.node("texture").is_none(), "and transitively");
    assert!(scene.node("mesh").is_some(), "the geometry survives");
}

/// ɴsɪ: a node is spared when it "also has connections which do not
/// eventually lead to the specified node".
#[test]
fn a_recursive_delete_spares_a_node_used_elsewhere() {
    let mut scene = Scene::default();
    scene.create("shared", "shader").unwrap();
    scene.create("a", "attributes").unwrap();
    scene.create("b", "attributes").unwrap();
    scene.connect("shared", None, "a", "surfaceshader").unwrap();
    scene.connect("shared", None, "b", "surfaceshader").unwrap();

    scene.delete_recursive("a").unwrap();

    assert!(scene.node("a").is_none());
    assert!(scene.node("shared").is_some(), "still feeds `b`");
    assert!(scene.node("b").is_some());
}

/// ɴsɪ: "a connection with a strength greater than 0 will block the
/// progression of a recursive NSIDelete."
#[test]
fn strength_blocks_a_recursive_delete() {
    let mut scene = Scene::default();
    scene.create("keep", "shader").unwrap();
    scene.create("go", "shader").unwrap();
    scene.create("attr", "attributes").unwrap();
    scene
        .connect_with_arguments(
            "keep",
            None,
            "attr",
            "surfaceshader",
            vec![strength(1)],
        )
        .unwrap();
    scene
        .connect("go", None, "attr", "displacementshader")
        .unwrap();

    scene.delete_recursive("attr").unwrap();

    assert!(scene.node("attr").is_none());
    assert!(scene.node("keep").is_some(), "strength blocked it");
    assert!(scene.node("go").is_none(), "the weak connection did not");
}

/// The strength rule has to hold transitively. Checking it only where a
/// candidate is first discovered lets the same node be swept in through
/// a second, weak path -- and ɴsɪ spares a node whose connection to the
/// deleted one has strength, however it was reached.
#[test]
fn strength_blocks_a_recursive_delete_through_a_second_path() {
    let mut scene = Scene::default();
    scene.create("attr", "attributes").unwrap();
    scene.create("relay", "attributes").unwrap();
    scene.create("keep", "shader").unwrap();
    // `relay` is swept in: its only connection leads to `attr`.
    scene
        .connect("relay", None, "attr", "surfaceshader")
        .unwrap();
    // `keep` holds `attr` strongly, but also feeds `relay` weakly.
    scene
        .connect_with_arguments(
            "keep",
            None,
            "attr",
            "displacementshader",
            vec![strength(1)],
        )
        .unwrap();
    scene
        .connect("keep", None, "relay", "surfaceshader")
        .unwrap();

    scene.delete_recursive("attr").unwrap();

    assert!(scene.node("attr").is_none());
    assert!(scene.node("relay").is_none(), "only fed the deleted node");
    assert!(
        scene.node("keep").is_some(),
        "its strong connection spares it, whichever path found it"
    );
}

/// A non-recursive delete still removes only the node named.
#[test]
fn a_plain_delete_is_not_recursive() {
    let mut scene = Scene::default();
    scene.create("attr", "attributes").unwrap();
    scene.create("shader", "shader").unwrap();
    scene
        .connect("shader", None, "attr", "surfaceshader")
        .unwrap();

    scene.delete("attr").unwrap();

    assert!(scene.node("shader").is_some());
}

/// The reserved nodes are not deletable either way.
#[test]
fn a_recursive_delete_still_refuses_the_reserved_nodes() {
    let mut scene = Scene::default();
    assert!(scene.delete_recursive(crate::ROOT).is_err());
}

/// ɴsɪ: "the nodes on which the connection is performed must
/// exist." A connection between handles that were never created
/// builds a graph whose nodes are missing, and resolution then
/// answers for it as though it were real. 3Delight's call log
/// cannot catch this, so the stream gate never would.
#[test]
fn connecting_an_uncreated_handle_is_an_error() {
    let mut scene = Scene::default();
    scene.create("real", "transform").unwrap();

    assert_eq!(
        scene.connect("ghost", None, "real", "objects"),
        Err(RecordError::UnknownHandle {
            handle: "ghost".to_string()
        })
    );
    assert_eq!(
        scene.connect("real", None, "ghost", "objects"),
        Err(RecordError::UnknownHandle {
            handle: "ghost".to_string()
        })
    );
    assert!(scene.edges.is_empty(), "nothing recorded");
}

/// ɴsɪ's `.root` and `.global` "don't need to be created", so they
/// are known without appearing in `nodes`.
#[test]
fn the_reserved_handles_need_no_create() {
    let mut scene = Scene::default();
    scene.create("xf", "transform").unwrap();
    assert!(scene.connect("xf", None, crate::ROOT, "objects").is_ok());
    assert!(scene.connect("xf", None, crate::GLOBAL, "objects").is_ok());
}

/// ɴsɪ puts `.all` in *four* positions, the source attribute
/// included. Classifying `Some(".all")` as a port name makes it
/// match nothing, so the call is a silent no-op.
#[test]
fn disconnect_all_matches_every_source_attribute() {
    let mut scene = Scene::default();
    scene.create("s1", "shader").unwrap();
    scene.create("s2", "shader").unwrap();
    scene
        .connect("s1", Some("outColor"), "s2", "inColor")
        .unwrap();
    scene
        .connect("s1", Some("outAlpha"), "s2", "inColor")
        .unwrap();

    scene
        .disconnect("s1", Some(crate::ALL), "s2", "inColor")
        .unwrap();

    assert!(scene.edges.is_empty(), "every source port matched");
}

/// ɴsɪ: "it is not possible to delete the root or the global node."
/// Deleting `.root` here would strip every membership edge in the
/// scene, quietly detaching everything.
#[test]
fn the_reserved_nodes_cannot_be_deleted() {
    let mut scene = Scene::default();
    scene.create("xf", "transform").unwrap();
    scene.connect("xf", None, crate::ROOT, "objects").unwrap();

    assert_eq!(
        scene.delete(crate::ROOT),
        Err(RecordError::Reserved {
            handle: crate::ROOT.to_string()
        })
    );
    assert_eq!(scene.edges.len(), 1, "the scene is intact");
    assert!(scene.delete(crate::GLOBAL).is_err());
}

/// ɴsɪ: re-`create` "does nothing if all other parameters match the
/// call which created that node. Otherwise, it emits an error."
#[test]
fn recreating_with_a_different_type_is_an_error() {
    let mut scene = Scene::default();
    scene.create("x", "mesh").unwrap();

    assert_eq!(
        scene.create("x", "transform"),
        Err(RecordError::TypeMismatch {
            handle: "x".to_string(),
            existing: "mesh".to_string(),
            requested: "transform".to_string(),
        })
    );
    assert_eq!(
        scene.node("x").unwrap().node_type(),
        "mesh",
        "type unchanged"
    );
}

/// Re-creating with the same type is the no-op ɴsɪ describes, and
/// must not disturb the node's attributes.
#[test]
fn recreating_with_the_same_type_is_a_no_op() {
    let mut scene = Scene::default();
    scene.create("x", "mesh").unwrap();
    scene.set_attribute("x", vec![arg("fov", 45.0)]).unwrap();

    scene.create("x", "mesh").unwrap();

    assert_eq!(
        scene.node("x").unwrap().attributes().count(),
        1,
        "attributes survive"
    );
}

/// 3Delight answers a non-finite sample time with `E6026 invalid time`.
/// Storing one produced a `motion_times` a backend could not iterate:
/// a `NaN` compares equal to nothing, an `inf` sorts past every real
/// shutter time.
#[test]
fn a_non_finite_sample_time_is_refused() {
    let mut scene = Scene::default();
    scene.create("xf", "transform").unwrap();

    for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
        assert_eq!(
            scene.set_attribute_at_time("xf", bad, vec![arg("t", 1.0)]),
            Err(RecordError::InvalidTime {
                handle: "xf".to_string()
            })
        );
    }
    assert!(scene.node("xf").unwrap().samples().next().is_none());
}

/// `-0.0` and `0.0` are **one** sample. The renderer reads a `-0` time
/// as `+0`, so keeping them apart handed a backend two matrices at
/// times that compare equal -- a zero-length motion segment where
/// 3Delight sees a single sample holding the later value.
#[test]
fn negative_zero_is_the_same_sample_time_as_zero() {
    let mut scene = Scene::default();
    scene.create("xf", "transform").unwrap();
    scene
        .set_attribute_at_time("xf", -0.0, vec![arg("t", 5.0)])
        .unwrap();
    scene
        .set_attribute_at_time("xf", 0.0, vec![arg("t", 9.0)])
        .unwrap();

    let samples = scene.attribute_samples("xf", "t").unwrap();
    assert_eq!(samples.len(), 1, "one sample, as the renderer has");
    assert!(!samples[0].0.is_sign_negative(), "normalised to +0");
    assert_eq!(samples[0].1.data, OwnedData::F32(vec![9.0]));
}

/// ɴsɪ's reserved handles exist already, and 3Delight answers a
/// `create` on one with "already exists". Accepting it kept a node that
/// replay drops, so the scene changed on its own first round trip.
#[test]
fn the_reserved_handles_cannot_be_created() {
    let mut scene = Scene::default();
    for handle in [crate::ROOT, crate::GLOBAL] {
        assert_eq!(
            scene.create(handle, "transform"),
            Err(RecordError::Reserved {
                handle: handle.to_string()
            })
        );
        assert!(scene.node(handle).is_none(), "nothing recorded");
    }
}

/// The value is the last **call**'s, not the greatest time's.
///
/// Rendered, with `visibility` set only through `SetAttributeAtTime`:
/// `t=1 -> 0` then `t=0 -> 1` leaves the object **visible**, and
/// `t=1 -> 1` then `t=0 -> 0` hides it. The same two times, opposite
/// answers, and reading the greatest time gets both backwards -- which
/// is what this did until `Node::samples` became a call log.
#[test]
fn effective_takes_the_last_call_not_the_greatest_time() {
    for (first, second, expected) in
        [(0.0, 1.0, 1.0), (1.0, 0.0, 0.0), (2.0, 3.0, 3.0)]
    {
        let mut scene = Scene::default();
        scene.create("a", "attributes").unwrap();
        // The later time is set first, so the two orders disagree.
        scene
            .set_attribute_at_time("a", 1.0, vec![arg("visibility", first)])
            .unwrap();
        scene
            .set_attribute_at_time("a", 0.0, vec![arg("visibility", second)])
            .unwrap();

        let node = scene.node("a").expect("created");
        assert_eq!(
            node.effective("visibility").expect("set at a time").data,
            OwnedData::F32(vec![expected]),
            "the t=0 call came last",
        );
    }
}

/// Re-setting a time already recorded is another **call**: the log
/// keeps both, the later one is the latest definition, and the two
/// together are one sample.
#[test]
fn a_re_set_time_is_another_call_and_the_later_one_stands() {
    let mut scene = Scene::default();
    scene.create("a", "attributes").unwrap();
    for (time, value) in [(0.0, 1.0), (1.0, 2.0), (0.0, 3.0)] {
        scene
            .set_attribute_at_time("a", time, vec![arg("visibility", value)])
            .unwrap();
    }

    let node = scene.node("a").expect("created");
    assert_eq!(
        node.sample_calls("visibility").unwrap().len(),
        3,
        "three calls"
    );
    assert_eq!(
        node.effective("visibility").expect("set at a time").data,
        OwnedData::F32(vec![3.0]),
        "the last of them",
    );
    assert_eq!(
        scene.attribute_times("a", "visibility").unwrap(),
        vec![0.0, 1.0],
        "but two samples",
    );
}

/// Every field of a [`Node`] is public, so a caller can build one no
/// recorder would. Reading it must not panic: a resolver that aborted
/// a render over a hand-built node would be a worse answer than an
/// attribute that goes quiet.
///
/// There is one table now rather than three, so the states a caller
/// can reach are far narrower than they were -- an empty call list is
/// what is left of them.
#[test]
fn a_hand_built_node_does_not_panic_the_readers() {
    let mut scene = Scene::default();
    scene.create("xf", "transform").unwrap();
    scene.create("q", "mesh").unwrap();
    scene.connect("xf", None, ".root", "objects").unwrap();
    scene.connect("q", None, "xf", "objects").unwrap();
    crate::handle::map_get_mut(&mut scene.nodes, "xf")
        .expect("created")
        .sample_table_mut()
        .insert(crate::handle::handle("transformationmatrix"), Vec::new());

    let node = scene.node("xf").expect("created");
    assert!(node.effective("transformationmatrix").is_none());
    assert!(scene.motion_times("q").unwrap().is_empty());
    assert!(scene.world_transform("q").is_ok());
    assert!(
        scene
            .attribute_samples("xf", "transformationmatrix")
            .unwrap()
            .is_empty()
    );

    let mut out = Vec::new();
    crate::write_stream(&scene, &mut out).expect("writes");
    assert!(
        !String::from_utf8(out)
            .unwrap()
            .contains("SetAttributeAtTime"),
        "a sample that is not there is not invented",
    );
}

/// A static call clears the log, as ɴsɪ says it should.
#[test]
fn a_static_call_clears_the_call_order() {
    let mut scene = Scene::default();
    scene.create("a", "attributes").unwrap();
    scene
        .set_attribute_at_time("a", 1.0, vec![arg("visibility", 1.0)])
        .unwrap();
    scene
        .set_attribute("a", vec![arg("visibility", 2.0)])
        .unwrap();

    let node = scene.node("a").expect("created");
    assert!(node.sample_calls("visibility").is_none());
    assert_eq!(
        node.effective("visibility").expect("static").data,
        OwnedData::F32(vec![2.0]),
    );
}

/// And `delete_attribute` forgets it too.
#[test]
fn delete_attribute_clears_the_log() {
    let mut scene = Scene::default();
    scene.create("a", "attributes").unwrap();
    scene
        .set_attribute_at_time("a", 1.0, vec![arg("visibility", 1.0)])
        .unwrap();
    scene.delete_attribute("a", "visibility");

    let node = scene.node("a").expect("created");
    assert!(node.sample_calls("visibility").is_none());
    assert!(node.effective("visibility").is_none());
}

/// The record is **net**, not a log: forty sets of one attribute are
/// one entry, and a handle created and deleted in one interval leaves
/// no live node behind.
#[test]
fn the_record_is_net_not_a_log() {
    let mut scene = Scene::default();
    scene.create("a", "attributes").unwrap();
    for value in 0..40u8 {
        scene
            .set_attribute("a", vec![arg("visibility", f32::from(value))])
            .unwrap();
    }
    scene.create("gone", "mesh").unwrap();
    scene.delete("gone").unwrap();

    let changes = scene.take_changes();
    assert_eq!(changes.attributes().count(), 1, "one name, forty calls");
    assert!(changes.attributes().any(|pair| pair == ("a", "visibility")));
    assert!(
        !changes.was_created("gone"),
        "created and deleted in one interval: the create is undone, and \
         a consumer that never saw the node has nothing to undo",
    );
    assert_eq!(
        changes.deleted_type("gone"),
        Some("mesh"),
        "only the delete stands, with the type the handle no longer has",
    );

    assert_eq!(
        scene.take_changes(),
        Changes::default(),
        "taking clears, so the next synchronise starts empty",
    );
}

/// A repeated `connect` that only changes `"priority"` adds and
/// removes no edge, and changes which shader wins. A record keyed on
/// additions and removals would miss it entirely.
#[test]
fn a_connect_rearmed_in_place_is_recorded() {
    let mut scene = Scene::default();
    scene.create("attr", "attributes").unwrap();
    scene.create("shader", "shader").unwrap();
    scene
        .connect("shader", None, "attr", "surfaceshader")
        .unwrap();
    scene.take_changes();

    scene
        .connect_with_arguments(
            "shader",
            None,
            "attr",
            "surfaceshader",
            vec![OwnedArgument::new(
                "priority",
                Type::I32,
                1,
                0,
                OwnedData::I32(vec![10]),
            )],
        )
        .unwrap();

    let changes = scene.take_changes();
    assert!(changes.edges_added.is_empty(), "no edge appeared");
    assert!(changes.edges_removed.is_empty(), "none disappeared");
    assert_eq!(changes.edges_rearmed.len(), 1);
    assert_eq!(changes.edges_rearmed[0].from, "shader");
}

/// The edge lists are net too: a host that re-`connect`s the same edge
/// every frame must not grow the record by a full `Edge`, arguments
/// included, on every one of them.
#[test]
fn re_arming_one_edge_repeatedly_is_one_entry() {
    let mut scene = Scene::default();
    scene.create("attr", "attributes").unwrap();
    scene.create("shader", "shader").unwrap();
    scene
        .connect("shader", None, "attr", "surfaceshader")
        .unwrap();
    scene.take_changes();

    for priority in 0..40 {
        scene
            .connect_with_arguments(
                "shader",
                None,
                "attr",
                "surfaceshader",
                vec![OwnedArgument::new(
                    "priority",
                    Type::I32,
                    1,
                    0,
                    OwnedData::I32(vec![priority]),
                )],
            )
            .unwrap();
    }

    let changes = scene.take_changes();
    assert_eq!(changes.edges_rearmed.len(), 1, "forty calls, one edge");
    assert_eq!(
        changes.edges_rearmed[0].args[0].as_i32(),
        Some(39),
        "and it carries the arguments of the last call",
    );
}

/// A `disconnect` naming `.all` is expanded into the edges it removed:
/// the pattern cannot be re-expanded once they are gone.
#[test]
fn a_wildcard_disconnect_records_what_it_removed() {
    let mut scene = Scene::default();
    scene.create("xf", "transform").unwrap();
    for handle in ["a", "b"] {
        scene.create(handle, "mesh").unwrap();
        scene.connect(handle, None, "xf", "objects").unwrap();
    }
    scene.take_changes();

    scene.disconnect(crate::ALL, None, "xf", "objects").unwrap();

    let changes = scene.take_changes();
    let removed: Vec<&str> = changes
        .edges_removed
        .iter()
        .map(|e| e.from.as_str())
        .collect();
    assert_eq!(removed, vec!["a", "b"], "both, by name, not the pattern");
}

/// A delete takes edges with it, and the record keeps them: working
/// out what was orphaned means walking down from a node the edge no
/// longer points at.
#[test]
fn a_delete_records_the_edges_it_took_with_it() {
    let mut scene = Scene::default();
    scene.create("xf", "transform").unwrap();
    scene.create("q", "mesh").unwrap();
    scene.connect("xf", None, ".root", "objects").unwrap();
    scene.connect("q", None, "xf", "objects").unwrap();
    scene.take_changes();

    scene.delete("xf").unwrap();

    let changes = scene.take_changes();
    assert_eq!(changes.deleted().count(), 1);
    let pairs: Vec<(&str, &str)> = changes
        .edges_removed
        .iter()
        .map(|e| (e.from.as_str(), e.to.as_str()))
        .collect();
    assert!(pairs.contains(&("q", "xf")), "the child's edge, {pairs:?}");
    assert!(pairs.contains(&("xf", ".root")), "and its own");
}

/// Pending changes are not part of what a scene *is*: a synchronised
/// scene still equals the identical unsynchronised one.
#[test]
fn changes_are_not_part_of_scene_equality() {
    let build = || {
        let mut scene = Scene::default();
        scene.create("a", "attributes").unwrap();
        scene
            .set_attribute("a", vec![arg("visibility", 1.0)])
            .unwrap();
        scene
    };
    let mut synchronised = build();
    synchronised.take_changes();

    assert_eq!(synchronised, build());
}

/// What an [`Affected`]'s roots stand for, expanded.
///
/// The roots are the answer; this is what a consumer that wants the
/// list does with them, and what these tests assert against.
fn affected_nodes<'a>(
    scene: &'a Scene,
    affected: &Affected<'a>,
) -> IndexSet<&'a str> {
    let mut all = IndexSet::new();
    for root in &affected.roots {
        all.extend(scene.descendants(root));
    }
    all
}

/// A transform edit dirties everything under it -- the inverse of the
/// chain walk resolution already does upward.
#[test]
fn a_moved_transform_dirties_its_subtree() {
    let mut scene = Scene::default();
    scene.create("outer", "transform").unwrap();
    scene.create("inner", "transform").unwrap();
    scene.create("q", "mesh").unwrap();
    scene.create("elsewhere", "mesh").unwrap();
    scene.connect("outer", None, ".root", "objects").unwrap();
    scene.connect("inner", None, "outer", "objects").unwrap();
    scene.connect("q", None, "inner", "objects").unwrap();
    scene
        .connect("elsewhere", None, ".root", "objects")
        .unwrap();
    scene.take_changes();

    scene
        .set_attribute("outer", vec![arg("transformationmatrix", 1.0)])
        .unwrap();

    let changes = scene.take_changes();
    let affected = scene.affected(&changes);
    assert!(
        affected_nodes(&scene, &affected).contains("q"),
        "two levels down"
    );
    assert!(affected_nodes(&scene, &affected).contains("inner"));
    assert!(
        !affected_nodes(&scene, &affected).contains("elsewhere"),
        "and nothing on another branch",
    );
}

/// A shader edit reaches every geometry bound through the `attributes`
/// node that carries it -- including when the binding is onto a `set`,
/// and including a repeated `connect` that only changed `"priority"`.
#[test]
fn a_shader_edit_reaches_the_geometry_bound_through_it() {
    let mut scene = Scene::default();
    scene.create("attr", "attributes").unwrap();
    scene.create("shader", "shader").unwrap();
    scene.create("group", "set").unwrap();
    scene.create("q", "mesh").unwrap();
    scene.create("other", "mesh").unwrap();
    scene.connect("q", None, ".root", "objects").unwrap();
    scene.connect("other", None, ".root", "objects").unwrap();
    scene.connect("q", None, "group", "members").unwrap();
    scene
        .connect("attr", None, "group", "geometryattributes")
        .unwrap();
    scene
        .connect("shader", None, "attr", "surfaceshader")
        .unwrap();
    scene.take_changes();

    // Re-arming the connection changes which shader wins and adds no
    // edge; the geometry behind the set must still be named.
    scene
        .connect_with_arguments(
            "shader",
            None,
            "attr",
            "surfaceshader",
            vec![OwnedArgument::new(
                "priority",
                Type::I32,
                1,
                0,
                OwnedData::I32(vec![10]),
            )],
        )
        .unwrap();

    let changes = scene.take_changes();
    let affected = scene.affected(&changes);
    assert!(
        affected_nodes(&scene, &affected).contains("q"),
        "through the set's members"
    );
    assert!(
        !affected_nodes(&scene, &affected).contains("other"),
        "not the whole scene"
    );
    assert!(affected.shaders.contains("shader"));
}

/// A shader's *own* attribute is a material parameter and no geometry
/// work: it must not drag the geometry bound through it into the
/// affected set.
#[test]
fn a_shader_parameter_edit_is_not_geometry_work() {
    let mut scene = Scene::default();
    scene.create("attr", "attributes").unwrap();
    scene.create("shader", "shader").unwrap();
    scene.create("q", "mesh").unwrap();
    scene.connect("q", None, ".root", "objects").unwrap();
    scene
        .connect("attr", None, "q", "geometryattributes")
        .unwrap();
    scene
        .connect("shader", None, "attr", "surfaceshader")
        .unwrap();
    scene.take_changes();

    scene
        .set_attribute("shader", vec![arg("roughness", 0.5)])
        .unwrap();

    let changes = scene.take_changes();
    let affected = scene.affected(&changes);
    assert!(affected.shaders.contains("shader"));
    assert!(
        affected_nodes(&scene, &affected).is_empty(),
        "a material parameter costs no geometry work: {:?}",
        affected_nodes(&scene, &affected),
    );
}

/// A prototype's ancestor reaches the instancer, which is **not**
/// below the transform that moved: it hangs off the other end of a
/// `sourcemodels` edge.
#[test]
fn a_prototypes_ancestor_reaches_the_instancer() {
    let mut scene = Scene::default();
    scene.create("xf", "transform").unwrap();
    scene.create("proto", "mesh").unwrap();
    scene.create("inst", "instances").unwrap();
    scene.connect("inst", None, ".root", "objects").unwrap();
    scene.connect("proto", None, "xf", "objects").unwrap();
    scene
        .connect("proto", None, "inst", "sourcemodels")
        .unwrap();
    scene.take_changes();

    scene
        .set_attribute("xf", vec![arg("transformationmatrix", 1.0)])
        .unwrap();

    let changes = scene.take_changes();
    let affected = scene.affected(&changes);
    assert!(affected_nodes(&scene, &affected).contains("proto"));
    assert!(
        affected_nodes(&scene, &affected).contains("inst"),
        "the instancer draws it, and is reached the other way round",
    );
}

/// An attribute on `.root` or `.global` is a candidate set of
/// "everything", and saying so beats listing the scene.
#[test]
fn a_global_edit_dirties_everything() {
    let mut scene = Scene::default();
    scene.create("q", "mesh").unwrap();
    scene.connect("q", None, ".root", "objects").unwrap();
    scene.take_changes();

    scene
        .set_attribute(crate::GLOBAL, vec![arg("quality.shadingsamples", 8.0)])
        .unwrap();

    let changes = scene.take_changes();
    let affected = scene.affected(&changes);
    assert!(affected.everything);
    assert!(
        affected_nodes(&scene, &affected).is_empty(),
        "not a copy of the scene"
    );
}

/// A `disconnect` naming `.all` severs several children at once, and
/// each one's subtree is a candidate.
#[test]
fn a_wildcard_disconnect_dirties_every_child_it_severed() {
    let mut scene = Scene::default();
    scene.create("xf", "transform").unwrap();
    scene.connect("xf", None, ".root", "objects").unwrap();
    for handle in ["a", "b"] {
        scene.create(handle, "mesh").unwrap();
        scene.connect(handle, None, "xf", "objects").unwrap();
    }
    scene.take_changes();

    scene.disconnect(crate::ALL, None, "xf", "objects").unwrap();

    let changes = scene.take_changes();
    let affected = scene.affected(&changes);
    assert!(affected_nodes(&scene, &affected).contains("a"));
    assert!(affected_nodes(&scene, &affected).contains("b"));
}

/// **The gate for the whole feature: `changed ⊆ affected`.**
///
/// The defect this crate can have here is an *under*-approximation --
/// a node whose resolved answer moved and which the candidate set does
/// not name. A backend acting on that synchronises everything except
/// the thing that changed, and renders the old state with no error and
/// no warning. No hand-written case can be trusted to find it, because
/// the rule that goes missing is the one nobody thought of.
///
/// So: a fixture carrying every feature the walks touch -- nested
/// transforms, an instancer with a prototype under its own transform,
/// a `set` with members, containers bound at two levels with a
/// priority, a shader network -- then a scripted run of edits, and a
/// brute-force comparison of every resolved answer before and after.
/// Over-approximating is allowed; missing one is not.
///
/// What it cannot see: an over-approximation. Dropping the
/// `sourcemodels` hop leaves this green, because moving a prototype's
/// parent transform does not change what the instancer draws in this
/// fixture -- naming the instancer there is a conservative choice, and
/// `a_prototypes_ancestor_reaches_the_instancer` is what pins it.
///
/// What it structurally cannot catch, established by mutating the walk
/// against it rather than assumed:
///
/// - **Over-approximation.** Naming a node that did not move breaks no
///   `changed ⊆ affected`, so filing a shader attribute under `nodes`
///   instead of `shaders` survives here;
///   `a_shader_parameter_edit_is_not_geometry_work` is what pins that.
/// - **A bare `create`.** A node with no edges resolves to the same
///   answers it did before it existed -- `world_transform` says
///   `Detached` for an unknown handle as readily as for an unconnected
///   one -- so dropping the walk over `Changes::created` survives. It
///   is over-approximation either way.
/// - **Dropping an `EdgeKind` arm.** That is now a compile error rather
///   than a surviving mutation: the match is exhaustive over the enum
///   instead of over `to_attribute()` strings, so a new edge class stops the
///   build at the place a decision is owed.
///
/// Widened three times, each because a mutation survived it: the
/// script's `transformationmatrix` was an `f32`, which `matrix_of`
/// refuses, so "move a transform" moved nothing; and its priorities
/// were `f32` too, which 3Delight does not read as priorities, so
/// precedence was never exercised. A gate that cannot fail proves only
/// its own fixture.
#[test]
fn every_changed_answer_is_named_in_the_affected_set() {
    // Answers a backend would act on, as text so they compare.
    fn answers(scene: &Scene, handle: &str) -> String {
        format!(
            "{:?}|{:?}|{:?}|{:?}",
            scene.world_transform(handle),
            scene.geometry_binding(handle),
            scene.attribute_value(handle, "visibility"),
            scene.placements(handle).map(|placements| placements
                .iter()
                .map(|placement| (placement.path.clone(), placement.transform))
                .collect::<Vec<_>>()),
        ) + &format!(
            "|{:?}|{:?}|{:?}",
            scene.instance_transforms(handle),
            scene.attribute_value(handle, "visibility.camera"),
            scene.instance_sources(handle),
        )
    }

    fn fixture() -> Scene {
        let mut scene = Scene::default();
        for (handle, node_type) in [
            ("outer", "transform"),
            ("inner", "transform"),
            ("protoxf", "transform"),
            ("q", "mesh"),
            ("r", "mesh"),
            ("proto", "mesh"),
            ("inst", "instances"),
            ("group", "set"),
            ("near", "attributes"),
            ("far", "attributes"),
            ("surface", "shader"),
            ("surface2", "shader"),
            ("texture", "shader"),
            ("cam", "perspectivecamera"),
            ("screen", "screen"),
            ("layer", "outputlayer"),
            ("driver", "outputdriver"),
        ] {
            scene.create(handle, node_type).unwrap();
        }
        for (from, to) in [
            ("outer", ".root"),
            ("inner", "outer"),
            ("q", "inner"),
            ("r", "outer"),
            ("protoxf", ".root"),
            ("proto", "protoxf"),
            ("inst", ".root"),
        ] {
            scene.connect(from, None, to, "objects").unwrap();
        }
        scene
            .connect("proto", None, "inst", "sourcemodels")
            .unwrap();
        // Matrices, or `instance_transforms` is `Ok([])` before and
        // after every edit and the instancer is invisible to the gate.
        scene
            .set_attribute(
                "inst",
                vec![OwnedArgument::new(
                    "transformationmatrices",
                    Type::MatrixF64,
                    1,
                    0,
                    OwnedData::F64(
                        [
                            [
                                1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0,
                                0.0, 1.0, 0.0, -1.0, 0.0, 0.0, 1.0,
                            ],
                            [
                                1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0,
                                0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0,
                            ],
                        ]
                        .concat(),
                    ),
                )],
            )
            .unwrap();
        scene.connect("cam", None, ".root", "objects").unwrap();
        scene.connect("screen", None, "cam", "screens").unwrap();
        scene
            .connect("layer", None, "screen", "outputlayers")
            .unwrap();
        scene
            .connect("driver", None, "layer", "outputdrivers")
            .unwrap();
        scene.connect("q", None, "group", "members").unwrap();
        scene
            .connect("near", None, "q", "geometryattributes")
            .unwrap();
        scene
            .connect("far", None, "group", "geometryattributes")
            .unwrap();
        scene
            .connect("surface", None, "near", "surfaceshader")
            .unwrap();
        // A rival on the same node: which of the two wins is decided
        // by the connection's arguments, so a re-arm that adds and
        // removes nothing changes the answer.
        scene
            .connect("surface2", None, "near", "surfaceshader")
            .unwrap();
        scene
            .connect("texture", Some("out"), "surface", "colour")
            .unwrap();
        scene
            .set_attribute(
                "outer",
                vec![OwnedArgument::new(
                    "transformationmatrix",
                    Type::MatrixF64,
                    1,
                    0,
                    OwnedData::F64(vec![
                        1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0,
                        0.0, 1.0, 0.0, 0.0, 1.0,
                    ]),
                )],
            )
            .unwrap();
        scene
            .set_attribute("near", vec![arg("visibility", 1.0)])
            .unwrap();
        scene
            .set_attribute(
                "far",
                vec![
                    arg("visibility", 0.0),
                    OwnedArgument::new(
                        "visibility.priority",
                        Type::I32,
                        1,
                        0,
                        OwnedData::I32(vec![10]),
                    ),
                ],
            )
            .unwrap();
        scene
    }

    let handles = [
        "outer", "inner", "protoxf", "q", "r", "proto", "inst", "group",
        "near", "far", "surface", "surface2", "texture", "cam", "screen",
        "layer", "driver",
        // The node a `create` edit makes. Without it in this list no
        // created node was ever checked, and dropping the walk over
        // `Changes::created` left the gate green.
        "fresh",
    ];

    // One edit is applied by `edit`, so the runs below can be
    // exhaustive over (handle x operation) rather than trusting a
    // random draw to have tried the one that matters.
    // A `doublematrix`, declared. An `f32` here is `E6007` to
    // 3Delight and `None` to `matrix_of`, so a script that used one
    // would be editing nothing at all -- which is how this fixture
    // first failed to notice a truncated descent.
    fn matrix(x: f64) -> OwnedArgument {
        OwnedArgument::new(
            "transformationmatrix",
            Type::MatrixF64,
            1,
            0,
            OwnedData::F64(vec![
                1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x,
                0.0, 0.0, 1.0,
            ]),
        )
    }

    fn edit(scene: &mut Scene, handle: &str, op: usize) {
        match op {
            0 => {
                let _ = scene.set_attribute(handle, vec![matrix(2.0)]);
            }
            1 => {
                let _ =
                    scene.set_attribute(handle, vec![arg("visibility", 0.0)]);
            }
            2 => {
                let _ =
                    scene.set_attribute_at_time(handle, 0.5, vec![matrix(3.0)]);
            }
            3 => scene.delete_attribute(handle, "visibility"),
            4 => {
                let _ = scene.delete(handle);
            }
            5 => {
                let _ = scene.disconnect(crate::ALL, None, handle, "objects");
            }
            6 => {
                let _ = scene.connect(handle, None, ".root", "objects");
            }
            7 => {
                // Re-arm: no edge added, none removed, and which of the
                // two rival shaders wins changes.
                let _ = scene.connect_with_arguments(
                    // Keyed on the *handle*, not on `op`: `op` is 7
                    // throughout this arm, so `op % 2` was a constant
                    // and only one of the two rivals was ever re-armed.
                    if handle.len().is_multiple_of(2) {
                        "surface"
                    } else {
                        "surface2"
                    },
                    None,
                    "near",
                    "surfaceshader",
                    vec![OwnedArgument::new(
                        "priority",
                        Type::I32,
                        1,
                        0,
                        OwnedData::I32(vec![7]),
                    )],
                );
            }
            9 => {
                // Created and left unconnected, on purpose: connecting
                // it would record an edge, the edge arm would name it,
                // and the walk over `Changes::created` could be deleted
                // with the gate still green.
                let _ = scene.create("fresh", "mesh");
            }
            10 => {
                let _ =
                    scene.disconnect(crate::ALL, None, handle, "sourcemodels");
            }
            _ => {
                // An `int`, and exactly one: anything else is not a
                // priority to 3Delight, so an `f32` here would rank
                // nothing and precedence would never be exercised.
                let _ = scene.set_attribute(
                    handle,
                    vec![OwnedArgument::new(
                        "visibility.priority",
                        Type::I32,
                        1,
                        0,
                        OwnedData::I32(vec![20]),
                    )],
                );
            }
        }
    }

    let check =
        |scene: &Scene, before: &Scene, affected: &Affected, what: &str| {
            if affected.everything {
                return;
            }
            // `render_outputs` is one answer for the whole scene, not
            // one per handle, so it is held against the flag that
            // exists for it. Folding it into every handle's answer made
            // deleting a camera look like every node in the scene
            // changing -- which is how this assertion first failed.
            assert!(
                format!("{:?}", before.render_outputs())
                    == format!("{:?}", scene.render_outputs())
                    || affected.outputs,
                "{what}: the outputs changed and `outputs` is false",
            );

            for handle in handles {
                let was = answers(before, handle);
                let now = answers(scene, handle);
                // `nodes` and `shaders` are separate answers -- one
                // costs geometry work and the other does not -- so a
                // geometry answer that moved must be in `nodes`.
                // Accepting either left the distinction the API sells
                // unverified.
                assert!(
                    was == now
                        || affected_nodes(scene, affected).contains(handle),
                    "{what}: `{handle}` answers differently and is not in the \
                 affected set\n  before: {was}\n   after: {now}",
                );
            }
        };

    // Every single edit, on every handle.
    for handle in handles {
        for op in 0..11 {
            let mut scene = fixture();
            let before = scene.clone();
            scene.take_changes();
            edit(&mut scene, handle, op);
            let changes = scene.take_changes();
            let affected = scene.affected(&changes);
            check(&scene, &before, &affected, &format!("{handle}/{op}"));
        }
    }

    // And pairs, for the interactions a single edit cannot show.
    for seed in 0..256u64 {
        let mut scene = fixture();
        let before = scene.clone();
        scene.take_changes();

        let mut state =
            seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
        for _ in 0..2 {
            state = state
                .wrapping_mul(6_364_136_223_846_793_005)
                .wrapping_add(1_442_695_040_888_963_407);
            let pick = (state >> 33) as usize;
            edit(&mut scene, handles[pick % handles.len()], pick % 11);
        }

        let changes = scene.take_changes();
        let affected = scene.affected(&changes);
        check(&scene, &before, &affected, &format!("seed {seed}"));
    }
}

/// `Node::effective` is what the resolver reads, so asking a node
/// directly gives the resolver's answer.
///
/// Reading `attributes` alone answers "not set" for an attribute set with
/// `SetAttributeAtTime`, which the renderer honours -- the silent wrong
/// answer this method exists to prevent a caller from reinventing.
#[test]
fn effective_reads_a_sampled_attribute() {
    let mut scene = Scene::default();
    scene.create("a", "attributes").unwrap();
    scene
        .set_attribute_at_time("a", 0.0, vec![arg("visibility", 0.0)])
        .unwrap();

    let node = scene.node("a").expect("created");
    assert!(
        node.attribute("visibility").is_none(),
        "it is not a static attribute",
    );
    assert!(
        node.effective("visibility").is_some(),
        "but it is the node's effective value",
    );
}

/// A node whose only attribute was deleted holds an emptied table
/// where a node that never had one holds none at all. They say the
/// same thing, so they compare equal -- a derived `PartialEq` on the
/// `Option` would call a scene different from a replay of itself.
#[test]
fn an_emptied_attribute_table_equals_an_absent_one() {
    let mut set_then_deleted = Scene::default();
    set_then_deleted.create("a", "attributes").unwrap();
    set_then_deleted
        .set_attribute("a", vec![arg("visibility", 0.0)])
        .unwrap();
    set_then_deleted.delete_attribute("a", "visibility");

    let mut never_set = Scene::default();
    never_set.create("a", "attributes").unwrap();

    assert_eq!(
        set_then_deleted.node("a").expect("created"),
        never_set.node("a").expect("created"),
    );
}

/// The same, for the sample table: `set_attribute` clears the samples
/// for that name and leaves the table behind.
#[test]
fn an_emptied_sample_table_equals_an_absent_one() {
    let mut sampled_then_static = Scene::default();
    sampled_then_static.create("a", "attributes").unwrap();
    sampled_then_static
        .set_attribute_at_time("a", 0.0, vec![arg("visibility", 0.0)])
        .unwrap();
    sampled_then_static
        .set_attribute("a", vec![arg("visibility", 0.0)])
        .unwrap();

    let mut static_only = Scene::default();
    static_only.create("a", "attributes").unwrap();
    static_only
        .set_attribute("a", vec![arg("visibility", 0.0)])
        .unwrap();

    assert_eq!(
        sampled_then_static.node("a").expect("created"),
        static_only.node("a").expect("created"),
    );
}