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
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
//! `GraphEngine3D` — the 3D sibling of [`crate::engine::GraphEngine`]
//! (W3D arc plan §1.2: a separate engine, NOT a `Dimension` mode bolted
//! onto the 2D facade). Reuses `Graph`/`SimTopology`/`NodeIndex`/
//! `EdgeIndex` unchanged; owns its own [`Camera3D`] and a 3D-aware
//! [`Layout`] impl ([`crate::layout::force_directed_3d::ForceDirectedLayout3D`]
//! by default).
//!
//! Wave 1 (plan §4) proved the physics core only
//! ([`GraphEngine3D::new`]/[`GraphEngine3D::tick`]). Wave 2 landed the
//! render path ([`GraphEngine3D::build_scene`], wired into
//! [`crate::render3d::build_scene`]) and camera event dispatch
//! ([`GraphEngine3D::on_event`] — drag-orbit, wheel-dolly, shift-drag
//! pan, per plan §1.4). Wave 3 lands CPU ray-vs-sphere hover/click
//! picking (`hovered`/`selected` actually changing,
//! [`crate::interaction::pick3d::screen_to_ray`]/
//! [`crate::interaction::pick3d::nearest_node_3d`]), a
//! [`GraphEngine3D::node_facts`] facts-panel accessor reusing
//! [`crate::engine::NodeFacts`] unchanged, and
//! [`GraphEngine3D::visible_labels`] (the label-overlay's project+LOD-
//! select half — see that method's own doc comment for the Wave 3
//! overlay-draw scope note).
use std::collections::{BTreeSet, HashMap, HashSet};
use std::sync::Arc;
use glam::Vec3;
use uzor::input::{ModifierKeys, MouseButton, PlatformEvent};
use uzor::render::RenderContext;
use uzor::types::Rect;
use uzor_figures::guide::text_protect::fill_text_with_halo;
use uzor_urx_3d::{Mesh, MeshLit, PerspectiveCamera, Scene3D};
use crate::camera3d::Camera3D;
use crate::cluster::{ClusterRegistry, GroupId};
use crate::engine::{box_select_mode_for, ease_in_out_cubic, normalized_rect, FilterSpec, NodeFacts, SelectMode, DEFAULT_LABEL_HALO};
use crate::graph::{Graph, NodeIndex, SimEdge, SimTopology};
use crate::interaction::pick3d;
use crate::label_grid;
use crate::layout::force_directed_3d::ForceDirectedLayout3D;
use crate::layout::{Layout, LayoutTickResult};
use crate::particle::Particle;
use crate::render::{draw_hover_card, HoverCardInfo};
use crate::render3d::{Graph3DEdgeStyle, Graph3DGridConfig, Graph3DLighting};
use crate::theme::GraphTheme;
/// Wheel-to-dolly screen-delta sensitivity — mirrors
/// [`crate::engine::GraphEngine`]'s own `ZOOM_SENSITIVITY` (`engine.rs`)
/// in magnitude, but flipped in sign: 2D's `zoom` grows for "zoom in"
/// (multiply), 3D's orbit `distance` SHRINKS for "zoom in" — see
/// [`GraphEngine3D::on_scroll`].
const DOLLY_SENSITIVITY: f32 = 0.0015;
const DOLLY_FACTOR_MIN: f32 = 0.8;
const DOLLY_FACTOR_MAX: f32 = 1.25;
/// Screen-space distance the pointer must travel since the last hover
/// pick before [`GraphEngine3D::pick_at`] re-runs (Wave 3 perf guard —
/// mirrors 2D's own `HOVER_PICK_MIN_MOVE_PX`, `engine.rs`; re-declared
/// here since that constant is private to `engine.rs` and the two
/// engines otherwise share no picking code).
const HOVER_PICK_MIN_MOVE_PX: f64 = 2.0;
/// Screen-space distance a `PointerDown`->`PointerUp` pair may travel
/// while orbiting and still count as a click-to-select (Wave 3 — mirrors
/// 2D's own `CLICK_DRAG_THRESHOLD_PX`, `engine.rs`, same rationale and
/// value).
const CLICK_DRAG_THRESHOLD_PX: f64 = 4.0;
/// z-plane-degeneracy guard (live-caught Wave 2 defect, fixed in Wave 3 —
/// see [`GraphEngine3D::seed_positions`]/`uzor-graph/CLAUDE.md`'s
/// divergence log). If the seeded z half-extent is below this fraction
/// of the xy half-extent, the seed is treated as "effectively planar"
/// and gets jittered — every 3D force in `ForceDirectedLayout3D` is
/// z-symmetric (repulsion/link/center all scale the SAME `(dx, dy, dz)`
/// direction vector), so a perfectly planar seed (`dz == 0` for every
/// pair) has an identically-zero z-force forever and the sim can never
/// leave the plane on its own.
const Z_DEGENERACY_RATIO: f32 = 0.05;
/// Deterministic z-jitter half-range, as a fraction of the xy
/// half-extent (owner's own spec: "uniform in ±0.5 * xy_half_extent").
const Z_JITTER_XY_FRACTION: f32 = 0.5;
/// Alpha [`GraphEngine3D::ensure_z_variance`] reheats to after jittering
/// — high enough that the sim actively resolves the newly-introduced z
/// spread into a real 3D layout instead of just sitting on the jittered
/// starting positions (mirrors 2D's own `DRAG_REHEAT_ALPHA`-style "make
/// it visibly move" convention, `engine.rs`).
const Z_JITTER_REHEAT_ALPHA: f32 = 0.6;
/// Deterministic per-index pseudo-random value in `[-1.0, 1.0)` —
/// splitmix64-style LCG, index-seeded, NO `Math::random`/wall-clock time
/// (same convention `force_directed_3d.rs`'s own test fixtures already
/// use). Backs [`GraphEngine3D::ensure_z_variance`]'s z-jitter: distinct
/// indices deterministically land on different offsets, and the exact
/// same graph produces the exact same jitter on every run.
/// Bounding box of every particle's current `(x, y, z)` position — `None`
/// for an empty particle set. Shared by [`GraphEngine3D::fit_view`] and
/// [`GraphEngine3D::build_scene`]'s grid geometry (Wave 5): the same
/// "walk every particle, min/max component-wise" shape
/// [`GraphEngine3D::ensure_z_variance`] already computes inline for its
/// own z-degeneracy check, factored out here now that two more callers
/// need the identical bounding box.
fn particle_aabb(particles: &[Particle]) -> Option<(Vec3, Vec3)> {
let mut iter = particles.iter();
let first = iter.next()?;
let mut min = Vec3::new(first.x, first.y, first.z);
let mut max = min;
for p in iter {
let v = Vec3::new(p.x, p.y, p.z);
min = min.min(v);
max = max.max(v);
}
Some((min, max))
}
fn z_jitter_unit(index: usize) -> f32 {
let mut state = (index as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ 0xD1B5_4A32_D192_ED03;
state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
let unit = ((state >> 40) as u32) as f32 / (1u32 << 24) as f32; // [0, 1)
unit * 2.0 - 1.0 // [-1, 1)
}
/// In-progress pointer gesture (plan §1.4) — resolved once at
/// `PointerDown` from the held modifiers (mirrors the 2D engine's own
/// `PointerMode`, `engine.rs`), never re-resolved mid-drag even if a
/// modifier is pressed/released while dragging.
#[derive(Debug, Clone, Copy)]
enum Pointer3DMode {
Idle,
/// Plain left-drag — orbits the camera. `total` accumulates the
/// screen-space path length travelled since `PointerDown` (Wave 3):
/// a release with `total < CLICK_DRAG_THRESHOLD_PX` is a click, not
/// a drag, and resolves a ray-pick select at the release point
/// (mirrors 2D's own `PointerMode::PanningCamera { last, total }`
/// click-vs-pan distinction exactly — node drag has no 3D
/// equivalent this arc, plan §5, so EVERY plain drag is the
/// "background" gesture 2D's `total` tracking already models).
Orbiting { last: (f64, f64), total: f64 },
/// Middle-drag or Shift+left-drag pan (plan §1.4). The initiating
/// button is retained so releasing another held button cannot end
/// the active pan. Deliberately does NOT resolve a click-select on
/// release — pan is a dedicated camera gesture, not the plain
/// left-drag/click gesture.
Panning { last: (f64, f64), button: MouseButton },
/// 3D node drag (owner-ordered live fix — previously EVERY plain
/// drag orbited the camera, even one starting directly on a node;
/// vasturiano `3d-force-graph`'s own convention). `node` is the
/// ANCHOR — the actual hit resolved once at `PointerDown` (CPU
/// `nearest_node_3d`, never re-resolved mid-drag — same "resolved
/// once" idiom every other `Pointer3DMode` variant already follows);
/// `plane_point`/`plane_normal` are the CAMERA-PARALLEL drag plane
/// (`plane_point` = the ANCHOR's own world position AT DRAG-START,
/// `plane_normal` = the camera's view direction at drag-start) that
/// [`GraphEngine3D::on_pointer_moved`] intersects every move — see
/// [`pick3d::ray_plane_intersection`]'s own doc comment for why a
/// camera-parallel plane, not the ray's first world-surface hit.
///
/// **Group-drag wave**: the actual SET of moved nodes lives in the
/// engine's own [`GraphEngine3D::drag_group`] (a `Vec<DragMember3>`,
/// captured at `PointerDown` — mirrors 2D's own `PointerMode::
/// DraggingNode` + external `drag_group` field split, `engine.rs`),
/// not inside this variant — every member (including a solo drag's
/// one-element set) is re-pinned every `PointerMoved` from the SAME
/// anchor ray-plane intersection plus that member's own fixed
/// `offset`, so `node`/`plane_point`/`plane_normal` here describe
/// only the anchor's own drag plane, shared by the whole group.
Dragging { node: NodeIndex, plane_point: Vec3, plane_normal: Vec3 },
/// Box-select drag (cluster/selection wave — 2D-parity decision:
/// mirrors [`crate::engine::GraphEngine`]'s own `PointerMode::
/// BoxSelecting`). **REPURPOSES 3D's own former "Shift+left-drag
/// pans" gesture** — held Shift (alone, or with Ctrl/Alt) now ALWAYS
/// starts a box-select instead, exactly mirroring 2D's own
/// `box_select_mode_for` precedence; plain MIDDLE-drag pan
/// (`on_pan_pointer_down`, dispatched from `on_event`'s own separate
/// `MouseButton::Middle` branch) is UNCHANGED and remains the only
/// way to pan the 3D camera. `origin` is the fixed down-point,
/// `current` tracks the live cursor (what
/// [`GraphEngine3D::box_select_rect`] reads for the rubber-band
/// overlay); `mode` is resolved ONCE at drag-start from the held
/// modifiers (see [`box_select_mode_for`]) and never re-resolved for
/// the rest of the gesture — same convention every other
/// `Pointer3DMode` variant already follows.
BoxSelecting { origin: (f64, f64), current: (f64, f64), mode: SelectMode },
}
/// One member of an in-progress 3D drag gesture (group-drag wave),
/// captured at drag-start — the 3D sibling of [`crate::engine::
/// DragMember`] (`engine.rs`), one extra axis. `offset` is a FIXED
/// world-space offset from the anchor node's own position AT DRAG-START;
/// every subsequent `PointerMoved` recomputes this member's `fx`/`fy`/`fz`
/// (via [`crate::particle::Particle::pin3`]) as `anchor_world_now +
/// offset` — the SAME single-shared-shift ("`silentShift`") convention
/// 2D's own `DragMember` doc comment covers in full: relative offsets
/// between drag-set members are preserved EXACTLY by construction, never
/// incrementally accumulated from a stale per-tick delta. For a solo drag
/// (drag set = `{anchor}` only) `offset` is `Vec3::ZERO`, which reproduces
/// this engine's pre-group-drag single-node behavior byte-for-byte.
///
/// **Known simplification vs. 2D's own `DragMember`**: no per-member
/// `prior_pinned` snapshot — 3D node drag is Sticky-only (no
/// `DragEndPolicy::RestorePrior` mode exists for 3D, see
/// [`GraphEngine3D::pin_node`]'s own doc comment for why a parallel
/// `pinned: Vec<bool>` array was already judged unnecessary), so every
/// member simply stays pinned at its release position — there's no prior
/// state to disambiguate a drag-pin from.
#[derive(Debug, Clone, Copy)]
struct DragMember3 {
node: NodeIndex,
offset: Vec3,
}
/// Sustained `alphaTarget` a node drag holds the sim at while active
/// (owner's own spec: "~0.3", mirrors 2D's own `DRAG_ALPHA_TARGET`
/// convention in spirit though not value — 2D's engine.rs constant is
/// private and 3D's drag physics needs its own tuning pass regardless).
const NODE_DRAG_ALPHA_TARGET: f32 = 0.3;
/// Alpha to reheat the 3D sim to after a cluster expands or a node is
/// unpinned (cluster/selection wave) — mirrors the 2D engine's own
/// `DRAG_REHEAT_ALPHA` convention (`engine.rs`), same value: enough to
/// visibly resettle the local neighborhood without a full
/// restart-from-scratch jolt.
const REHEAT_ALPHA: f32 = 0.35;
/// Shared unit-sphere node mesh geometry (plan §1.3) — latitude/longitude
/// resolution tuned for a smooth silhouette at typical node screen sizes
/// without an excessive vertex count. One shared mesh serves every node
/// via `uzor-urx-3d`'s Arc-identity instancing, so this cost is paid
/// once per engine, not once per node.
///
/// Bumped from `12`/`16` (round-1 visual-quality wave — owner: large
/// spheres showed visible FACETING/low tessellation up close). `rings`
/// = latitude bands (pole-to-pole steps), `slices` = longitude bands
/// (segments around the equator) — `MeshLit::sphere`'s own vertex/index
/// generation already emits per-vertex (not per-face) normals (each
/// `(ring, slice)` grid point gets its own shared vertex, normal =
/// unit-sphere position direction — verified by direct read, no change
/// needed there), so this is a pure tessellation-density bump: cost is
/// `(rings+1)*(slices+1)` vertices for ONE shared instanced mesh (paid
/// once per engine, not once per node) — negligible at these numbers.
const NODE_SPHERE_RINGS: u32 = 22;
const NODE_SPHERE_SLICES: u32 = 30;
/// [`Camera3D::fit_bounds`]'s own multiplicative margin, applied by
/// [`GraphEngine3D::fit_view`] — the owner's own spec ("~1.1").
const FIT_VIEW_PADDING: f32 = 1.1;
/// Below this node count, a bounding-box fit doesn't mean much (there's
/// no real graph SHAPE yet) — [`GraphEngine3D::fit_view`] falls back to
/// [`Camera3D::default`]'s own distance instead of zooming to an
/// arbitrary (possibly degenerate) extent, per this wave's own spec.
const FIT_VIEW_MIN_NODES: usize = 3;
/// A particle cloud whose half-diagonal sits below this world-unit
/// threshold is treated as "effectively a single point" for fit purposes
/// (e.g. every particle still sitting at [`GraphEngine3D::new`]'s shared
/// origin, before any seeding/settling has spread them out) — guards the
/// same degenerate case [`FIT_VIEW_MIN_NODES`] targets by COUNT, but by
/// actual EXTENT instead, since 3+ coincident nodes are just as
/// meaningless a `fit_bounds` target as 0-2 nodes are.
const FIT_VIEW_MIN_HALF_DIAGONAL: f32 = 1e-3;
/// Default local-subgraph BFS depth (filter/local-subgraph wave) —
/// mirrors 2D's own `engine::DEFAULT_LOCAL_DEPTH` value (`2`) exactly;
/// redeclared here since that constant is private to `engine.rs` and this
/// is the only 3D consumer.
const DEFAULT_LOCAL_DEPTH_3D: u8 = 2;
// ── Dimension transition (dimension-transition wave — the animated
// 2D<->3D switch, `force_graph_demo`'s own `set_dimension` action) ──────
/// Fixed aspect assumed for [`GraphEngine3D::front_on_camera`]'s own
/// [`Camera3D::fit_bounds`] solve — [`GraphEngine3D::start_transition`]'s
/// literal signature (`direction`, `duration_ms`) takes no viewport/
/// aspect parameter, unlike every OTHER viewport-needing method on this
/// engine (`fit_view`/`box_select`/`on_event`, all of which take one
/// explicitly): the front-on pose only needs to be "close enough" to
/// fill the viewport for the ~600ms the transition itself runs, and
/// `Camera3D::fit_bounds`'s own fallback for a non-finite/invalid aspect
/// is this SAME 16:9 default already — this just applies that existing
/// fallback unconditionally instead of only on invalid input, rather than
/// threading a real aspect through a brand new parameter this wave's own
/// task spec didn't ask for.
const FRONT_ON_ASPECT: f32 = 16.0 / 9.0;
/// Direction of an in-flight [`DimensionTransition`]. `In` = entering 3D
/// (the flat layout inflates into a volume while the camera eases from a
/// front-on framing toward the settled orbit pose); `Out` = leaving 3D
/// (the volume flattens back to the plane while the camera eases from the
/// orbit pose back toward a front-on framing, before the caller hands
/// control back to the 2D engine — see `force_graph_demo`'s own
/// `set_dimension` handling).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TransitionDirection {
In,
Out,
}
impl TransitionDirection {
/// Stable lowercase string form — `force_graph_demo`'s own
/// `agent_state`'s `dimension_transition.direction` field reads this.
pub fn as_str(self) -> &'static str {
match self {
TransitionDirection::In => "in",
TransitionDirection::Out => "out",
}
}
}
/// An in-flight animated 2D<->3D dimension transition — ticked once per
/// [`GraphEngine3D::tick`] call via
/// [`GraphEngine3D::advance_dimension_transition`]. Mirrors
/// [`crate::engine`]'s own `CameraTransition`'s `ease_in_out_cubic`
/// convention EXACTLY (that function was promoted `pub(crate)` for this
/// reuse — see its own doc comment) rather than a duplicated copy: only
/// the PROGRESS FRACTION is eased; every interpolated quantity (z-scale,
/// yaw, pitch, distance, target) is then linearly interpolated against
/// that SAME eased fraction.
#[derive(Debug, Clone, Copy)]
struct DimensionTransition {
direction: TransitionDirection,
elapsed_s: f32,
duration_s: f32,
/// The render z-scale this transition eases FROM — the pure
/// canonical `0.0` (`In`) or `1.0` (`Out`) for a FRESH transition,
/// but a mid-transition REVERSAL (a second [`GraphEngine3D::
/// start_transition`] call while one is already in flight) captures
/// whatever the CURRENT instantaneous scale happens to be instead, so
/// the reversed ease continues smoothly with no visual snap (see
/// `start_transition`'s own doc comment).
start_scale: f32,
/// The render z-scale this transition eases TOWARD — always the pure
/// canonical endpoint (`1.0` for `In`, `0.0` for `Out`), regardless of
/// whether this is a fresh transition or a reversal.
end_scale: f32,
start_camera: Camera3D,
end_camera: Camera3D,
}
impl DimensionTransition {
/// Raw linear progress in `[0, 1]` — `duration_s <= 0.0` (an explicit
/// instant transition) short-circuits to `1.0` immediately, mirroring
/// `CameraTransition::step`'s own convention.
fn progress(&self) -> f64 {
if self.duration_s <= 0.0 {
1.0
} else {
(self.elapsed_s / self.duration_s).clamp(0.0, 1.0) as f64
}
}
}
/// The 3D sibling of [`crate::engine::GraphEngine`] — see the module doc.
pub struct GraphEngine3D<N, E, L: Layout = ForceDirectedLayout3D> {
pub graph: Graph<N, E>,
pub particles: Vec<Particle>,
pub layout: L,
pub camera: Camera3D,
pub hovered: Option<NodeIndex>,
pub selected: Option<NodeIndex>,
/// The current multi-selection (cluster/selection wave — mirrors
/// [`crate::engine::GraphEngine::selection`] exactly, including the
/// "`selected` = last individually clicked, `selection` = the bulk
/// set box-select/`apply_selection` mutate" separation: a click
/// (`GraphEngine3D::select`) sets BOTH to `{node}`, but
/// [`GraphEngine3D::apply_selection`]/[`GraphEngine3D::box_select`]
/// touch ONLY this field). Iterated in deterministic ascending
/// `NodeIndex` order (`BTreeSet`).
pub selection: BTreeSet<NodeIndex>,
/// Caller-declared cluster collapse/expand registry (cluster wave) —
/// mirrors [`crate::engine::GraphEngine::clusters`]; the registry
/// struct itself is engine-agnostic (see `crate::cluster`'s own doc
/// comment), the position math the 2D/3D paths drive it through
/// differs (`ClusterRegistry::collapse`/`expand` vs.
/// `ClusterRegistry::collapse_3d`/`expand_3d`).
pub clusters: ClusterRegistry,
/// Shared unit sphere every node instances from (plan §1.3) — built
/// once at construction, never mutated.
node_mesh: Arc<MeshLit>,
/// Shared torus/cone meshes used by optional semantic node markers.
marker_meshes: crate::render3d::Graph3DMarkerMeshes,
/// Shared unit edge-quad every edge instances from (Wave C/D — see
/// `crate::render3d`'s own module doc for why edges are a
/// screen-space billboarded quad, not a cylinder or a hardware
/// `LineList`, as of the edge-quality overhaul).
edge_mesh: Arc<Mesh>,
/// Held keyboard-modifier state (Wave 2) — mirrors the 2D engine's
/// own `PlatformEvent::ModifiersChanged` tracking pattern
/// (`engine.rs`), read by [`GraphEngine3D::on_pointer_down`] to pick
/// orbit vs. shift-drag pan (plan §1.4).
modifiers: ModifierKeys,
mode: Pointer3DMode,
/// Every node moved by the in-progress drag gesture, captured at
/// drag-start (group-drag wave) — mirrors [`crate::engine::
/// GraphEngine::drag_group`] exactly (2D's own `DragMember`, one
/// extra axis — see [`DragMember3`]). Empty when nothing is being
/// dragged.
drag_group: Vec<DragMember3>,
/// Whether the grabbed (anchor) node was ALREADY in `selection` at
/// drag-start (group-drag wave) — mirrors [`crate::engine::
/// GraphEngine::drag_was_group`] exactly: decides `on_pointer_up`'s
/// `Dragging` arm branching (whole selection stays selected vs. a
/// solo drag Replace-selects itself).
drag_was_group: bool,
/// Last pointer position in screen px — [`GraphEngine3D::on_scroll`]'s
/// "is the cursor currently over this viewport" gate (mirrors
/// `GraphEngine::on_scroll`, which reads its own
/// `last_pointer_screen` the same way).
last_pointer_screen: (f64, f64),
/// Every graph node id, cached once at construction (Wave 3) — the
/// CPU ray-picking candidate slice `pick3d::nearest_node_3d` needs.
/// 3D has no visibility-CULLING infrastructure of its own (plan §5
/// exclusion — every node is always a RENDER/CULL candidate), so
/// this stays the full graph; [`GraphEngine3D::pick_candidates`]
/// narrows it by the filter/local-subgraph wave's own EXCLUSION set
/// ([`GraphEngine3D::compute_excluded_nodes_3d`]) instead. Caching
/// this `Vec` once avoids rebuilding it on every guarded hover/click
/// pick.
all_node_ids: Vec<NodeIndex>,
/// Screen position at the last hover pick (Wave 3) — `None` forces
/// the very next `PointerMoved` inside the viewport to re-pick
/// unconditionally (mirrors `GraphEngine`'s own
/// `last_hover_pick_screen`).
last_hover_pick_screen: Option<(f64, f64)>,
/// Sigma `LabelGrid` per-cell quota density (Wave 3) — see
/// [`GraphEngine3D::visible_labels`]. Defaults to
/// `label_grid::DEFAULT_LABEL_DENSITY`, same as the 2D engine.
label_density: f64,
/// Shared unit sphere for the GPU color-ID id-pass (Wave 4) — plain
/// `Unlit` geometry, distinct from `node_mesh`'s `MeshLit` sphere
/// (same tessellation, different vertex format — see
/// [`crate::render3d::build_id_pass_mesh`]'s own doc comment).
id_pass_mesh: Arc<Mesh>,
/// Node-count threshold above which hover picking escalates to the
/// GPU color-ID pass (Wave 4, plan §1.5) — defaults to
/// [`pick3d::GPU_PICK_NODE_THRESHOLD`], overridable via
/// [`GraphEngine3D::set_gpu_pick_threshold`] so a test can exercise
/// the switch without a literal >10k-node fixture.
gpu_pick_threshold: usize,
/// Deferred GPU pick request/result state machine (Wave 4) — see
/// [`pick3d::GpuPickPipeline`]'s own doc comment. Driving the real
/// `wgpu` I/O ([`pick3d::request_gpu_pick`]/[`pick3d::poll_gpu_pick`])
/// is the CALLER's job (this engine owns no `wgpu::Device`); see
/// [`GraphEngine3D::apply_gpu_pick_result`].
gpu_pick_pipeline: pick3d::GpuPickPipeline,
/// Ground-reference grid toggle (Wave 5) — OFF by default: a force
/// graph has no semantic axes of its own, so the grid is purely an
/// opt-in orientation aid, not a default-on feature. See
/// [`GraphEngine3D::set_grid_enabled`]/[`GraphEngine3D::grid_enabled`].
grid_enabled: bool,
/// Hover info-card toggle — mirrors [`crate::engine::GraphEngine`]'s
/// independent overlay control. Hover picking and [`Self::hovered`]
/// remain active while this is disabled; only the card emitted by
/// [`Self::draw_overlay`] is suppressed. Defaults to `true`.
hover_card: bool,
/// Node-label halo color — the 3D sibling of [`crate::engine::
/// GraphEngine::label_halo`] (same [`DEFAULT_LABEL_HALO`] default). See
/// [`GraphEngine3D::label_halo`]/[`GraphEngine3D::set_label_halo`].
label_halo: String,
/// Local-subgraph root + BFS depth (filter/local-subgraph wave) —
/// mirrors [`crate::engine::GraphEngine::local_root`] exactly: `None`
/// shows the full graph. VIEW-ONLY (see [`GraphEngine3D::tick`]'s own
/// doc comment for the DIFFERENT, topology-changing [`Self::filter`]
/// field) — the simulation ticks every particle regardless; only
/// render/pick/label eligibility is restricted. See
/// [`GraphEngine3D::set_local_root`]/[`GraphEngine3D::local_root`].
local_root: Option<(NodeIndex, u8)>,
/// Query filter (filter/local-subgraph wave) — mirrors
/// [`crate::engine::GraphEngine::filter`] exactly, reusing the exact
/// SAME [`FilterSpec`] type (not a parallel 3D-only shape). DOES
/// change the force topology — see [`GraphEngine3D::tick`]'s own doc
/// comment. See [`GraphEngine3D::set_filter`]/[`GraphEngine3D::filter`].
filter: Option<FilterSpec>,
/// In-flight animated 2D<->3D dimension transition (dimension-
/// transition wave), if any — `None` is this engine's ordinary,
/// full-volume steady state. See [`GraphEngine3D::start_transition`].
dim_transition: Option<DimensionTransition>,
/// Last known SETTLED (non-transitional) orbit-camera pose —
/// remembered separately from `camera` (which a transition's own ease
/// continuously overwrites while in flight) so any number of
/// transitions/reversals always converges back on the pose the user
/// actually last chose interactively. See
/// [`GraphEngine3D::start_transition`]'s own doc comment.
orbit_camera: Camera3D,
/// Current instantaneous render-time z-scale — a PERSISTENT, STICKY
/// field (mirrors `camera` itself: both are written eagerly by
/// [`GraphEngine3D::start_transition`] and every subsequent
/// [`GraphEngine3D::advance_dimension_transition`] tick, never
/// recomputed transiently from `dim_transition`'s mere presence).
/// Defaults to `1.0` (full volume) and STAYS at whatever value a
/// transition last eased it to even after that transition completes
/// and `dim_transition` clears — e.g. an `Out` transition that just
/// reached `0.0` (flat) must keep reading `0.0`, not spuriously jump
/// back to a hardcoded "no transition" default the instant it
/// finishes; a caller (`force_graph_demo`'s own `scene3d` poll) is
/// expected to stop rendering this engine at exactly that point
/// anyway, but the field itself stays internally consistent either
/// way. See [`GraphEngine3D::render_z_scale`].
z_scale: f32,
/// Wave G3 item 5 fix — whether [`GraphEngine3D::start_transition`]
/// has EVER been called on this engine instance, regardless of
/// direction. Set `true` unconditionally on every call, never reset.
/// This is the signal `start_transition` needs beyond mere
/// `dim_transition.is_some()` (`is_fresh`) to distinguish a genuine
/// first-ever `In` (whose `z_scale`/`camera` still hold their raw
/// construction defaults, `1.0`/`Camera3D::default()`, and must be
/// forced to the canonical flat/front-on start) from a REDUNDANT
/// `In` call on an engine that already ran at least one transition
/// to completion (whose `z_scale`/`camera` already hold an honest
/// reflection of the real visual state — reading them directly is
/// always correct there, even though `dim_transition` is `None` for
/// the unrelated reason that the prior transition already finished).
/// See [`GraphEngine3D::start_transition`]'s own doc comment.
transition_ever_started: bool,
// ── Graph-strengthening arc Wave G2b — 3D configurability. Every
// field below replaces a former private constant/hardcoded literal
// the 3D quality audit's own inventory flagged with no caller-facing
// override; each follows the SAME "private field + accessor pair"
// convention `label_halo`/`set_label_halo` above already established.
/// Overlay paint (selection ring, node/cluster labels, box-select,
/// hover card) — see [`GraphEngine3D::theme`]/[`GraphEngine3D::set_theme`].
/// Reuses the exact SAME [`GraphTheme`] type the 2D engine owns (not a
/// parallel 3D-only theme type) — most of its fields already carry
/// values that happen to match what this engine's `draw_overlay`
/// hardcoded before this wave (selection ring, node label fill/font,
/// cluster label color, hover card, box-select); [`GraphTheme`]
/// gained a handful of 3D-only fields (`label_offset_3d_x`/`_y`,
/// `cluster_label_extra_offset_3d_x`, `grid_tick_font`,
/// `grid_tick_color`) for the few offsets/fonts that have no 2D
/// equivalent value to share.
theme: GraphTheme,
/// Node lit-material response + default scene lighting rig — see
/// [`GraphEngine3D::lighting`]/[`GraphEngine3D::set_lighting`].
lighting: Graph3DLighting,
/// Edge/cluster-edge tint, alpha, and width-scale ceiling — see
/// [`GraphEngine3D::edge_style`]/[`GraphEngine3D::set_edge_style`].
edge_style: Graph3DEdgeStyle,
/// Reference-grid tuning (line/strong-line alpha, tint, cadence,
/// ground-plane margin, distance-LOD target, axis-label cap) — see
/// [`GraphEngine3D::grid_config`]/[`GraphEngine3D::set_grid_config`].
/// Distinct from [`Self::grid_enabled`], which stays the plain on/off
/// toggle.
grid_config: Graph3DGridConfig,
/// World-space hit-test slack added to a node's paint radius before
/// the CPU ray-sphere pick test — was the private
/// [`pick3d::PICK_RADIUS_SLACK_WORLD`] constant read directly by
/// every [`pick3d::nearest_node_3d`] call site. Exposed now (per this
/// wave's own scope); making it scale with zoom instead of staying a
/// flat world-space margin is Wave G3, not this one. See
/// [`GraphEngine3D::pick_radius_slack_world`]/
/// [`GraphEngine3D::set_pick_radius_slack_world`].
pick_radius_slack_world: f32,
/// Label-LOD grid/fade tuning fed to [`label_grid::select_labels`]/
/// [`label_grid::label_alpha`] — reuses the exact SAME
/// [`label_grid::LabelLodConfig`] type the 2D engine's own
/// `GraphEngine::label_lod` already owns (was this engine's own
/// `LabelLodConfig::default()` placeholder, passed at both call
/// sites without ever being a real, caller-configurable field). See
/// [`GraphEngine3D::label_lod`]/[`GraphEngine3D::set_label_lod`].
label_lod: label_grid::LabelLodConfig,
}
impl<N, E, L: Layout> GraphEngine3D<N, E, L> {
pub fn new(graph: Graph<N, E>, layout: L) -> Self {
let n = graph.node_count();
let all_node_ids: Vec<NodeIndex> = graph.nodes().map(|(id, _)| id).collect();
Self {
graph,
particles: vec![Particle::default(); n],
layout,
camera: Camera3D::default(),
hovered: None,
selected: None,
selection: BTreeSet::new(),
clusters: ClusterRegistry::default(),
node_mesh: Arc::new(MeshLit::sphere(1.0, NODE_SPHERE_RINGS, NODE_SPHERE_SLICES, [1.0, 1.0, 1.0, 1.0])),
marker_meshes: crate::render3d::Graph3DMarkerMeshes::default(),
edge_mesh: Arc::new(Mesh::unit_edge_quad([1.0, 1.0, 1.0, 1.0])),
modifiers: ModifierKeys::default(),
mode: Pointer3DMode::Idle,
drag_group: Vec::new(),
drag_was_group: false,
last_pointer_screen: (0.0, 0.0),
all_node_ids,
last_hover_pick_screen: None,
label_density: label_grid::DEFAULT_LABEL_DENSITY,
id_pass_mesh: Arc::new(crate::render3d::build_id_pass_mesh(NODE_SPHERE_RINGS, NODE_SPHERE_SLICES)),
gpu_pick_threshold: pick3d::GPU_PICK_NODE_THRESHOLD,
gpu_pick_pipeline: pick3d::GpuPickPipeline::new(),
grid_enabled: false,
hover_card: true,
label_halo: DEFAULT_LABEL_HALO.to_owned(),
local_root: None,
filter: None,
dim_transition: None,
orbit_camera: Camera3D::default(),
z_scale: 1.0,
transition_ever_started: false,
theme: GraphTheme::default(),
lighting: Graph3DLighting::default(),
edge_style: Graph3DEdgeStyle::default(),
grid_config: Graph3DGridConfig::default(),
pick_radius_slack_world: pick3d::PICK_RADIUS_SLACK_WORLD,
label_lod: label_grid::LabelLodConfig::default(),
}
}
/// Shared node-sphere mesh — exposed read-only so a future render
/// pass (Wave 2) can reuse it without re-generating geometry.
pub fn node_mesh(&self) -> &Arc<MeshLit> {
&self.node_mesh
}
/// Shared edge-line mesh — see [`GraphEngine3D::node_mesh`].
pub fn edge_mesh(&self) -> &Arc<Mesh> {
&self.edge_mesh
}
/// Advance the 3D force simulation by `dt` real seconds (plan §4 Wave
/// 1's proof surface) — also advances any in-flight
/// [`DimensionTransition`] (dimension-transition wave, see
/// [`GraphEngine3D::advance_dimension_transition`]), which only ever
/// touches [`GraphEngine3D::camera`]/the render-time z-scale, never
/// [`GraphEngine3D::particles`]. Filter/local-subgraph wave: ticks
/// against a FILTERED topology when [`Self::filter`] is active —
/// mirrors [`crate::engine::GraphEngine::tick`]'s own
/// filtered-topology branch literally: an edge is dropped from the
/// topology fed to `Layout::tick` the instant EITHER endpoint fails
/// the filter, so surviving nodes' link-force no longer pulls toward
/// an excluded one. [`Self::local_root`] does NOT affect this — local
/// mode is VIEW-ONLY (see [`GraphEngine3D::set_local_root`]'s own doc
/// comment), every particle keeps ticking under the full topology
/// regardless of the local-subgraph restriction.
pub fn tick(&mut self, dt: f32) -> LayoutTickResult {
self.advance_dimension_transition(dt);
let topo = self.graph.topology();
match &self.filter {
Some(filter) => {
let filtered_edges: Vec<SimEdge> = topo
.edges
.iter()
.copied()
.filter(|e| filter.matches(&self.graph, e.from) && filter.matches(&self.graph, e.to))
.collect();
let filtered_topo =
SimTopology { node_count: topo.node_count, edges: &filtered_edges, degree: topo.degree, radii: topo.radii };
self.layout.tick(&filtered_topo, &mut self.particles, dt)
}
None => self.layout.tick(&topo, &mut self.particles, dt),
}
}
/// Advance view-only transitions without invoking the graph layout.
///
/// This is the production path for projections whose particle
/// coordinates are supplied externally and pinned.
pub fn tick_view(&mut self, dt: f32) {
self.advance_dimension_transition(dt);
}
/// Seed every particle's `(x, y)` from `positions` (mirrors
/// [`crate::engine::GraphEngine::seed_positions`]'s own 2D-position
/// signature — the common bootstrap shape, migrating an existing
/// flat/2D layout into 3D), then [`GraphEngine3D::ensure_z_variance`]s
/// the result. This is the ENGINE-level fix for a live-caught Wave 2
/// defect (`uzor-graph/CLAUDE.md`'s divergence log has the full
/// writeup): seeding every node at `z = 0` makes every 3D force
/// z-symmetric, so the sim never leaves the plane on its own — this
/// is the one seeding entry point that guards against it, so any
/// caller (not just `force_graph_demo`) gets the fix for free.
pub fn seed_positions(&mut self, positions: &[(f32, f32)]) {
for (p, &(x, y)) in self.particles.iter_mut().zip(positions.iter()) {
p.x = x;
p.y = y;
}
self.ensure_z_variance();
}
/// If the particles' current z half-extent is degenerate relative to
/// their xy half-extent (below [`Z_DEGENERACY_RATIO`] — covers both
/// "every z is exactly 0" and "z has only trivial noise"),
/// deterministically jitters every particle's `z` by an
/// index-seeded, uniformly-distributed offset in
/// `±(xy_half_extent * Z_JITTER_XY_FRACTION)` (splitmix64-style LCG —
/// no `Math::random`/time, same convention this crate's own
/// deterministic test fixtures already use, e.g.
/// `force_directed_3d.rs`'s `deterministic_particles_3d`), then
/// reheats so the sim actively resolves into a true volume instead of
/// just sitting on the jittered starting positions.
///
/// A degenerate XY extent (every particle at the same `x`/`y` too —
/// e.g. right after [`GraphEngine3D::new`], before any seeding) is
/// left untouched: there's no meaningful scale to derive a jitter
/// range from yet, and [`GraphEngine3D::seed_positions`] is the
/// caller that gives this a real xy extent to work with.
pub fn ensure_z_variance(&mut self) {
if self.particles.is_empty() {
return;
}
let (mut min_x, mut max_x) = (f32::MAX, f32::MIN);
let (mut min_y, mut max_y) = (f32::MAX, f32::MIN);
let (mut min_z, mut max_z) = (f32::MAX, f32::MIN);
for p in &self.particles {
min_x = min_x.min(p.x);
max_x = max_x.max(p.x);
min_y = min_y.min(p.y);
max_y = max_y.max(p.y);
min_z = min_z.min(p.z);
max_z = max_z.max(p.z);
}
let xy_half_extent = ((max_x - min_x).max(max_y - min_y)) * 0.5;
if xy_half_extent <= 1e-6 {
return;
}
let z_half_extent = (max_z - min_z) * 0.5;
if z_half_extent > xy_half_extent * Z_DEGENERACY_RATIO {
// Already has a real z spread — an intentional 3D seed from
// some other source, don't disturb it.
return;
}
let jitter_range = xy_half_extent * Z_JITTER_XY_FRACTION;
for (i, p) in self.particles.iter_mut().enumerate() {
p.z += z_jitter_unit(i) * jitter_range;
}
self.layout.reheat(Z_JITTER_REHEAT_ALPHA);
}
/// Raw `PlatformEvent` handler — orbit-drag, wheel-dolly,
/// middle-drag/shift-drag pan (plan §1.4), hover on `PointerMoved` and click-to-select on a
/// low-movement `PointerDown`->`PointerUp` pair (Wave 3, plan §1.5).
/// Wire this from the app's 3D dispatch (see
/// `uzor-desktop::scene3d_app`'s divergence log for how
/// `force_graph_demo` routes events to whichever dimension is
/// active). Returns `true` if the event was consumed.
pub fn on_event(&mut self, event: &PlatformEvent, viewport: Rect) -> bool {
match event {
PlatformEvent::PointerDown { x, y, button: MouseButton::Left } => self.on_pointer_down(*x, *y, viewport),
PlatformEvent::PointerDown { x, y, button: MouseButton::Middle } => {
self.on_pan_pointer_down(*x, *y, MouseButton::Middle, viewport)
}
PlatformEvent::PointerMoved { x, y } => self.on_pointer_moved(*x, *y, viewport),
PlatformEvent::PointerUp { x, y, button: MouseButton::Left } => {
self.on_pointer_up(*x, *y, MouseButton::Left, viewport)
}
PlatformEvent::PointerUp { x, y, button: MouseButton::Middle } => {
self.on_pointer_up(*x, *y, MouseButton::Middle, viewport)
}
PlatformEvent::Scroll { dy, .. } => self.on_scroll(*dy, viewport),
PlatformEvent::ModifiersChanged { modifiers } => {
self.modifiers = *modifiers;
true
}
PlatformEvent::KeyDown { modifiers, .. } | PlatformEvent::KeyUp { modifiers, .. } => {
self.modifiers = *modifiers;
false
}
// Graph-strengthening arc G1.4 — the 3D mirror of the 2D
// engine's own `on_event` fix (`engine.rs`): a lost
// `PointerUp` (mouse released outside the window) otherwise
// wedges `Pointer3DMode::Orbiting`/`Panning`/`Dragging`/
// `BoxSelecting` forever. Finalizes exactly as a real
// `PointerUp` at the last known pointer position would, via
// the SAME `on_pointer_up` body.
PlatformEvent::PointerLeft => self.cancel_pointer_gesture(viewport),
PlatformEvent::WindowFocused(false) => self.cancel_pointer_gesture(viewport),
_ => false,
}
}
/// Finalize any in-progress orbit/pan/node-drag/box-select at
/// [`Self::last_pointer_screen`] — see [`Self::on_event`]'s
/// `PointerLeft`/`WindowFocused(false)` arms. A no-op (`false`) while
/// [`Pointer3DMode::Idle`]. A `Panning` gesture must release with the
/// SAME button that started it (`on_pointer_up`'s own contract) — read
/// straight from the live mode rather than guessing `Left`.
fn cancel_pointer_gesture(&mut self, viewport: Rect) -> bool {
let button = match self.mode {
Pointer3DMode::Idle => return false,
Pointer3DMode::Panning { button, .. } => button,
_ => MouseButton::Left,
};
let (x, y) = self.last_pointer_screen;
self.on_pointer_up(x, y, button, viewport)
}
/// Shift-held left-drag pans; a plain left-drag starting ON a node
/// drags THAT node (owner-ordered live fix — see [`Pointer3DMode::Dragging`]'s
/// own doc comment), everything else orbits the camera — the drag
/// KIND is resolved once here, at drag-start, and held for the whole
/// gesture (mirrors the 2D engine's own box-select-mode resolution,
/// `box_select_mode_for` in `engine.rs`). `false` (event not
/// consumed) if `(x, y)` lands outside `viewport`.
fn on_pointer_down(&mut self, x: f64, y: f64, viewport: Rect) -> bool {
if !viewport.contains(x, y) {
return false;
}
// Cluster/selection wave: a held Shift (alone, or with Ctrl/Alt)
// ALWAYS starts a box-select drag — mirrors the 2D engine's own
// `box_select_mode_for` precedence exactly, even ahead of the
// node-drag ray-pick below (same "modifier-held mousedown wins
// over node-grab" rule 2D's own divergence log documents). This
// REPURPOSES 3D's own former "Shift-drag pans" gesture — see
// [`Pointer3DMode::BoxSelecting`]'s own doc comment for the
// 2D-parity reasoning; plain middle-drag pan
// (`on_pan_pointer_down`) is unaffected.
if let Some(mode) = box_select_mode_for(self.modifiers) {
self.mode = Pointer3DMode::BoxSelecting { origin: (x, y), current: (x, y), mode };
return true;
}
// Node-drag ray-pick — ALWAYS the CPU path (`nearest_node_3d`),
// never the GPU color-ID pass, regardless of
// `should_use_gpu_pick()`: drag-start needs a synchronous,
// same-frame answer, and the plan's GPU escalation is scoped to
// hover refinement only (see `GraphEngine3D::apply_gpu_pick_result`'s
// own doc comment). Candidates exclude any node currently hidden
// by a collapsed cluster or the filter/local-subgraph exclusion
// set (see [`GraphEngine3D::pick_candidates`]).
//
// Dimension-transition wave: the HIT TEST itself runs against
// [`GraphEngine3D::render_particles`] (what's actually on screen
// mid-transition), but the drag PLANE/anchor position read just
// below is the REAL, unscaled `self.particles` position — a drag
// manipulates the simulated node directly and must never inherit
// a transition's cosmetic z-scale into the sim itself.
let aspect = (viewport.width / viewport.height.max(1.0)) as f32;
let camera = self.camera.to_perspective(aspect);
let (ray_origin, ray_dir) = pick3d::screen_to_ray(&camera, viewport, (x, y));
let candidates = self.pick_candidates();
let render_particles = self.render_particles();
if let Some(hit) =
pick3d::nearest_node_3d(&self.graph, &render_particles, ray_origin, ray_dir, &candidates, self.pick_radius_slack_world)
{
if let Some(p) = self.particles.get(hit.index()) {
let anchor_pos = Vec3::new(p.x, p.y, p.z);
let plane_point = anchor_pos;
let plane_normal = (camera.target - camera.eye).normalize_or_zero();
self.mode = Pointer3DMode::Dragging { node: hit, plane_point, plane_normal };
// Group-drag wave: dragging a node already IN the
// multi-selection moves the WHOLE selection together;
// dragging anything else drags just that one node (and,
// on release, Replace-selects it — see `on_pointer_up`).
// Mirrors 2D's own `on_pointer_down` group-drag decision
// (`engine.rs`) exactly.
let was_selected = self.selection.contains(&hit);
self.drag_was_group = was_selected;
let group: Vec<NodeIndex> = if was_selected { self.selection.iter().copied().collect() } else { vec![hit] };
self.drag_group = group
.into_iter()
.map(|node| {
let offset = self
.particles
.get(node.index())
.map(|mp| Vec3::new(mp.x, mp.y, mp.z) - anchor_pos)
.unwrap_or(Vec3::ZERO);
DragMember3 { node, offset }
})
.collect();
// Pin every member immediately at its own current
// position (`anchor_pos + offset` — a no-op positionally
// for the FIRST frame, since `offset` was just derived
// from that same current position; reproduces this
// engine's pre-group-drag single-node behavior
// byte-for-byte for a solo drag, where `offset ==
// Vec3::ZERO`). Every subsequent `PointerMoved` re-pins
// from the anchor's ray-plane intersection instead.
for member in &self.drag_group {
if let Some(pm) = self.particles.get_mut(member.node.index()) {
let target = anchor_pos + member.offset;
pm.pin3(target.x, target.y, target.z);
}
}
// Sustained reheat (mirrors 2D's own drag contract,
// `engine.rs`): hold alpha at the drag target for the
// whole gesture instead of a one-shot bump that starts
// cooling right away.
self.layout.set_alpha_target(NODE_DRAG_ALPHA_TARGET);
self.layout.reheat(NODE_DRAG_ALPHA_TARGET);
return true;
}
}
// Graph-strengthening arc G1.6 (3D mirror of 2D's `engine.rs`
// background-pan fix): real-time user input wins over an
// in-flight PROGRAMMATIC dimension transition — without this,
// `advance_dimension_transition`'s unconditional per-tick camera
// write fights the user's own orbit-drag every frame until the
// transition completes.
self.dim_transition = None;
self.mode = Pointer3DMode::Orbiting { last: (x, y), total: 0.0 };
true
}
fn on_pan_pointer_down(
&mut self,
x: f64,
y: f64,
button: MouseButton,
viewport: Rect,
) -> bool {
if !viewport.contains(x, y) {
return false;
}
// Same rule as the `Orbiting` branch above — see its own comment.
self.dim_transition = None;
self.mode = Pointer3DMode::Panning { last: (x, y), button };
true
}
fn on_pointer_moved(&mut self, x: f64, y: f64, viewport: Rect) -> bool {
self.last_pointer_screen = (x, y);
let mut handled = false;
match self.mode {
Pointer3DMode::Orbiting { last, total } => {
let dx = x - last.0;
let dy = y - last.1;
self.camera.orbit(dx as f32, dy as f32);
self.mode = Pointer3DMode::Orbiting { last: (x, y), total: total + (dx * dx + dy * dy).sqrt() };
handled = true;
}
Pointer3DMode::Panning { last, button } => {
self.camera.pan((x - last.0) as f32, (y - last.1) as f32);
self.mode = Pointer3DMode::Panning { last: (x, y), button };
handled = true;
}
Pointer3DMode::Dragging { plane_point, plane_normal, .. } => {
// Camera-parallel drag plane, fixed at drag-start (the
// camera itself never orbits/pans/dollies during a node
// drag — `on_pointer_down` chose `Dragging` INSTEAD of
// `Orbiting`/`Panning`, so `self.camera` is frozen for
// the whole gesture) — recompute the ray fresh from the
// CURRENT cursor position every move and intersect it
// against that same plane (see
// `pick3d::ray_plane_intersection`'s own doc comment).
// Group-drag wave: the resolved anchor world position
// feeds EVERY member of `self.drag_group` via its own
// fixed `offset` (the shared-delta shift — see
// [`DragMember3`]'s own doc comment); a solo drag's
// one-element group (`offset == Vec3::ZERO`) reproduces
// this engine's pre-group-drag single-node behavior
// byte-for-byte.
let aspect = (viewport.width / viewport.height.max(1.0)) as f32;
let camera = self.camera.to_perspective(aspect);
let (ray_origin, ray_dir) = pick3d::screen_to_ray(&camera, viewport, (x, y));
if let Some(anchor_world) = pick3d::ray_plane_intersection(ray_origin, ray_dir, plane_point, plane_normal) {
for member in &self.drag_group {
if let Some(p) = self.particles.get_mut(member.node.index()) {
let target = anchor_world + member.offset;
p.pin3(target.x, target.y, target.z);
}
}
}
handled = true;
}
Pointer3DMode::BoxSelecting { origin, mode, .. } => {
self.mode = Pointer3DMode::BoxSelecting { origin, current: (x, y), mode };
handled = true;
}
Pointer3DMode::Idle => {}
}
// Wave 3 hover pick — same movement-guard idiom as 2D's own
// `on_pointer_moved` (`engine.rs`): re-run the O(candidates)
// ray-sphere scan only once the pointer has actually moved
// `HOVER_PICK_MIN_MOVE_PX` since the last pick, and regardless of
// whether this move is ALSO orbiting/panning the camera (2D does
// the same — hover keeps tracking the cursor's current screen
// position against whatever the camera looks like right now,
// even mid-drag).
if viewport.contains(x, y) {
let moved_enough = match self.last_hover_pick_screen {
Some((lx, ly)) => {
let ddx = x - lx;
let ddy = y - ly;
(ddx * ddx + ddy * ddy).sqrt() >= HOVER_PICK_MIN_MOVE_PX
}
None => true,
};
if moved_enough {
self.last_hover_pick_screen = Some((x, y));
// CPU ray-pick is ALWAYS the same-frame answer (plan §4
// Wave 4: "the CPU ray pick as the same-frame answer
// while a GPU result is in flight") — above the GPU-pick
// threshold this ALSO kicks off a deferred GPU color-ID
// request (see `GraphEngine3D::apply_gpu_pick_result`),
// which refines `hovered` a frame or two later once it
// resolves. Below the threshold the GPU pipeline is
// never touched at all.
self.hovered = self.pick_at(x, y, viewport);
if self.should_use_gpu_pick() {
self.gpu_pick_pipeline.request((x, y));
}
}
handled = true;
} else if self.hovered.is_some() {
self.hovered = None;
self.last_hover_pick_screen = None;
}
handled
}
/// Ends the in-progress drag/orbit/pan/node-drag/box-select gesture; a
/// plain orbit-drag that travelled less than [`CLICK_DRAG_THRESHOLD_PX`]
/// since `PointerDown` resolves as a click — a designated single click
/// on a COLLAPSED cluster representative expands it (mirrors the 2D
/// engine's own `on_pointer_up`'s `PanningCamera` arm, `engine.rs` —
/// see `crate::cluster`'s own module doc for why this isn't a
/// double-click gesture); any other node Replace-selects it
/// ([`GraphEngine3D::select`]); empty space clears the selection
/// ([`GraphEngine3D::clear_selection`], mirroring 2D's own background-
/// click behavior). Shift-drag no longer pans (see
/// [`Pointer3DMode::BoxSelecting`]'s own doc comment) and never
/// resolves a click of its own — it resolves the box-select instead.
/// Middle-drag pan never resolves a click (see [`Pointer3DMode::Panning`]'s
/// doc comment). A node drag ALWAYS selects the dragged node on
/// release (a plain click on a node and a click-and-drag both end in
/// the node being selected — there's no ambiguous "was this a click
/// or a drag" question for a node hit the way there is for
/// background) and applies the STICKY drag-end policy (owner order,
/// same default [`crate::engine::DragEndPolicy::Sticky`] the 2D
/// engine uses): every member of [`Self::drag_group`] stays pinned
/// exactly where the last `PointerMoved` left it — `fx`/`fy`/`fz`
/// already hold that position via `pin3`, nothing further to do here
/// beyond releasing `alpha_target`. 3D is Sticky-ONLY (no
/// `DragEndPolicy::RestorePrior` equivalent — see [`DragMember3`]'s
/// own doc comment).
///
/// **Group-drag wave**: mirrors 2D's own `on_pointer_up`'s
/// `DraggingNode` arm branching exactly (`engine.rs`) — a group drag
/// (the anchor was already in [`Self::selection`] at drag-start, see
/// [`Self::drag_was_group`]) keeps the WHOLE selection selected as-is
/// (only [`Self::selected`], the facts-panel "last clicked" value,
/// moves to the physically-grabbed anchor); a solo drag
/// Replace-selects the dragged node ([`GraphEngine3D::select`]).
fn on_pointer_up(&mut self, x: f64, y: f64, button: MouseButton, viewport: Rect) -> bool {
let mode = self.mode;
if let Pointer3DMode::Panning { button: active_button, .. } = mode {
if button != active_button {
return false;
}
}
self.mode = Pointer3DMode::Idle;
match mode {
Pointer3DMode::Orbiting { total, .. } => {
if total < CLICK_DRAG_THRESHOLD_PX && viewport.contains(x, y) {
match self.pick_at(x, y, viewport) {
Some(hit) if self.clusters.cluster_of(hit).is_some_and(|id| self.clusters.is_collapsed(id)) => {
if let Some(id) = self.clusters.cluster_of(hit) {
self.expand_cluster(id);
}
}
Some(hit) => self.select(hit),
None => self.clear_selection(),
}
}
true
}
Pointer3DMode::Panning { .. } => true,
Pointer3DMode::Dragging { node, .. } => {
self.layout.set_alpha_target(0.0);
let was_group = self.drag_was_group;
self.drag_group.clear();
if was_group {
// The whole multi-selection just moved together — it
// STAYS selected as-is; only the facts-panel "last
// clicked" value moves to the physically-grabbed
// anchor (mirrors 2D's own `on_pointer_up` exactly).
self.selected = Some(node);
} else {
// A single un-selected node was dragged solo —
// Replace-selects itself on release (matches the
// pre-group-drag behavior exactly for this case).
self.select(node);
}
true
}
Pointer3DMode::BoxSelecting { origin, mode, .. } => {
self.box_select(origin, (x, y), mode, viewport);
true
}
Pointer3DMode::Idle => false,
}
}
/// Shared CPU ray-pick primitive (plan §1.5 v1) — resolves the
/// nearest node the ray through `(x, y)` in `viewport` hits, using
/// the CURRENT camera state. Both hover ([`GraphEngine3D::on_pointer_moved`])
/// and click-select ([`GraphEngine3D::on_pointer_up`]) funnel
/// through this one function so they can never diverge on which
/// camera/candidate set they pick against. Candidates exclude every
/// currently-excluded node (see [`GraphEngine3D::pick_candidates`]).
///
/// **Dimension-transition wave**: ray-vs-sphere hit-testing runs
/// against [`GraphEngine3D::render_particles`] (the `z`-scaled
/// snapshot), not `self.particles` directly, so hover/click always
/// hit whatever's ACTUALLY on screen mid-transition, not the
/// full-depth simulated position.
fn pick_at(&self, x: f64, y: f64, viewport: Rect) -> Option<NodeIndex> {
let aspect = (viewport.width / viewport.height.max(1.0)) as f32;
let camera = self.camera.to_perspective(aspect);
let (origin, dir) = pick3d::screen_to_ray(&camera, viewport, (x, y));
let candidates = self.pick_candidates();
let render_particles = self.render_particles();
pick3d::nearest_node_3d(&self.graph, &render_particles, origin, dir, &candidates, self.pick_radius_slack_world)
}
/// Node ids currently eligible for hover/click/drag picking, box-select
/// containment, and label emission — every graph node MINUS
/// [`GraphEngine3D::compute_excluded_nodes_3d`]'s union (cluster-hidden
/// ∪ local-subgraph-excluded ∪ filter-excluded — filter/local-subgraph
/// wave; cluster wave — mirrors the 2D engine's own visible-set
/// discipline, `GraphEngine::visible_nodes`/`compute_excluded_nodes`;
/// 3D has no viewport-culling pass of its own yet, see
/// [`GraphEngine3D::all_node_ids`]'s own doc comment). Scene-instance
/// emission ([`GraphEngine3D::build_scene`]) applies the SAME
/// exclusion independently at the `render3d` function level — both
/// derive from the identical `compute_excluded_nodes_3d` source, so a
/// node can never be pickable yet invisible, or vice versa.
fn pick_candidates(&self) -> Vec<NodeIndex> {
let excluded = self.compute_excluded_nodes_3d();
if excluded.is_empty() {
return self.all_node_ids.clone();
}
self.all_node_ids.iter().copied().filter(|id| !excluded.contains(id)).collect()
}
/// The union of every 3D exclusion source (filter/local-subgraph
/// wave) — cluster-hidden (pre-existing) ∪ local-subgraph-excluded ∪
/// filter-excluded. Mirrors [`crate::engine::GraphEngine::
/// compute_excluded_nodes`] exactly, one wave later: the SAME choke
/// point [`GraphEngine3D::pick_candidates`] (hover/click/drag picking,
/// box-select containment, `visible_labels`' candidate set — all
/// routed through `pick_candidates`) and [`GraphEngine3D::build_scene`]
/// (no node instance, no touching edges — the wave-1 `hidden` param
/// plumbing, no second parallel mechanism) both feed from.
fn compute_excluded_nodes_3d(&self) -> HashSet<NodeIndex> {
let mut excluded: HashSet<NodeIndex> =
if self.clusters.any_collapsed() { self.clusters.hidden_nodes().collect() } else { HashSet::new() };
if let Some((root, depth)) = self.local_root {
let local_set = self.local_bfs_nodes_3d(root, depth);
for (id, _) in self.graph.nodes() {
if !local_set.contains(&id) {
excluded.insert(id);
}
}
}
if let Some(filter) = &self.filter {
for (id, _) in self.graph.nodes() {
if !filter.matches(&self.graph, id) {
excluded.insert(id);
}
}
}
excluded
}
/// BFS depth-`depth` node set from `root` (filter/local-subgraph
/// wave) — mirrors [`crate::engine::GraphEngine::local_bfs_nodes`]
/// exactly: reuses [`Graph::neighborhood_focus_keys_depth`]'s existing
/// BFS rather than a parallel walk, converting its tagged `FocusSet`
/// keys back to plain `NodeIndex` via the even/odd convention
/// `graph.rs`'s `From<NodeIndex> for u64` already established (node
/// keys are even).
fn local_bfs_nodes_3d(&self, root: NodeIndex, depth: u8) -> HashSet<NodeIndex> {
self.graph
.neighborhood_focus_keys_depth(root, depth)
.into_iter()
.filter(|k| k % 2 == 0)
.map(|k| NodeIndex((k >> 1) as u32))
.collect()
}
/// Wheel-to-dolly, gated on the cursor currently sitting over
/// `viewport` (mirrors `GraphEngine::on_scroll`'s own gate). Positive
/// `dy` means "zoom in" (matches the 2D engine's own convention) —
/// in orbit-camera terms that means a SMALLER `distance`, the
/// inverse of 2D's "bigger `zoom`", so the sign is flipped relative
/// to the 2D formula this mirrors.
fn on_scroll(&mut self, dy: f64, viewport: Rect) -> bool {
if !viewport.contains(self.last_pointer_screen.0, self.last_pointer_screen.1) {
return false;
}
// Same "live user input supersedes a running animation" rule as
// the `Orbiting`/`Panning` gesture-start sites above.
self.dim_transition = None;
let factor = (1.0 - dy as f32 * DOLLY_SENSITIVITY).clamp(DOLLY_FACTOR_MIN, DOLLY_FACTOR_MAX);
self.camera.dolly(factor);
true
}
/// Frame the WHOLE graph in view — dolly + retarget only, current
/// yaw/pitch are kept (Wave 5, mirrors the 2D engine's own
/// `GraphEngine::fit_view`'s "keep the user's orientation" spirit).
/// `aspect` is the caller's real render-surface aspect — this engine
/// has no viewport of its own to derive one from (same reason
/// [`GraphEngine3D::camera`] takes an explicit `aspect` too). A no-op
/// if there isn't a single particle yet; a too-small or
/// near-degenerate (effectively coincident) particle cloud (see
/// [`FIT_VIEW_MIN_NODES`]/[`FIT_VIEW_MIN_HALF_DIAGONAL`]) recenters on
/// whatever IS there but falls back to [`Camera3D::default`]'s own
/// distance rather than an arbitrary [`Camera3D::fit_bounds`] result.
pub fn fit_view(&mut self, aspect: f32) {
let Some((min, max)) = particle_aabb(&self.particles) else { return };
// Graph-strengthening arc G1.6: an explicit user-requested fit
// (Home/F, or the `fit_view_3d` agent action) is real-time input
// too — clear any in-flight dimension transition first, same rule
// as the pointer/scroll gesture-start sites in `on_pointer_down`/
// `on_pan_pointer_down`/`on_scroll` above, so this write isn't
// immediately overwritten by `advance_dimension_transition`'s own
// unconditional per-tick camera write on the very next `tick()`.
self.dim_transition = None;
let half_diagonal = (max - min).length() * 0.5;
if self.particles.len() < FIT_VIEW_MIN_NODES || half_diagonal < FIT_VIEW_MIN_HALF_DIAGONAL {
self.camera.target = (min + max) * 0.5;
self.camera.distance = Camera3D::default().distance;
return;
}
self.camera.fit_bounds(min, max, aspect, FIT_VIEW_PADDING);
}
// ── Dimension transition (dimension-transition wave — animated
// 2D<->3D switch driven by `force_graph_demo`'s own `set_dimension`
// action) ─────────────────────────────────────────────────────────
/// Current render-time z-scale — a thin getter over the persistent
/// [`Self::z_scale`] field (see that field's own doc comment for why
/// this is a STORED, sticky value rather than recomputed transiently
/// from `dim_transition`'s mere presence). `1.0` absent any
/// transition ever having run (this engine's ordinary, full-volume 3D
/// state); eased between `0.0`/`1.0` while
/// [`GraphEngine3D::transition_active`]; STAYS at whatever a
/// transition last eased it to even after that transition completes.
/// Every RENDER/PICK/LABEL/OVERLAY consumer of particle positions
/// applies this scale to `z` via [`GraphEngine3D::render_particles`]
/// (whole-slice consumers: [`GraphEngine3D::build_scene`], the grid
/// AABB, CPU ray-picking) or inline against a single particle
/// (`visible_labels`/`draw_overlay`/box-select containment) — the
/// SIMULATION itself ([`GraphEngine3D::particles`]/
/// [`GraphEngine3D::tick`]) never reads this and is never mutated by
/// it.
fn render_z_scale(&self) -> f32 {
self.z_scale
}
/// Owned snapshot of every particle with `z` scaled by
/// [`GraphEngine3D::render_z_scale`] — the choke point every
/// whole-slice RENDER/PICK consumer reads instead of `self.particles`
/// directly. `Particle` is `Copy`, so this clone is cheap at this
/// crate's node-count scale — no attempt is made to skip the
/// allocation in the always-`1.0` steady state, matching this file's
/// own established "small per-frame allocations are an acceptable
/// cost at this scale" convention (e.g. [`GraphEngine3D::
/// compute_excluded_nodes_3d`]'s own `HashSet`s).
fn render_particles(&self) -> Vec<Particle> {
let scale = self.render_z_scale();
self.particles
.iter()
.map(|p| {
let mut p = *p;
p.z *= scale;
p
})
.collect()
}
/// A front-on, 2D-like camera framing of the CURRENT particle layout
/// — `yaw = 0`, `pitch = 0` (looking straight down the world `-Z`
/// axis at the flat `xy` plane, the same front-on view a 2D camera
/// would show), `target`/`distance` derived via [`Camera3D::
/// fit_bounds`] against the layout's own FLATTENED (`z = 0`) AABB so
/// the graph fills the viewport the way 2D's own `Camera2D::fit_view`
/// framing does. Falls back to [`Camera3D::default`]'s own distance,
/// centered at the origin, if there isn't a single particle yet. Uses
/// a fixed [`FRONT_ON_ASPECT`] — see that constant's own doc comment.
fn front_on_camera(&self) -> Camera3D {
let mut camera = Camera3D { target: Vec3::ZERO, distance: Camera3D::default().distance, yaw: 0.0, pitch: 0.0, ..Camera3D::default() };
if let Some((min, max)) = particle_aabb(&self.particles) {
let flat_min = Vec3::new(min.x, min.y, 0.0);
let flat_max = Vec3::new(max.x, max.y, 0.0);
camera.fit_bounds(flat_min, flat_max, FRONT_ON_ASPECT, FIT_VIEW_PADDING);
}
camera
}
/// Start (or REVERSE) an animated 2D<->3D dimension transition —
/// `direction: In` inflates the flat layout into a volume while the
/// camera eases from a front-on framing toward the settled orbit
/// pose; `Out` reverses both (the volume flattens, the camera eases
/// back toward the front-on framing). `duration_ms <= 0.0` completes
/// on the very next [`GraphEngine3D::tick`] (an explicit instant
/// transition, the same convention [`crate::engine`]'s own
/// `CameraTransition` uses).
///
/// **Continuity, no snap**: calling this again while a transition is
/// ALREADY in flight (a caller toggling back before the first one
/// finished) does NOT reset to the canonical `0.0`/`1.0`/front-on/
/// orbit endpoints — the new transition's START is whatever the
/// CURRENT instantaneous z-scale/camera pose happens to be
/// ([`GraphEngine3D::render_z_scale`]/`self.camera`, both already
/// continuously updated every tick by the transition in progress), so
/// reversing direction eases smoothly from exactly where the visual
/// state already is. The END is always the pure canonical target for
/// the NEW direction.
///
/// **Remembering the orbit pose across a flatten-out-and-back
/// cycle**: `self.camera` itself gets overwritten by the ease every
/// tick, so [`Self::orbit_camera`] separately remembers the last
/// SETTLED (non-transitional) orbit pose — refreshed only when a
/// FRESH (not-already-in-flight) `Out` transition starts, since that
/// is the one moment `self.camera` is guaranteed to hold the caller's
/// own most recent real orbit/pan/dolly interaction, undisturbed by
/// any ease. `In`'s own end target reads this snapshot (not
/// `self.camera`), so any number of reversals always still converges
/// back on the SAME real orbit pose, never a stale or mid-flight one.
///
/// **Wave G3 item 5 fix — idempotent against a REDUNDANT `In`.** The
/// "genuinely fresh vs. already in flight" question above is
/// answered by `is_fresh` (`dim_transition.is_none()`), which is
/// correct for REVERSAL detection but NOT for distinguishing a
/// genuine first-ever `In` from a redundant one: `dim_transition`
/// also reads `None` the instant a PRIOR transition simply finished
/// — a caller re-invoking `start_transition(In, _)` on an engine
/// that's already fully, steadily 3D (`z_scale == 1.0`, no
/// transition object because the last one already completed) would,
/// under the old `is_fresh`-only test, still force `start_scale` back
/// to `0.0` and the camera back to `front_on` — a spurious
/// flatten-then-reinflate/camera-jump glitch, not a genuine
/// visual reset. [`Self::transition_ever_started`] is the signal
/// that actually distinguishes the two: `false` only on a
/// construction-fresh (or never-transitioned) engine, where
/// `z_scale`/`camera` still hold their raw, never-set defaults and
/// genuinely need forcing to the canonical flat/front-on start;
/// `true` for every call after the first, where `z_scale`/`camera`
/// already hold an honest reflection of the real visual state
/// (steady, or live mid-flight, or the honest result of the LAST
/// completed transition — e.g. after a real `Out` finishes, `z_scale`
/// is genuinely `0.0`, and a SECOND `In` correctly eases up FROM that
/// real flat state) — reading them directly is always correct there.
/// Scoped to `In` only, matching the one reachable redundant-call
/// path (`Out`'s own `is_fresh`-gated `orbit_camera` capture is
/// unaffected — a redundant `Out` is not reachable through this
/// crate's own call sites, since every existing caller only invokes
/// `Out` while genuinely `ThreeD`).
pub fn start_transition(&mut self, direction: TransitionDirection, duration_ms: f64) {
let is_fresh = self.dim_transition.is_none();
// Wave G3 item 5 fix: `bootstrapping` (not `is_fresh`) governs
// whether `In` forces the canonical flat/front-on start — see
// this method's own doc comment above.
let bootstrapping = direction == TransitionDirection::In && !self.transition_ever_started;
let start_scale = if bootstrapping { 0.0 } else { self.render_z_scale() };
let end_scale = match direction {
TransitionDirection::In => 1.0,
TransitionDirection::Out => 0.0,
};
if is_fresh && direction == TransitionDirection::Out {
self.orbit_camera = self.camera;
}
let front_on = self.front_on_camera();
let (start_camera, end_camera) = match direction {
TransitionDirection::In => (if bootstrapping { front_on } else { self.camera }, self.orbit_camera),
TransitionDirection::Out => (self.camera, front_on),
};
self.camera = start_camera;
self.z_scale = start_scale;
self.transition_ever_started = true;
self.dim_transition = Some(DimensionTransition {
direction,
elapsed_s: 0.0,
duration_s: (duration_ms.max(0.0) / 1000.0) as f32,
start_scale,
end_scale,
start_camera,
end_camera,
});
}
/// Whether an animated dimension transition is currently in flight —
/// the completion probe a caller's `set_dimension`-equivalent handling
/// polls every tick to know when to hand control back to the 2D
/// engine (`force_graph_demo`'s own `scene3d` does exactly this for
/// its `Out` case — see that function's own doc comment). This engine
/// has no freeze/wake concept of its own (`uzor-graph/CLAUDE.md`'s
/// divergence log), so it isn't a new redraw gate — the demo already
/// ticks every frame while 3D is active regardless.
pub fn transition_active(&self) -> bool {
self.dim_transition.is_some()
}
/// Current transition direction, if any. See
/// [`GraphEngine3D::start_transition`].
pub fn transition_direction(&self) -> Option<TransitionDirection> {
self.dim_transition.as_ref().map(|t| t.direction)
}
/// Current transition's raw linear progress in `[0, 1]` — `0.0` when
/// no transition is active.
pub fn transition_progress(&self) -> f64 {
self.dim_transition.as_ref().map(DimensionTransition::progress).unwrap_or(0.0)
}
/// Advance the in-flight [`DimensionTransition`], if any, and clear it
/// once it reaches `progress >= 1.0` — mirrors
/// [`crate::engine::GraphEngine`]'s own `advance_camera_transition`
/// convention: `self.camera`'s yaw/pitch/distance/target AND
/// [`Self::z_scale`] are each linearly interpolated against the SAME
/// eased fraction ("ease the fraction, lerp every field against it",
/// not a curved fly-to path). `z_scale` is written into the
/// persistent field even on the very tick that finishes the
/// transition (before `dim_transition` is cleared), so it lands
/// EXACTLY on the pure canonical endpoint and stays there afterward —
/// see that field's own doc comment for why this must be a stored
/// write, not a value recomputed from `dim_transition.is_some()`.
fn advance_dimension_transition(&mut self, dt: f32) {
let Some(t) = self.dim_transition.as_mut() else { return };
t.elapsed_s += dt.max(0.0);
let progress = t.progress();
let eased = ease_in_out_cubic(progress) as f32;
let start_scale = t.start_scale;
let end_scale = t.end_scale;
let start_camera = t.start_camera;
let end_camera = t.end_camera;
let finished = progress >= 1.0;
self.z_scale = start_scale + (end_scale - start_scale) * eased;
self.camera.yaw = start_camera.yaw + (end_camera.yaw - start_camera.yaw) * eased;
self.camera.pitch = start_camera.pitch + (end_camera.pitch - start_camera.pitch) * eased;
self.camera.distance = start_camera.distance + (end_camera.distance - start_camera.distance) * eased;
self.camera.target = start_camera.target + (end_camera.target - start_camera.target) * eased;
if finished {
self.dim_transition = None;
}
}
/// Whether [`GraphEngine3D::build_scene`]/[`GraphEngine3D::draw_overlay`]
/// currently emit the ground-reference grid + axis tick labels (Wave
/// 5) — default `false`. See [`GraphEngine3D::set_grid_enabled`].
pub fn grid_enabled(&self) -> bool {
self.grid_enabled
}
/// Toggle the ground-reference grid (Wave 5) — see
/// [`GraphEngine3D::grid_enabled`]'s own doc comment for why it
/// defaults off.
pub fn set_grid_enabled(&mut self, enabled: bool) {
self.grid_enabled = enabled;
}
/// Whether [`Self::draw_overlay`] paints the generic info card near a
/// hovered node. Hover picking remains enabled independently.
pub fn hover_card_enabled(&self) -> bool {
self.hover_card
}
/// Toggle only the generic hovered-node info card. This does not
/// clear or disable [`Self::hovered`].
pub fn set_hover_card_enabled(&mut self, enabled: bool) {
self.hover_card = enabled;
}
/// Node-label halo color — the 3D sibling of [`crate::engine::
/// GraphEngine::label_halo`] (same [`DEFAULT_LABEL_HALO`] default).
pub fn label_halo(&self) -> &str {
&self.label_halo
}
/// Set this engine's own node-label halo color to match a caller's OWN
/// canvas background — see [`crate::engine::GraphEngine::
/// set_label_halo`]'s own doc comment for the same reasoning.
pub fn set_label_halo(&mut self, color: impl Into<String>) {
self.label_halo = color.into();
}
// ── Graph-strengthening arc Wave G2b — 3D configurability accessors.
// Same "private field + accessor pair" convention as
// `label_halo`/`set_label_halo` above. ──────────────────────────────
/// This engine's own overlay theme — see [`Self::theme`] field's own
/// doc comment. Default: [`GraphTheme::default`] (`dark()`),
/// byte-identical to this engine's own pre-existing hardcoded overlay
/// literals.
pub fn theme(&self) -> &GraphTheme {
&self.theme
}
/// Replace this engine's overlay theme — e.g. [`GraphTheme::light`]/
/// [`GraphTheme::high_contrast`], or a struct-update literal changing
/// just one field.
pub fn set_theme(&mut self, theme: GraphTheme) {
self.theme = theme;
}
/// This engine's own node-material + default lighting rig — see
/// [`Self::lighting`] field's own doc comment. Default:
/// [`Graph3DLighting::default`], byte-identical to this engine's own
/// pre-existing hardcoded material/lighting literals.
pub fn lighting(&self) -> &Graph3DLighting {
&self.lighting
}
pub fn set_lighting(&mut self, lighting: Graph3DLighting) {
self.lighting = lighting;
}
/// This engine's own edge/cluster-edge paint style — see
/// [`Self::edge_style`] field's own doc comment. Default:
/// [`Graph3DEdgeStyle::default`], byte-identical to this engine's own
/// pre-existing hardcoded edge-tint/width literals.
pub fn edge_style(&self) -> &Graph3DEdgeStyle {
&self.edge_style
}
pub fn set_edge_style(&mut self, style: Graph3DEdgeStyle) {
self.edge_style = style;
}
/// This engine's own reference-grid tuning — see [`Self::grid_config`]
/// field's own doc comment. Default: [`Graph3DGridConfig::default`],
/// byte-identical to this engine's own pre-existing hardcoded grid
/// literals. Distinct from [`Self::grid_enabled`]/
/// [`Self::set_grid_enabled`], which stays the plain on/off toggle.
pub fn grid_config(&self) -> &Graph3DGridConfig {
&self.grid_config
}
pub fn set_grid_config(&mut self, config: Graph3DGridConfig) {
self.grid_config = config;
}
/// World-space hit-test slack currently added to a node's paint
/// radius before the CPU ray-sphere pick test — see [`Self::pick_radius_slack_world`]
/// field's own doc comment. Default: [`pick3d::PICK_RADIUS_SLACK_WORLD`].
pub fn pick_radius_slack_world(&self) -> f32 {
self.pick_radius_slack_world
}
pub fn set_pick_radius_slack_world(&mut self, slack: f32) {
self.pick_radius_slack_world = slack;
}
/// This engine's own label-LOD grid/fade tuning — see
/// [`Self::label_lod`] field's own doc comment. Default:
/// [`label_grid::LabelLodConfig::default`], byte-identical to this
/// engine's own pre-existing `LabelLodConfig::default()` placeholder.
pub fn label_lod(&self) -> &label_grid::LabelLodConfig {
&self.label_lod
}
pub fn set_label_lod(&mut self, lod: label_grid::LabelLodConfig) {
self.label_lod = lod;
}
// ── Filter / local subgraph (filter/local-subgraph wave — mirrors
// `GraphEngine`'s own `set_local_root`/`local_root`/`set_filter`/
// `filter` API 1:1, reusing the exact SAME [`FilterSpec`] type) ──────
/// Restrict the visible/pick/label set to the BFS depth-`depth`
/// neighborhood of `root` — everything else is EXCLUDED entirely (not
/// dimmed), the same mechanism a collapsed cluster's hidden members
/// already use (see [`GraphEngine3D::compute_excluded_nodes_3d`]).
/// Mirrors [`crate::engine::GraphEngine::set_local_root`] exactly:
/// VIEW-ONLY — [`GraphEngine3D::tick`] keeps ticking every particle
/// under the full, unrestricted force topology regardless (contrast
/// [`GraphEngine3D::set_filter`], which DOES change the force
/// topology). `depth` defaults to [`DEFAULT_LOCAL_DEPTH_3D`] (`2`)
/// when `None`. `root = None` restores the full view.
///
/// **Divergence from 2D, by explicit task instruction**: does NOT
/// auto-fit the camera. 2D's own `set_local_root` animates
/// `zoom_to_fit` on every change because `GraphEngine` owns a
/// `canvas_rect` of its own; this engine owns no viewport (every
/// other viewport-needing method here — `on_event`/`fit_view`/
/// `box_select` — already takes one explicitly), so there is no
/// implicit aspect ratio to fit against. The caller decides when to
/// fit and with which real aspect — see [`GraphEngine3D::fit_view`];
/// `force_graph_demo`'s own `set_local_root` forwarding calls
/// `fit_view(real_aspect)` right after this, mirroring 2D's own
/// "activation frames the local neighborhood" convention at the
/// demo/caller layer instead of inside the engine.
pub fn set_local_root(&mut self, root: Option<NodeIndex>, depth: Option<u8>) {
self.local_root = root.map(|node| (node, depth.unwrap_or(DEFAULT_LOCAL_DEPTH_3D)));
}
/// Current local-subgraph root + depth, if active. See
/// [`GraphEngine3D::set_local_root`].
pub fn local_root(&self) -> Option<(NodeIndex, u8)> {
self.local_root
}
/// Query filter — mirrors [`crate::engine::GraphEngine::set_filter`]
/// exactly, including the "removed from the sim" scope boundary
/// documented on that method's own doc comment: filtered-out nodes
/// are EXCLUDED from render/pick/labels (the same mechanism
/// [`GraphEngine3D::set_local_root`] uses) AND from the force
/// topology fed to `Layout::tick` every subsequent
/// [`GraphEngine3D::tick`] call (see that method's own doc comment).
/// Reheats so the re-settle under the new topology is visible.
pub fn set_filter(&mut self, filter: Option<FilterSpec>) {
self.filter = filter;
self.layout.reheat(REHEAT_ALPHA);
}
/// Current query filter, if active. See [`GraphEngine3D::set_filter`].
pub fn filter(&self) -> Option<&FilterSpec> {
self.filter.as_ref()
}
// ── Cluster collapse/expand (cluster wave — mirrors `GraphEngine`'s
// own `define_cluster`/`collapse_cluster`/`expand_cluster` API 1:1,
// driven through `ClusterRegistry`'s 3D-aware `collapse_3d`/
// `expand_3d` instead of the 2D-only `collapse`/`expand`) ───────────
/// Declare a cluster over `members` (first member becomes the
/// collapse representative — see `cluster.rs` module docs). `None` if
/// `members` is empty.
pub fn define_cluster(&mut self, members: Vec<NodeIndex>) -> Option<GroupId> {
self.clusters.define(&self.graph, members)
}
pub fn is_collapsed(&self, id: GroupId) -> bool {
self.clusters.is_collapsed(id)
}
/// Collapse `id` into one super-node — 3D centroid position (all 3
/// axes), member-count radius, aggregated cross-cluster edge weights
/// (see [`ClusterRegistry::collapse_3d`]). No-op (`false`) if `id` is
/// unknown or already collapsed.
pub fn collapse_cluster(&mut self, id: GroupId) -> bool {
self.clusters.collapse_3d(id, &mut self.graph, &mut self.particles)
}
/// Expand `id` back to its individual members, restoring EXACT
/// pre-collapse `(x, y, z)` positions (round-trip identity — see
/// [`ClusterRegistry::expand_3d`]), then reheats so the layout
/// visibly resettles around them (mirrors [`GraphEngine3D::unpin_node`]'s
/// own convention). No-op (`false`) if `id` is unknown or not
/// currently collapsed.
pub fn expand_cluster(&mut self, id: GroupId) -> bool {
let ok = self.clusters.expand_3d(id, &mut self.graph, &mut self.particles);
if ok {
self.layout.reheat(REHEAT_ALPHA);
}
ok
}
// ── Multi-selection (cluster/selection wave — mirrors `GraphEngine`'s
// own `select`/`clear_selection`/`apply_selection`/`box_select`/
// `collapse_selection`/`pin_selection`/`unpin_selection` API) ───────
/// A CLICK (or a node-drag-then-release — see `on_pointer_up`'s
/// `Dragging` arm) always Replace-selects: `selected` (facts-panel
/// value) AND `selection` (the multi-select set [`GraphEngine3D::
/// draw_overlay`]'s selection rings derive from) both become exactly
/// `{node}` — mirrors [`crate::engine::GraphEngine::select`] exactly.
pub fn select(&mut self, node: NodeIndex) {
self.selected = Some(node);
self.selection = std::iter::once(node).collect();
}
/// Clears BOTH `selected` and `selection` — mirrors
/// [`crate::engine::GraphEngine::clear_selection`].
pub fn clear_selection(&mut self) {
self.selected = None;
self.selection.clear();
}
/// Combine `nodes` into the current [`GraphEngine3D::selection`] per
/// `mode` — mirrors [`crate::engine::GraphEngine::apply_selection`]
/// exactly, including deliberately NOT touching
/// [`GraphEngine3D::selected`] (a bulk selection op is a different
/// gesture from a click). Drives [`GraphEngine3D::box_select`] and the
/// `select_nodes`/`box_select` agent-forwarding actions.
///
/// **Known divergence from 2D**: this method does not recompute any
/// hover/selection dim-highlight `FocusSet`-equivalent, because 3D has
/// none yet (`render3d::build_scene` tints every node by category
/// only) — see [`GraphEngine3D::draw_overlay`]'s own doc comment for
/// what 3D DOES paint for a selection (rings), not a dim/highlight
/// reducer.
pub fn apply_selection(&mut self, nodes: impl IntoIterator<Item = NodeIndex>, mode: SelectMode) {
match mode {
SelectMode::Replace => self.selection = nodes.into_iter().collect(),
SelectMode::Union => self.selection.extend(nodes),
SelectMode::Diff => {
for node in nodes {
if !self.selection.remove(&node) {
self.selection.insert(node);
}
}
}
}
}
/// Screen-space rectangle box-select — the 3D counterpart of
/// [`crate::engine::GraphEngine::box_select`]. `corner_a`/`corner_b`
/// are any two opposite corners in screen px, order-independent
/// (corner-normalized internally via [`normalized_rect`]).
/// Containment is a node's projected screen CENTER
/// ([`pick3d::project_world_to_screen`]) falling inside the rect —
/// same "screen center, not full node-bounds overlap" convention 2D
/// uses. Candidates are drawn from [`GraphEngine3D::pick_candidates`]
/// (every node MINUS anything hidden by a collapsed cluster).
///
/// **Known divergence from 2D**: takes an explicit `viewport`
/// parameter — unlike `GraphEngine`, this engine owns no `canvas_rect`
/// of its own (every other viewport-needing method here, e.g.
/// `on_event`/`fit_view`, already takes one explicitly too), so there
/// is no implicit viewport to read a projection/aspect from.
pub fn box_select(&mut self, corner_a: (f64, f64), corner_b: (f64, f64), mode: SelectMode, viewport: Rect) {
let rect = normalized_rect(corner_a, corner_b);
let aspect = (viewport.width / viewport.height.max(1.0)) as f32;
let camera = self.camera.to_perspective(aspect);
let nodes = self.nodes_in_screen_rect(&camera, viewport, rect);
self.apply_selection(nodes, mode);
}
fn nodes_in_screen_rect(&self, camera: &PerspectiveCamera, viewport: Rect, rect: Rect) -> Vec<NodeIndex> {
// Dimension-transition wave: containment against the `z`-scaled
// render position (see `GraphEngine3D::render_z_scale`), not the
// raw simulated `z` — same "hit what's on screen" reasoning as
// `pick_at`.
let scale = self.render_z_scale();
self.pick_candidates()
.into_iter()
.filter(|&id| {
let Some(p) = self.particles.get(id.index()) else { return false };
match pick3d::project_world_to_screen(camera, Vec3::new(p.x, p.y, p.z * scale), viewport) {
Some((sx, sy)) => rect.contains(sx, sy),
None => false,
}
})
.collect()
}
/// Live screen-space rectangle of an in-progress box-select drag,
/// already corner-normalized — `None` when no box-select is active.
/// Mirrors [`crate::engine::GraphEngine::box_select_rect`]; a caller's
/// overlay draw reads this every frame via `render::draw_box_select_rect`
/// (see [`GraphEngine3D::draw_overlay`]).
pub fn box_select_rect(&self) -> Option<Rect> {
match self.mode {
Pointer3DMode::BoxSelecting { origin, current, .. } => Some(normalized_rect(origin, current)),
_ => None,
}
}
/// Define a cluster over the CURRENT [`GraphEngine3D::selection`] and
/// immediately collapse it — mirrors
/// [`crate::engine::GraphEngine::collapse_selection`] exactly. `None`
/// if the selection is empty.
pub fn collapse_selection(&mut self) -> Option<GroupId> {
if self.selection.is_empty() {
return None;
}
let members: Vec<NodeIndex> = self.selection.iter().copied().collect();
let id = self.define_cluster(members)?;
self.collapse_cluster(id);
Some(id)
}
/// The [`GroupId`] whose FULL member set is EXACTLY the current
/// selection and which is currently collapsed — mirrors
/// [`crate::engine::GraphEngine::selection_collapsed_group`], purely
/// derived, no separate bookkeeping.
pub fn selection_collapsed_group(&self) -> Option<GroupId> {
if self.selection.is_empty() {
return None;
}
self.clusters.iter().find_map(|(id, cluster)| {
if !cluster.is_collapsed() {
return None;
}
let members: BTreeSet<NodeIndex> = cluster.members.iter().copied().collect();
(members == self.selection).then_some(id)
})
}
/// Persistently pin `node` at its current `(x, y, z)` position.
/// **Known simplification vs. 2D**: no separate `pinned: Vec<bool>`
/// bookkeeping array — [`GraphEngine3D::node_facts`]'s own `pinned`
/// field already reads [`Particle::is_pinned_3d`] directly, and this
/// engine's node-drag only ever uses [`crate::engine::DragEndPolicy::Sticky`]
/// (no `RestorePrior` mode to disambiguate a transient drag-pin from a
/// persistent one), so there's no state a parallel bool would need to
/// carry that the particle's own `fx`/`fy`/`fz` don't already capture.
pub fn pin_node(&mut self, node: NodeIndex) {
if let Some(p) = self.particles.get_mut(node.index()) {
let (x, y, z) = (p.x, p.y, p.z);
p.pin3(x, y, z);
}
}
/// Release the persistent pin and reheat so the node visibly rejoins
/// the simulation — mirrors [`crate::engine::GraphEngine::unpin_node`].
pub fn unpin_node(&mut self, node: NodeIndex) {
if let Some(p) = self.particles.get_mut(node.index()) {
p.unpin3();
}
self.layout.reheat(REHEAT_ALPHA);
}
/// Persistently pin every node in the current selection — mirrors
/// [`crate::engine::GraphEngine::pin_selection`].
pub fn pin_selection(&mut self) {
let nodes: Vec<NodeIndex> = self.selection.iter().copied().collect();
for node in nodes {
self.pin_node(node);
}
}
/// Release the persistent pin on every node in the current selection —
/// mirrors [`crate::engine::GraphEngine::unpin_selection`].
pub fn unpin_selection(&mut self) {
let nodes: Vec<NodeIndex> = self.selection.iter().copied().collect();
for node in nodes {
self.unpin_node(node);
}
}
/// Instanced sphere nodes + billboarded edge quads (plan §1.3) — wires
/// straight into [`crate::render3d::build_scene`], which is
/// independently unit-tested (no GPU needed) for the node/edge
/// instance construction itself; see `uzor-graph/tests/render3d_gpu.rs`
/// for the headless-GPU proof that the result actually renders
/// visually-distinct pixels.
///
/// **Cluster wave, extended by the filter/local-subgraph wave**: nodes
/// in [`GraphEngine3D::compute_excluded_nodes_3d`]'s union
/// (cluster-hidden — every member except that cluster's own
/// representative — ∪ local-subgraph-excluded ∪ filter-excluded) emit
/// NO node instance and NO edges touching them (`hidden` forwarded to
/// `render3d::build_node_instances`/`build_edge_instances` — the SAME
/// wave-1 `hidden` param, no second parallel mechanism); the
/// aggregated cross-cluster substitute edges are appended separately
/// via [`crate::render3d::build_cluster_edge_instances`] — mirrors the
/// 2D engine's own `GraphEngine::draw`'s separate `draw_edges`/
/// `draw_cluster_edges` calls (which is likewise NOT filtered by the
/// local/filter exclusion, only by the cluster registry itself). The
/// representative's own scaled-up radius needs no special-case here —
/// `ClusterRegistry::collapse_3d` already bumped `graph`'s own
/// `node.radius` field in place, which `build_node_instances` reads
/// unconditionally.
///
/// **Wave 5**: while [`GraphEngine3D::grid_enabled`], also appends the
/// ground-reference grid's own instanced lines
/// (`crate::render3d::build_grid_plan`/`build_grid_instances`),
/// sharing the exact same edge-quad mesh edges instance from. `viewport_height_px`
/// is the render surface's pixel height — needed for the grid's
/// distance-LOD step (`crate::render3d::grid_step_for_scale`); a
/// caller not using the grid can pass any positive value. A no-op
/// (no grid appended) while there isn't a single particle yet.
///
/// **Dimension-transition wave**: every position here is read from
/// [`GraphEngine3D::render_particles`] (a `z`-scaled SNAPSHOT), not
/// `self.particles` directly — while a [`DimensionTransition`] is in
/// flight this renders the eased-flat/inflating volume without ever
/// mutating the simulated particles themselves.
///
/// **Wave G3 item 4 fix**: every transparent billboarded-edge entry
/// (graph edges + cluster synthetic edges + grid lines — all share
/// ONE instanced draw call, see `render3d::sort_line_nodes_back_to_front`'s
/// own doc comment) is depth-sorted back-to-front against the
/// CURRENT camera eye right before this returns, after every source
/// has finished appending — previously arbitrary graph-edge
/// iteration order.
pub fn build_scene(&self, viewport_height_px: f64) -> Scene3D {
let hidden = self.compute_excluded_nodes_3d();
let render_particles = self.render_particles();
let mut scene = crate::render3d::build_scene_with_markers(
&self.graph,
&render_particles,
&self.node_mesh,
&self.edge_mesh,
&self.marker_meshes,
&hidden,
&self.lighting,
&self.edge_style,
);
// Post-effects OFF for graph scenes (perf pass 2026-07-24):
// `SceneEffects::default()` arms shadows + bloom + SSAO, and
// `Renderer3D` genuinely runs the whole bloom mip pyramid + SSAO
// pass every frame when armed — none of which a flat-shaded
// node-link graph benefits from (the foxhound reference app
// disables all three for the same reason). `Renderer3D`'s
// composite zeroes the corresponding strengths when disabled, so
// this skips real GPU passes, not just their visual contribution.
scene.effects = uzor_urx_3d::SceneEffects { shadows: false, bloom: false, ssao: false };
scene.nodes.extend(crate::render3d::build_cluster_edge_instances(
&render_particles,
&self.edge_mesh,
&self.clusters,
self.edge_style.cluster_edge_tint,
));
if self.grid_enabled {
if let Some((min, max)) = particle_aabb(&render_particles) {
let fov_y = self.camera.to_perspective(1.0).fov_y;
let step = crate::render3d::grid_step_for_scale(self.camera.distance, fov_y, viewport_height_px, &self.grid_config);
let plan = crate::render3d::build_grid_plan(min, max, step, &self.grid_config);
scene.nodes.extend(crate::render3d::build_grid_instances(&plan, &self.edge_mesh, &self.grid_config));
}
}
// Wave G3 item 4 fix — back-to-front depth sort for every
// transparent billboarded-edge entry now that the FULL edge set
// (graph edges + cluster synthetic edges + grid lines, all
// sharing one instanced draw call) is assembled. See
// `render3d::sort_line_nodes_back_to_front`'s own doc comment.
crate::render3d::sort_line_nodes_back_to_front(&mut scene.nodes, self.camera.eye());
scene
}
/// Shared id-pass sphere mesh (Wave 4) — see
/// [`GraphEngine3D::build_id_pass_scene`].
pub fn id_pass_mesh(&self) -> &Arc<Mesh> {
&self.id_pass_mesh
}
/// GPU color-ID id-pass scene (Wave 4, plan §1.5/§4) — wires into
/// [`crate::render3d::build_id_pass_scene`]. A caller with a live
/// `wgpu::Device`/`Renderer3D` renders this via
/// [`pick3d::request_gpu_pick`] instead of the ordinary
/// [`GraphEngine3D::build_scene`] Lit scene.
///
/// **Graph-strengthening arc G1.2**: now shares the SAME `hidden`
/// exclusion set (`compute_excluded_nodes_3d`) as
/// [`GraphEngine3D::build_scene`]/[`GraphEngine3D::pick_candidates`] —
/// before this fix, every graph node got an id-pass sphere
/// unconditionally, so a cluster-collapsed/local-excluded/filtered
/// node's invisible sphere could occlude a visible node's own pixel in
/// the id-pass. Also reads [`GraphEngine3D::render_particles`] (the
/// z-scaled snapshot every other whole-slice render/pick consumer
/// reads — see that method's own doc comment) instead of the raw,
/// un-eased `self.particles`, so the id-pass renders the SAME
/// mid-dimension-transition positions the visible scene does.
pub fn build_id_pass_scene(&self) -> Scene3D {
let hidden = self.compute_excluded_nodes_3d();
let render_particles = self.render_particles();
crate::render3d::build_id_pass_scene(&self.graph, &render_particles, &self.id_pass_mesh, &hidden)
}
/// Current GPU-pick escalation threshold (Wave 4) — see
/// [`GraphEngine3D::should_use_gpu_pick`].
pub fn gpu_pick_threshold(&self) -> usize {
self.gpu_pick_threshold
}
/// Override the GPU-pick escalation threshold — see the field's own
/// doc comment. `0` forces GPU picking for any non-empty graph; a
/// very large value pins the engine to CPU-only picking regardless
/// of graph size.
pub fn set_gpu_pick_threshold(&mut self, threshold: usize) {
self.gpu_pick_threshold = threshold;
}
/// `true` once `graph.node_count()` exceeds
/// [`GraphEngine3D::gpu_pick_threshold`] (plan §1.5's own escalation
/// rule) — the "which path" probe a test/caller can read without
/// touching any `wgpu` state.
pub fn should_use_gpu_pick(&self) -> bool {
self.graph.node_count() > self.gpu_pick_threshold
}
/// Total number of GPU pick requests [`GraphEngine3D::on_event`] has
/// actually started (Wave 4's own call-counter/probe gate — see
/// [`pick3d::GpuPickPipeline::requests_started`]).
pub fn gpu_pick_requests_started(&self) -> usize {
self.gpu_pick_pipeline.requests_started()
}
/// `true` while a GPU pick request is outstanding (see
/// [`pick3d::GpuPickPipeline::is_in_flight`]).
pub fn gpu_pick_pending(&self) -> bool {
self.gpu_pick_pipeline.is_in_flight()
}
/// Feed back a resolved GPU pick result (Wave 4) — the caller drives
/// the real `wgpu` readback externally via
/// [`pick3d::request_gpu_pick`]/[`pick3d::poll_gpu_pick`] (this
/// engine owns no `wgpu::Device`) and calls this once
/// [`pick3d::poll_gpu_pick`] returns `Some(_)`. Refines `hovered`
/// ONLY — click-select stays CPU-only/synchronous always, so a click
/// never changes retroactively after the fact once the user has
/// already acted on it (a deliberate Wave 4 scope decision, see
/// `uzor-graph/CLAUDE.md`'s own divergence log). A no-op if no GPU
/// pick is currently in flight (stale/duplicate feed).
///
/// **Graph-strengthening arc G1.2 — belt-and-braces guard.**
/// [`GraphEngine3D::build_id_pass_scene`] now excludes every hidden
/// node from the id-pass texture at RENDER time, so a FRESH GPU
/// readback can no longer name a node outside [`GraphEngine3D::
/// pick_candidates`]. But the readback resolves asynchronously — the
/// request is fired from `on_pointer_moved`, the id-pass texture is
/// rendered and read back by the caller, and this method is only
/// called once that round trip completes, typically 1-2 frames later
/// (per this method's own doc comment above). If a cluster collapsed,
/// the local-subgraph root changed, or the filter changed in that
/// window, `r` can still name a node that was eligible when the
/// REQUEST was made but no longer is by the time the RESULT arrives.
/// A stale `Some(node)` outside the CURRENT `pick_candidates()` is
/// therefore dropped — `hovered` keeps whatever the synchronous CPU
/// pick already set it to for this frame, rather than being pulled
/// back onto a node that just became invisible.
pub fn apply_gpu_pick_result(&mut self, result: Option<NodeIndex>) {
self.gpu_pick_pipeline.complete(result);
if let Some(r) = self.gpu_pick_pipeline.poll_consume() {
match r {
Some(node) if self.pick_candidates().contains(&node) => self.hovered = Some(node),
Some(_) => {}
None => self.hovered = None,
}
}
}
/// Fresh `PerspectiveCamera` for the current orbit-camera state.
pub fn camera(&self, aspect: f32) -> PerspectiveCamera {
self.camera.to_perspective(aspect)
}
pub fn hovered(&self) -> Option<NodeIndex> {
self.hovered
}
pub fn selected(&self) -> Option<NodeIndex> {
self.selected
}
/// Generic per-node facts for a caller's sidebar/inspector — REUSES
/// [`crate::engine::NodeFacts`] unchanged (Wave 3, plan §4: "the same
/// type the 2D engine already exposes, zero-cost reuse, no new
/// struct"). **Known divergence**: `NodeFacts::position` is a 2D
/// `(f32, f32)` shape the plan deliberately keeps as-is — a 3D
/// node's `z` is NOT reported here (`uzor-graph/CLAUDE.md`'s Wave 3
/// divergence log has the full reasoning). `pinned` reads
/// [`Particle::is_pinned_3d`] — always `false` this wave, since node
/// drag/pin has no 3D implementation yet (plan §5 exclusion), but
/// wired correctly for whenever that lands.
pub fn node_facts(&self, node: NodeIndex) -> Option<NodeFacts<'_>> {
let n = self.graph.get_node(node)?;
let p = self.particles.get(node.index())?;
Some(NodeFacts { index: node, label: &n.label, category: &n.category, degree: self.graph.degree(node), position: (p.x, p.y), pinned: p.is_pinned_3d() })
}
/// LOD-selected label positions for `camera`/`viewport` this frame
/// (plan §1.3/§4 Wave 3, the "project + LOD-select" half of the
/// label-overlay design): projects every node's world position
/// through `camera` (silently dropping any behind the eye — see
/// [`crate::interaction::pick3d::project_world_to_screen`]), hands
/// the resulting screen positions to the EXISTING
/// `label_grid::select_labels` quota/ranking pass completely
/// unchanged, and returns the `(node, screen_x, screen_y)` triples a
/// caller would draw text at.
///
/// `screen_radius` (an input `label_grid::select_labels` uses only
/// for its crowded-cell tie-break, not for culling) is approximated
/// from the standard pinhole-camera size formula
/// (`node.radius / (distance * tan(fov_y / 2)) * viewport.height /
/// 2`) — exact enough for ranking, not claimed pixel-perfect. The
/// per-cell quota's "zoom" input (2D's `Camera2D::zoom`, which this
/// engine has no direct equivalent of) is approximated as
/// `Camera3D::default().distance / self.camera.distance` — `1.0` at
/// the default orbit distance (matching 2D's own zoom-identity
/// convention, `quota == ceil(density)`), growing as the user dollies
/// in, same qualitative "more room, more labels" behavior 2D's zoom
/// drives.
///
/// **Wave 3 overlay-draw scope note** (`uzor-graph/CLAUDE.md`/
/// `uzor-desktop/CLAUDE.md` divergence logs have the full grounding):
/// this method is the real, tested, engine-level API a label-overlay
/// DRAW call needs, but that draw call is NOT wired into the live
/// 3D-composed frame this wave. `uzor-desktop`'s `Manager` skips
/// `app.ui()`/the whole 2D chrome pass entirely on a 3D-active frame
/// (Wave 2's own forced divergence), and `submit_urx_composed`'s own
/// 2D pass reads a render channel (`state.urx_ctx`/`active_urx`)
/// this `Manager` never populates — painting a real label overlay
/// needs new `uzor-render-hub`/`Manager` integration surface (wiring
/// `set_active_urx`, or teaching `submit_urx_composed` to accept a
/// pre-built 2D scene), out of this wave's scope. Reachable this
/// wave via the demo's agent surface for screenshot/JSON
/// verification of the underlying pick/project math, not as painted
/// pixels.
///
/// Candidates exclude any node hidden by a collapsed cluster (cluster
/// wave — [`GraphEngine3D::pick_candidates`], instead of the whole
/// `all_node_ids` this previously scanned): a hidden member has no
/// scene presence, so it must not get a label slot either. Forced
/// union (cluster wave): every collapsed cluster's own representative
/// ALWAYS keeps its label regardless of quota (mirrors the 2D
/// engine's own `forced_labels` union, `render.rs`'s `DrawContext::
/// forced_labels`) — hover/selection-neighbor forcing still has NO
/// equivalent (3D has no `FocusSet`-style dim/highlight reducer yet;
/// see [`GraphEngine3D::draw_overlay`]'s own doc comment for what 3D
/// DOES paint for a selection instead — rings, not label forcing).
pub fn visible_labels(&self, camera: &PerspectiveCamera, viewport: Rect) -> Vec<(NodeIndex, f64, f64)> {
// Dimension-transition wave: projected from the `z`-scaled render
// position, not the raw simulated `z` (see
// `GraphEngine3D::render_z_scale`) — a label always sits on the
// node's ACTUAL on-screen position mid-transition.
let scale = self.render_z_scale();
let candidate_ids = self.pick_candidates();
let mut candidates = Vec::with_capacity(candidate_ids.len());
let mut screen_positions: HashMap<NodeIndex, (f64, f64)> = HashMap::with_capacity(candidate_ids.len());
for id in candidate_ids {
let (Some(p), Some(node)) = (self.particles.get(id.index()), self.graph.get_node(id)) else { continue };
let world = Vec3::new(p.x, p.y, p.z * scale);
let Some(screen_pos) = pick3d::project_world_to_screen(camera, world, viewport) else { continue };
let screen_radius = project_screen_radius(camera, viewport, world, node.radius);
candidates.push(label_grid::LabelCandidate { node: id, screen_pos, degree: self.graph.degree(id), screen_radius });
screen_positions.insert(id, screen_pos);
}
let zoom_analog = (Camera3D::default().distance / self.camera.distance.max(1e-3)) as f64;
let forced: HashSet<NodeIndex> = self.clusters.collapsed_clusters().map(|c| c.representative).collect();
// Graph-strengthening arc Wave G2b: `self.label_lod` is now a
// real, caller-configurable field (was an unconditional
// `LabelLodConfig::default()` placeholder) — reuses the exact
// SAME type the 2D engine's own `GraphEngine::label_lod` owns,
// via `GraphEngine3D::label_lod`/`set_label_lod`.
let shown = label_grid::select_labels(&candidates, viewport, zoom_analog, self.label_density, &forced, &self.label_lod);
shown.into_iter().filter_map(|id| screen_positions.get(&id).map(|&(x, y)| (id, x, y))).collect()
}
/// Current label-LOD quota density (Wave 3) — see
/// [`GraphEngine3D::visible_labels`]. Defaults to
/// `label_grid::DEFAULT_LABEL_DENSITY`, same as the 2D engine.
pub fn label_density(&self) -> f64 {
self.label_density
}
/// Set the label-LOD quota density; negative input clamps to `0.0`
/// (empty per-cell quota) — mirrors `GraphEngine::set_label_density`'s
/// own clamp convention.
pub fn set_label_density(&mut self, density: f64) {
self.label_density = density.max(0.0);
}
/// Paint the label overlay + hover info card for `camera`/`viewport`
/// this frame (Wave 4 / W3D arc plan §1.3 label-overlay gap, closed
/// here — `uzor-graph/CLAUDE.md`'s Wave 3 divergence log has the full
/// grounding for why the actual DRAW call was deferred to this wave).
/// `render` is an ordinary 2D `RenderContext` in the SAME logical
/// pixel space as `viewport` (screen-space overlay, no z-test — the
/// plan's own §1.3 "industry standard for 3D graph labels" call, same
/// approach vasturiano's `3d-force-graph` uses) — a caller wires this
/// via `uzor-desktop::Scene3DFrame::overlay`, see that field's own
/// doc comment for the exact composition point.
///
/// Labels: every `(node, screen_x, screen_y)` [`GraphEngine3D::visible_labels`]
/// returns (which already culls anything behind the camera via
/// [`crate::interaction::pick3d::project_world_to_screen`] returning
/// `None`, and applies the LOD grid quota) is drawn with the SAME
/// font/fill-color/alpha-fade convention `crate::render::draw_nodes`
/// uses for the 2D engine's own labels (`label_grid::label_alpha`,
/// degree-boosted fade) — "same quality as 2D mode's labels" per the
/// plan's own goal — just at a fixed text offset
/// ([`crate::theme::GraphTheme::label_offset_3d_x`]/`label_offset_3d_y`,
/// distinct from [`crate::theme::GraphTheme::label_offset_x`]/`label_offset_y`
/// — see that field's own doc comment for why, unlike 2D, this isn't
/// `node_screen_radius`-based).
///
/// Hover card: reuses [`crate::render::draw_hover_card`] (the SAME
/// function the 2D engine's own hover card calls) anchored at the
/// hovered node's projected screen position, built from
/// [`GraphEngine3D::node_facts`] — one hover-card implementation for
/// both dimensions, not a second one invented here.
///
/// **Selection rings + cluster supernode "×N" labels (cluster/
/// selection wave)** — a 3D-side selection/cluster highlight now
/// exists (the [`GraphEngine3D::selection`] set + `ClusterRegistry`),
/// so both are painted here as cheap screen-space overlays rather
/// than skipped (superseding the earlier Wave 3/4 "no 3D-side
/// highlight exists yet" deferral this doc comment used to record):
/// one white ring per currently-selected, non-hidden node at its
/// projected screen position (radius from the SAME
/// [`project_screen_radius`] pinhole approximation `visible_labels`
/// already uses, `+2px` — the exact ring-offset convention
/// `crate::render::draw_nodes`'s own selection ring uses), and one
/// "×N" member-count label per collapsed cluster's representative
/// (mirrors `crate::render::draw_cluster_supernodes`'s own label,
/// WITH the halo — both gained it in this same pass, see
/// `uzor-graph/CLAUDE.md`'s divergence log).
///
/// **Wave 5**: while [`GraphEngine3D::grid_enabled`], also paints a
/// numeric axis-tick label for every STRONG gridline — see
/// [`GraphEngine3D::draw_grid_overlay`]'s own doc comment for why
/// this is a direct walk of `crate::render3d`'s `GridLine`s rather
/// than a `label_grid::LabelGrid` pass.
pub fn draw_overlay(&self, render: &mut dyn RenderContext, camera: &PerspectiveCamera, viewport: Rect) -> OverlayDrawStats {
// 3D quality audit A1 / graph-strengthening arc G1.3 — this
// whole overlay pass (labels, grid tick labels, cluster "×N"
// labels, selection rings) mutates font/stroke/global-alpha state
// with no restore of its own; `draw_hover_card`/`draw_box_select_rect`
// below bracket THEMSELVES but a caller has no guarantee about
// what this function's OWN direct `set_*` calls leave behind.
// Bracketed here so `draw_overlay` gives the same "leaves the
// context exactly as it found it" guarantee every other public
// draw entry point in this crate now does.
render.save();
// Dimension-transition wave: every projection below (cluster
// label, selection ring, hover card) reads the SAME `z`-scaled
// render position `GraphEngine3D::visible_labels` already uses
// for the ordinary node labels above it — an anchor always sits
// on the node's ACTUAL on-screen position mid-transition, never
// the full-depth simulated one.
let scale = self.render_z_scale();
let max_degree = self.graph.nodes().map(|(id, _)| self.graph.degree(id)).max().unwrap_or(0).max(1);
let zoom_analog = (Camera3D::default().distance / self.camera.distance.max(1e-3)) as f64;
let forced: HashSet<NodeIndex> = self.clusters.collapsed_clusters().map(|c| c.representative).collect();
// Filter/local-subgraph wave: the selection-ring skip now uses the
// FULL exclusion union (cluster-hidden ∪ local ∪ filter), not just
// cluster-hidden — mirrors 2D's own `draw_nodes`, which only ever
// iterates `ctx.visible` (a selected node excluded by ANY source
// gets no ring, even though it stays in `self.selection`).
let hidden = self.compute_excluded_nodes_3d();
let mut labels_drawn = 0usize;
for (id, sx, sy) in self.visible_labels(camera, viewport) {
let Some(node) = self.graph.get_node(id) else { continue };
// Forced (a collapsed-cluster representative) always draws at
// full opacity — the zoom+degree fade curve only governs the
// ordinary, non-forced case, mirroring `crate::render::
// draw_nodes`'s own forced-label convention.
let alpha = if forced.contains(&id) {
1.0
} else {
let normalized_degree = self.graph.degree(id) as f64 / max_degree as f64;
label_grid::label_alpha(zoom_analog, normalized_degree, &self.label_lod)
};
if alpha <= 0.01 {
continue;
}
render.set_global_alpha(alpha);
render.set_font(&self.theme.label_font);
// Halo (owner defect report: thin edge strokes crossing node
// label text made it unreadable) — same treatment
// `crate::render::draw_nodes` uses for the 2D engine's labels.
fill_text_with_halo(
render,
&node.label,
sx + self.theme.label_offset_3d_x,
sy + self.theme.label_offset_3d_y,
&self.theme.label_fill,
&self.label_halo,
);
render.set_global_alpha(1.0);
labels_drawn += 1;
}
let grid_labels_drawn = if self.grid_enabled { self.draw_grid_overlay(render, camera, viewport) } else { 0 };
// Cluster supernode "×N" labels — see this method's own doc
// comment above.
let mut cluster_labels_drawn = 0usize;
for cluster in self.clusters.collapsed_clusters() {
let Some(p) = self.particles.get(cluster.representative.index()) else { continue };
let world = Vec3::new(p.x, p.y, p.z * scale);
let Some((sx, sy)) = pick3d::project_world_to_screen(camera, world, viewport) else { continue };
let text = format!("×{}", cluster.member_count());
render.set_font(&self.theme.label_font);
fill_text_with_halo(
render,
&text,
sx + self.theme.label_offset_3d_x + self.theme.cluster_label_extra_offset_3d_x,
sy + self.theme.label_offset_3d_y,
&self.theme.cluster_label_color,
&self.label_halo,
);
cluster_labels_drawn += 1;
}
// Selection rings — see this method's own doc comment above.
// Hidden (cluster-collapsed, non-representative) members are
// skipped even if they remain in `self.selection` — mirrors 2D's
// own `draw_nodes`, which only ever iterates `ctx.visible`.
let mut selection_rings_drawn = 0usize;
for &node in &self.selection {
if hidden.contains(&node) {
continue;
}
let (Some(p), Some(graph_node)) = (self.particles.get(node.index()), self.graph.get_node(node)) else { continue };
let world = Vec3::new(p.x, p.y, p.z * scale);
let Some((sx, sy)) = pick3d::project_world_to_screen(camera, world, viewport) else { continue };
let r = project_screen_radius(camera, viewport, world, graph_node.radius);
render.set_stroke_color(&self.theme.selection_ring_color);
render.set_stroke_width(self.theme.selection_ring_width);
render.begin_path();
render.arc(sx, sy, r + self.theme.selection_ring_offset_px, 0.0, std::f64::consts::TAU);
render.stroke();
selection_rings_drawn += 1;
}
let mut hover_card_drawn = false;
if self.hover_card {
if let Some(hovered) = self.hovered {
if let (Some(facts), Some(p)) = (self.node_facts(hovered), self.particles.get(hovered.index())) {
let world = Vec3::new(p.x, p.y, p.z * scale);
if let Some(anchor) = pick3d::project_world_to_screen(camera, world, viewport) {
let info = HoverCardInfo { label: facts.label, category: facts.category, degree: facts.degree, pinned: facts.pinned };
// Graph-strengthening arc Wave G2b — the hover card's
// `FigureTheme` is now this engine's OWN `self.theme.hover_card`
// (was an unconditional `FigureTheme::dark()` literal;
// `GraphTheme::dark().hover_card` is byte-identical to
// that prior literal, so this preserves default
// behavior while a caller can now override it via
// `set_theme`).
draw_hover_card(render, anchor, &info, viewport, &self.theme.hover_card);
hover_card_drawn = true;
}
}
}
}
// Live box-select rubber band — LAST, always on top of every
// other overlay element (same z-convention as 2D's own
// `GraphEngine::draw`, which paints `draw_box_select_rect`
// after nodes/labels/hover card).
if let Some(rect) = self.box_select_rect() {
// Graph-strengthening arc Wave G2b — now this engine's OWN
// `self.theme` (was an unconditional `GraphTheme::dark()`
// literal; `GraphTheme::dark()` is byte-identical, so this
// preserves default behavior while a caller can now override
// it via `set_theme`).
crate::render::draw_box_select_rect(render, rect, &self.theme);
}
render.restore();
OverlayDrawStats { labels_drawn, grid_labels_drawn, cluster_labels_drawn, selection_rings_drawn, hover_card_drawn }
}
/// Axis tick labels for every STRONG gridline (Wave 5) — see
/// `crate::render3d`'s own module doc for why this is a direct walk
/// of the same [`crate::render3d::GridLine`] list
/// [`GraphEngine3D::build_scene`] instances from, not a
/// `label_grid::LabelGrid` pass: axis ticks are already sparse and
/// perfectly regular, so a flat off-viewport cull plus a count cap
/// ([`crate::render3d::Graph3DGridConfig::max_axis_labels`]) is the
/// whole LOD this needs. Recomputes the SAME
/// `crate::render3d::grid_step_for_scale`/`build_grid_plan`
/// [`GraphEngine3D::build_scene`] used, from `viewport.height` — a
/// caller feeding a different height here than it fed `build_scene`
/// this frame would see labels that don't quite match the rendered
/// grid; the demo wiring keeps both fed from the SAME real surface
/// height every tick, per this method's own contract. Returns `0`
/// (no-op) once there isn't a single particle.
fn draw_grid_overlay(&self, render: &mut dyn RenderContext, camera: &PerspectiveCamera, viewport: Rect) -> usize {
// Dimension-transition wave: the SAME `z`-scaled snapshot
// `build_scene` uses for its own grid geometry this frame (see
// that method's own doc comment) — keeps the axis-tick labels
// aligned with the actually-rendered grid while flattening/
// inflating.
let render_particles = self.render_particles();
let Some((min, max)) = particle_aabb(&render_particles) else { return 0 };
let step = crate::render3d::grid_step_for_scale(self.camera.distance, camera.fov_y, viewport.height, &self.grid_config);
let plan = crate::render3d::build_grid_plan(min, max, step, &self.grid_config);
render.set_font(&self.theme.grid_tick_font);
let mut drawn = 0usize;
for line in plan.lines.iter().filter(|l| l.strong) {
if drawn >= self.grid_config.max_axis_labels {
break;
}
let Some((sx, sy)) = pick3d::project_world_to_screen(camera, line.from, viewport) else { continue };
if sx < viewport.x || sx > viewport.x + viewport.width || sy < viewport.y || sy > viewport.y + viewport.height {
continue;
}
let text = crate::render3d::format_tick_value(line.tick_value, plan.step);
// Halo (deferred tail from the label-halo pass — see
// `uzor-graph/CLAUDE.md`'s divergence log): grid tick labels
// gained the same 8-direction halo protection node/cluster
// labels already had.
fill_text_with_halo(
render,
&text,
sx + self.theme.label_offset_3d_x,
sy + self.theme.label_offset_3d_y,
&self.theme.grid_tick_color,
&self.label_halo,
);
drawn += 1;
}
drawn
}
}
/// Pinhole-camera apparent screen radius for a node at `world` with
/// world-space `node_radius`, at `camera`'s current eye/fov (cluster/
/// selection wave) — factored out of [`GraphEngine3D::visible_labels`]'s
/// own inline `screen_radius` tie-break input formula, now that
/// [`GraphEngine3D::draw_overlay`]'s selection-ring pass needs the
/// identical approximation for its own ring radius. Exact enough for
/// ranking/ring-sizing, not claimed pixel-perfect (same caveat
/// `visible_labels`'s own doc comment already carried).
fn project_screen_radius(camera: &PerspectiveCamera, viewport: Rect, world: Vec3, node_radius: f32) -> f64 {
let dist = (world - camera.eye).length().max(1e-3);
let half_fov_tan = (camera.fov_y * 0.5).tan().max(1e-6);
((node_radius / (dist * half_fov_tan)) * (viewport.height as f32 * 0.5)) as f64
}
/// Per-frame draw counts for [`GraphEngine3D::draw_overlay`] — a
/// test/verification aid (mirrors [`crate::render::NodeDrawStats`]'s own
/// role for the 2D engine), not consumed by any production call site.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct OverlayDrawStats {
pub labels_drawn: usize,
/// Numeric axis-tick labels painted this frame (Wave 5) — always `0`
/// while [`GraphEngine3D::grid_enabled`] is `false`.
pub grid_labels_drawn: usize,
/// Cluster supernode "×N" member-count labels painted this frame
/// (cluster wave) — always `0` while no cluster is collapsed.
pub cluster_labels_drawn: usize,
/// Selection rings painted this frame (selection wave) — always `0`
/// while [`GraphEngine3D::selection`] is empty.
pub selection_rings_drawn: usize,
pub hover_card_drawn: bool,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::graph::Graph;
// `StateTrackingContext3D` below calls `Painter`/`TextRenderer`
// methods directly on a concrete type (not through `&mut dyn
// RenderContext`) — the traits must be in scope for that.
use uzor::render::{Painter, TextRenderer};
// ── `RecordingRenderContext` — Wave 4's `draw_overlay` test double ──
//
// Same boilerplate-minimal "implement every RenderContext supertrait
// with a no-op body" pattern already used throughout the workspace
// (`uzor/src/core/render/context.rs`'s own `NoImageContext` test,
// `uzor/src/ui/themes/macos/widgets/switch_toggle.rs`'s own
// `MockContext`) — the ONE addition here is recording every
// `fill_text` call (text + position), since `draw_overlay`'s own
// gate is "assert via a recording RenderContext mock", not just
// "compiles against a mock".
struct RecordingRenderContext {
fill_texts: Vec<(String, f64, f64)>,
// Graph-strengthening arc Wave G2b — the theme-threading tests
// below need to observe WHICH color/font a draw call actually
// used, not just that text was painted somewhere; the pre-
// existing no-op `set_fill_color`/`set_stroke_color`/`set_font`
// gave no way to do that.
fill_colors: Vec<String>,
stroke_colors: Vec<String>,
stroke_widths: Vec<f64>,
fonts: Vec<String>,
}
impl RecordingRenderContext {
fn new() -> Self {
Self { fill_texts: Vec::new(), fill_colors: Vec::new(), stroke_colors: Vec::new(), stroke_widths: Vec::new(), fonts: Vec::new() }
}
}
impl uzor::render::Painter for RecordingRenderContext {
fn save(&mut self) {}
fn restore(&mut self) {}
fn translate(&mut self, _x: f64, _y: f64) {}
fn rotate(&mut self, _angle: f64) {}
fn scale(&mut self, _x: f64, _y: f64) {}
fn set_fill_color(&mut self, color: &str) {
self.fill_colors.push(color.to_owned());
}
fn set_global_alpha(&mut self, _alpha: f64) {}
fn set_stroke_color(&mut self, color: &str) {
self.stroke_colors.push(color.to_owned());
}
fn set_stroke_width(&mut self, width: f64) {
self.stroke_widths.push(width);
}
fn set_line_dash(&mut self, _pattern: &[f64]) {}
fn set_line_cap(&mut self, _cap: &str) {}
fn set_line_join(&mut self, _join: &str) {}
fn begin_path(&mut self) {}
fn move_to(&mut self, _x: f64, _y: f64) {}
fn line_to(&mut self, _x: f64, _y: f64) {}
fn close_path(&mut self) {}
fn rect(&mut self, _x: f64, _y: f64, _w: f64, _h: f64) {}
fn arc(&mut self, _cx: f64, _cy: f64, _r: f64, _s: f64, _e: f64) {}
fn ellipse(&mut self, _cx: f64, _cy: f64, _rx: f64, _ry: f64, _rot: f64, _s: f64, _e: f64) {}
fn quadratic_curve_to(&mut self, _cpx: f64, _cpy: f64, _x: f64, _y: f64) {}
fn bezier_curve_to(&mut self, _cp1x: f64, _cp1y: f64, _cp2x: f64, _cp2y: f64, _x: f64, _y: f64) {}
fn stroke(&mut self) {}
fn fill(&mut self) {}
}
impl uzor::render::TextRenderer for RecordingRenderContext {
fn set_font(&mut self, font: &str) {
self.fonts.push(font.to_owned());
}
fn set_text_align(&mut self, _align: uzor::render::TextAlign) {}
fn set_text_baseline(&mut self, _baseline: uzor::render::TextBaseline) {}
fn fill_text(&mut self, text: &str, x: f64, y: f64) {
self.fill_texts.push((text.to_owned(), x, y));
}
fn stroke_text(&mut self, _text: &str, _x: f64, _y: f64) {}
}
impl uzor::render::TextMetrics for RecordingRenderContext {
fn measure_text(&self, _text: &str) -> f64 {
0.0
}
fn text_bounds(&self, _text: &str, _font: &str) -> uzor::render::TextBounds {
uzor::render::TextBounds { x: 0.0, y: 0.0, w: 0.0, h: 0.0, ascent: 0.0, descent: 0.0 }
}
}
impl uzor::render::Masking for RecordingRenderContext {
fn clip(&mut self) {}
}
impl uzor::render::Effects for RecordingRenderContext {}
impl uzor::render::ShapeHelpers for RecordingRenderContext {
fn fill_rect(&mut self, _x: f64, _y: f64, _w: f64, _h: f64) {}
fn stroke_rect(&mut self, _x: f64, _y: f64, _w: f64, _h: f64) {}
}
impl uzor::render::GradientPainter for RecordingRenderContext {}
impl uzor::render::UiEffectHelpers for RecordingRenderContext {}
impl uzor::render::BatchPainter for RecordingRenderContext {}
impl uzor::render::RenderContext for RecordingRenderContext {
fn dpr(&self) -> f64 {
1.0
}
}
// ── Graph-strengthening arc G1.3: `draw_overlay`'s own state-leak
// gate ───────────────────────────────────────────────────────────────
//
// `RecordingRenderContext` above has NO-OP `save`/`restore` (it exists
// only to record `fill_text` calls) — it cannot prove a bracket
// actually restores anything. `StateTrackingContext3D` is a REAL
// `save`/`restore` stack (mirrors `render.rs`'s own
// `StateTrackingContext` test mock 1:1) so `restore()` genuinely pops
// back to whatever `PaintState` was live at the matching `save()`.
#[derive(Clone, Debug, PartialEq)]
struct PaintState {
font: String,
fill_color: String,
stroke_color: String,
stroke_width: f64,
global_alpha: f64,
text_align: uzor::render::TextAlign,
text_baseline: uzor::render::TextBaseline,
line_cap: String,
line_join: String,
}
impl Default for PaintState {
fn default() -> Self {
Self {
font: String::new(),
fill_color: String::new(),
stroke_color: String::new(),
stroke_width: 1.0,
global_alpha: 1.0,
text_align: uzor::render::TextAlign::default(),
text_baseline: uzor::render::TextBaseline::default(),
line_cap: "butt".to_owned(),
line_join: "miter".to_owned(),
}
}
}
struct StateTrackingContext3D {
state: PaintState,
stack: Vec<PaintState>,
}
impl StateTrackingContext3D {
fn new() -> Self {
Self { state: PaintState::default(), stack: Vec::new() }
}
}
impl uzor::render::Painter for StateTrackingContext3D {
fn save(&mut self) {
self.stack.push(self.state.clone());
}
fn restore(&mut self) {
if let Some(s) = self.stack.pop() {
self.state = s;
}
}
fn translate(&mut self, _x: f64, _y: f64) {}
fn rotate(&mut self, _angle: f64) {}
fn scale(&mut self, _x: f64, _y: f64) {}
fn set_fill_color(&mut self, color: &str) {
self.state.fill_color = color.to_owned();
}
fn set_global_alpha(&mut self, alpha: f64) {
self.state.global_alpha = alpha;
}
fn set_stroke_color(&mut self, color: &str) {
self.state.stroke_color = color.to_owned();
}
fn set_stroke_width(&mut self, width: f64) {
self.state.stroke_width = width;
}
fn set_line_dash(&mut self, _pattern: &[f64]) {}
fn set_line_cap(&mut self, cap: &str) {
self.state.line_cap = cap.to_owned();
}
fn set_line_join(&mut self, join: &str) {
self.state.line_join = join.to_owned();
}
fn begin_path(&mut self) {}
fn move_to(&mut self, _x: f64, _y: f64) {}
fn line_to(&mut self, _x: f64, _y: f64) {}
fn close_path(&mut self) {}
fn rect(&mut self, _x: f64, _y: f64, _w: f64, _h: f64) {}
fn arc(&mut self, _cx: f64, _cy: f64, _r: f64, _s: f64, _e: f64) {}
fn ellipse(&mut self, _cx: f64, _cy: f64, _rx: f64, _ry: f64, _rot: f64, _s: f64, _e: f64) {}
fn quadratic_curve_to(&mut self, _cpx: f64, _cpy: f64, _x: f64, _y: f64) {}
fn bezier_curve_to(&mut self, _cp1x: f64, _cp1y: f64, _cp2x: f64, _cp2y: f64, _x: f64, _y: f64) {}
fn stroke(&mut self) {}
fn fill(&mut self) {}
}
impl uzor::render::TextRenderer for StateTrackingContext3D {
fn set_font(&mut self, font: &str) {
self.state.font = font.to_owned();
}
fn set_text_align(&mut self, align: uzor::render::TextAlign) {
self.state.text_align = align;
}
fn set_text_baseline(&mut self, baseline: uzor::render::TextBaseline) {
self.state.text_baseline = baseline;
}
fn fill_text(&mut self, _text: &str, _x: f64, _y: f64) {}
fn stroke_text(&mut self, _text: &str, _x: f64, _y: f64) {}
}
impl uzor::render::TextMetrics for StateTrackingContext3D {
fn measure_text(&self, _text: &str) -> f64 {
0.0
}
fn text_bounds(&self, _text: &str, _font: &str) -> uzor::render::TextBounds {
uzor::render::TextBounds { x: 0.0, y: 0.0, w: 0.0, h: 0.0, ascent: 0.0, descent: 0.0 }
}
}
impl uzor::render::Masking for StateTrackingContext3D {
fn clip(&mut self) {}
}
impl uzor::render::Effects for StateTrackingContext3D {}
impl uzor::render::ShapeHelpers for StateTrackingContext3D {
fn fill_rect(&mut self, _x: f64, _y: f64, _w: f64, _h: f64) {}
fn stroke_rect(&mut self, _x: f64, _y: f64, _w: f64, _h: f64) {}
}
impl uzor::render::GradientPainter for StateTrackingContext3D {}
impl uzor::render::UiEffectHelpers for StateTrackingContext3D {}
impl uzor::render::BatchPainter for StateTrackingContext3D {}
impl uzor::render::RenderContext for StateTrackingContext3D {
fn dpr(&self) -> f64 {
1.0
}
}
type DemoGraph = Graph<(), ()>;
fn triangle() -> DemoGraph {
let mut graph = DemoGraph::new();
let a = graph.push_node((), "a", "x", 4.0);
let b = graph.push_node((), "b", "x", 4.0);
let c = graph.push_node((), "c", "x", 4.0);
graph.push_edge(a, b, 1.0, ());
graph.push_edge(b, c, 1.0, ());
graph.push_edge(c, a, 1.0, ());
graph
}
#[test]
fn new_seeds_one_particle_per_node_and_ticks_without_panicking() {
let mut engine: GraphEngine3D<(), (), ForceDirectedLayout3D> =
GraphEngine3D::new(triangle(), ForceDirectedLayout3D::default());
assert_eq!(engine.particles.len(), 3);
let result = engine.tick(1.0 / 60.0);
assert!(result.alpha <= 1.0);
}
#[test]
fn build_scene_returns_one_instanced_sphere_per_node_and_one_edge_quad_per_edge() {
let mut engine: GraphEngine3D<(), (), ForceDirectedLayout3D> =
GraphEngine3D::new(triangle(), ForceDirectedLayout3D::default());
// `new()` seeds every particle at the origin — non-coincident
// positions are needed here so none of the 3 edges gets skipped
// as degenerate (see `render3d.rs`'s own
// `build_edge_instances_skips_a_coincident_degenerate_edge`).
engine.particles[0] = Particle::at3(-4.0, 0.0, 0.0);
engine.particles[1] = Particle::at3(4.0, 0.0, 0.0);
engine.particles[2] = Particle::at3(0.0, 4.0, 0.0);
let scene = engine.build_scene(900.0);
// Triangle fixture: 3 nodes, 3 edges.
assert_eq!(scene.nodes.len(), 6, "build_scene must emit one Node per graph node plus one per edge (Wave 2)");
assert!(!scene.lights.is_empty(), "build_scene must light the scene so MeshLit tints are visible");
}
#[test]
fn on_event_plain_drag_orbits_the_camera_and_is_consumed() {
let mut engine: GraphEngine3D<(), (), ForceDirectedLayout3D> =
GraphEngine3D::new(triangle(), ForceDirectedLayout3D::default());
let viewport = Rect::new(0.0, 0.0, 400.0, 300.0);
let before_yaw = engine.camera.yaw;
assert!(engine.on_event(&PlatformEvent::PointerDown { x: 50.0, y: 50.0, button: uzor::input::MouseButton::Left }, viewport));
assert!(engine.on_event(&PlatformEvent::PointerMoved { x: 150.0, y: 50.0 }, viewport));
assert!(engine.camera.yaw != before_yaw, "a plain left-drag must orbit the camera (plan §1.4)");
assert!(engine.on_event(&PlatformEvent::PointerUp { x: 150.0, y: 50.0, button: uzor::input::MouseButton::Left }, viewport));
let handled_outside =
engine.on_event(&PlatformEvent::PointerDown { x: -10.0, y: -10.0, button: uzor::input::MouseButton::Left }, viewport);
assert!(!handled_outside, "a pointer-down outside the viewport must not start a drag");
}
#[test]
fn on_event_shift_drag_starts_a_box_select_instead_of_panning_or_orbiting() {
// Cluster/selection wave — 2D-parity decision (see
// `Pointer3DMode::BoxSelecting`'s own doc comment): shift-drag no
// longer pans the 3D camera at all, it starts a box-select drag.
// Plain middle-drag pan (`on_event_middle_drag_pans_camera_target`,
// just below) is unaffected.
let mut engine: GraphEngine3D<(), (), ForceDirectedLayout3D> =
GraphEngine3D::new(triangle(), ForceDirectedLayout3D::default());
let viewport = Rect::new(0.0, 0.0, 400.0, 300.0);
let before_yaw = engine.camera.yaw;
let before_target = engine.camera.target;
engine.on_event(&PlatformEvent::ModifiersChanged { modifiers: uzor::input::ModifierKeys::shift() }, viewport);
engine.on_event(&PlatformEvent::PointerDown { x: 50.0, y: 50.0, button: uzor::input::MouseButton::Left }, viewport);
engine.on_event(&PlatformEvent::PointerMoved { x: 150.0, y: 90.0 }, viewport);
assert_eq!(engine.camera.yaw, before_yaw, "shift-drag must not orbit the camera");
assert_eq!(engine.camera.target, before_target, "shift-drag must not pan the camera either — it box-selects now");
assert_eq!(
engine.box_select_rect(),
Some(Rect::new(50.0, 50.0, 100.0, 40.0)),
"shift-drag must be a live box-select rect from origin to the current cursor"
);
}
#[test]
fn on_event_middle_drag_pans_camera_target() {
let mut engine: GraphEngine3D<(), (), ForceDirectedLayout3D> =
GraphEngine3D::new(triangle(), ForceDirectedLayout3D::default());
let viewport = Rect::new(0.0, 0.0, 400.0, 300.0);
let before_yaw = engine.camera.yaw;
let before_target = engine.camera.target;
assert!(engine.on_event(&PlatformEvent::PointerDown {
x: 50.0,
y: 50.0,
button: uzor::input::MouseButton::Middle,
}, viewport));
assert!(engine.on_event(&PlatformEvent::PointerMoved { x: 150.0, y: 90.0 }, viewport));
assert_eq!(engine.camera.yaw, before_yaw, "middle-drag must pan, not orbit");
assert!(engine.camera.target != before_target, "middle-drag must move the camera target");
assert!(engine.on_event(&PlatformEvent::PointerUp {
x: 150.0,
y: 90.0,
button: uzor::input::MouseButton::Middle,
}, viewport));
}
#[test]
fn on_event_scroll_dollies_only_when_the_cursor_is_over_the_viewport() {
let mut engine: GraphEngine3D<(), (), ForceDirectedLayout3D> =
GraphEngine3D::new(triangle(), ForceDirectedLayout3D::default());
let viewport = Rect::new(0.0, 0.0, 400.0, 300.0);
let before_distance = engine.camera.distance;
engine.on_event(&PlatformEvent::PointerMoved { x: 200.0, y: 150.0 }, viewport);
assert!(engine.on_event(&PlatformEvent::Scroll { dx: 0.0, dy: 10.0 }, viewport));
assert!(engine.camera.distance < before_distance, "positive scroll dy must dolly in (smaller distance)");
let before_distance = engine.camera.distance;
engine.on_event(&PlatformEvent::PointerMoved { x: -50.0, y: -50.0 }, viewport);
let handled = engine.on_event(&PlatformEvent::Scroll { dx: 0.0, dy: 10.0 }, viewport);
assert!(!handled, "scroll must not be consumed while the cursor sits outside the viewport");
assert_eq!(engine.camera.distance, before_distance);
}
// ── Wave 3: hover/click picking, node_facts, visible_labels ────────────
/// Fixture: triangle with distinct, well-separated 3D positions so a
/// `PointerMoved` over one node's projected screen position never
/// accidentally also lands on another node's projection.
fn spread_triangle_engine() -> GraphEngine3D<(), (), ForceDirectedLayout3D> {
let mut engine: GraphEngine3D<(), (), ForceDirectedLayout3D> =
GraphEngine3D::new(triangle(), ForceDirectedLayout3D::default());
engine.particles[0] = Particle::at3(-40.0, 0.0, 0.0);
engine.particles[1] = Particle::at3(40.0, 0.0, 0.0);
engine.particles[2] = Particle::at3(0.0, 40.0, 0.0);
engine
}
#[test]
fn on_event_pointer_moved_over_a_projected_node_hovers_it_and_a_click_selects_it() {
let mut engine = spread_triangle_engine();
let viewport = Rect::new(0.0, 0.0, 400.0, 300.0);
let aspect = (viewport.width / viewport.height) as f32;
let camera = engine.camera(aspect);
let (sx, sy) = pick3d::project_world_to_screen(&camera, Vec3::new(-40.0, 0.0, 0.0), viewport)
.expect("node 0 must project inside the default orbit view for this deterministic fixture");
assert_eq!(engine.hovered(), None, "nothing is hovered before any pointer event");
assert!(engine.on_event(&PlatformEvent::PointerMoved { x: sx, y: sy }, viewport));
assert_eq!(engine.hovered(), Some(NodeIndex(0)), "moving over node 0's own projected screen position must hover it");
assert_eq!(engine.selected(), None, "nothing is selected before any click");
assert!(engine.on_event(&PlatformEvent::PointerDown { x: sx, y: sy, button: uzor::input::MouseButton::Left }, viewport));
assert!(engine.on_event(&PlatformEvent::PointerUp { x: sx, y: sy, button: uzor::input::MouseButton::Left }, viewport));
assert_eq!(engine.selected(), Some(NodeIndex(0)), "a down/up pair at the same spot (within the click-drag threshold) must select it");
}
#[test]
fn on_event_a_background_drag_past_the_click_threshold_orbits_but_does_not_select() {
// Node-drag (added later in this same file's Wave 4/5 test
// block below) means a `PointerDown` ON a node no longer
// orbits at all — it ALWAYS drags that node and ALWAYS selects
// it on release, regardless of drag distance (there's no
// ambiguous "was this a click or a drag" question for a node
// hit the way there is for background). This test now starts
// on EMPTY SPACE, the only case the click-vs-drag distance
// threshold still governs.
let mut engine = spread_triangle_engine();
let viewport = Rect::new(0.0, 0.0, 400.0, 300.0);
engine.on_event(&PlatformEvent::PointerDown { x: 5.0, y: 5.0, button: uzor::input::MouseButton::Left }, viewport);
engine.on_event(&PlatformEvent::PointerMoved { x: 65.0, y: 5.0 }, viewport);
engine.on_event(&PlatformEvent::PointerUp { x: 65.0, y: 5.0, button: uzor::input::MouseButton::Left }, viewport);
assert_eq!(engine.selected(), None, "a background drag past the click-drag threshold must orbit, not select");
}
#[test]
fn on_event_click_on_empty_space_clears_the_selection() {
let mut engine = spread_triangle_engine();
let viewport = Rect::new(0.0, 0.0, 400.0, 300.0);
let aspect = (viewport.width / viewport.height) as f32;
let camera = engine.camera(aspect);
let (sx, sy) = pick3d::project_world_to_screen(&camera, Vec3::new(-40.0, 0.0, 0.0), viewport).expect("node 0 must project inside the view");
engine.on_event(&PlatformEvent::PointerDown { x: sx, y: sy, button: uzor::input::MouseButton::Left }, viewport);
engine.on_event(&PlatformEvent::PointerUp { x: sx, y: sy, button: uzor::input::MouseButton::Left }, viewport);
assert_eq!(engine.selected(), Some(NodeIndex(0)));
// Click far from every node's projection — empty space.
engine.on_event(&PlatformEvent::PointerDown { x: 5.0, y: 5.0, button: uzor::input::MouseButton::Left }, viewport);
engine.on_event(&PlatformEvent::PointerUp { x: 5.0, y: 5.0, button: uzor::input::MouseButton::Left }, viewport);
assert_eq!(engine.selected(), None, "clicking empty space must clear the previous selection");
}
#[test]
fn node_facts_reuses_the_2d_engines_nodefacts_shape() {
let engine = spread_triangle_engine();
let facts = engine.node_facts(NodeIndex(0)).expect("node 0 exists in the triangle fixture");
assert_eq!(facts.index, NodeIndex(0));
assert_eq!(facts.label, "a");
assert_eq!(facts.category, "x");
assert_eq!(facts.degree, 2);
assert_eq!(facts.position, (-40.0, 0.0), "position reports (x, y) only — z is a known Wave 3 divergence, see CLAUDE.md");
assert!(!facts.pinned, "nothing is pinned this wave (no 3D node-drag/pin yet)");
assert!(engine.node_facts(NodeIndex(99)).is_none(), "an out-of-range node must yield None, not panic");
}
#[test]
fn visible_labels_returns_a_screen_position_for_every_unoccluded_node() {
let mut engine = spread_triangle_engine();
// At the default orbit distance the 3 fixture nodes project close
// enough together to share a single 100px `label_grid` cell — a
// high density removes the LOD quota as a confound so this test
// proves the project+return plumbing itself, not the (separately
// tested, in `label_grid.rs`) quota math.
engine.set_label_density(100.0);
let viewport = Rect::new(0.0, 0.0, 400.0, 300.0);
let aspect = (viewport.width / viewport.height) as f32;
let camera = engine.camera(aspect);
let labels = engine.visible_labels(&camera, viewport);
assert_eq!(labels.len(), 3, "all 3 well-separated triangle nodes should get a label slot at this camera/density");
let ids: std::collections::HashSet<NodeIndex> = labels.iter().map(|(id, _, _)| *id).collect();
assert_eq!(ids, [NodeIndex(0), NodeIndex(1), NodeIndex(2)].into_iter().collect());
// Each returned screen position must match `project_world_to_screen`
// for that node's own particle position — no drift between the
// LOD pass and the underlying projection.
for (id, sx, sy) in labels {
let p = engine.particles[id.index()];
let expected = pick3d::project_world_to_screen(&camera, Vec3::new(p.x, p.y, p.z), viewport).expect("visible node must project");
assert!((sx - expected.0).abs() < 1e-6 && (sy - expected.1).abs() < 1e-6);
}
}
#[test]
fn label_density_defaults_and_set_label_density_updates_the_getter_and_clamps_negative_input() {
let mut engine = spread_triangle_engine();
assert_eq!(engine.label_density(), label_grid::DEFAULT_LABEL_DENSITY);
engine.set_label_density(3.5);
assert_eq!(engine.label_density(), 3.5);
engine.set_label_density(-1.0);
assert_eq!(engine.label_density(), 0.0, "negative density must clamp to 0.0, not go negative");
}
// ── Live-caught Wave 2 defect, fixed in Wave 3: z-plane degeneracy ─────
//
// Every 3D force in `ForceDirectedLayout3D` is z-symmetric (repulsion/
// link/center all scale the SAME `(dx, dy, dz)` direction vector), so
// seeding every node at `z = 0` (as `force_graph_demo`'s old manual
// `p.x = x; p.y = y;` loop did, leaving `z` at its `Particle::default()`
// value) makes the z-force identically zero forever — the sim can
// never leave the plane on its own. `seed_positions` is the fix.
#[test]
fn seed_positions_escapes_a_degenerate_z_plane_and_settles_into_a_true_3d_volume() {
let mut graph = DemoGraph::new();
let n = 20;
for i in 0..n {
graph.push_node((), format!("n{i}"), "x", 4.0);
}
// Ring positions in the xy plane — every particle starts at
// `z = 0` (`Particle::default()`), the exact degenerate seed the
// owner's live screenshot caught.
let positions: Vec<(f32, f32)> = (0..n)
.map(|i| {
let a = i as f32 / n as f32 * std::f32::consts::TAU;
(a.cos() * 100.0, a.sin() * 100.0)
})
.collect();
let mut engine: GraphEngine3D<(), (), ForceDirectedLayout3D> = GraphEngine3D::new(graph, ForceDirectedLayout3D::default());
engine.seed_positions(&positions);
assert!(engine.particles.iter().any(|p| p.z != 0.0), "seed_positions must jitter z off the degenerate plane immediately, before any tick");
let mut settled = false;
for _ in 0..2000 {
let r = engine.tick(1.0 / 60.0);
for p in &engine.particles {
assert!(p.x.is_finite() && p.y.is_finite() && p.z.is_finite(), "position went non-finite: {p:?}");
}
if r.settled {
settled = true;
break;
}
}
assert!(settled, "the sim must settle within 2000 ticks after the z-jitter reheat");
let (mut min_x, mut max_x) = (f32::MAX, f32::MIN);
let (mut min_y, mut max_y) = (f32::MAX, f32::MIN);
let (mut min_z, mut max_z) = (f32::MAX, f32::MIN);
for p in &engine.particles {
min_x = min_x.min(p.x);
max_x = max_x.max(p.x);
min_y = min_y.min(p.y);
max_y = max_y.max(p.y);
min_z = min_z.min(p.z);
max_z = max_z.max(p.z);
}
let xy_extent = (max_x - min_x).max(max_y - min_y);
let z_extent = max_z - min_z;
assert!(
z_extent > xy_extent * 0.1,
"the settled sim must occupy a true 3D volume, not a flat pancake: xy_extent={xy_extent}, z_extent={z_extent}"
);
}
#[test]
fn seed_positions_z_jitter_is_deterministic_across_identical_runs() {
let build_graph = || {
let mut graph = DemoGraph::new();
for i in 0..10 {
graph.push_node((), format!("n{i}"), "x", 4.0);
}
graph
};
let positions: Vec<(f32, f32)> = (0..10).map(|i| (i as f32 * 15.0, 0.0)).collect();
let mut e1: GraphEngine3D<(), (), ForceDirectedLayout3D> = GraphEngine3D::new(build_graph(), ForceDirectedLayout3D::default());
e1.seed_positions(&positions);
let mut e2: GraphEngine3D<(), (), ForceDirectedLayout3D> = GraphEngine3D::new(build_graph(), ForceDirectedLayout3D::default());
e2.seed_positions(&positions);
for (p1, p2) in e1.particles.iter().zip(e2.particles.iter()) {
assert_eq!(p1.z, p2.z, "identical seeds must jitter to the identical z on every run — no Math::random/time");
}
}
#[test]
fn ensure_z_variance_leaves_an_already_3d_seed_untouched() {
let mut engine = spread_triangle_engine();
engine.particles[0].z = 30.0;
engine.particles[1].z = -25.0;
engine.particles[2].z = 15.0;
let before: Vec<f32> = engine.particles.iter().map(|p| p.z).collect();
engine.ensure_z_variance();
let after: Vec<f32> = engine.particles.iter().map(|p| p.z).collect();
assert_eq!(before, after, "an intentional, already-varied z seed must not be disturbed");
}
#[test]
fn ensure_z_variance_is_a_no_op_on_a_fully_degenerate_xy_seed() {
// Right after `new()` every particle sits at the origin — no
// meaningful xy scale exists yet to derive a jitter range from.
let mut engine: GraphEngine3D<(), (), ForceDirectedLayout3D> =
GraphEngine3D::new(triangle(), ForceDirectedLayout3D::default());
engine.ensure_z_variance();
assert!(engine.particles.iter().all(|p| p.z == 0.0), "with a degenerate xy seed too, there's nothing to scale a jitter against");
}
#[test]
fn camera_reflects_the_default_orbit_state() {
let engine: GraphEngine3D<(), (), ForceDirectedLayout3D> =
GraphEngine3D::new(triangle(), ForceDirectedLayout3D::default());
let persp = engine.camera(16.0 / 9.0);
assert!((persp.eye - engine.camera.eye()).length() < 1e-4);
}
// ── Wave 4: `draw_overlay` — label + hover-card overlay draw calls ──
#[test]
fn draw_overlay_paints_label_text_for_every_visible_node_in_a_deterministic_fixture() {
let mut engine = spread_triangle_engine();
// Same "remove the LOD quota as a confound" convention as
// `visible_labels_returns_a_screen_position_for_every_unoccluded_node`
// — this test's own job is proving the paint plumbing, not
// re-proving `label_grid.rs`'s already-covered quota math.
engine.set_label_density(100.0);
let viewport = Rect::new(0.0, 0.0, 400.0, 300.0);
let aspect = (viewport.width / viewport.height) as f32;
let camera = engine.camera(aspect);
let mut ctx = RecordingRenderContext::new();
let stats = engine.draw_overlay(&mut ctx, &camera, viewport);
assert_eq!(stats.labels_drawn, 3, "all 3 well-separated triangle nodes must get a painted label at this camera/density");
// Each shown label now paints through `fill_text_with_halo` (owner
// defect report: thin edge strokes crossing node label text made
// it unreadable) — 8 halo copies + 1 real fill per label, 9 raw
// `fill_text` calls per label, not 1.
const FILL_TEXT_CALLS_PER_LABEL: usize = 9;
assert_eq!(
ctx.fill_texts.len(),
3 * FILL_TEXT_CALLS_PER_LABEL,
"draw_overlay must issue exactly {FILL_TEXT_CALLS_PER_LABEL} fill_text draw calls (halo + real fill) per shown label"
);
let drawn_labels: HashSet<&str> = ctx.fill_texts.iter().map(|(t, _, _)| t.as_str()).collect();
assert_eq!(drawn_labels, HashSet::from(["a", "b", "c"]), "every fixture node's own label text must be drawn");
assert!(!stats.hover_card_drawn, "nothing is hovered in this fixture, so no hover card should be painted");
}
#[test]
fn draw_overlay_culls_a_label_for_a_node_behind_the_camera() {
let mut engine = spread_triangle_engine();
engine.set_label_density(100.0);
let viewport = Rect::new(0.0, 0.0, 400.0, 300.0);
let aspect = (viewport.width / viewport.height) as f32;
let camera = engine.camera(aspect);
// Move node 0 directly behind the camera eye, opposite the view
// direction — `project_world_to_screen`'s own behind-the-eye
// guard (`clip.w <= 1e-5`) must reject it, and `visible_labels`
// (which `draw_overlay` iterates) must therefore never surface
// it as a label candidate.
let forward = (camera.target - camera.eye).normalize();
let behind = camera.eye - forward * 50.0;
engine.particles[0] = Particle::at3(behind.x, behind.y, behind.z);
assert!(
pick3d::project_world_to_screen(&camera, behind, viewport).is_none(),
"fixture sanity check: the behind-camera point must itself fail to project"
);
let mut ctx = RecordingRenderContext::new();
let stats = engine.draw_overlay(&mut ctx, &camera, viewport);
assert_eq!(stats.labels_drawn, 2, "the behind-camera node's label must be culled, the other two must still draw");
assert!(
!ctx.fill_texts.iter().any(|(t, _, _)| t == "a"),
"node 0's own label text must never be drawn while it sits behind the camera"
);
}
#[test]
fn draw_overlay_paints_a_hover_card_for_the_hovered_node() {
let mut engine = spread_triangle_engine();
let viewport = Rect::new(0.0, 0.0, 400.0, 300.0);
let aspect = (viewport.width / viewport.height) as f32;
let camera = engine.camera(aspect);
engine.hovered = Some(NodeIndex(0));
assert!(engine.hover_card_enabled(), "3D hover cards must remain enabled by default");
let mut ctx = RecordingRenderContext::new();
let stats = engine.draw_overlay(&mut ctx, &camera, viewport);
assert!(stats.hover_card_drawn, "a hovered node with a valid projection must paint a hover card");
// `draw_hover_card` (`crate::render::draw_hover_card`, reused
// verbatim from the 2D engine) issues a key/value `fill_text`
// pair per `NodeFacts` field — the hovered node's own label
// text must show up among the card's drawn text.
assert!(
ctx.fill_texts.iter().any(|(t, _, _)| t == "a"),
"the hover card must show the hovered node's own label text"
);
}
#[test]
fn disabling_hover_card_suppresses_only_the_card_and_keeps_hover_active() {
let mut engine = spread_triangle_engine();
let viewport = Rect::new(0.0, 0.0, 400.0, 300.0);
let aspect = (viewport.width / viewport.height) as f32;
let camera = engine.camera(aspect);
engine.hovered = Some(NodeIndex(0));
engine.set_hover_card_enabled(false);
let mut ctx = RecordingRenderContext::new();
let stats = engine.draw_overlay(&mut ctx, &camera, viewport);
assert!(!engine.hover_card_enabled());
assert!(!stats.hover_card_drawn, "disabled hover cards must not emit overlay paint");
assert_eq!(engine.hovered(), Some(NodeIndex(0)), "disabling the card must not disable or clear hover picking state");
}
#[test]
fn draw_overlay_draws_no_hover_card_when_nothing_is_hovered() {
let engine = spread_triangle_engine();
let viewport = Rect::new(0.0, 0.0, 400.0, 300.0);
let aspect = (viewport.width / viewport.height) as f32;
let camera = engine.camera(aspect);
let mut ctx = RecordingRenderContext::new();
let stats = engine.draw_overlay(&mut ctx, &camera, viewport);
assert!(!stats.hover_card_drawn, "no hover, no card — draw_overlay must not paint a hover card without a hovered node");
}
/// Graph-strengthening arc G1.3 — `draw_overlay`'s own state-leak
/// gate, the 3D mirror of `render.rs`'s
/// `every_public_draw_fn_leaves_the_render_context_paint_state_unchanged`.
/// Exercises every branch that touches paint state in one call
/// (ordinary labels, the grid overlay, a cluster "×N" label, a
/// selection ring, a hover card, AND a live box-select rubber band)
/// so a bracket that only wraps SOME of them still fails this test.
#[test]
fn draw_overlay_leaves_the_render_context_paint_state_unchanged() {
let mut engine = spread_triangle_engine();
engine.set_label_density(100.0);
engine.set_grid_enabled(true);
let viewport = Rect::new(0.0, 0.0, 400.0, 300.0);
let aspect = (viewport.width / viewport.height) as f32;
let camera = engine.camera(aspect);
// Cluster "×N" label branch.
let cluster_id = engine.define_cluster(vec![NodeIndex(1), NodeIndex(2)]).expect("non-empty cluster");
assert!(engine.collapse_cluster(cluster_id));
// Selection-ring branch.
engine.select(NodeIndex(0));
// Live box-select rubber-band branch. `on_pointer_moved` also
// re-runs hover-pick unconditionally (Tier B6 of the 2D audit —
// out of this arc's own scope), so this must run BEFORE the
// hover-card branch below, not after, or it clobbers `hovered`
// with whatever the box-select drag's own endpoint happens to
// ray-pick (background, in this fixture).
engine.modifiers = uzor::input::ModifierKeys::shift();
engine.on_event(&PlatformEvent::PointerDown { x: 5.0, y: 5.0, button: uzor::input::MouseButton::Left }, viewport);
engine.on_event(&PlatformEvent::PointerMoved { x: 60.0, y: 40.0 }, viewport);
assert!(engine.box_select_rect().is_some(), "fixture sanity: a box-select must genuinely be in progress");
// Hover-card branch.
engine.hovered = Some(NodeIndex(0));
let mut render = StateTrackingContext3D::new();
// A caller-set state distinct from every default this function's
// own draw calls happen to use, so the test can't pass by
// coincidence.
render.set_font("20px serif");
render.set_fill_color("#123456");
render.set_stroke_color("#abcdef");
render.set_stroke_width(9.0);
render.set_global_alpha(0.42);
render.set_text_align(uzor::render::TextAlign::Right);
render.set_text_baseline(uzor::render::TextBaseline::Bottom);
render.set_line_cap("square");
render.set_line_join("bevel");
let caller_state = render.state.clone();
let stats = engine.draw_overlay(&mut render, &camera, viewport);
assert!(stats.labels_drawn > 0 && stats.hover_card_drawn, "fixture sanity: draw_overlay must genuinely have painted labels and a hover card");
assert_eq!(render.state, caller_state, "draw_overlay must not leak paint state past its own call");
}
// ── Wave 4: GPU color-ID picking escalation ─────────────────────────
#[test]
fn should_use_gpu_pick_reflects_the_threshold_override() {
let mut engine = spread_triangle_engine(); // 3 nodes
assert_eq!(engine.gpu_pick_threshold(), pick3d::GPU_PICK_NODE_THRESHOLD);
assert!(!engine.should_use_gpu_pick(), "3 nodes must stay under the default 10_000 threshold");
engine.set_gpu_pick_threshold(2);
assert_eq!(engine.gpu_pick_threshold(), 2);
assert!(engine.should_use_gpu_pick(), "3 nodes > an overridden threshold of 2 must flip to the GPU path");
}
#[test]
fn hover_above_the_gpu_pick_threshold_starts_exactly_one_gpu_pick_request() {
let mut engine = spread_triangle_engine();
engine.set_gpu_pick_threshold(2);
let viewport = Rect::new(0.0, 0.0, 400.0, 300.0);
assert_eq!(engine.gpu_pick_requests_started(), 0);
engine.on_event(&PlatformEvent::PointerMoved { x: 200.0, y: 150.0 }, viewport);
assert_eq!(engine.gpu_pick_requests_started(), 1, "an above-threshold hover move must start a GPU pick request");
assert!(engine.gpu_pick_pending());
}
#[test]
fn hover_below_the_gpu_pick_threshold_never_touches_the_gpu_pick_pipeline() {
let mut engine = spread_triangle_engine(); // default threshold, 3 nodes well under it
let viewport = Rect::new(0.0, 0.0, 400.0, 300.0);
engine.on_event(&PlatformEvent::PointerMoved { x: 200.0, y: 150.0 }, viewport);
assert_eq!(engine.gpu_pick_requests_started(), 0);
assert!(!engine.gpu_pick_pending());
}
#[test]
fn hover_still_resolves_via_cpu_pick_as_the_same_frame_answer_even_above_the_gpu_pick_threshold() {
let mut engine = spread_triangle_engine();
engine.set_gpu_pick_threshold(2);
let viewport = Rect::new(0.0, 0.0, 400.0, 300.0);
let aspect = (viewport.width / viewport.height) as f32;
let camera = engine.camera(aspect);
let (sx, sy) = pick3d::project_world_to_screen(&camera, Vec3::new(-40.0, 0.0, 0.0), viewport).expect("node 0 projects inside the view");
engine.on_event(&PlatformEvent::PointerMoved { x: sx, y: sy }, viewport);
assert_eq!(engine.hovered(), Some(NodeIndex(0)), "even in GPU-pick mode, the CPU ray-pick must still resolve this SAME frame");
assert!(engine.gpu_pick_pending(), "a GPU refinement request must also be in flight in parallel");
}
#[test]
fn apply_gpu_pick_result_refines_hovered_once_the_deferred_readback_resolves() {
let mut engine = spread_triangle_engine();
engine.set_gpu_pick_threshold(2);
let viewport = Rect::new(0.0, 0.0, 400.0, 300.0);
engine.on_event(&PlatformEvent::PointerMoved { x: 200.0, y: 150.0 }, viewport);
assert!(engine.gpu_pick_pending());
engine.apply_gpu_pick_result(Some(NodeIndex(2)));
assert!(!engine.gpu_pick_pending(), "applying the result must consume the in-flight request");
assert_eq!(engine.hovered(), Some(NodeIndex(2)), "the resolved GPU pick result must refine hovered");
}
#[test]
fn apply_gpu_pick_result_with_nothing_in_flight_is_a_no_op() {
let mut engine = spread_triangle_engine();
let before = engine.hovered();
engine.apply_gpu_pick_result(Some(NodeIndex(1)));
assert_eq!(engine.hovered(), before, "feeding a stray GPU result with no request in flight must not touch hovered");
}
/// Graph-strengthening arc G1.2 belt-and-braces guard: the id-pass
/// scene now excludes hidden nodes at RENDER time, but the GPU
/// readback is asynchronous (request now, result 1-2 frames later per
/// this method's own doc comment) — a local-subgraph/filter/cluster
/// change in that window can make a request-time-eligible node no
/// longer eligible by the time the result arrives. `apply_gpu_pick_result`
/// must drop a stale `Some(node)` outside the CURRENT
/// `pick_candidates()` rather than pulling `hovered` back onto it.
#[test]
fn apply_gpu_pick_result_rejects_a_stale_result_naming_a_node_the_current_pick_candidates_no_longer_include() {
let mut engine = spread_triangle_engine();
engine.set_gpu_pick_threshold(2);
let viewport = Rect::new(0.0, 0.0, 400.0, 300.0);
engine.on_event(&PlatformEvent::PointerMoved { x: 200.0, y: 150.0 }, viewport);
assert!(engine.gpu_pick_pending());
let hovered_before_result = engine.hovered();
// The async gap this guard exists for: a local-subgraph
// restriction excludes node 2 between the GPU-pick REQUEST above
// and the RESULT arriving below.
engine.set_local_root(Some(NodeIndex(0)), Some(0));
assert!(!engine.pick_candidates().contains(&NodeIndex(2)), "fixture sanity: node 2 must actually be excluded now");
engine.apply_gpu_pick_result(Some(NodeIndex(2)));
assert!(!engine.gpu_pick_pending(), "the stale result must still consume the in-flight request");
assert_eq!(
engine.hovered(),
hovered_before_result,
"a stale GPU result naming a now-excluded node must be dropped, not applied to hovered"
);
}
#[test]
fn build_id_pass_scene_emits_one_unlit_node_per_graph_node() {
let engine = spread_triangle_engine();
let scene = engine.build_id_pass_scene();
assert_eq!(scene.nodes.len(), 3);
assert!(scene.nodes.iter().all(|n| !n.is_lit()), "the id-pass must use Unlit geometry");
assert_eq!(scene.clear_color, [1.0, 1.0, 1.0, 1.0]);
}
/// Graph-strengthening arc G1.2: a cluster-hidden node must not emit
/// an id-pass sphere — mirrors `render3d::build_id_pass_scene_emits_no_node_for_a_hidden_node`
/// but exercised through the real engine (`compute_excluded_nodes_3d`
/// wiring, not the bare `render3d` function in isolation).
#[test]
fn build_id_pass_scene_excludes_a_node_hidden_by_a_collapsed_cluster() {
let mut engine = spread_triangle_engine();
let id = engine.define_cluster(vec![NodeIndex(1), NodeIndex(2)]).expect("non-empty cluster");
assert!(engine.collapse_cluster(id));
let scene = engine.build_id_pass_scene();
assert_eq!(scene.nodes.len(), 2, "the collapsed cluster's non-representative member must not get an id-pass sphere");
}
// ── Owner-ordered live fix: 3D node drag ────────────────────────────
#[test]
fn pointer_down_on_a_node_drags_it_along_the_camera_parallel_plane_and_it_stays_pinned_after_release() {
let mut engine = spread_triangle_engine();
let viewport = Rect::new(0.0, 0.0, 400.0, 300.0);
let aspect = (viewport.width / viewport.height) as f32;
let camera = engine.camera(aspect);
let (sx, sy) = pick3d::project_world_to_screen(&camera, Vec3::new(-40.0, 0.0, 0.0), viewport).expect("node 0 must project inside the default orbit view");
assert!(engine.on_event(&PlatformEvent::PointerDown { x: sx, y: sy, button: uzor::input::MouseButton::Left }, viewport));
assert!(engine.particles[0].is_pinned_3d(), "drag-start must pin the grabbed node immediately");
let move_x = sx + 30.0;
let move_y = sy + 15.0;
assert!(engine.on_event(&PlatformEvent::PointerMoved { x: move_x, y: move_y }, viewport));
// Independently recompute the expected ray-plane intersection —
// NOT copy-pasted from `on_pointer_moved`'s own implementation —
// to actually prove the production wiring, not just restate it.
let (origin, dir) = pick3d::screen_to_ray(&camera, viewport, (move_x, move_y));
let plane_point = Vec3::new(-40.0, 0.0, 0.0);
let plane_normal = (camera.target - camera.eye).normalize_or_zero();
let expected = pick3d::ray_plane_intersection(origin, dir, plane_point, plane_normal).expect("the moved cursor ray must still cross the drag plane");
let p = engine.particles[0];
assert!(
(p.x - expected.x).abs() < 1e-3 && (p.y - expected.y).abs() < 1e-3 && (p.z - expected.z).abs() < 1e-3,
"dragged node must move to the exact ray-plane intersection: got ({}, {}, {}), expected {expected:?}",
p.x,
p.y,
p.z
);
assert!(p.is_pinned_3d(), "a node being actively dragged must stay pinned so the sim doesn't fight the drag");
assert!(engine.on_event(&PlatformEvent::PointerUp { x: move_x, y: move_y, button: uzor::input::MouseButton::Left }, viewport));
assert_eq!(engine.selected(), Some(NodeIndex(0)), "releasing a node drag must select the dragged node");
let released_pos = (engine.particles[0].x, engine.particles[0].y, engine.particles[0].z);
for _ in 0..30 {
engine.tick(1.0 / 60.0);
}
let after = engine.particles[0];
assert_eq!(
(after.x, after.y, after.z),
released_pos,
"Sticky drag-end policy: the node must stay exactly where it was released, unaffected by subsequent ticks"
);
assert!(after.is_pinned_3d(), "Sticky policy must leave the node pinned after release");
}
#[test]
fn pointer_down_on_empty_space_still_orbits_the_camera_and_drags_no_node() {
let mut engine = spread_triangle_engine();
let viewport = Rect::new(0.0, 0.0, 400.0, 300.0);
let before_positions: Vec<Particle> = engine.particles.clone();
let before_yaw = engine.camera.yaw;
// Far from every fixture node's projected screen position —
// background.
assert!(engine.on_event(&PlatformEvent::PointerDown { x: 5.0, y: 5.0, button: uzor::input::MouseButton::Left }, viewport));
assert!(engine.on_event(&PlatformEvent::PointerMoved { x: 105.0, y: 5.0 }, viewport));
assert!(engine.camera.yaw != before_yaw, "a miss on pointer-down must fall back to orbiting the camera exactly as before this fix");
for (before, after) in before_positions.iter().zip(engine.particles.iter()) {
assert_eq!((before.x, before.y, before.z), (after.x, after.y, after.z), "no node position may move from an orbit drag");
assert!(!after.is_pinned_3d(), "no node may become pinned from an orbit drag");
}
}
// ── Round 2 of the edge-quality overhaul: sphere tessellation bump ──
/// A headless-GPU pixel-level "no long straight facet run" silhouette
/// check turned out too fiddly to make robust at this crate's own
/// 128×128 test-target resolution (a facet edge's own screen-space
/// length depends on camera distance/fov in a way that's easy to
/// mistune into either a flaky test or a vacuously-passing one) — per
/// the task's own "if too fiddly headlessly, document and leave to
/// the coordinator's visual check" allowance, that's what this test
/// does NOT attempt. What it DOES prove, cheaply and robustly: the
/// actual tessellation density the owner asked for
/// ("28-32 longitudinal / 18-24 latitudinal") is really wired into
/// the shared node-sphere mesh every graph node instances from — a
/// regression that silently dropped `NODE_SPHERE_RINGS`/`SLICES`
/// back down would otherwise pass every other test in this file
/// (none of them inspect mesh density).
#[test]
fn shared_node_sphere_mesh_uses_the_re_tuned_tessellation_density() {
let engine: GraphEngine3D<(), (), ForceDirectedLayout3D> =
GraphEngine3D::new(triangle(), ForceDirectedLayout3D::default());
assert_eq!(NODE_SPHERE_SLICES, 30, "longitudinal segments must land in the owner's requested 28-32 band");
assert!((18..=24).contains(&NODE_SPHERE_RINGS), "latitudinal bands must land in the owner's requested 18-24 band");
let mesh = engine.node_mesh();
let expected_vertices = ((NODE_SPHERE_RINGS + 1) * (NODE_SPHERE_SLICES + 1)) as usize;
let expected_indices = (NODE_SPHERE_RINGS * NODE_SPHERE_SLICES * 6) as usize;
assert_eq!(mesh.vertices.len(), expected_vertices, "the shared node-sphere mesh's own vertex grid must match rings/slices exactly");
assert_eq!(mesh.indices.len(), expected_indices, "the shared node-sphere mesh's own index count must match rings/slices exactly");
// Every vertex's own normal must equal its (unit-radius) position
// direction — the per-vertex, not per-face, smoothness [`crate::render3d`]'s
// own module doc already asserted from a direct code read; this
// re-confirms it holds at the NEW, bumped density too (a
// regression that duplicated vertices per-face, breaking smooth
// shading, wouldn't show up in the count assertions above).
for v in &mesh.vertices {
let p = glam::Vec3::from_array(v.pos);
let n = glam::Vec3::from_array(v.normal);
assert!((p.normalize() - n).length() < 1e-4, "vertex normal must equal its own unit-sphere position direction: pos={p:?} normal={n:?}");
}
}
// ── Wave 5: Camera3D::fit_bounds fit_view wiring ────────────────────
#[test]
fn fit_view_frames_every_node_inside_the_ndc_unit_square_and_keeps_yaw_pitch() {
let mut engine = spread_triangle_engine();
engine.camera.yaw = 0.9;
engine.camera.pitch = -0.25;
let aspect = 16.0 / 9.0;
engine.fit_view(aspect);
assert_eq!(engine.camera.yaw, 0.9, "fit_view must keep the existing yaw — dolly+retarget only");
assert_eq!(engine.camera.pitch, -0.25, "fit_view must keep the existing pitch");
let persp = engine.camera(aspect);
let view_proj = persp.view_proj();
for p in &engine.particles {
let world = Vec3::new(p.x, p.y, p.z);
let clip = view_proj * world.extend(1.0);
assert!(clip.w > 1e-5, "node at {world:?} must sit in front of the fitted camera");
let ndc_x = clip.x / clip.w;
let ndc_y = clip.y / clip.w;
assert!(ndc_x.abs() <= 1.0 + 1e-3 && ndc_y.abs() <= 1.0 + 1e-3, "node at {world:?} escaped NDC: ({ndc_x}, {ndc_y})");
}
}
#[test]
fn fit_view_on_a_fresh_engine_with_a_degenerate_zero_extent_seed_falls_back_to_the_default_distance() {
// Right after `new()`, every particle sits at the shared origin —
// 3 nodes but a fully degenerate (zero-extent) AABB.
let mut engine: GraphEngine3D<(), (), ForceDirectedLayout3D> =
GraphEngine3D::new(triangle(), ForceDirectedLayout3D::default());
engine.camera.yaw = 0.4;
engine.fit_view(16.0 / 9.0);
assert_eq!(engine.camera.distance, Camera3D::default().distance);
assert_eq!(engine.camera.target, Vec3::ZERO);
assert_eq!(engine.camera.yaw, 0.4, "the degenerate fallback must still keep yaw/pitch untouched");
}
#[test]
fn fit_view_on_too_few_nodes_falls_back_to_the_default_distance_even_with_a_real_extent() {
let mut two_node_graph = DemoGraph::new();
two_node_graph.push_node((), "a", "x", 4.0);
two_node_graph.push_node((), "b", "x", 4.0);
let mut engine: GraphEngine3D<(), (), ForceDirectedLayout3D> =
GraphEngine3D::new(two_node_graph, ForceDirectedLayout3D::default());
engine.particles[0] = Particle::at3(-100.0, 0.0, 0.0);
engine.particles[1] = Particle::at3(100.0, 0.0, 0.0);
engine.fit_view(16.0 / 9.0);
assert_eq!(engine.camera.distance, Camera3D::default().distance, "2 nodes is too few for a meaningful bounding-box fit, regardless of extent");
assert_eq!(engine.camera.target, Vec3::ZERO);
}
#[test]
fn fit_view_on_an_empty_graph_is_a_no_op() {
let mut engine: GraphEngine3D<(), (), ForceDirectedLayout3D> =
GraphEngine3D::new(DemoGraph::new(), ForceDirectedLayout3D::default());
let before = engine.camera;
engine.fit_view(16.0 / 9.0);
assert_eq!(engine.camera, before, "fit_view must not touch the camera when there are zero particles");
}
// ── Wave 5: ground-reference grid toggle + build_scene/draw_overlay ─
#[test]
fn grid_enabled_defaults_to_off_and_the_setter_toggles_it() {
let mut engine: GraphEngine3D<(), (), ForceDirectedLayout3D> =
GraphEngine3D::new(triangle(), ForceDirectedLayout3D::default());
assert!(!engine.grid_enabled(), "a force graph has no semantic axes of its own — the grid must default OFF");
engine.set_grid_enabled(true);
assert!(engine.grid_enabled());
engine.set_grid_enabled(false);
assert!(!engine.grid_enabled());
}
#[test]
fn label_halo_defaults_and_the_setter_updates_it() {
let mut engine: GraphEngine3D<(), (), ForceDirectedLayout3D> =
GraphEngine3D::new(triangle(), ForceDirectedLayout3D::default());
assert_eq!(engine.label_halo(), DEFAULT_LABEL_HALO, "default halo must match the 2D engine's own default");
engine.set_label_halo("#112233");
assert_eq!(engine.label_halo(), "#112233");
}
// ── Graph-strengthening arc Wave G2b — 3D configurability accessors ─
#[test]
fn theme_defaults_to_dark_and_set_theme_updates_the_getter() {
let mut engine: GraphEngine3D<(), (), ForceDirectedLayout3D> =
GraphEngine3D::new(triangle(), ForceDirectedLayout3D::default());
assert_eq!(engine.theme().selection_ring_color, GraphTheme::dark().selection_ring_color);
engine.set_theme(GraphTheme::light());
assert_eq!(engine.theme().selection_ring_color, GraphTheme::light().selection_ring_color);
}
/// Wave G2b configurability gate: the theme's own overlay fields
/// must actually reach the paint calls `draw_overlay` makes — not
/// just exist as an unread struct.
#[test]
fn draw_overlay_paints_the_node_label_using_the_engines_own_theme() {
let mut engine = spread_triangle_engine();
engine.set_label_density(100.0);
let custom = GraphTheme { label_fill: "#ff00ff".to_owned(), label_font: "22px monospace".to_owned(), ..GraphTheme::dark() };
engine.set_theme(custom);
let viewport = Rect::new(0.0, 0.0, 400.0, 300.0);
let aspect = (viewport.width / viewport.height) as f32;
let camera = engine.camera(aspect);
let mut ctx = RecordingRenderContext::new();
engine.draw_overlay(&mut ctx, &camera, viewport);
assert!(ctx.fill_colors.contains(&"#ff00ff".to_owned()), "the custom label_fill must actually be used to paint a node label");
assert!(ctx.fonts.contains(&"22px monospace".to_owned()), "the custom label_font must actually be set before painting a node label");
}
#[test]
fn draw_overlay_paints_the_selection_ring_using_the_engines_own_theme() {
let mut engine = spread_triangle_engine();
let ids: Vec<NodeIndex> = engine.graph.nodes().map(|(id, _)| id).collect();
engine.select(ids[0]);
let custom = GraphTheme { selection_ring_color: "#00ffaa".to_owned(), selection_ring_width: 5.0, ..GraphTheme::dark() };
engine.set_theme(custom);
let viewport = Rect::new(0.0, 0.0, 400.0, 300.0);
let aspect = (viewport.width / viewport.height) as f32;
let camera = engine.camera(aspect);
let mut ctx = RecordingRenderContext::new();
let stats = engine.draw_overlay(&mut ctx, &camera, viewport);
assert_eq!(stats.selection_rings_drawn, 1);
assert!(ctx.stroke_colors.contains(&"#00ffaa".to_owned()), "the custom selection_ring_color must actually be used");
assert!(ctx.stroke_widths.contains(&5.0), "the custom selection_ring_width must actually be used");
}
#[test]
fn draw_overlay_paints_grid_tick_labels_using_the_engines_own_theme() {
let mut engine = spread_triangle_engine();
engine.set_grid_enabled(true);
let custom = GraphTheme { grid_tick_color: "#123456".to_owned(), grid_tick_font: "9px cursive".to_owned(), ..GraphTheme::dark() };
engine.set_theme(custom);
let viewport = Rect::new(0.0, 0.0, 800.0, 600.0);
let aspect = (viewport.width / viewport.height) as f32;
let camera = engine.camera(aspect);
let mut ctx = RecordingRenderContext::new();
let stats = engine.draw_overlay(&mut ctx, &camera, viewport);
assert!(stats.grid_labels_drawn > 0, "the fixture/viewport must actually produce at least one strong gridline label");
assert!(ctx.fill_colors.contains(&"#123456".to_owned()), "the custom grid_tick_color must actually be used");
assert!(ctx.fonts.contains(&"9px cursive".to_owned()), "the custom grid_tick_font must actually be used");
}
#[test]
fn lighting_defaults_and_set_lighting_updates_the_getter_and_reaches_build_scene() {
let mut engine = spread_triangle_engine();
assert_eq!(engine.lighting().node_material.ambient_strength, Graph3DLighting::default().node_material.ambient_strength);
let custom = Graph3DLighting { ambient: [0.0, 0.0, 0.0], light_intensity: 0.05, ..Graph3DLighting::default() };
engine.set_lighting(custom);
assert_eq!(engine.lighting().ambient, [0.0, 0.0, 0.0]);
let scene = engine.build_scene(300.0);
assert_eq!(scene.ambient, [0.0, 0.0, 0.0], "a caller-supplied lighting config must actually reach build_scene's own Scene3D");
}
#[test]
fn edge_style_defaults_and_set_edge_style_updates_the_getter_and_reaches_build_scene() {
let mut engine = spread_triangle_engine();
assert_eq!(engine.edge_style().tint_rgb, Graph3DEdgeStyle::default().tint_rgb);
let custom = Graph3DEdgeStyle { tint_rgb: [0.9, 0.1, 0.1], alpha: 0.77, ..Graph3DEdgeStyle::default() };
engine.set_edge_style(custom);
assert_eq!(engine.edge_style().alpha, 0.77);
let scene = engine.build_scene(300.0);
let edge_node = scene.nodes.iter().find(|n| matches!(n.geometry, uzor_urx_3d::NodeMesh::Line(_))).expect("at least one edge instance");
assert_eq!(edge_node.color_tint, [0.9, 0.1, 0.1, 0.77], "a caller-supplied edge style must actually reach build_scene's own edge tint");
}
#[test]
fn grid_config_defaults_and_set_grid_config_updates_the_getter_and_reaches_the_overlay_cap() {
let mut engine = spread_triangle_engine();
assert_eq!(engine.grid_config().max_axis_labels, Graph3DGridConfig::default().max_axis_labels);
engine.set_grid_enabled(true);
let capped = Graph3DGridConfig { max_axis_labels: 0, ..Graph3DGridConfig::default() };
engine.set_grid_config(capped);
let viewport = Rect::new(0.0, 0.0, 800.0, 600.0);
let aspect = (viewport.width / viewport.height) as f32;
let camera = engine.camera(aspect);
let mut ctx = RecordingRenderContext::new();
let stats = engine.draw_overlay(&mut ctx, &camera, viewport);
assert_eq!(stats.grid_labels_drawn, 0, "a max_axis_labels of 0 must actually suppress every grid tick label");
}
#[test]
fn pick_radius_slack_world_defaults_and_the_setter_updates_the_getter() {
let engine = spread_triangle_engine();
assert_eq!(engine.pick_radius_slack_world(), pick3d::PICK_RADIUS_SLACK_WORLD);
}
/// Wave G2b configurability gate: `set_pick_radius_slack_world` must
/// actually reach the real CPU ray-pick, changing whether the SAME
/// screen point resolves a hit — not just update the getter. One
/// node, radius 1.0, offset 1.5 world units from the screen-center
/// ray (mirrors `interaction::pick3d`'s own
/// `nearest_node_3d_slack_widens_or_narrows_the_hit_test_radius`
/// unit-level proof, here exercised through the full engine's own
/// `pick_at`).
#[test]
fn set_pick_radius_slack_world_changes_which_node_pick_at_actually_resolves() {
let mut graph = DemoGraph::new();
graph.push_node((), "a", "x", 1.0);
let mut engine: GraphEngine3D<(), (), ForceDirectedLayout3D> = GraphEngine3D::new(graph, ForceDirectedLayout3D::default());
engine.particles[0] = Particle::at3(0.0, 1.5, 0.0);
engine.camera = Camera3D { target: Vec3::ZERO, distance: 10.0, yaw: 0.0, pitch: 0.0, ..Camera3D::default() };
let viewport = Rect::new(0.0, 0.0, 200.0, 200.0);
let ids: Vec<NodeIndex> = engine.graph.nodes().map(|(id, _)| id).collect();
engine.set_pick_radius_slack_world(0.0);
assert_eq!(engine.pick_at(100.0, 100.0, viewport), None, "zero slack must miss — the screen-center ray clears the bare radius by 0.5 units");
engine.set_pick_radius_slack_world(1.0);
assert_eq!(engine.pick_at(100.0, 100.0, viewport), Some(ids[0]), "a slack of 1.0 must cover the 0.5-unit gap and hit the same screen point");
}
#[test]
fn label_lod_defaults_and_the_setter_updates_the_getter() {
let mut engine: GraphEngine3D<(), (), ForceDirectedLayout3D> =
GraphEngine3D::new(triangle(), ForceDirectedLayout3D::default());
assert_eq!(*engine.label_lod(), label_grid::LabelLodConfig::default());
let custom = label_grid::LabelLodConfig { grid_cell_size_px: 42.0, ..label_grid::LabelLodConfig::default() };
engine.set_label_lod(custom);
assert_eq!(engine.label_lod().grid_cell_size_px, 42.0);
}
#[test]
fn build_scene_appends_grid_lines_only_once_enabled() {
let mut engine = spread_triangle_engine();
let scene_without_grid = engine.build_scene(900.0);
assert_eq!(scene_without_grid.nodes.len(), 6, "disabled grid must emit zero grid nodes — 3 spheres + 3 edges only");
engine.set_grid_enabled(true);
let scene_with_grid = engine.build_scene(900.0);
assert!(
scene_with_grid.nodes.len() > scene_without_grid.nodes.len(),
"enabling the grid must append extra instanced line nodes"
);
}
#[test]
fn build_scene_grid_is_a_no_op_on_an_empty_graph() {
let mut engine: GraphEngine3D<(), (), ForceDirectedLayout3D> =
GraphEngine3D::new(DemoGraph::new(), ForceDirectedLayout3D::default());
engine.set_grid_enabled(true);
let scene = engine.build_scene(900.0);
assert!(scene.nodes.is_empty(), "an empty graph has no AABB to grid — must not panic or fabricate geometry");
}
#[test]
fn draw_overlay_paints_axis_tick_labels_for_strong_gridlines_once_the_grid_is_enabled() {
let mut engine = spread_triangle_engine();
engine.set_grid_enabled(true);
let viewport = Rect::new(0.0, 0.0, 800.0, 600.0);
let aspect = (viewport.width / viewport.height) as f32;
let camera = engine.camera(aspect);
let mut ctx = RecordingRenderContext::new();
let stats = engine.draw_overlay(&mut ctx, &camera, viewport);
assert!(stats.grid_labels_drawn > 0, "at least one strong gridline must be labeled once the grid is enabled");
assert!(
ctx.fill_texts.iter().any(|(text, _, _)| text.parse::<f64>().is_ok()),
"a numeric axis-tick label must actually be painted once the grid is enabled: {:?}",
ctx.fill_texts
);
}
#[test]
fn draw_overlay_paints_no_axis_tick_labels_while_the_grid_stays_disabled() {
let engine = spread_triangle_engine();
let viewport = Rect::new(0.0, 0.0, 800.0, 600.0);
let aspect = (viewport.width / viewport.height) as f32;
let camera = engine.camera(aspect);
let mut ctx = RecordingRenderContext::new();
let stats = engine.draw_overlay(&mut ctx, &camera, viewport);
assert_eq!(stats.grid_labels_drawn, 0, "grid_labels_drawn must stay 0 while the grid defaults off");
assert!(
!ctx.fill_texts.iter().any(|(text, _, _)| text.parse::<f64>().is_ok()),
"no numeric axis-tick label should be painted while the grid is off: {:?}",
ctx.fill_texts
);
}
// ── Cluster/selection wave: 3D collapse/expand, box-select, rings ──
/// 4-member cluster (m0..m3) plus one outside node, spread on distinct
/// well-separated 3D positions — mirrors `cluster.rs`'s own
/// `small_graph_with_cluster` fixture shape, adapted to
/// `GraphEngine3D`. Two cross-cluster edges (weights 2.0 + 3.0) land
/// on the SAME outside node, so a collapse must aggregate them into
/// one synthetic edge of weight 5.0.
fn clustered_engine() -> (GraphEngine3D<(), (), ForceDirectedLayout3D>, Vec<NodeIndex>, NodeIndex) {
let mut graph = DemoGraph::new();
let outside = graph.push_node((), "outside", "x", 4.0);
let mut members = Vec::new();
for i in 0..4 {
members.push(graph.push_node((), format!("m{i}"), "cluster", 4.0));
}
for i in 0..members.len() {
graph.push_edge(members[i], members[(i + 1) % members.len()], 1.0, ());
}
graph.push_edge(members[0], outside, 2.0, ());
graph.push_edge(outside, members[2], 3.0, ());
let mut engine: GraphEngine3D<(), (), ForceDirectedLayout3D> = GraphEngine3D::new(graph, ForceDirectedLayout3D::default());
engine.particles[outside.index()] = Particle::at3(100.0, 0.0, 0.0);
engine.particles[members[0].index()] = Particle::at3(-10.0, 0.0, 5.0);
engine.particles[members[1].index()] = Particle::at3(0.0, -10.0, -5.0);
engine.particles[members[2].index()] = Particle::at3(10.0, 0.0, 5.0);
engine.particles[members[3].index()] = Particle::at3(0.0, 10.0, -5.0);
(engine, members, outside)
}
#[test]
fn collapse_cluster_and_expand_cluster_round_trip_via_the_engine_level_api() {
let (mut engine, members, _outside) = clustered_engine();
let original: Vec<Particle> = members.iter().map(|&m| engine.particles[m.index()]).collect();
let id = engine.define_cluster(members.clone()).expect("non-empty cluster");
assert!(!engine.is_collapsed(id));
assert!(engine.collapse_cluster(id));
assert!(!engine.collapse_cluster(id), "collapsing an already-collapsed cluster is a no-op");
assert!(engine.is_collapsed(id));
// Every non-representative member is pinned exactly onto the
// representative's own (real 3D) position.
let rep = engine.particles[members[0].index()];
for &m in &members[1..] {
let p = engine.particles[m.index()];
assert!(p.is_pinned_3d());
assert_eq!((p.x, p.y, p.z), (rep.x, rep.y, rep.z));
}
// Representative's radius grew to reflect the member count.
assert!(engine.graph.get_node(members[0]).unwrap().radius > 4.0);
assert!(engine.expand_cluster(id));
assert!(!engine.expand_cluster(id), "expanding an already-expanded cluster is a no-op");
assert!(!engine.is_collapsed(id));
for (&m, before) in members.iter().zip(original.iter()) {
let p = engine.particles[m.index()];
assert_eq!((p.x, p.y, p.z), (before.x, before.y, before.z), "expand must restore the EXACT pre-collapse 3D position");
assert!(!p.is_pinned_3d());
}
}
#[test]
fn pick_candidates_excludes_hidden_cluster_members_but_keeps_the_representative_and_outside_nodes() {
let (mut engine, members, outside) = clustered_engine();
let id = engine.define_cluster(members.clone()).expect("non-empty cluster");
assert_eq!(engine.pick_candidates().len(), 5, "nothing hidden yet — every node is a candidate");
engine.collapse_cluster(id);
let candidates = engine.pick_candidates();
assert_eq!(candidates.len(), 2, "3 hidden members excluded — only the representative + outside remain");
assert!(candidates.contains(&members[0]), "the representative itself must stay a pick candidate");
assert!(candidates.contains(&outside), "an unrelated outside node must stay a pick candidate");
for &hidden_member in &members[1..] {
assert!(!candidates.contains(&hidden_member), "a hidden cluster member must never be a pick candidate");
}
}
#[test]
fn build_scene_hides_cluster_members_and_appends_one_aggregated_cross_cluster_edge() {
let (mut engine, members, _outside) = clustered_engine();
let id = engine.define_cluster(members.clone()).expect("non-empty cluster");
let scene_before = engine.build_scene(600.0);
// 5 nodes + 6 edges (4 ring + 2 cross-cluster) = 11 instances.
assert_eq!(scene_before.nodes.len(), 11);
assert!(engine.collapse_cluster(id));
let scene_after = engine.build_scene(600.0);
// Node spheres: 2 (representative + outside) instead of 5 — 3
// hidden members emit none. Edges: the 4 ring edges all touch a
// hidden non-representative member and drop; the `m0-outside`
// cross-cluster edge does NOT (the representative itself is
// NEVER hidden — `hidden_nodes()`'s own doc comment — so this
// raw edge survives the `hidden` filter untouched, mirroring the
// SAME quirk the 2D engine's own `draw_edges` has for exactly
// this reason); the OTHER cross-cluster edge (`outside-m2`) DOES
// drop (m2 is hidden). Plus exactly 1 aggregated cross-cluster
// synthetic edge, summing BOTH raw cross-cluster edges (2.0+3.0)
// onto the one outside node. Total: 2 nodes + 1 surviving raw
// edge + 1 aggregated edge = 4.
assert_eq!(
scene_after.nodes.len(),
4,
"collapse must hide 3 member spheres, drop only the fully-internal-or-hidden-touching edges, and add the aggregated substitute"
);
}
#[test]
fn visible_labels_and_draw_overlay_exclude_hidden_cluster_members_and_force_the_representatives_label() {
let (mut engine, members, outside) = clustered_engine();
engine.set_label_density(100.0); // remove the LOD quota as a confound
let id = engine.define_cluster(members.clone()).expect("non-empty cluster");
engine.collapse_cluster(id);
let viewport = Rect::new(0.0, 0.0, 400.0, 300.0);
let aspect = (viewport.width / viewport.height) as f32;
let camera = engine.camera(aspect);
let labels = engine.visible_labels(&camera, viewport);
let labeled_ids: HashSet<NodeIndex> = labels.iter().map(|(id, _, _)| *id).collect();
assert!(labeled_ids.contains(&members[0]), "the representative's own label must always be forced-shown");
assert!(labeled_ids.contains(&outside), "an unrelated outside node keeps its ordinary label");
for &hidden_member in &members[1..] {
assert!(!labeled_ids.contains(&hidden_member), "a hidden cluster member must never get a label slot");
}
let mut ctx = RecordingRenderContext::new();
let stats = engine.draw_overlay(&mut ctx, &camera, viewport);
assert_eq!(stats.cluster_labels_drawn, 1, "exactly one collapsed cluster's own supernode label must be painted");
assert!(
ctx.fill_texts.iter().any(|(t, _, _)| t == "×4"),
"the supernode label text must be the exact member count: {:?}",
ctx.fill_texts
);
}
#[test]
fn draw_overlay_paints_one_selection_ring_per_selected_visible_node_and_skips_a_hidden_one() {
let (mut engine, members, outside) = clustered_engine();
let id = engine.define_cluster(members.clone()).expect("non-empty cluster");
engine.collapse_cluster(id);
// Select the (visible) representative, a hidden member, and the
// (visible) outside node.
engine.apply_selection([members[0], members[1], outside], SelectMode::Replace);
let viewport = Rect::new(0.0, 0.0, 400.0, 300.0);
let aspect = (viewport.width / viewport.height) as f32;
let camera = engine.camera(aspect);
let mut ctx = RecordingRenderContext::new();
let stats = engine.draw_overlay(&mut ctx, &camera, viewport);
assert_eq!(stats.selection_rings_drawn, 2, "the hidden member in the selection must be skipped — only 2 of 3 rings drawn");
}
#[test]
fn apply_selection_replace_union_and_diff_produce_exact_expected_sets() {
let (mut engine, members, outside) = clustered_engine();
engine.apply_selection([members[0], members[1]], SelectMode::Replace);
assert_eq!(engine.selection, [members[0], members[1]].into_iter().collect());
engine.apply_selection([outside], SelectMode::Union);
assert_eq!(engine.selection, [members[0], members[1], outside].into_iter().collect());
engine.apply_selection([members[0]], SelectMode::Diff);
assert_eq!(engine.selection, [members[1], outside].into_iter().collect(), "Diff must toggle: remove an already-selected node");
engine.apply_selection([members[2]], SelectMode::Diff);
assert_eq!(engine.selection, [members[1], members[2], outside].into_iter().collect(), "Diff must toggle: add a not-yet-selected node");
}
#[test]
fn select_sets_both_selected_and_a_one_element_selection_and_clear_selection_clears_both() {
let (mut engine, members, _outside) = clustered_engine();
engine.select(members[0]);
assert_eq!(engine.selected(), Some(members[0]));
assert_eq!(engine.selection, std::iter::once(members[0]).collect());
engine.clear_selection();
assert_eq!(engine.selected(), None);
assert!(engine.selection.is_empty());
}
#[test]
fn box_select_rect_is_corner_normalized_regardless_of_drag_direction() {
let mut engine: GraphEngine3D<(), (), ForceDirectedLayout3D> =
GraphEngine3D::new(triangle(), ForceDirectedLayout3D::default());
let viewport = Rect::new(0.0, 0.0, 400.0, 300.0);
engine.on_event(&PlatformEvent::ModifiersChanged { modifiers: uzor::input::ModifierKeys::shift() }, viewport);
engine.on_event(&PlatformEvent::PointerDown { x: 250.0, y: 180.0, button: uzor::input::MouseButton::Left }, viewport);
engine.on_event(&PlatformEvent::PointerMoved { x: 60.0, y: 40.0 }, viewport);
assert_eq!(
engine.box_select_rect(),
Some(Rect::new(60.0, 40.0, 190.0, 140.0)),
"the rubber-band rect must be corner-normalized even when the drag runs bottom-right -> top-left"
);
engine.on_event(&PlatformEvent::PointerUp { x: 60.0, y: 40.0, button: uzor::input::MouseButton::Left }, viewport);
assert_eq!(engine.box_select_rect(), None, "box_select_rect must clear once the drag ends");
}
#[test]
fn box_select_selects_only_nodes_whose_projected_center_falls_inside_the_screen_rect() {
let mut engine = spread_triangle_engine();
let viewport = Rect::new(0.0, 0.0, 400.0, 300.0);
let aspect = (viewport.width / viewport.height) as f32;
let camera = engine.camera(aspect);
let (sx0, sy0) = pick3d::project_world_to_screen(&camera, Vec3::new(-40.0, 0.0, 0.0), viewport).expect("node 0 projects");
let (sx1, sy1) = pick3d::project_world_to_screen(&camera, Vec3::new(40.0, 0.0, 0.0), viewport).expect("node 1 projects");
// A rect covering only node 0's own projected position, well away
// from nodes 1/2 (well-separated fixture — see
// `spread_triangle_engine`'s own doc comment).
engine.box_select((sx0 - 5.0, sy0 - 5.0), (sx0 + 5.0, sy0 + 5.0), SelectMode::Replace, viewport);
assert_eq!(engine.selection, std::iter::once(NodeIndex(0)).collect());
// Union in node 1.
engine.box_select((sx1 - 5.0, sy1 - 5.0), (sx1 + 5.0, sy1 + 5.0), SelectMode::Union, viewport);
assert_eq!(engine.selection, [NodeIndex(0), NodeIndex(1)].into_iter().collect());
}
#[test]
fn collapse_selection_defines_and_collapses_a_cluster_from_the_current_selection_and_expand_reverts_it() {
let (mut engine, members, _outside) = clustered_engine();
assert!(engine.collapse_selection().is_none(), "collapse_selection with nothing selected is a no-op");
engine.apply_selection(members.clone(), SelectMode::Replace);
let id = engine.collapse_selection().expect("a non-empty selection must collapse");
assert!(engine.is_collapsed(id));
assert_eq!(engine.selection_collapsed_group(), Some(id));
assert!(engine.expand_cluster(id));
assert_eq!(engine.selection_collapsed_group(), None, "collapsed_group clears once expanded");
}
#[test]
fn pin_selection_and_unpin_selection_apply_to_every_selected_member() {
let (mut engine, members, _outside) = clustered_engine();
engine.apply_selection([members[0], members[1]], SelectMode::Replace);
engine.pin_selection();
assert!(engine.particles[members[0].index()].is_pinned_3d());
assert!(engine.particles[members[1].index()].is_pinned_3d());
assert!(!engine.particles[members[2].index()].is_pinned_3d(), "an unselected node must not be pinned");
engine.unpin_selection();
assert!(!engine.particles[members[0].index()].is_pinned_3d());
assert!(!engine.particles[members[1].index()].is_pinned_3d());
}
// ── 3D interaction parity wave 2, item 3: group-drag ────────────────
#[test]
fn group_drag_preserves_relative_offsets_via_a_single_shared_delta() {
let mut engine = spread_triangle_engine();
engine.apply_selection([NodeIndex(0), NodeIndex(1)], SelectMode::Replace);
let viewport = Rect::new(0.0, 0.0, 400.0, 300.0);
let aspect = (viewport.width / viewport.height) as f32;
let camera = engine.camera(aspect);
let (sx0, sy0) = pick3d::project_world_to_screen(&camera, Vec3::new(-40.0, 0.0, 0.0), viewport)
.expect("node 0 must project inside the default orbit view");
let anchor_before = Vec3::new(engine.particles[0].x, engine.particles[0].y, engine.particles[0].z);
let member_before = Vec3::new(engine.particles[1].x, engine.particles[1].y, engine.particles[1].z);
let unselected_before = engine.particles[2];
let offset = member_before - anchor_before;
// Drag the anchor (node 0), already a member of `selection`.
assert!(engine.on_event(&PlatformEvent::PointerDown { x: sx0, y: sy0, button: MouseButton::Left }, viewport));
let move_x = sx0 + 25.0;
let move_y = sy0 + 15.0;
assert!(engine.on_event(&PlatformEvent::PointerMoved { x: move_x, y: move_y }, viewport));
// Independently recompute the expected anchor world position via
// the SAME ray-plane primitive `on_pointer_moved` uses — NOT
// copy-pasted from production — to actually prove the wiring.
let (origin, dir) = pick3d::screen_to_ray(&camera, viewport, (move_x, move_y));
let plane_normal = (camera.target - camera.eye).normalize_or_zero();
let expected_anchor = pick3d::ray_plane_intersection(origin, dir, anchor_before, plane_normal)
.expect("the moved cursor ray must still cross the drag plane");
let expected_member = expected_anchor + offset;
let p0 = engine.particles[0];
let p1 = engine.particles[1];
let p2 = engine.particles[2];
assert!(
(Vec3::new(p0.x, p0.y, p0.z) - expected_anchor).length() < 1e-3,
"the anchor must move to the exact ray-plane intersection"
);
assert!(
(Vec3::new(p1.x, p1.y, p1.z) - expected_member).length() < 1e-3,
"the other selected member must keep its EXACT relative offset from the anchor, not drift"
);
assert_eq!(
(p2.x, p2.y, p2.z),
(unselected_before.x, unselected_before.y, unselected_before.z),
"an unselected node must never move during a group drag"
);
assert!(p0.is_pinned_3d());
assert!(p1.is_pinned_3d());
assert!(!p2.is_pinned_3d());
assert!(engine.on_event(&PlatformEvent::PointerUp { x: move_x, y: move_y, button: MouseButton::Left }, viewport));
// Group drag keeps the WHOLE selection selected; only `selected`
// (facts-panel value) moves to the physically-grabbed anchor.
assert_eq!(engine.selected(), Some(NodeIndex(0)));
assert_eq!(engine.selection, [NodeIndex(0), NodeIndex(1)].into_iter().collect());
// Sticky release: both members stay held across subsequent ticks.
let released0 = (engine.particles[0].x, engine.particles[0].y, engine.particles[0].z);
let released1 = (engine.particles[1].x, engine.particles[1].y, engine.particles[1].z);
for _ in 0..30 {
engine.tick(1.0 / 60.0);
}
assert_eq!((engine.particles[0].x, engine.particles[0].y, engine.particles[0].z), released0);
assert_eq!((engine.particles[1].x, engine.particles[1].y, engine.particles[1].z), released1);
assert!(engine.particles[0].is_pinned_3d(), "Sticky policy must leave every group member pinned after release");
assert!(engine.particles[1].is_pinned_3d());
}
#[test]
fn dragging_a_non_selected_node_drags_just_it_and_replace_selects_it() {
let mut engine = spread_triangle_engine();
engine.apply_selection([NodeIndex(1), NodeIndex(2)], SelectMode::Replace);
let viewport = Rect::new(0.0, 0.0, 400.0, 300.0);
let aspect = (viewport.width / viewport.height) as f32;
let camera = engine.camera(aspect);
let (sx0, sy0) = pick3d::project_world_to_screen(&camera, Vec3::new(-40.0, 0.0, 0.0), viewport)
.expect("node 0 must project inside the default orbit view");
let before1 = engine.particles[1];
let before2 = engine.particles[2];
assert!(engine.on_event(&PlatformEvent::PointerDown { x: sx0, y: sy0, button: MouseButton::Left }, viewport));
assert!(engine.on_event(&PlatformEvent::PointerMoved { x: sx0 + 20.0, y: sy0 + 8.0 }, viewport));
assert_eq!(
(engine.particles[1].x, engine.particles[1].y, engine.particles[1].z),
(before1.x, before1.y, before1.z),
"a member of the OLD (unrelated) selection must not move — dragging node 0 is a SOLO drag"
);
assert_eq!((engine.particles[2].x, engine.particles[2].y, engine.particles[2].z), (before2.x, before2.y, before2.z));
assert!(!engine.particles[1].is_pinned_3d());
assert!(!engine.particles[2].is_pinned_3d());
assert!(engine.on_event(&PlatformEvent::PointerUp { x: sx0 + 20.0, y: sy0 + 8.0, button: MouseButton::Left }, viewport));
assert_eq!(engine.selected(), Some(NodeIndex(0)));
assert_eq!(
engine.selection,
std::iter::once(NodeIndex(0)).collect(),
"a solo drag must Replace-select ONLY the dragged node, dropping the prior selection"
);
}
// ── 3D interaction parity wave 2, item 4: filter + local subgraph ───
/// `a - b - c - d` chain on a line — mirrors `crate::engine`'s own
/// `chain4_engine_on_a_line` test fixture.
fn chain4_engine_3d() -> (GraphEngine3D<(), (), ForceDirectedLayout3D>, [NodeIndex; 4]) {
let mut graph = DemoGraph::new();
let a = graph.push_node((), "a", "x", 4.0);
let b = graph.push_node((), "b", "x", 4.0);
let c = graph.push_node((), "c", "x", 4.0);
let d = graph.push_node((), "d", "x", 4.0);
graph.push_edge(a, b, 1.0, ());
graph.push_edge(b, c, 1.0, ());
graph.push_edge(c, d, 1.0, ());
let mut engine: GraphEngine3D<(), (), ForceDirectedLayout3D> = GraphEngine3D::new(graph, ForceDirectedLayout3D::default());
engine.particles[a.index()] = Particle::at3(0.0, 0.0, 0.0);
engine.particles[b.index()] = Particle::at3(20.0, 0.0, 0.0);
engine.particles[c.index()] = Particle::at3(40.0, 0.0, 0.0);
engine.particles[d.index()] = Particle::at3(60.0, 0.0, 0.0);
(engine, [a, b, c, d])
}
#[test]
fn set_local_root_restricts_pick_candidates_to_exactly_the_bfs_depth_k_neighborhood_and_restores_on_clear() {
let (mut engine, [a, b, c, d]) = chain4_engine_3d();
assert_eq!(engine.pick_candidates().len(), 4, "sanity: all 4 nodes are candidates with no restriction");
engine.set_local_root(Some(b), Some(1));
let candidates: HashSet<NodeIndex> = engine.pick_candidates().into_iter().collect();
assert_eq!(candidates, [a, b, c].into_iter().collect(), "depth-1 from b in a 4-chain is exactly {{a,b,c}}");
assert_eq!(engine.local_root(), Some((b, 1)));
engine.set_local_root(None, None);
let candidates_full: HashSet<NodeIndex> = engine.pick_candidates().into_iter().collect();
assert_eq!(candidates_full, [a, b, c, d].into_iter().collect(), "clearing local_root restores the full candidate set");
assert!(engine.local_root().is_none());
}
#[test]
fn set_local_root_default_depth_is_two() {
let (mut engine, [a, b, _c, d]) = chain4_engine_3d();
engine.set_local_root(Some(a), None);
assert_eq!(engine.local_root(), Some((a, 2)));
let candidates: HashSet<NodeIndex> = engine.pick_candidates().into_iter().collect();
assert!(!candidates.contains(&d), "d is 3 hops from a — outside a depth-2 neighborhood");
assert!(candidates.contains(&b));
}
#[test]
fn set_local_root_excludes_nodes_from_build_scene_too() {
let (mut engine, _ids) = chain4_engine_3d();
engine.set_local_root(Some(NodeIndex(1)), Some(1));
let scene = engine.build_scene(600.0);
// Local set {a,b,c}: 3 node spheres + edges a-b/b-c survive (both
// endpoints inside); c-d touches the excluded node d and drops.
assert_eq!(scene.nodes.len(), 5, "excluded node d and its touching edge must be gone from the scene");
}
/// `a - b - c` chain where `b` gets a DIFFERENT category from `a`/`c`
/// — the fixture the 3D filter tests exclude `b` with (mirrors
/// `crate::engine`'s own `three_node_chain_with_a_hideable_middle`).
fn three_node_chain_with_a_hideable_middle_3d() -> (DemoGraph, NodeIndex, NodeIndex, NodeIndex) {
let mut graph = DemoGraph::new();
let a = graph.push_node((), "a", "x", 4.0);
let b = graph.push_node((), "b", "hidden", 4.0);
let c = graph.push_node((), "c", "x", 4.0);
graph.push_edge(a, b, 1.0, ());
graph.push_edge(b, c, 1.0, ());
(graph, a, b, c)
}
/// A filtered-out node is excluded from the scene/picking AND from the
/// force topology fed to the layout: dropping its edges measurably
/// changes where the SURVIVING nodes settle, compared to an
/// otherwise-identical unfiltered run — mirrors `crate::engine`'s own
/// `filter_removes_a_node_from_render_and_from_the_force_topology_so_settled_positions_differ`
/// in 3D.
#[test]
fn filter_removes_a_node_from_scene_and_picking_and_changes_settled_positions() {
let settle = |engine: &mut GraphEngine3D<(), (), ForceDirectedLayout3D>| {
for _ in 0..600 {
engine.tick(1.0 / 60.0);
}
};
let (graph, a, _b, _c) = three_node_chain_with_a_hideable_middle_3d();
let mut baseline: GraphEngine3D<(), (), ForceDirectedLayout3D> = GraphEngine3D::new(graph, ForceDirectedLayout3D::default());
baseline.seed_positions(&[(-40.0, 0.0), (0.0, 0.0), (40.0, 0.0)]);
settle(&mut baseline);
let baseline_a = baseline.particles[a.index()];
let (graph2, a2, b2, c2) = three_node_chain_with_a_hideable_middle_3d();
let mut filtered: GraphEngine3D<(), (), ForceDirectedLayout3D> = GraphEngine3D::new(graph2, ForceDirectedLayout3D::default());
filtered.seed_positions(&[(-40.0, 0.0), (0.0, 0.0), (40.0, 0.0)]);
filtered.set_filter(Some(FilterSpec { categories: Some(vec!["x".to_owned()]), ..Default::default() }));
let candidates: HashSet<NodeIndex> = filtered.pick_candidates().into_iter().collect();
assert!(!candidates.contains(&b2), "the filtered-out node must be excluded from picking");
assert!(candidates.contains(&a2));
assert!(candidates.contains(&c2));
let scene = filtered.build_scene(600.0);
// a/c spheres survive (b excluded); NEITHER edge survives — both
// a-b and b-c touch the excluded node b.
assert_eq!(scene.nodes.len(), 2, "the filtered-out node and every edge touching it must be gone from the scene");
settle(&mut filtered);
let filtered_a = filtered.particles[a2.index()];
let dist = ((baseline_a.x - filtered_a.x).powi(2) + (baseline_a.y - filtered_a.y).powi(2) + (baseline_a.z - filtered_a.z).powi(2))
.sqrt();
assert!(
dist > 1.0,
"losing the link-force pull toward the filtered-out node must measurably change where `a` settles in 3D too: \
baseline ({}, {}, {}) vs filtered ({}, {}, {}), dist {dist}",
baseline_a.x,
baseline_a.y,
baseline_a.z,
filtered_a.x,
filtered_a.y,
filtered_a.z
);
}
#[test]
fn filter_defaults_to_none_and_set_filter_none_clears_a_previous_filter() {
let (mut engine, _members, outside) = clustered_engine();
assert!(engine.filter().is_none());
engine.set_filter(Some(FilterSpec { categories: Some(vec!["cluster".to_owned()]), ..Default::default() }));
assert!(engine.filter().is_some());
let candidates: HashSet<NodeIndex> = engine.pick_candidates().into_iter().collect();
assert!(!candidates.contains(&outside), "the outside node's category (\"x\") fails the \"cluster\"-only filter");
engine.set_filter(None);
assert!(engine.filter().is_none());
let candidates_full: HashSet<NodeIndex> = engine.pick_candidates().into_iter().collect();
assert!(candidates_full.contains(&outside), "clearing the filter must restore the excluded node");
}
/// Star graph — root + 4 leaves, alternating categories `"keep"`/
/// `"drop"` — mirrors `crate::engine`'s own `star_graph_with_categories`.
fn star_graph_with_categories_3d() -> (DemoGraph, NodeIndex, [NodeIndex; 4]) {
let mut graph = DemoGraph::new();
let root = graph.push_node((), "root", "keep", 4.0);
let mut leaves = Vec::with_capacity(4);
for i in 0..4 {
let category = if i % 2 == 0 { "keep" } else { "drop" };
let leaf = graph.push_node((), format!("leaf{i}"), category, 4.0);
graph.push_edge(root, leaf, 1.0, ());
leaves.push(leaf);
}
(graph, root, [leaves[0], leaves[1], leaves[2], leaves[3]])
}
/// Filter and local-subgraph mode compose as an INTERSECTION in 3D too
/// — mirrors `crate::engine`'s own
/// `filter_and_local_mode_compose_as_an_intersection`.
#[test]
fn filter_and_local_mode_compose_as_an_intersection() {
let (graph, root, [l0, l1, l2, l3]) = star_graph_with_categories_3d();
let mut engine: GraphEngine3D<(), (), ForceDirectedLayout3D> = GraphEngine3D::new(graph, ForceDirectedLayout3D::default());
engine.seed_positions(&[(0.0, 0.0), (50.0, 0.0), (0.0, 50.0), (-50.0, 0.0), (0.0, -50.0)]);
engine.set_local_root(Some(root), Some(1));
engine.set_filter(Some(FilterSpec { categories: Some(vec!["keep".to_owned()]), ..Default::default() }));
let candidates: HashSet<NodeIndex> = engine.pick_candidates().into_iter().collect();
// BFS depth-1 from root = {root, l0, l1, l2, l3}; filter keeps
// only category "keep" = {root, l0, l2}. Intersection = {root, l0, l2}.
assert_eq!(candidates, [root, l0, l2].into_iter().collect());
assert!(!candidates.contains(&l1), "l1 fails the filter even though it's in the local BFS set");
assert!(!candidates.contains(&l3));
}
/// Triangle where the third node is otherwise box-selectable, but a
/// filter that keeps only `a`/`b`'s own category excludes it —
/// mirrors the fixture shape [`clustered_engine`]/[`spread_triangle_engine`]
/// already use, purpose-built here for a clean category split.
fn triangle_with_a_distinct_third_category() -> GraphEngine3D<(), (), ForceDirectedLayout3D> {
let mut graph = DemoGraph::new();
let a = graph.push_node((), "a", "x", 4.0);
let b = graph.push_node((), "b", "x", 4.0);
let c = graph.push_node((), "c", "y", 4.0);
graph.push_edge(a, b, 1.0, ());
graph.push_edge(b, c, 1.0, ());
graph.push_edge(c, a, 1.0, ());
let mut engine: GraphEngine3D<(), (), ForceDirectedLayout3D> = GraphEngine3D::new(graph, ForceDirectedLayout3D::default());
engine.particles[a.index()] = Particle::at3(-40.0, 0.0, 0.0);
engine.particles[b.index()] = Particle::at3(40.0, 0.0, 0.0);
engine.particles[c.index()] = Particle::at3(0.0, 40.0, 0.0);
engine
}
#[test]
fn box_select_ignores_excluded_nodes_as_candidates() {
let mut engine = triangle_with_a_distinct_third_category();
let viewport = Rect::new(0.0, 0.0, 400.0, 300.0);
let aspect = (viewport.width / viewport.height) as f32;
let camera = engine.camera(aspect);
let (sx2, sy2) = pick3d::project_world_to_screen(&camera, Vec3::new(0.0, 40.0, 0.0), viewport).expect("node c must project inside the view");
// Sanity: with no exclusion active, node c IS box-selectable.
engine.box_select((sx2 - 5.0, sy2 - 5.0), (sx2 + 5.0, sy2 + 5.0), SelectMode::Replace, viewport);
assert_eq!(engine.selection, std::iter::once(NodeIndex(2)).collect());
engine.clear_selection();
// Category filter that excludes node c ("y") but keeps a/b ("x").
engine.set_filter(Some(FilterSpec { categories: Some(vec!["x".to_owned()]), ..Default::default() }));
engine.box_select((sx2 - 5.0, sy2 - 5.0), (sx2 + 5.0, sy2 + 5.0), SelectMode::Replace, viewport);
assert!(engine.selection.is_empty(), "a filter-excluded node must never be a box-select candidate");
}
// ── Dimension transition (dimension-transition wave — animated
// 2D<->3D switch) ────────────────────────────────────────────────────
/// Triangle fixture with a genuine `z` spread (unlike `triangle()`'s
/// own callers, which mostly only need `x`/`y`) so `z * scale` is
/// actually visible/provable, not a `0.0 * scale == 0.0` degenerate
/// case.
fn engine_with_z_spread() -> GraphEngine3D<(), (), ForceDirectedLayout3D> {
let mut engine: GraphEngine3D<(), (), ForceDirectedLayout3D> =
GraphEngine3D::new(triangle(), ForceDirectedLayout3D::default());
engine.particles[0] = Particle::at3(-40.0, 0.0, 20.0);
engine.particles[1] = Particle::at3(40.0, 0.0, -30.0);
engine.particles[2] = Particle::at3(0.0, 40.0, 15.0);
engine
}
#[test]
fn dimension_transition_z_scale_eases_monotonically_in_and_hits_exact_endpoints() {
let mut engine = engine_with_z_spread();
assert_eq!(engine.render_z_scale(), 1.0, "absent a transition, render z-scale is the identity");
engine.start_transition(TransitionDirection::In, 600.0);
assert_eq!(engine.render_z_scale(), 0.0, "a fresh `In` transition must start perfectly flat");
assert!(engine.transition_active());
assert_eq!(engine.transition_direction(), Some(TransitionDirection::In));
// 600ms at a fixed 20ms tick is 30 ticks in EXACT arithmetic, but
// `f32` summation of `0.02` 30 times can under/overshoot by a
// fraction of a tick — loop until completion (capped well above
// 30 as a deadlock guard) rather than assuming an exact count.
let mut last = engine.render_z_scale();
let mut ticks = 0;
while engine.transition_active() {
ticks += 1;
assert!(ticks <= 100, "the In transition must complete well within 100 20ms ticks (2s) of a 600ms duration");
engine.tick(0.02);
let now = engine.render_z_scale();
assert!(now >= last - 1e-6, "z-scale must never regress while easing In (was {last}, now {now})");
last = now;
}
assert!((last - 1.0).abs() < 1e-4, "In must converge to the full z-scale, got {last}");
}
#[test]
fn dimension_transition_z_scale_eases_monotonically_out_and_hits_exact_endpoints() {
let mut engine = engine_with_z_spread();
assert_eq!(engine.render_z_scale(), 1.0);
engine.start_transition(TransitionDirection::Out, 600.0);
assert_eq!(engine.render_z_scale(), 1.0, "a fresh `Out` transition must start at the full z-scale");
assert_eq!(engine.transition_direction(), Some(TransitionDirection::Out));
// See the `In` sibling test above for why this loops to
// completion instead of assuming an exact tick count.
let mut last = engine.render_z_scale();
let mut ticks = 0;
while engine.transition_active() {
ticks += 1;
assert!(ticks <= 100, "the Out transition must complete well within 100 20ms ticks (2s) of a 600ms duration");
engine.tick(0.02);
let now = engine.render_z_scale();
assert!(now <= last + 1e-6, "z-scale must never increase while easing Out (was {last}, now {now})");
last = now;
}
assert!(last.abs() < 1e-4, "Out must converge to a zero z-scale, got {last}");
}
#[test]
fn dimension_transition_camera_converges_from_front_on_to_the_orbit_state_on_in() {
let mut engine = engine_with_z_spread();
let settled_orbit = engine.camera; // `Camera3D::default()` here — never touched yet.
engine.start_transition(TransitionDirection::In, 600.0);
let front_on = engine.front_on_camera();
assert_eq!(engine.camera.yaw, front_on.yaw, "t=0 of In must sample the front-on framing exactly");
assert_eq!(engine.camera.pitch, front_on.pitch);
assert!((engine.camera.distance - front_on.distance).abs() < 1e-4);
assert!((engine.camera.target - front_on.target).length() < 1e-4);
assert_eq!(front_on.yaw, 0.0, "front-on framing must look straight down -Z (yaw 0)");
assert_eq!(front_on.pitch, 0.0, "front-on framing must look straight down -Z (pitch 0)");
let mut ticks = 0;
while engine.transition_active() {
ticks += 1;
assert!(ticks <= 100, "600ms must complete well within 100 20ms ticks");
engine.tick(0.02);
}
assert!((engine.camera.yaw - settled_orbit.yaw).abs() < 1e-3, "t=1 of In must converge to the settled orbit yaw");
assert!((engine.camera.pitch - settled_orbit.pitch).abs() < 1e-3);
assert!((engine.camera.distance - settled_orbit.distance).abs() < 1e-2);
assert!((engine.camera.target - settled_orbit.target).length() < 1e-2);
}
#[test]
fn dimension_transition_camera_converges_from_the_orbit_state_to_front_on_on_out() {
let mut engine = engine_with_z_spread();
// A distinctive orbit pose so convergence provably targets THIS
// pose, not the untouched default.
engine.camera.yaw = 1.1;
engine.camera.pitch = 0.4;
engine.camera.distance = 777.0;
let settled_orbit = engine.camera;
engine.start_transition(TransitionDirection::Out, 600.0);
assert_eq!(engine.camera, settled_orbit, "t=0 of an Out transition must sample the CURRENT settled orbit pose exactly");
// Captured BEFORE any tick runs — the physics sim also advances
// every tick and would otherwise drift the particle AABB (and
// therefore a freshly-recomputed front-on framing) out from under
// the ALREADY-FROZEN `end_camera` this transition committed to at
// `start_transition` time.
let front_on = engine.front_on_camera();
let mut ticks = 0;
while engine.transition_active() {
ticks += 1;
assert!(ticks <= 100, "600ms must complete well within 100 20ms ticks");
engine.tick(0.02);
}
assert!((engine.camera.yaw - front_on.yaw).abs() < 1e-3, "t=1 of Out must converge to the front-on yaw");
assert!((engine.camera.pitch - front_on.pitch).abs() < 1e-3);
assert!((engine.camera.distance - front_on.distance).abs() < 1e-2);
}
#[test]
fn dimension_transition_never_mutates_the_simulated_particle_positions() {
let mut engine = engine_with_z_spread();
engine.start_transition(TransitionDirection::In, 600.0);
engine.tick(0.02); // advance the sim (legitimate physics movement) + the transition once.
let scale = engine.render_z_scale();
assert!(scale > 0.0 && scale < 1.0, "must genuinely be mid-flight for this to be a meaningful proof, got {scale}");
let before: Vec<(f32, f32, f32)> = engine.particles.iter().map(|p| (p.x, p.y, p.z)).collect();
// Render/pick repeatedly WITHOUT ticking again — none of these
// may touch `self.particles`, even mid-transition.
let viewport = Rect::new(0.0, 0.0, 400.0, 300.0);
let _ = engine.build_scene(300.0);
let camera = engine.camera(400.0 / 300.0);
let _ = engine.visible_labels(&camera, viewport);
let _ = engine.pick_at(200.0, 150.0, viewport);
let _ = engine.draw_overlay(&mut RecordingRenderContext::new(), &camera, viewport);
let after: Vec<(f32, f32, f32)> = engine.particles.iter().map(|p| (p.x, p.y, p.z)).collect();
assert_eq!(before, after, "build_scene/pick_at/visible_labels/draw_overlay must never mutate the simulated particles");
}
#[test]
fn dimension_transition_is_deterministic_across_identical_runs() {
let mut engine1 = engine_with_z_spread();
let mut engine2 = engine_with_z_spread();
engine1.start_transition(TransitionDirection::In, 500.0);
engine2.start_transition(TransitionDirection::In, 500.0);
for _ in 0..25 {
engine1.tick(0.017);
engine2.tick(0.017);
assert_eq!(engine1.render_z_scale(), engine2.render_z_scale());
assert_eq!(engine1.camera, engine2.camera);
}
assert_eq!(engine1.transition_active(), engine2.transition_active());
}
#[test]
fn dimension_transition_reversal_mid_flight_continues_without_a_snap() {
let mut engine = engine_with_z_spread();
engine.start_transition(TransitionDirection::In, 600.0);
for _ in 0..10 {
engine.tick(0.02); // ~200ms elapsed — genuinely mid-flight.
}
let scale_before_reversal = engine.render_z_scale();
let camera_before_reversal = engine.camera;
assert!(scale_before_reversal > 0.0 && scale_before_reversal < 1.0, "must genuinely be mid-flight before reversing");
engine.start_transition(TransitionDirection::Out, 600.0);
// No snap: the instant a reversal starts, both the z-scale and
// the camera pose must be UNCHANGED from the moment before —
// only the TARGET (not the current visual state) flips.
assert!((engine.render_z_scale() - scale_before_reversal).abs() < 1e-6, "reversing must not snap the z-scale");
assert_eq!(engine.camera, camera_before_reversal, "reversing must not snap the camera pose");
assert_eq!(engine.transition_direction(), Some(TransitionDirection::Out));
// And it must actually reverse — the following ticks ease TOWARD
// 0.0 (flat/front-on), not keep climbing toward 1.0.
let mut last = engine.render_z_scale();
let mut ticks = 0;
while engine.transition_active() {
ticks += 1;
assert!(ticks <= 100, "the reversed Out transition must complete well within 100 20ms ticks");
engine.tick(0.02);
let now = engine.render_z_scale();
assert!(now <= last + 1e-6, "after reversing, z-scale must ease DOWN toward 0, not keep climbing");
last = now;
}
assert!(last.abs() < 1e-4);
}
// ── Wave G3 item 5 — `start_transition(In, _)` idempotency ─────────
/// The actual defect: a REDUNDANT `start_transition(In, _)` call on
/// an engine that's already fully, steadily 3D (the first `In`
/// completed long ago, `dim_transition` is `None` again for the
/// unrelated reason that it finished, not because nothing has ever
/// run) must NOT force a spurious flatten-then-reinflate — before
/// the fix, `start_scale` was forced to `0.0` regardless.
#[test]
fn a_redundant_in_transition_after_the_first_one_completed_does_not_reflatten() {
let mut engine = engine_with_z_spread();
engine.start_transition(TransitionDirection::In, 50.0);
let mut ticks = 0;
while engine.transition_active() {
ticks += 1;
assert!(ticks <= 100);
engine.tick(0.02);
}
assert_eq!(engine.render_z_scale(), 1.0, "the first In must have settled at the full z-scale");
engine.start_transition(TransitionDirection::In, 600.0);
assert_eq!(
engine.render_z_scale(),
1.0,
"a redundant In on an already-steady-3D engine must NOT force a spurious flatten back to 0.0"
);
// A start==end transition is legitimately a no-op that settles
// immediately (or within a couple ticks) rather than genuinely
// animating anything, since there's nothing to ease between.
let mut ticks = 0;
while engine.transition_active() {
ticks += 1;
assert!(ticks <= 100);
engine.tick(0.02);
assert_eq!(engine.render_z_scale(), 1.0, "z-scale must stay at 1.0 throughout a redundant, already-settled In");
}
}
/// The redundant call must ALSO not snap the camera back to the
/// front-on framing — the analogous glitch on the camera side of
/// the same `is_fresh`-only bug.
#[test]
fn a_redundant_in_transition_after_the_first_one_completed_does_not_snap_the_camera() {
let mut engine = engine_with_z_spread();
engine.start_transition(TransitionDirection::In, 50.0);
let mut ticks = 0;
while engine.transition_active() {
ticks += 1;
assert!(ticks <= 100);
engine.tick(0.02);
}
let settled_camera = engine.camera;
let front_on = engine.front_on_camera();
assert_ne!(settled_camera, front_on, "sanity: the settled orbit pose must genuinely differ from the front-on framing");
engine.start_transition(TransitionDirection::In, 600.0);
assert_eq!(engine.camera, settled_camera, "a redundant In must NOT snap the camera back to the front-on framing");
}
/// A genuine SECOND entry (after a real `Out` flatten actually
/// completed) must still animate correctly — the fix must not break
/// the legitimate "flatten, then re-enter" cycle while closing the
/// redundant-call glitch.
#[test]
fn a_genuine_second_in_after_a_completed_out_still_animates_from_flat() {
let mut engine = engine_with_z_spread();
engine.start_transition(TransitionDirection::In, 50.0);
let mut ticks = 0;
while engine.transition_active() {
ticks += 1;
assert!(ticks <= 100);
engine.tick(0.02);
}
engine.start_transition(TransitionDirection::Out, 50.0);
let mut ticks = 0;
while engine.transition_active() {
ticks += 1;
assert!(ticks <= 100);
engine.tick(0.02);
}
assert!(engine.render_z_scale().abs() < 1e-4, "the Out must have genuinely flattened to 0.0");
engine.start_transition(TransitionDirection::In, 600.0);
assert!(engine.render_z_scale().abs() < 1e-4, "a genuine second In must start from the real flat state, not skip the animation");
let mut last = engine.render_z_scale();
let mut ticks = 0;
while engine.transition_active() {
ticks += 1;
assert!(ticks <= 100);
engine.tick(0.02);
let now = engine.render_z_scale();
assert!(now >= last - 1e-6, "must ease monotonically back up toward 1.0");
last = now;
}
assert!((last - 1.0).abs() < 1e-4);
}
// ── Graph-strengthening arc G1.6: camera input vs. an in-flight
// dimension transition (3D mirror of the 2D engine's own G1.5 fix) ──
#[test]
fn a_background_orbit_drag_started_mid_transition_clears_the_transition_immediately() {
let mut engine = engine_with_z_spread();
let viewport = Rect::new(0.0, 0.0, 400.0, 300.0);
engine.start_transition(TransitionDirection::In, 600.0);
assert!(engine.transition_active());
// A corner far from every fixture node — background, not a node hit.
engine.on_event(&PlatformEvent::PointerDown { x: 2.0, y: 2.0, button: uzor::input::MouseButton::Left }, viewport);
assert!(!engine.transition_active(), "starting a background orbit-drag must clear an in-flight dimension transition");
}
#[test]
fn a_middle_drag_pan_started_mid_transition_clears_the_transition_immediately() {
let mut engine = engine_with_z_spread();
let viewport = Rect::new(0.0, 0.0, 400.0, 300.0);
engine.start_transition(TransitionDirection::In, 600.0);
assert!(engine.transition_active());
engine.on_event(&PlatformEvent::PointerDown { x: 2.0, y: 2.0, button: uzor::input::MouseButton::Middle }, viewport);
assert!(!engine.transition_active(), "starting a middle-drag pan must clear an in-flight dimension transition");
}
#[test]
fn a_wheel_dolly_mid_transition_clears_the_transition_immediately() {
let mut engine = engine_with_z_spread();
let viewport = Rect::new(0.0, 0.0, 400.0, 300.0);
engine.on_event(&PlatformEvent::PointerMoved { x: 200.0, y: 150.0 }, viewport);
engine.start_transition(TransitionDirection::In, 600.0);
assert!(engine.transition_active());
engine.on_event(&PlatformEvent::Scroll { dx: 0.0, dy: -1.0 }, viewport);
assert!(!engine.transition_active(), "a wheel-dolly must clear an in-flight dimension transition");
}
#[test]
fn an_explicit_fit_view_mid_transition_clears_the_transition_immediately() {
let mut engine = engine_with_z_spread();
engine.start_transition(TransitionDirection::In, 600.0);
assert!(engine.transition_active());
engine.fit_view(4.0 / 3.0);
assert!(!engine.transition_active(), "an explicit fit_view() call must clear an in-flight dimension transition");
}
// ── Graph-strengthening arc G1.4: lost PointerUp (3D mirror) ────────
#[test]
fn pointer_left_finalizes_an_in_progress_orbit_exactly_like_a_pointer_up_would() {
let mut engine = engine_with_z_spread();
let viewport = Rect::new(0.0, 0.0, 400.0, 300.0);
engine.on_event(&PlatformEvent::PointerDown { x: 2.0, y: 2.0, button: uzor::input::MouseButton::Left }, viewport);
assert!(matches!(engine.mode, Pointer3DMode::Orbiting { .. }), "fixture sanity: must genuinely be orbiting");
assert!(engine.on_event(&PlatformEvent::PointerLeft, viewport));
assert!(matches!(engine.mode, Pointer3DMode::Idle), "PointerLeft must finalize the in-progress orbit, same as a real PointerUp");
}
#[test]
fn window_defocus_finalizes_an_in_progress_node_drag_and_leaves_it_pinned() {
let mut engine = spread_triangle_engine();
let viewport = Rect::new(0.0, 0.0, 400.0, 300.0);
let aspect = (viewport.width / viewport.height) as f32;
let camera = engine.camera(aspect);
let (sx, sy) = pick3d::project_world_to_screen(&camera, Vec3::new(-40.0, 0.0, 0.0), viewport).expect("node 0 projects inside the default orbit view");
engine.on_event(&PlatformEvent::PointerDown { x: sx, y: sy, button: uzor::input::MouseButton::Left }, viewport);
assert!(matches!(engine.mode, Pointer3DMode::Dragging { .. }), "fixture sanity: must genuinely be dragging node 0");
assert!(engine.on_event(&PlatformEvent::WindowFocused(false), viewport));
assert!(matches!(engine.mode, Pointer3DMode::Idle), "losing window focus must finalize the in-progress node drag");
assert_eq!(engine.selected(), Some(NodeIndex(0)), "a node drag must select the dragged node on finalize, same as a real PointerUp");
assert!(engine.particles[0].is_pinned_3d(), "the STICKY drag-end policy must leave the node pinned where the drag left it");
}
#[test]
fn window_refocus_true_is_not_a_gesture_cancel() {
let mut engine = engine_with_z_spread();
let viewport = Rect::new(0.0, 0.0, 400.0, 300.0);
engine.on_event(&PlatformEvent::PointerDown { x: 2.0, y: 2.0, button: uzor::input::MouseButton::Left }, viewport);
assert!(matches!(engine.mode, Pointer3DMode::Orbiting { .. }));
assert!(!engine.on_event(&PlatformEvent::WindowFocused(true), viewport), "gaining focus is not a drag-cancel and must not be consumed as one");
assert!(matches!(engine.mode, Pointer3DMode::Orbiting { .. }), "gaining focus must not disturb an in-progress orbit");
}
#[test]
fn pointer_left_with_nothing_in_progress_is_a_no_op() {
let mut engine = engine_with_z_spread();
let viewport = Rect::new(0.0, 0.0, 400.0, 300.0);
assert!(matches!(engine.mode, Pointer3DMode::Idle));
assert!(!engine.on_event(&PlatformEvent::PointerLeft, viewport), "PointerLeft with no gesture in progress must not be reported as consumed");
}
}