alice-sdf 6.0.0

ALICE-SDF: 3D/Spatial Data Specialist — Store laws, not polygons. GLSL/WGSL/HLSL transpile, SVO, GPU marching cubes, texture-fit, procedural CSG. Optional bridges to alice-physics / alice-codec / libasp / alice-cache behind features.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
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
//! Core types for ALICE-SDF
//!
//! Defines the SdfNode tree structure and related types.
//!
//! Author: Moroya Sakamoto

use glam::{Quat, Vec2, Vec3};
use serde::{Deserialize, Serialize};
use std::sync::Arc;

mod constructors;
mod containers;
mod drop;
mod modifiers;
mod operations;
mod transforms;

pub use containers::{Aabb, Hit, Ray, SdfMetadata, SdfTree};

/// Category of an SDF node variant
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SdfCategory {
    /// Leaf geometry nodes (spheres, boxes, cylinders, etc.)
    Primitive,
    /// Boolean and blending operations (union, intersection, smooth union, etc.)
    Operation,
    /// Spatial transform nodes (translate, rotate, scale, etc.)
    Transform,
    /// Surface and domain modifiers (twist, bend, shell, etc.)
    Modifier,
}

impl SdfCategory {
    /// Number of SdfNode variants in this category
    ///
    /// Checked against one node per variant by
    /// `tests/test_node_backend_matrix.rs::category_counts_match_one_node_per_variant`.
    pub const fn count(self) -> u32 {
        match self {
            Self::Primitive => 74,
            Self::Operation => 25,
            Self::Transform => 7,
            Self::Modifier => 24,
        }
    }

    /// Total number of all SdfNode variants
    pub const fn total() -> u32 {
        Self::Primitive.count()
            + Self::Operation.count()
            + Self::Transform.count()
            + Self::Modifier.count()
    }
}

/// serde default for `SdfNode::Taper::reach` (files written before 2.0).
const fn taper_reach_unknown() -> [f32; 2] {
    [f32::INFINITY; 2]
}

/// Signed Distance Function Node
///
/// Represents a node in the SDF tree. Each node can be:
/// - A primitive shape (sphere, box, etc.)
/// - An operation combining two shapes (union, intersection, etc.)
/// - A transform applied to a child node
/// - A modifier deforming a child node
#[derive(Debug, Clone, Serialize, Deserialize)]
// 4.0.0: variant の追加は破壊的変更なので、これ以降の primitive 追加を minor
// で出せるように宣言する。downstream の `match` には wildcard arm が必要。
#[non_exhaustive]
pub enum SdfNode {
    // === Primitives ===
    /// Sphere with radius
    Sphere {
        /// Sphere radius
        radius: f32,
    },

    /// Axis-aligned box with half-extents
    Box3d {
        /// Half-extents along each axis
        half_extents: Vec3,
    },

    /// Cylinder along Y-axis with radius and half-height
    Cylinder {
        /// Cylinder radius
        radius: f32,
        /// Half the cylinder height
        half_height: f32,
    },

    /// Torus in XZ plane with major and minor radius
    Torus {
        /// Distance from center to tube center
        major_radius: f32,
        /// Tube radius
        minor_radius: f32,
    },

    /// Infinite plane with normal and distance from origin
    Plane {
        /// Plane normal direction
        normal: Vec3,
        /// Signed distance from origin along normal
        distance: f32,
    },

    /// Capsule between two points with radius
    Capsule {
        /// First endpoint
        point_a: Vec3,
        /// Second endpoint
        point_b: Vec3,
        /// Capsule radius
        radius: f32,
    },

    /// Cone along Y-axis with base radius and half-height
    Cone {
        /// Base radius
        radius: f32,
        /// Half the cone height
        half_height: f32,
    },

    /// Ellipsoid with semi-axis radii
    Ellipsoid {
        /// Semi-axis radii (x, y, z)
        radii: Vec3,
    },

    /// Rounded cone along Y-axis with bottom radius r1, top radius r2
    RoundedCone {
        /// Bottom sphere radius
        r1: f32,
        /// Top sphere radius
        r2: f32,
        /// Half the cone height
        half_height: f32,
    },

    /// 4-sided pyramid with square base (side=1) centered at origin
    Pyramid {
        /// Half the pyramid height
        half_height: f32,
    },

    /// Regular octahedron centered at origin
    Octahedron {
        /// Distance from center to vertex
        size: f32,
    },

    /// Hexagonal prism centered at origin
    HexPrism {
        /// Hexagon circumradius
        hex_radius: f32,
        /// Half the prism height
        half_height: f32,
    },

    /// Chain link shape centered at origin
    Link {
        /// Half the straight section length
        half_length: f32,
        /// Major radius (center to tube center)
        r1: f32,
        /// Minor radius (tube thickness)
        r2: f32,
    },

    /// Triangle defined by three vertices (unsigned distance)
    Triangle {
        /// First vertex
        point_a: Vec3,
        /// Second vertex
        point_b: Vec3,
        /// Third vertex
        point_c: Vec3,
    },

    /// Quadratic Bezier curve with radius (tube around curve)
    Bezier {
        /// Start point
        point_a: Vec3,
        /// Control point
        point_b: Vec3,
        /// End point
        point_c: Vec3,
        /// Tube radius
        radius: f32,
    },

    /// Box with rounded edges
    RoundedBox {
        /// Half-extents (before rounding)
        half_extents: Vec3,
        /// Edge rounding radius
        round_radius: f32,
    },

    /// Capped cone (frustum) along Y-axis
    CappedCone {
        /// Half the cone height
        half_height: f32,
        /// Bottom radius
        r1: f32,
        /// Top radius
        r2: f32,
    },

    /// Partial torus (arc) in XZ plane
    CappedTorus {
        /// Distance from center to tube center
        major_radius: f32,
        /// Tube radius
        minor_radius: f32,
        /// Half opening angle (radians)
        cap_angle: f32,
    },

    /// Cylinder with rounded edges along Y-axis
    RoundedCylinder {
        /// Cylinder radius
        radius: f32,
        /// Edge rounding radius
        round_radius: f32,
        /// Half the cylinder height
        half_height: f32,
    },

    /// Equilateral triangular prism along Z-axis
    TriangularPrism {
        /// Half-width of the triangle cross-section
        width: f32,
        /// Half the prism depth along Z
        half_depth: f32,
    },

    /// Sphere with a planar cut
    CutSphere {
        /// Sphere radius
        radius: f32,
        /// Y height of the cut plane
        cut_height: f32,
    },

    /// Hollow sphere shell with a planar cut
    CutHollowSphere {
        /// Sphere radius
        radius: f32,
        /// Y height of the cut plane
        cut_height: f32,
        /// Shell thickness
        thickness: f32,
    },

    /// Death Star: sphere with spherical indentation
    DeathStar {
        /// Main sphere radius
        ra: f32,
        /// Carving sphere radius
        rb: f32,
        /// Distance between sphere centers
        d: f32,
    },

    /// Solid angle (cone sector)
    SolidAngle {
        /// Half-angle in radians
        angle: f32,
        /// Bounding radius
        radius: f32,
    },

    /// 3D rhombus (diamond shape)
    Rhombus {
        /// Half-diagonal along X
        la: f32,
        /// Half-diagonal along Z
        lb: f32,
        /// Half-height along Y
        half_height: f32,
        /// Edge rounding
        round_radius: f32,
    },

    /// Horseshoe (U-shape)
    Horseshoe {
        /// Opening half-angle (radians)
        angle: f32,
        /// Ring radius
        radius: f32,
        /// Straight extension half-length
        half_length: f32,
        /// Cross-section half-width
        width: f32,
        /// Cross-section half-thickness
        thickness: f32,
    },

    /// 3D vesica (lens shape, revolved)
    Vesica {
        /// Arc radius
        radius: f32,
        /// Half distance between arc centers
        half_dist: f32,
    },

    /// Infinite cylinder along Y-axis
    InfiniteCylinder {
        /// Cylinder radius
        radius: f32,
    },

    /// Infinite cone along Y-axis
    InfiniteCone {
        /// Half-angle in radians
        angle: f32,
    },

    /// Gyroid triply-periodic minimal surface
    Gyroid {
        /// Spatial frequency
        scale: f32,
        /// Shell half-thickness
        thickness: f32,
    },

    /// Ball of a weighted norm — `w₁‖p‖₁ + w₂‖p‖₂ + w∞‖p‖∞ − radius`.
    ///
    /// The three weights choose the shape: `(0, 1, 0)` is a sphere,
    /// `(0, 0, 1)` a cube, `(1, 0, 0)` an octahedron, and anything in
    /// between a convex blend of those unit balls. They are non-negative and
    /// not all zero — [`SdfNode::metric_ball`] takes a validated
    /// `MetricWeights`, which is the only way to build one.
    MetricBall {
        /// Radius in the ball's own metric.
        radius: f32,
        /// Weight of `‖·‖₁` (octahedral).
        w_l1: f32,
        /// Weight of `‖·‖₂` (Euclidean).
        w_l2: f32,
        /// Weight of `‖·‖∞` (cubic).
        w_linf: f32,
    },

    /// Two fields blended over a spherical skin — the inner field inside a
    /// bubble, the outer one beyond it, smoothly joined across the skin.
    ///
    /// Inside `radius` the result is the inner field *exactly*, beyond
    /// `radius + skin` the outer one *exactly* (the blend weight is exactly
    /// 0 and 1 there, and the interpolation is endpoint-exact), so placing a
    /// bubble never perturbs the world outside it.
    ///
    /// The blend of two unrelated fields is not a distance function: across
    /// the skin the gradient picks up `|f_in − f_out| · |∇w|`, which no
    /// static bound can know, so
    /// [`eval_lipschitz`](crate::interval::eval_lipschitz) reports infinity
    /// for it. Use [`measure_tension`](crate::measure::measure_tension) over
    /// the skin to find out what it actually does.
    MetricBlend {
        /// Field inside the bubble.
        inner: Arc<Self>,
        /// Field outside it.
        outer: Arc<Self>,
        /// Bubble centre.
        center: Vec3,
        /// Radius at which the skin starts.
        radius: f32,
        /// Skin width; the blend spans `[radius, radius + skin]`.
        skin: f32,
    },

    /// 3D heart shape (revolved contour)
    Heart {
        /// Overall size
        size: f32,
    },

    /// Hollow cylinder (tube/pipe) along Y-axis
    Tube {
        /// Radius of the tube center-line
        outer_radius: f32,
        /// Half-wall thickness
        thickness: f32,
        /// Half the tube height
        half_height: f32,
    },

    /// Cylinder with parabolic radial bulge along Y-axis
    Barrel {
        /// Base radius at caps
        radius: f32,
        /// Half the barrel height
        half_height: f32,
        /// Additional radius at the middle
        bulge: f32,
    },

    /// Bipyramid (double-cone) with revolution symmetry
    Diamond {
        /// Equator radius
        radius: f32,
        /// Half the total height
        half_height: f32,
    },

    /// Box with chamfered (beveled) edges
    ChamferedCube {
        /// Half-extents along each axis
        half_extents: Vec3,
        /// Chamfer amount
        chamfer: f32,
    },

    /// Schwarz P triply-periodic minimal surface
    SchwarzP {
        /// Spatial frequency
        scale: f32,
        /// Shell half-thickness
        thickness: f32,
    },

    /// Generalized ellipsoid (sphere-box morph)
    Superellipsoid {
        /// Semi-axis radii
        half_extents: Vec3,
        /// North-south roundness
        e1: f32,
        /// East-west roundness
        e2: f32,
    },

    /// Rounded X shape extruded along Y-axis
    RoundedX {
        /// Arm length
        width: f32,
        /// Rounding radius
        round_radius: f32,
        /// Half the extrusion height
        half_height: f32,
    },

    /// Pie (sector) shape extruded along Y-axis
    Pie {
        /// Half opening angle in radians
        angle: f32,
        /// Pie radius
        radius: f32,
        /// Half the extrusion height
        half_height: f32,
    },

    /// Trapezoid prism in XY plane, extruded along Z
    Trapezoid {
        /// Half-width at bottom
        r1: f32,
        /// Half-width at top
        r2: f32,
        /// Half-height of the 2D trapezoid
        trap_height: f32,
        /// Half the extrusion depth along Z
        half_depth: f32,
    },

    /// Parallelogram prism in XY plane, extruded along Z
    Parallelogram {
        /// Half-width
        width: f32,
        /// Half-height
        para_height: f32,
        /// Horizontal skew
        skew: f32,
        /// Half the extrusion depth along Z
        half_depth: f32,
    },

    /// Tunnel (arch opening) in XY plane, extruded along Z
    Tunnel {
        /// Half-width of the tunnel
        width: f32,
        /// Height of the 2D tunnel opening
        height_2d: f32,
        /// Half the extrusion depth along Z
        half_depth: f32,
    },

    /// Uneven capsule prism in XY plane, extruded along Z
    UnevenCapsule {
        /// Bottom circle radius
        r1: f32,
        /// Top circle radius
        r2: f32,
        /// Half-height between circle centers
        cap_height: f32,
        /// Half the extrusion depth along Z
        half_depth: f32,
    },

    /// Egg shape (revolution body) around Y-axis
    Egg {
        /// Overall size / base radius
        ra: f32,
        /// Top deformation (controls pointiness)
        rb: f32,
    },

    /// Arc shape (thick ring sector) in XZ plane, extruded along Y
    ArcShape {
        /// Half opening angle in radians
        aperture: f32,
        /// Arc center radius
        radius: f32,
        /// Ring half-thickness
        thickness: f32,
        /// Half the extrusion height along Y
        half_height: f32,
    },

    /// Moon (crescent) shape in XZ plane, extruded along Y
    Moon {
        /// Distance between circle centers
        d: f32,
        /// Outer circle radius
        ra: f32,
        /// Inner (subtracted) circle radius
        rb: f32,
        /// Half the extrusion height along Y
        half_height: f32,
    },

    /// Cross (plus) shape in XZ plane, extruded along Y
    CrossShape {
        /// Half-length of cross arms
        length: f32,
        /// Half-thickness of cross arms
        thickness: f32,
        /// Rounding radius
        round_radius: f32,
        /// Half the extrusion height along Y
        half_height: f32,
    },

    /// Blobby cross (organic) in XZ plane, extruded along Y
    BlobbyCross {
        /// Overall size
        size: f32,
        /// Half the extrusion height along Y
        half_height: f32,
    },

    /// Parabola segment in XY plane, extruded along Z
    ParabolaSegment {
        /// Half-width of the parabola base
        width: f32,
        /// Height of the parabola
        para_height: f32,
        /// Half the extrusion depth along Z
        half_depth: f32,
    },

    /// Regular N-sided polygon prism in XZ plane, extruded along Y
    RegularPolygon {
        /// Circumscribed circle radius (center to vertex)
        radius: f32,
        /// Number of sides (as f32)
        n_sides: f32,
        /// Half the extrusion height along Y
        half_height: f32,
    },

    /// Star polygon prism in XZ plane, extruded along Y
    StarPolygon {
        /// Outer vertex radius
        radius: f32,
        /// Number of star points (as f32)
        n_points: f32,
        /// Inner vertex radius (spike depth)
        m: f32,
        /// Half the extrusion height along Y
        half_height: f32,
    },

    /// Staircase shape in XY plane, extruded along Z
    Stairs {
        /// Width of each step
        step_width: f32,
        /// Height of each step
        step_height: f32,
        /// Number of steps (as f32)
        n_steps: f32,
        /// Half the extrusion depth along Z
        half_depth: f32,
    },

    /// Helix (spiral tube) along Y-axis
    Helix {
        /// Major radius (distance from Y-axis to helix center)
        major_r: f32,
        /// Minor radius (tube thickness)
        minor_r: f32,
        /// Vertical distance per full revolution
        pitch: f32,
        /// Half the height along Y
        half_height: f32,
    },

    /// Regular tetrahedron centered at origin
    Tetrahedron {
        /// Distance from center to face
        size: f32,
    },

    /// Regular dodecahedron centered at origin (GDF)
    Dodecahedron {
        /// Distance from center to face
        radius: f32,
    },

    /// Regular icosahedron centered at origin (GDF)
    Icosahedron {
        /// Distance from center to face
        radius: f32,
    },

    /// Truncated octahedron centered at origin (GDF)
    TruncatedOctahedron {
        /// Distance from center to face
        radius: f32,
    },

    /// Truncated icosahedron (soccer ball) centered at origin (GDF)
    TruncatedIcosahedron {
        /// Distance from center to face
        radius: f32,
    },

    /// Box frame (wireframe box, edges only)
    BoxFrame {
        /// Half-extents along each axis
        half_extents: Vec3,
        /// Edge thickness
        edge: f32,
    },

    /// Diamond surface (Schwarz D TPMS)
    DiamondSurface {
        /// Spatial frequency
        scale: f32,
        /// Shell half-thickness
        thickness: f32,
    },

    /// Neovius surface (TPMS)
    Neovius {
        /// Spatial frequency
        scale: f32,
        /// Shell half-thickness
        thickness: f32,
    },

    /// Lidinoid surface (TPMS)
    Lidinoid {
        /// Spatial frequency
        scale: f32,
        /// Shell half-thickness
        thickness: f32,
    },

    /// IWP surface (TPMS)
    IWP {
        /// Spatial frequency
        scale: f32,
        /// Shell half-thickness
        thickness: f32,
    },

    /// FRD surface (TPMS)
    FRD {
        /// Spatial frequency
        scale: f32,
        /// Shell half-thickness
        thickness: f32,
    },

    /// Fischer-Koch S surface (TPMS)
    FischerKochS {
        /// Spatial frequency
        scale: f32,
        /// Shell half-thickness
        thickness: f32,
    },

    /// PMY surface (TPMS)
    PMY {
        /// Spatial frequency
        scale: f32,
        /// Shell half-thickness
        thickness: f32,
    },

    // === 2D Primitives (extruded to 3D) ===
    /// 2D Circle extruded along Z
    Circle2D {
        /// Circle radius
        radius: f32,
        /// Half-height of extrusion along Z
        half_height: f32,
    },
    /// 2D Rectangle extruded along Z
    Rect2D {
        /// Half-width and half-height of the rectangle
        half_extents: Vec2,
        /// Half-depth of extrusion along Z
        half_height: f32,
    },
    /// 2D Line Segment extruded along Z
    Segment2D {
        /// Start point
        a: Vec2,
        /// End point
        b: Vec2,
        /// Segment thickness (radius)
        thickness: f32,
        /// Half-depth of extrusion along Z
        half_height: f32,
    },
    /// 2D Polygon (convex, up to 8 vertices) extruded along Z
    Polygon2D {
        /// Vertices (up to 8)
        vertices: Vec<Vec2>,
        /// Half-depth of extrusion along Z
        half_height: f32,
    },
    /// 2D Rounded Rectangle extruded along Z
    RoundedRect2D {
        /// Half-extents of the rectangle
        half_extents: Vec2,
        /// Corner rounding radius
        round_radius: f32,
        /// Half-depth of extrusion along Z
        half_height: f32,
    },
    /// 2D Annular (ring) shape extruded along Z
    Annular2D {
        /// Outer radius
        outer_radius: f32,
        /// Ring thickness
        thickness: f32,
        /// Half-depth of extrusion along Z
        half_height: f32,
    },

    // === Operations ===
    /// Union of two shapes (min distance)
    Union {
        /// First operand
        a: Arc<Self>,
        /// Second operand
        b: Arc<Self>,
    },

    /// Intersection of two shapes (max distance)
    Intersection {
        /// First operand
        a: Arc<Self>,
        /// Second operand
        b: Arc<Self>,
    },

    /// Subtraction: a minus b (max of a and -b)
    Subtraction {
        /// Shape to subtract from
        a: Arc<Self>,
        /// Shape to subtract
        b: Arc<Self>,
    },

    /// Smooth union with blending factor k
    SmoothUnion {
        /// First operand
        a: Arc<Self>,
        /// Second operand
        b: Arc<Self>,
        /// Blending radius
        k: f32,
    },

    /// Smooth intersection with blending factor k
    SmoothIntersection {
        /// First operand
        a: Arc<Self>,
        /// Second operand
        b: Arc<Self>,
        /// Blending radius
        k: f32,
    },

    /// Smooth subtraction with blending factor k
    SmoothSubtraction {
        /// Shape to subtract from
        a: Arc<Self>,
        /// Shape to subtract
        b: Arc<Self>,
        /// Blending radius
        k: f32,
    },

    /// Chamfer union: 45-degree beveled blend
    ChamferUnion {
        /// First operand
        a: Arc<Self>,
        /// Second operand
        b: Arc<Self>,
        /// Chamfer radius
        r: f32,
    },

    /// Chamfer intersection: 45-degree beveled blend
    ChamferIntersection {
        /// First operand
        a: Arc<Self>,
        /// Second operand
        b: Arc<Self>,
        /// Chamfer radius
        r: f32,
    },

    /// Chamfer subtraction: 45-degree beveled blend
    ChamferSubtraction {
        /// Shape to subtract from
        a: Arc<Self>,
        /// Shape to subtract
        b: Arc<Self>,
        /// Chamfer radius
        r: f32,
    },

    /// Stairs union: stepped/terraced blend (Mercury hg_sdf)
    StairsUnion {
        /// First operand
        a: Arc<Self>,
        /// Second operand
        b: Arc<Self>,
        /// Blend radius
        r: f32,
        /// Number of steps (n-1 visible steps)
        n: f32,
    },

    /// Stairs intersection: stepped/terraced blend
    StairsIntersection {
        /// First operand
        a: Arc<Self>,
        /// Second operand
        b: Arc<Self>,
        /// Blend radius
        r: f32,
        /// Number of steps
        n: f32,
    },

    /// Stairs subtraction: stepped/terraced blend
    StairsSubtraction {
        /// Shape to subtract from
        a: Arc<Self>,
        /// Shape to subtract
        b: Arc<Self>,
        /// Blend radius
        r: f32,
        /// Number of steps
        n: f32,
    },

    /// XOR (symmetric difference)
    XOR {
        /// Left operand
        a: Arc<Self>,
        /// Right operand
        b: Arc<Self>,
    },

    /// Morph (linear interpolation between two shapes)
    Morph {
        /// Source shape
        a: Arc<Self>,
        /// Target shape
        b: Arc<Self>,
        /// Blend factor (0=a, 1=b)
        t: f32,
    },

    /// Columns union: column-shaped blend
    ColumnsUnion {
        /// Left operand
        a: Arc<Self>,
        /// Right operand
        b: Arc<Self>,
        /// Column radius
        r: f32,
        /// Number of columns
        n: f32,
    },

    /// Columns intersection: column-shaped blend
    ColumnsIntersection {
        /// Left operand
        a: Arc<Self>,
        /// Right operand
        b: Arc<Self>,
        /// Column radius
        r: f32,
        /// Number of columns
        n: f32,
    },

    /// Columns subtraction: column-shaped blend
    ColumnsSubtraction {
        /// Left operand
        a: Arc<Self>,
        /// Right operand
        b: Arc<Self>,
        /// Column radius
        r: f32,
        /// Number of columns
        n: f32,
    },

    /// Pipe: cylindrical surface at intersection
    Pipe {
        /// Left operand
        a: Arc<Self>,
        /// Right operand
        b: Arc<Self>,
        /// Pipe radius
        r: f32,
    },

    /// Engrave: engrave shape b into shape a
    Engrave {
        /// Base shape (receives the engraving)
        a: Arc<Self>,
        /// Engraving shape
        b: Arc<Self>,
        /// Engrave depth
        r: f32,
    },

    /// Groove: cut a groove of shape b into shape a
    Groove {
        /// Base shape (receives the groove)
        a: Arc<Self>,
        /// Groove profile shape
        b: Arc<Self>,
        /// Groove width
        ra: f32,
        /// Groove depth
        rb: f32,
    },

    /// Tongue: add a tongue protrusion
    Tongue {
        /// Base shape
        a: Arc<Self>,
        /// Tongue profile shape
        b: Arc<Self>,
        /// Tongue width
        ra: f32,
        /// Tongue height
        rb: f32,
    },

    /// Exponential smooth union (IQ): exp-weighted smooth min
    ExpSmoothUnion {
        /// Left operand
        a: Arc<Self>,
        /// Right operand
        b: Arc<Self>,
        /// Smoothness parameter
        k: f32,
    },
    /// Exponential smooth intersection
    ExpSmoothIntersection {
        /// Left operand
        a: Arc<Self>,
        /// Right operand
        b: Arc<Self>,
        /// Smoothness parameter
        k: f32,
    },
    /// Exponential smooth subtraction
    ExpSmoothSubtraction {
        /// Left operand
        a: Arc<Self>,
        /// Right operand
        b: Arc<Self>,
        /// Smoothness parameter
        k: f32,
    },

    // === Transforms ===
    /// Translation
    Translate {
        /// Child node
        child: Arc<Self>,
        /// Translation offset
        offset: Vec3,
    },

    /// Rotation (quaternion)
    Rotate {
        /// Child node
        child: Arc<Self>,
        /// Rotation quaternion
        rotation: Quat,
    },

    /// Uniform scale
    Scale {
        /// Child node
        child: Arc<Self>,
        /// Scale factor
        factor: f32,
    },

    /// Non-uniform scale (stretches the shape)
    ScaleNonUniform {
        /// Child node
        child: Arc<Self>,
        /// Scale factors per axis
        factors: Vec3,
    },

    /// Projective (perspective) transform with Lipschitz correction
    ProjectiveTransform {
        /// Child node
        child: Arc<Self>,
        /// Inverse projection matrix (column-major)
        inv_matrix: [f32; 16],
        /// Lipschitz bound for distance correction
        lipschitz_bound: f32,
    },

    /// Free-Form Deformation via control point lattice
    LatticeDeform {
        /// Child node
        child: Arc<Self>,
        /// Control points array
        control_points: Vec<Vec3>,
        /// Number of control points along X
        nx: u32,
        /// Number of control points along Y
        ny: u32,
        /// Number of control points along Z
        nz: u32,
        /// Lattice bounding box minimum
        bbox_min: Vec3,
        /// Lattice bounding box maximum
        bbox_max: Vec3,
    },

    /// SDF Skinning — bone-weight based spatial blending
    SdfSkinning {
        /// Child node
        child: Arc<Self>,
        /// Bone transforms with weights
        bones: Vec<crate::transforms::skinning::BoneTransform>,
    },

    // === Modifiers ===
    /// Twist around Y-axis (radians per unit height)
    Twist {
        /// Child node
        child: Arc<Self>,
        /// Twist strength (radians per unit)
        strength: f32,
    },

    /// Bend around Y-axis
    Bend {
        /// Child node
        child: Arc<Self>,
        /// Bend curvature
        curvature: f32,
    },

    /// Infinite repetition with spacing
    RepeatInfinite {
        /// Child node
        child: Arc<Self>,
        /// Spacing between repetitions
        spacing: Vec3,
    },

    /// Finite repetition with count and spacing
    RepeatFinite {
        /// Child node
        child: Arc<Self>,
        /// Repeat count per axis
        count: [u32; 3],
        /// Spacing between repetitions
        spacing: Vec3,
    },

    /// Perlin noise displacement
    Noise {
        /// Child node
        child: Arc<Self>,
        /// Noise amplitude
        amplitude: f32,
        /// Noise frequency
        frequency: f32,
        /// Random seed
        seed: u32,
    },

    /// Round edges by subtracting radius
    Round {
        /// Child node
        child: Arc<Self>,
        /// Rounding radius
        radius: f32,
    },

    /// Onion: creates a shell with thickness
    Onion {
        /// Child node
        child: Arc<Self>,
        /// Shell thickness
        thickness: f32,
    },

    /// Elongate along an axis
    Elongate {
        /// Child node
        child: Arc<Self>,
        /// Elongation amount per axis
        amount: Vec3,
    },

    /// Mirror along specified axes (takes absolute value of coordinates)
    Mirror {
        /// Child node
        child: Arc<Self>,
        /// Mirror axes (nonzero = mirrored)
        axes: Vec3,
    },

    /// Revolution around Y-axis (creates rotational symmetry)
    Revolution {
        /// Child node
        child: Arc<Self>,
        /// Radial offset
        offset: f32,
    },

    /// Extrude along Z-axis (creates 3D from XY cross-section)
    Extrude {
        /// Child node
        child: Arc<Self>,
        /// Half the extrusion height
        half_height: f32,
    },

    /// Sweep along a quadratic Bezier curve in the XZ plane.
    /// The child SDF is evaluated at (perpendicular_distance, y, 0).
    /// Creates tubes, channels, or any cross-section shape along a curved path.
    SweepBezier {
        /// Child node (2D cross-section, evaluated in XY)
        child: Arc<Self>,
        /// Bezier start point (XZ plane)
        p0: Vec2,
        /// Bezier control point (XZ plane)
        p1: Vec2,
        /// Bezier end point (XZ plane)
        p2: Vec2,
    },

    /// Taper: the child is evaluated at `(x, y, z) / (1 − y·factor)` (a
    /// perspective map with centre `(0, 1/factor, 0)`), and its distance is
    /// turned into a parent-space bound by `real::taper_bound`.
    Taper {
        /// Child node
        child: Arc<Self>,
        /// Taper factor
        factor: f32,
        /// Reach of the child in its own space, `[r_xz, r_y]` (`|q_xz| ≤ r_xz`,
        /// `|q_y| ≤ r_y`), computed by [`SdfNode::taper`] from the child's
        /// AABB. It bounds the parent-space shape by a cone ∩ slab so that the
        /// singular plane `y = 1/factor` is not reported as a surface.
        /// `[INFINITY; 2]` (unbounded child, or a file written before 2.0)
        /// keeps only the Jacobian bound. Must be recomputed
        /// (`SdfNode::taper`) if the child changes.
        #[serde(default = "taper_reach_unknown")]
        reach: [f32; 2],
    },

    /// Sin-based displacement (post-processing modifier)
    Displacement {
        /// Child node
        child: Arc<Self>,
        /// Displacement strength
        strength: f32,
    },

    /// Sin-based displacement with custom amplitude and per-axis frequency
    /// (= Vec3 frequency for anisotropic patterns、 e.g. elongated diamond scales)
    SineDisplacement {
        /// Child node
        child: Arc<Self>,
        /// Displacement amplitude (= strength magnitude)
        amplitude: f32,
        /// Sin wave frequency per axis (= use `Vec3::splat(f)` for isotropic)
        frequency: glam::Vec3,
    },

    /// Polar repetition around Y-axis
    PolarRepeat {
        /// Child node
        child: Arc<Self>,
        /// Number of copies around Y-axis
        count: u32,
    },

    /// Octant mirror: maps point to first octant with x >= y >= z (48-fold symmetry)
    OctantMirror {
        /// Child node
        child: Arc<Self>,
    },

    /// Shear deformation (modifies evaluation point)
    Shear {
        /// Child node
        child: Arc<Self>,
        /// Shear factors: (xy, xz, yz)
        shear: Vec3,
    },

    /// Animated modifier: applies time-based transformation
    Animated {
        /// Child node
        child: Arc<Self>,
        /// Animation speed multiplier
        speed: f32,
        /// Animation amplitude
        amplitude: f32,
    },

    /// Assign a material ID to a subtree (transparent for distance evaluation)
    WithMaterial {
        /// Child node
        child: Arc<Self>,
        /// Material ID (indexes into MaterialLibrary)
        material_id: u32,
    },

    /// Icosahedral symmetry (120-fold) — maps to fundamental domain
    IcosahedralSymmetry {
        /// Child node
        child: Arc<Self>,
    },

    /// Iterated Function System — fractal self-similar folding
    IFS {
        /// Child node
        child: Arc<Self>,
        /// Affine transforms (column-major Mat4)
        transforms: Vec<[f32; 16]>,
        /// Number of iterations
        iterations: u32,
    },

    /// Heightmap displacement — image-based surface perturbation
    HeightmapDisplacement {
        /// Child node
        child: Arc<Self>,
        /// Heightmap data (row-major, grayscale)
        heightmap: Vec<f32>,
        /// Heightmap width
        width: u32,
        /// Heightmap height
        height: u32,
        /// Displacement amplitude
        amplitude: f32,
        /// UV scale
        scale: f32,
    },

    /// Surface roughness — FBM micro-detail noise
    SurfaceRoughness {
        /// Child node
        child: Arc<Self>,
        /// Noise frequency
        frequency: f32,
        /// Noise amplitude
        amplitude: f32,
        /// Number of octaves
        octaves: u32,
    },

    /// Biome terrain — procedural terrain with FBM + Voronoi erosion
    /// Uses radial biome blending (snow, desert, rock, grassland)
    Terrain {
        /// Overall terrain scale (higher = larger terrain features)
        scale: f32,
        /// Vertical amplitude multiplier
        amplitude: f32,
    },
}

impl SdfNode {
    /// Returns the category of this node variant
    pub const fn category(&self) -> SdfCategory {
        match self {
            // === Primitives ===
            Self::Sphere { .. }
            | Self::Box3d { .. }
            | Self::Cylinder { .. }
            | Self::Torus { .. }
            | Self::Plane { .. }
            | Self::Capsule { .. }
            | Self::Cone { .. }
            | Self::Ellipsoid { .. }
            | Self::RoundedCone { .. }
            | Self::Pyramid { .. }
            | Self::Octahedron { .. }
            | Self::HexPrism { .. }
            | Self::Link { .. }
            | Self::Triangle { .. }
            | Self::Bezier { .. }
            | Self::RoundedBox { .. }
            | Self::CappedCone { .. }
            | Self::CappedTorus { .. }
            | Self::RoundedCylinder { .. }
            | Self::TriangularPrism { .. }
            | Self::CutSphere { .. }
            | Self::CutHollowSphere { .. }
            | Self::DeathStar { .. }
            | Self::SolidAngle { .. }
            | Self::Rhombus { .. }
            | Self::Horseshoe { .. }
            | Self::Vesica { .. }
            | Self::InfiniteCylinder { .. }
            | Self::InfiniteCone { .. }
            | Self::Gyroid { .. }
            | Self::MetricBall { .. }
            | Self::Heart { .. }
            | Self::Tube { .. }
            | Self::Barrel { .. }
            | Self::Diamond { .. }
            | Self::ChamferedCube { .. }
            | Self::SchwarzP { .. }
            | Self::Superellipsoid { .. }
            | Self::RoundedX { .. }
            | Self::Pie { .. }
            | Self::Trapezoid { .. }
            | Self::Parallelogram { .. }
            | Self::Tunnel { .. }
            | Self::UnevenCapsule { .. }
            | Self::Egg { .. }
            | Self::ArcShape { .. }
            | Self::Moon { .. }
            | Self::CrossShape { .. }
            | Self::BlobbyCross { .. }
            | Self::ParabolaSegment { .. }
            | Self::RegularPolygon { .. }
            | Self::StarPolygon { .. }
            | Self::Stairs { .. }
            | Self::Helix { .. }
            | Self::Tetrahedron { .. }
            | Self::Dodecahedron { .. }
            | Self::Icosahedron { .. }
            | Self::TruncatedOctahedron { .. }
            | Self::TruncatedIcosahedron { .. }
            | Self::BoxFrame { .. }
            | Self::DiamondSurface { .. }
            | Self::Neovius { .. }
            | Self::Lidinoid { .. }
            | Self::IWP { .. }
            | Self::FRD { .. }
            | Self::FischerKochS { .. }
            | Self::PMY { .. }
            | Self::Circle2D { .. }
            | Self::Rect2D { .. }
            | Self::Segment2D { .. }
            | Self::Polygon2D { .. }
            | Self::RoundedRect2D { .. }
            | Self::Annular2D { .. }
            | Self::Terrain { .. } => SdfCategory::Primitive,

            // === Operations ===
            Self::Union { .. }
            | Self::MetricBlend { .. }
            | Self::Intersection { .. }
            | Self::Subtraction { .. }
            | Self::SmoothUnion { .. }
            | Self::SmoothIntersection { .. }
            | Self::SmoothSubtraction { .. }
            | Self::ChamferUnion { .. }
            | Self::ChamferIntersection { .. }
            | Self::ChamferSubtraction { .. }
            | Self::StairsUnion { .. }
            | Self::StairsIntersection { .. }
            | Self::StairsSubtraction { .. }
            | Self::XOR { .. }
            | Self::Morph { .. }
            | Self::ColumnsUnion { .. }
            | Self::ColumnsIntersection { .. }
            | Self::ColumnsSubtraction { .. }
            | Self::Pipe { .. }
            | Self::Engrave { .. }
            | Self::Groove { .. }
            | Self::Tongue { .. }
            | Self::ExpSmoothUnion { .. }
            | Self::ExpSmoothIntersection { .. }
            | Self::ExpSmoothSubtraction { .. } => SdfCategory::Operation,

            // === Transforms ===
            Self::Translate { .. }
            | Self::Rotate { .. }
            | Self::Scale { .. }
            | Self::ScaleNonUniform { .. }
            | Self::ProjectiveTransform { .. }
            | Self::LatticeDeform { .. }
            | Self::SdfSkinning { .. } => SdfCategory::Transform,

            // === Modifiers ===
            Self::Twist { .. }
            | Self::Bend { .. }
            | Self::RepeatInfinite { .. }
            | Self::RepeatFinite { .. }
            | Self::Noise { .. }
            | Self::Round { .. }
            | Self::Onion { .. }
            | Self::Elongate { .. }
            | Self::Mirror { .. }
            | Self::Revolution { .. }
            | Self::Extrude { .. }
            | Self::SweepBezier { .. }
            | Self::Taper { .. }
            | Self::Displacement { .. }
            | Self::SineDisplacement { .. }
            | Self::PolarRepeat { .. }
            | Self::OctantMirror { .. }
            | Self::Shear { .. }
            | Self::Animated { .. }
            | Self::WithMaterial { .. }
            | Self::IcosahedralSymmetry { .. }
            | Self::IFS { .. }
            | Self::HeightmapDisplacement { .. }
            | Self::SurfaceRoughness { .. } => SdfCategory::Modifier,
        }
    }

    /// Count total nodes in the tree
    pub fn node_count(&self) -> u32 {
        match self {
            // Primitives: 1 node
            Self::Sphere { .. }
            | Self::Box3d { .. }
            | Self::Cylinder { .. }
            | Self::Torus { .. }
            | Self::Plane { .. }
            | Self::Capsule { .. }
            | Self::Cone { .. }
            | Self::Ellipsoid { .. }
            | Self::RoundedCone { .. }
            | Self::Pyramid { .. }
            | Self::Octahedron { .. }
            | Self::HexPrism { .. }
            | Self::Link { .. }
            | Self::Triangle { .. }
            | Self::Bezier { .. }
            | Self::RoundedBox { .. }
            | Self::CappedCone { .. }
            | Self::CappedTorus { .. }
            | Self::RoundedCylinder { .. }
            | Self::TriangularPrism { .. }
            | Self::CutSphere { .. }
            | Self::CutHollowSphere { .. }
            | Self::DeathStar { .. }
            | Self::SolidAngle { .. }
            | Self::Rhombus { .. }
            | Self::Horseshoe { .. }
            | Self::Vesica { .. }
            | Self::InfiniteCylinder { .. }
            | Self::InfiniteCone { .. }
            | Self::Gyroid { .. }
            | Self::Heart { .. }
            | Self::Tube { .. }
            | Self::Barrel { .. }
            | Self::Diamond { .. }
            | Self::ChamferedCube { .. }
            | Self::SchwarzP { .. }
            | Self::Superellipsoid { .. }
            | Self::RoundedX { .. }
            | Self::Pie { .. }
            | Self::Trapezoid { .. }
            | Self::Parallelogram { .. }
            | Self::Tunnel { .. }
            | Self::UnevenCapsule { .. }
            | Self::Egg { .. }
            | Self::ArcShape { .. }
            | Self::Moon { .. }
            | Self::CrossShape { .. }
            | Self::BlobbyCross { .. }
            | Self::ParabolaSegment { .. }
            | Self::RegularPolygon { .. }
            | Self::StarPolygon { .. }
            | Self::Stairs { .. }
            | Self::Helix { .. }
            | Self::Tetrahedron { .. }
            | Self::Dodecahedron { .. }
            | Self::Icosahedron { .. }
            | Self::TruncatedOctahedron { .. }
            | Self::TruncatedIcosahedron { .. }
            | Self::BoxFrame { .. }
            | Self::DiamondSurface { .. }
            | Self::Neovius { .. }
            | Self::Lidinoid { .. }
            | Self::IWP { .. }
            | Self::FRD { .. }
            | Self::FischerKochS { .. }
            | Self::PMY { .. }
            | Self::Terrain { .. } => 1,

            // Operations: 1 + children
            Self::Union { a, b }
            | Self::Intersection { a, b }
            | Self::Subtraction { a, b }
            | Self::SmoothUnion { a, b, .. }
            | Self::SmoothIntersection { a, b, .. }
            | Self::SmoothSubtraction { a, b, .. }
            | Self::ChamferUnion { a, b, .. }
            | Self::ChamferIntersection { a, b, .. }
            | Self::ChamferSubtraction { a, b, .. }
            | Self::StairsUnion { a, b, .. }
            | Self::StairsIntersection { a, b, .. }
            | Self::StairsSubtraction { a, b, .. }
            | Self::XOR { a, b }
            | Self::Morph { a, b, .. }
            | Self::ColumnsUnion { a, b, .. }
            | Self::ColumnsIntersection { a, b, .. }
            | Self::ColumnsSubtraction { a, b, .. }
            | Self::ExpSmoothUnion { a, b, .. }
            | Self::ExpSmoothIntersection { a, b, .. }
            | Self::ExpSmoothSubtraction { a, b, .. }
            | Self::Pipe { a, b, .. }
            | Self::Engrave { a, b, .. }
            | Self::Groove { a, b, .. }
            | Self::Tongue { a, b, .. } => 1 + a.node_count() + b.node_count(),

            // Transforms and modifiers: 1 + child
            Self::Translate { child, .. }
            | Self::Rotate { child, .. }
            | Self::Scale { child, .. }
            | Self::ScaleNonUniform { child, .. }
            | Self::ProjectiveTransform { child, .. }
            | Self::LatticeDeform { child, .. }
            | Self::SdfSkinning { child, .. }
            | Self::Twist { child, .. }
            | Self::Bend { child, .. }
            | Self::RepeatInfinite { child, .. }
            | Self::RepeatFinite { child, .. }
            | Self::Noise { child, .. }
            | Self::Round { child, .. }
            | Self::Onion { child, .. }
            | Self::Elongate { child, .. }
            | Self::Mirror { child, .. }
            | Self::Revolution { child, .. }
            | Self::Extrude { child, .. }
            | Self::SweepBezier { child, .. }
            | Self::Taper { child, .. }
            | Self::Displacement { child, .. }
            | Self::SineDisplacement { child, .. }
            | Self::PolarRepeat { child, .. }
            | Self::OctantMirror { child, .. }
            | Self::Shear { child, .. }
            | Self::Animated { child, .. }
            | Self::WithMaterial { child, .. }
            | Self::IcosahedralSymmetry { child, .. }
            | Self::IFS { child, .. }
            | Self::HeightmapDisplacement { child, .. }
            | Self::SurfaceRoughness { child, .. } => 1 + child.node_count(),

            Self::MetricBlend { inner, outer, .. } => 1 + inner.node_count() + outer.node_count(),

            #[allow(unreachable_patterns)]
            _ => 1,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_sphere_creation() {
        let sphere = SdfNode::sphere(1.0);
        assert_eq!(sphere.node_count(), 1);
    }

    #[test]
    fn test_union() {
        let a = SdfNode::sphere(1.0);
        let b = SdfNode::box3d(2.0, 2.0, 2.0);
        let union = a.union(b);
        assert_eq!(union.node_count(), 3);
    }

    #[test]
    fn test_transform_chain() {
        let shape = SdfNode::sphere(1.0)
            .translate(1.0, 0.0, 0.0)
            .rotate_euler(0.0, std::f32::consts::PI, 0.0)
            .scale(2.0);
        assert_eq!(shape.node_count(), 4);
    }

    #[test]
    fn test_category_primitive() {
        assert_eq!(SdfNode::sphere(1.0).category(), SdfCategory::Primitive);
        assert_eq!(
            SdfNode::box3d(1.0, 1.0, 1.0).category(),
            SdfCategory::Primitive
        );
        assert_eq!(
            SdfNode::cylinder(0.5, 1.0).category(),
            SdfCategory::Primitive
        );
        assert_eq!(SdfNode::torus(1.0, 0.3).category(), SdfCategory::Primitive);
    }

    #[test]
    fn test_category_operation() {
        let u = SdfNode::sphere(1.0).union(SdfNode::box3d(1.0, 1.0, 1.0));
        assert_eq!(u.category(), SdfCategory::Operation);
        let s = SdfNode::sphere(1.0).smooth_union(SdfNode::box3d(1.0, 1.0, 1.0), 0.2);
        assert_eq!(s.category(), SdfCategory::Operation);
    }

    #[test]
    fn test_category_transform() {
        let t = SdfNode::sphere(1.0).translate(1.0, 0.0, 0.0);
        assert_eq!(t.category(), SdfCategory::Transform);
        let r = SdfNode::sphere(1.0).rotate_euler(0.0, 1.0, 0.0);
        assert_eq!(r.category(), SdfCategory::Transform);
        let s = SdfNode::sphere(1.0).scale(2.0);
        assert_eq!(s.category(), SdfCategory::Transform);
    }

    #[test]
    fn test_category_modifier() {
        let t = SdfNode::sphere(1.0).twist(0.5);
        assert_eq!(t.category(), SdfCategory::Modifier);
        let b = SdfNode::sphere(1.0).bend(0.3);
        assert_eq!(b.category(), SdfCategory::Modifier);
    }

    #[test]
    fn test_category_total() {
        assert_eq!(SdfCategory::total(), 130);
    }

    #[test]
    fn test_node_count_leaf() {
        assert_eq!(SdfNode::sphere(1.0).node_count(), 1);
        assert_eq!(SdfNode::box3d(1.0, 1.0, 1.0).node_count(), 1);
        assert_eq!(SdfNode::torus(1.0, 0.3).node_count(), 1);
    }

    #[test]
    fn test_node_count_deep_tree() {
        let tree = SdfNode::sphere(1.0)
            .union(SdfNode::box3d(1.0, 1.0, 1.0))
            .translate(1.0, 0.0, 0.0)
            .scale(2.0)
            .twist(0.5);
        assert_eq!(tree.node_count(), 6); // sphere + box + union + translate + scale + twist
    }

    #[test]
    fn test_clone_equivalence() {
        let a = SdfNode::sphere(1.0).smooth_union(SdfNode::box3d(1.0, 1.0, 1.0), 0.2);
        let b = a.clone();
        assert_eq!(format!("{:?}", a), format!("{:?}", b));
    }

    #[test]
    fn test_sdf_tree_creation() {
        let node = SdfNode::sphere(1.0).union(SdfNode::box3d(1.0, 1.0, 1.0));
        let tree = SdfTree::new(node);
        assert!(tree.node_count() >= 3);
    }

    #[test]
    fn test_node_count_operations() {
        let xor = SdfNode::sphere(1.0).xor(SdfNode::box3d(1.0, 1.0, 1.0));
        assert_eq!(xor.node_count(), 3);
        let morph = SdfNode::sphere(1.0).morph(SdfNode::box3d(1.0, 1.0, 1.0), 0.5);
        assert_eq!(morph.node_count(), 3);
    }
}