symbios-shape 0.4.0

A derivation engine for CGA Shape Grammars.
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
use serde::{Deserialize, Serialize};

use crate::expr::Expr;
use crate::model::Material;
use crate::scope::Vec3;

/// A reference to a production rule, optionally carrying call arguments.
///
/// Every successor position in the grammar — bare rule ops, split slots,
/// `Comp` / `Offset` / `Roof` / `Attach` cases, occlusion conditionals — is a
/// `RuleCall`. Arguments are expressions evaluated in the *calling* shape's
/// context at push time; the callee binds the resulting values to its
/// declared parameter names (see `Interpreter::add_rule_def`).
///
/// ```text
/// Spire(4)                       // bare call with one argument
/// Split(Y) { 3: Base | ~1: Tier(depth + 1) }
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RuleCall {
    pub name: String,
    /// Call arguments; empty for plain references. Skipped in serde when
    /// empty so pre-0.3 serialized ops round-trip unchanged.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub args: Vec<Expr>,
}

impl RuleCall {
    /// Plain, argument-less reference.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            args: Vec::new(),
        }
    }

    /// Reference with call arguments.
    pub fn with_args(name: impl Into<String>, args: Vec<Expr>) -> Self {
        Self {
            name: name.into(),
            args,
        }
    }
}

impl From<&str> for RuleCall {
    fn from(name: &str) -> Self {
        Self::new(name)
    }
}

/// Argument-less calls compare equal to their bare name — keeps assertions
/// and look-ups terse (`assert_eq!(slot.rule, "Floor")`). A call *with*
/// arguments never equals a bare name.
impl PartialEq<&str> for RuleCall {
    fn eq(&self, other: &&str) -> bool {
        self.args.is_empty() && self.name == *other
    }
}

impl PartialEq<str> for RuleCall {
    fn eq(&self, other: &str) -> bool {
        self.args.is_empty() && self.name == other
    }
}

impl From<String> for RuleCall {
    fn from(name: String) -> Self {
        Self::new(name)
    }
}

/// Optional snap-binding attached to a `Split` op.
///
/// When set, after the slot sizes are resolved the interior boundaries are
/// snapped to the nearest registered snap-plane along the split axis carrying
/// the matching `label`, provided the snap-plane lies within `tolerance`
/// world-space units of the resolved boundary. Slots on either side of a
/// snapped boundary stretch / shrink to absorb the offset; total scope
/// length is preserved.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SnapBinding {
    /// Group label of snap-planes to align to (matches `RegSnap("label")`).
    pub label: String,
    /// Maximum world-space distance between a slot boundary and a snap-plane
    /// for the snap to apply. When `None`, defaults to `5%` of the split-axis
    /// scope length at interpret time.
    pub tolerance: Option<f64>,
}

/// The axis along which a `Split` or `Repeat` operation acts.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Axis {
    X,
    Y,
    Z,
}

/// Sizing mode for a single slot within a `Split` operation.
///
/// Mirrors CityEngine CGA syntax:
/// - `Absolute(e)`: a fixed world-unit size.
/// - `Relative(e)`: a fraction of the scope's total dimension (prefix `'` in CGA text).
/// - `Floating(e)`: a weight that shares the remaining space after absolutes are consumed
///   (prefix `~` in CGA text). Multiple floating slots divide the remainder proportionally.
///
/// Sizes are [`Expr`]s evaluated per shape at derivation time; validation
/// (finite, positive) happens on the evaluated value in the interpreter.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum SplitSize {
    Absolute(Expr),
    Relative(Expr),
    Floating(Expr),
}

impl SplitSize {
    /// Convenience constructors for literal sizes (tests, programmatic use).
    pub fn abs(v: f64) -> Self {
        SplitSize::Absolute(Expr::lit(v))
    }
    pub fn rel(v: f64) -> Self {
        SplitSize::Relative(Expr::lit(v))
    }
    pub fn float(v: f64) -> Self {
        SplitSize::Floating(Expr::lit(v))
    }

    /// The size expression, whatever the mode.
    pub fn expr(&self) -> &Expr {
        match self {
            SplitSize::Absolute(e) | SplitSize::Relative(e) | SplitSize::Floating(e) => e,
        }
    }

    /// Mutable access to the size expression (genetics mutation hook).
    pub fn expr_mut(&mut self) -> &mut Expr {
        match self {
            SplitSize::Absolute(e) | SplitSize::Relative(e) | SplitSize::Floating(e) => e,
        }
    }
}

/// A single slot in a `Split` operation: a size mode paired with a successor rule call.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SplitSlot {
    pub size: SplitSize,
    /// The shape rule invoked on the resulting child scope.
    pub rule: RuleCall,
}

/// One entry in a `Split` body: a single slot, or a rhythm group
/// `{ a | b }*` whose slot pattern repeats to fill the space left by the
/// entries outside it.
///
/// ```text
/// Split(X) { 1.2: Corner | { 0.5: Pier | ~1: Win }* | 1.2: Corner }
/// ```
///
/// Constraints (enforced at parse / derivation): at most **one** group per
/// split, no nested groups. Allocation: fixed entries outside the group are
/// placed first; the group tiles `k` whole copies of its nominal width into
/// the remainder; leftover space goes to floating slots outside the group,
/// or — when there are none — the copies stretch uniformly to close the gap
/// exactly. Sizes inside a copy resolve like a mini-split of the copy width.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum SplitEntry {
    Slot(SplitSlot),
    Group(Vec<SplitSlot>),
}

impl SplitEntry {
    /// The single slot, when this entry is not a group.
    pub fn as_slot(&self) -> Option<&SplitSlot> {
        match self {
            SplitEntry::Slot(s) => Some(s),
            SplitEntry::Group(_) => None,
        }
    }
}

impl From<SplitSlot> for SplitEntry {
    fn from(s: SplitSlot) -> Self {
        SplitEntry::Slot(s)
    }
}

/// Face selectors for the `Comp(Faces)` decomposition.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum FaceSelector {
    Top,
    Bottom,
    Front,
    Back,
    Left,
    Right,
    /// Matches all non-top, non-bottom faces (shorthand for the four sides).
    Side,
    /// Matches all faces not otherwise mapped.
    All,
}

impl FaceSelector {
    pub fn parse(s: &str) -> Option<Self> {
        match s {
            "top" | "Top" => Some(Self::Top),
            "bottom" | "Bottom" => Some(Self::Bottom),
            "front" | "Front" => Some(Self::Front),
            "back" | "Back" => Some(Self::Back),
            "left" | "Left" => Some(Self::Left),
            "right" | "Right" => Some(Self::Right),
            "side" | "Side" => Some(Self::Side),
            "all" | "All" | "_" => Some(Self::All),
            _ => None,
        }
    }
}

/// A single mapping in a `Comp(Faces)` block: a face selector → rule name.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CompFaceCase {
    pub selector: FaceSelector,
    pub rule: RuleCall,
}

/// Edge-class selectors for the `Comp(Edges)` decomposition.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum EdgeSelector {
    /// Vertical edges: a volume's four corner posts; a face's left/right rim.
    Vertical,
    /// All horizontal edges (both rings on a volume; top+bottom on a face).
    Horizontal,
    /// The top horizontal ring / edge only.
    Top,
    /// The bottom horizontal ring / edge only.
    Bottom,
    /// Matches all edges not otherwise mapped.
    All,
}

impl EdgeSelector {
    pub fn parse(s: &str) -> Option<Self> {
        match s {
            "vertical" | "Vertical" => Some(Self::Vertical),
            "horizontal" | "Horizontal" => Some(Self::Horizontal),
            "top" | "Top" => Some(Self::Top),
            "bottom" | "Bottom" => Some(Self::Bottom),
            "all" | "All" | "_" => Some(Self::All),
            _ => None,
        }
    }
}

/// A single mapping in a `Comp(Edges)` block: an edge selector → rule call.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CompEdgeCase {
    pub selector: EdgeSelector,
    pub rule: RuleCall,
}

/// The decomposition target for a `Comp` operation.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum CompTarget {
    /// Decomposes the volume into its six axis-aligned face scopes.
    Faces(Vec<CompFaceCase>),
    /// Decomposes into zero-cross-section edge scopes: 12 for a volume,
    /// 4 for a face. Local X runs along the edge; give the scope thickness
    /// with `Size(scope.x, t, t)` and centre it with `Translate`.
    Edges(Vec<CompEdgeCase>),
}

/// Face selectors for the `Offset` operation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum OffsetSelector {
    /// The inset/outset region (the area inside the border).
    Inside,
    /// The surrounding border strips.
    Border,
    /// Matches any selector not otherwise mapped.
    All,
}

impl OffsetSelector {
    pub fn parse(s: &str) -> Option<Self> {
        match s {
            "inside" | "Inside" => Some(Self::Inside),
            "border" | "Border" => Some(Self::Border),
            "all" | "All" | "_" => Some(Self::All),
            _ => None,
        }
    }
}

/// A single mapping in an `Offset` block: a selector → rule name.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct OffsetCase {
    pub selector: OffsetSelector,
    pub rule: RuleCall,
}

/// Roof shape types for the `Roof` operation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum RoofType {
    // ── Original types ────────────────────────────────────────────────────────
    /// Four triangular slope panels meeting at a single apex.
    Pyramid,
    /// Single slope panel from front eave to back eave.
    Shed,
    /// Two slope panels meeting at a horizontal ridge; two triangular gable ends.
    Gable,
    /// Four trapezoidal slope panels meeting at a horizontal ridge.
    Hip,

    // ── New types ─────────────────────────────────────────────────────────────
    /// Flat horizontal roof — a single horizontal panel covering the scope top.
    Flat,
    /// Two rectangular slope panels only (Gable without the triangular end panels).
    OpenGable,
    /// Two slope panels + two rectangular (non-tapered) gable-end wall panels.
    BoxGable,
    /// Four panels from a rectangular base meeting at a single apex point (no ridge).
    /// Equivalent to `Pyramid` for square footprints; left/right end panels are triangular.
    PyramidHip,
    /// Two inward-tilting slopes forming a central valley (inverted Gable).
    Butterfly,
    /// Four panels forming two parallel ridges with a central valley between them (M profile).
    MShaped,
    /// Two pitches per slope: steeper lower zone + shallower upper zone (barn roof).
    /// Requires `secondary_pitch` in `RoofConfig`.
    Gambrel,
    /// Gambrel applied to all four sides: 4 steep lower panels + 4 shallow upper panels.
    /// Requires `secondary_pitch` in `RoofConfig`.
    Mansard,
    /// Asymmetric Gable: the ridge is offset toward one end (`ridge_offset` in `RoofConfig`).
    /// Front slope is steeper; back slope is shallower. Gable ends are asymmetric triangles.
    Saltbox,
    /// Gable with clipped hip ends: the upper corners of each gable end are replaced by
    /// small triangular hip panels. Controlled by `tier_height` in `RoofConfig`.
    Jerkinhead,
    /// Hip roof with a small gable rising from the ridge centre.
    /// Controlled by `tier_height` (fraction of slope from base where the gable starts).
    DutchGable,
}

impl RoofType {
    pub fn parse(s: &str) -> Option<Self> {
        match s {
            "pyramid" | "Pyramid" => Some(Self::Pyramid),
            "shed" | "Shed" => Some(Self::Shed),
            "gable" | "Gable" => Some(Self::Gable),
            "hip" | "Hip" => Some(Self::Hip),
            "flat" | "Flat" => Some(Self::Flat),
            "openGable" | "OpenGable" => Some(Self::OpenGable),
            "boxGable" | "BoxGable" => Some(Self::BoxGable),
            "pyramidHip" | "PyramidHip" => Some(Self::PyramidHip),
            "butterfly" | "Butterfly" => Some(Self::Butterfly),
            "mShaped" | "MShaped" => Some(Self::MShaped),
            "gambrel" | "Gambrel" => Some(Self::Gambrel),
            "mansard" | "Mansard" => Some(Self::Mansard),
            "saltbox" | "Saltbox" => Some(Self::Saltbox),
            "jerkinhead" | "Jerkinhead" => Some(Self::Jerkinhead),
            "dutchGable" | "DutchGable" => Some(Self::DutchGable),
            _ => None,
        }
    }
}

/// Face selectors for the `Roof` operation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum RoofFaceSelector {
    /// The main sloped panel(s) — front/back in most roof types.
    Slope,
    /// The triangular vertical end panels of a Gable or Saltbox roof.
    GableEnd,
    /// The steeper, lower zone of a Gambrel or Mansard roof.
    LowerSlope,
    /// The shallower, upper zone of a Gambrel or Mansard roof.
    UpperSlope,
    /// The small triangular hip panels at the clipped ends of a Jerkinhead roof.
    HipEnd,
    /// The inward-facing slopes of a Butterfly or MShaped valley.
    ValleySlope,
    /// The outer slopes of an MShaped roof (facing away from the valley).
    OuterSlope,
    /// The inner slopes of an MShaped roof (facing toward the valley).
    InnerSlope,
    /// The vertical back wall of a `Shed` roof — the raised face under the
    /// high eave (the glazed "northlight" of a sawtooth factory profile).
    Back,
    /// Vertical fascia bands hanging below the eaves.
    /// Generated when [`RoofConfig::fascia_depth`] is `> 0`. One panel per perimeter
    /// slope eave; supported for all roof types whose slope panels share a horizontal
    /// eave at the perimeter (Gable, Hip, Pyramid, Shed, Saltbox, Jerkinhead, DutchGable,
    /// Gambrel, Mansard, MShaped, BoxGable, OpenGable, PyramidHip). `Flat` and `Butterfly`
    /// have no perimeter eave at the slope-panel level and produce no fascia panels.
    Fascia,
    /// Matches any selector not otherwise mapped.
    All,
}

impl RoofFaceSelector {
    pub fn parse(s: &str) -> Option<Self> {
        match s {
            "slope" | "Slope" => Some(Self::Slope),
            "gable" | "GableEnd" | "gableEnd" => Some(Self::GableEnd),
            "lowerSlope" | "LowerSlope" => Some(Self::LowerSlope),
            "upperSlope" | "UpperSlope" => Some(Self::UpperSlope),
            "hipEnd" | "HipEnd" => Some(Self::HipEnd),
            "valleySlope" | "ValleySlope" => Some(Self::ValleySlope),
            "outerSlope" | "OuterSlope" => Some(Self::OuterSlope),
            "innerSlope" | "InnerSlope" => Some(Self::InnerSlope),
            "back" | "Back" => Some(Self::Back),
            "fascia" | "Fascia" => Some(Self::Fascia),
            "all" | "All" | "_" => Some(Self::All),
            _ => None,
        }
    }
}

/// A single mapping in a `Roof` block: a face selector → rule name.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RoofCase {
    pub selector: RoofFaceSelector,
    pub rule: RuleCall,
}

/// Rich parametric configuration for the `Roof` operation.
///
/// All angular values are in degrees. Lengths are in world units.
/// Optional fields default as described; see each field doc.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RoofConfig {
    pub roof_type: RoofType,
    /// Primary pitch angle in degrees from horizontal. Must be in (0°, 90°).
    pub pitch: f64,
    /// Secondary pitch angle in degrees. Used by `Gambrel` (upper zone) and `Mansard`.
    /// If `None` when required, defaults to `pitch / 2`.
    pub secondary_pitch: Option<f64>,
    /// Extra overhang beyond the scope footprint on each side. Default `0.0`.
    pub overhang: f64,
    /// Ridge offset for `Saltbox`: fraction [0, 1] of the scope depth (Z) where the
    /// ridge is positioned from the front. Default `0.5` (symmetric / centred ridge).
    pub ridge_offset: f64,
    /// Thickness of the roof fascia edge in world units. Default `0.0` (flat panels).
    pub fascia_depth: f64,
    /// Normalised tier parameter for `Gambrel`, `Mansard`, `Jerkinhead`, and
    /// `DutchGable`. For the pitch-break types (`Gambrel`, `Mansard`,
    /// `DutchGable`) it is the height at which the break occurs: `0.5` means
    /// the break is at half the eave-to-ridge distance. For `Jerkinhead` it
    /// is the **fraction of the half-depth that is clipped**: `0.25` clips a
    /// quarter of each gable end into a hip-let, and larger values clip
    /// more. `None` uses a type-specific default.
    pub tier_height: Option<f64>,
}

impl RoofConfig {
    /// Creates a minimal config for deterministic types (Pyramid, Shed, Gable, Hip, Flat, …).
    pub fn new(roof_type: RoofType, pitch: f64) -> Self {
        Self {
            roof_type,
            pitch,
            secondary_pitch: None,
            overhang: 0.0,
            ridge_offset: 0.5,
            fascia_depth: 0.0,
            tier_height: None,
        }
    }

    /// Returns the secondary pitch, defaulting to `pitch / 2` if unset.
    pub fn secondary_pitch_or_default(&self) -> f64 {
        self.secondary_pitch.unwrap_or(self.pitch / 2.0)
    }

    /// Returns the tier height, defaulting to `default` if unset.
    pub fn tier_height_or(&self, default: f64) -> f64 {
        self.tier_height.unwrap_or(default)
    }
}

/// Expression-valued roof parameters as they appear in the grammar.
///
/// The interpreter evaluates every field against the current shape's context
/// and produces a resolved [`RoofConfig`] for the geometry builder. `pitch`
/// and `height` are mutually exclusive ways to set the roof's steepness:
/// when `height` is `Some`, the pitch is derived from it and the scope's
/// half-span at derivation time (CGA `byHeight` parity), letting mixed-width
/// wings share one ridge line.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RoofSpec {
    pub roof_type: RoofType,
    /// Primary pitch angle in degrees, exclusive range (0°, 90°). Ignored
    /// when `height` is set.
    pub pitch: Expr,
    /// Absolute roof rise in world units (`height=` named arg). Overrides
    /// `pitch` when present.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub height: Option<Expr>,
    /// Secondary pitch in degrees for `Gambrel` / `Mansard`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub secondary_pitch: Option<Expr>,
    /// Eave overhang beyond the footprint, world units. Default `0`.
    pub overhang: Expr,
    /// Ridge offset fraction for `Saltbox`. Default `0.5`.
    pub ridge_offset: Expr,
    /// Fascia band depth below each perimeter eave. Default `0`.
    pub fascia_depth: Expr,
    /// Pitch-break height fraction for tiered types.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tier_height: Option<Expr>,
    /// Forces the ridge to run along the given scope axis (`ridge=X` /
    /// `ridge=Z`), overriding the default longest-axis heuristic.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ridge_axis: Option<Axis>,
}

/// Wraps every numeric field of a resolved config back into literal
/// expressions — the programmatic bridge for builders that think in numbers.
impl From<RoofConfig> for RoofSpec {
    fn from(c: RoofConfig) -> Self {
        Self {
            roof_type: c.roof_type,
            pitch: Expr::lit(c.pitch),
            height: None,
            secondary_pitch: c.secondary_pitch.map(Expr::lit),
            overhang: Expr::lit(c.overhang),
            ridge_offset: Expr::lit(c.ridge_offset),
            fascia_depth: Expr::lit(c.fascia_depth),
            tier_height: c.tier_height.map(Expr::lit),
            ridge_axis: None,
        }
    }
}

impl RoofSpec {
    /// Literal spec with defaults matching `RoofConfig::new` — the
    /// programmatic construction path for tests and builders.
    pub fn new(roof_type: RoofType, pitch: f64) -> Self {
        Self {
            roof_type,
            pitch: Expr::lit(pitch),
            height: None,
            secondary_pitch: None,
            overhang: Expr::lit(0.0),
            ridge_offset: Expr::lit(0.5),
            fascia_depth: Expr::lit(0.0),
            tier_height: None,
            ridge_axis: None,
        }
    }
}

/// Selector for the `Attach` operation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum AttachSelector {
    /// The projected scope that sits on (or comes out of) the surface.
    Surface,
    /// Matches any selector not otherwise mapped.
    All,
}

impl AttachSelector {
    pub fn parse(s: &str) -> Option<Self> {
        match s {
            "surface" | "Surface" => Some(Self::Surface),
            "all" | "All" | "_" => Some(Self::All),
            _ => None,
        }
    }
}

/// A single mapping in an `Attach` block: a selector → rule name.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AttachCase {
    pub selector: AttachSelector,
    pub rule: RuleCall,
}

/// How one variant of a rule is selected during derivation.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum VariantSelector {
    /// Stochastic: relative weight among the rule's weighted variants
    /// (`70% ops | 30% ops`). Weights need not sum to 1.
    Weight(f64),
    /// Guarded: taken when the expression evaluates non-zero, top-down
    /// (`when(scope.x < 4): ops`). A guarded rule's variants are evaluated
    /// in order; the first true guard wins.
    When(Expr),
    /// Fallback for a guarded rule (`else: ops`); must be last. In weighted
    /// rules `else:` is parse-time sugar resolved into a `Weight` of the
    /// remaining probability mass, so it never reaches the interpreter.
    Else,
}

/// One alternative in a rule: how it is selected, and what it does.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RuleVariant {
    pub selector: VariantSelector,
    pub ops: Vec<ShapeOp>,
}

impl RuleVariant {
    /// Weighted variant — the pre-0.3 shape.
    pub fn weighted(weight: f64, ops: Vec<ShapeOp>) -> Self {
        Self {
            selector: VariantSelector::Weight(weight),
            ops,
        }
    }

    /// The stochastic weight, when this variant is weighted.
    pub fn weight(&self) -> Option<f64> {
        match self.selector {
            VariantSelector::Weight(w) => Some(w),
            _ => None,
        }
    }
}

/// Region selectors for the `ShapeL` / `ShapeU` footprint-carving ops.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum CarveSelector {
    /// The carved letter shape. `ShapeL` delivers it as TWO rectangular
    /// scopes (front bar + side leg), `ShapeU` as three — OBB purity means a
    /// letter footprint is a set of boxes, never one polygon.
    Shape,
    /// The rectangular remainder cut away from the letter.
    Remainder,
    /// Matches any selector not otherwise mapped.
    All,
}

impl CarveSelector {
    pub fn parse(s: &str) -> Option<Self> {
        match s {
            "shape" | "Shape" => Some(Self::Shape),
            "remainder" | "Remainder" | "rest" | "Rest" => Some(Self::Remainder),
            "all" | "All" | "_" => Some(Self::All),
            _ => None,
        }
    }
}

/// A single mapping in a `ShapeL` / `ShapeU` block: selector → rule call.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CarveCase {
    pub selector: CarveSelector,
    pub rule: RuleCall,
}

/// One candidate in a `Fit` op: the minimum extent it needs, and the rule
/// invoked on the whole scope when it is the first that fits.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FitCandidate {
    pub min_size: Expr,
    pub rule: RuleCall,
}

/// The atomic CGA operations that the interpreter executes.
///
/// Every operation transforms the current `Scope` into zero or more child scopes,
/// each tagged with a rule name that will be recursively evaluated.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ShapeOp {
    /// Lifts a 2-D footprint (XZ plane) into a 3-D volume by setting the Y size.
    Extrude(Expr),

    /// Pyramidal taper: scales the top face toward the centroid.
    /// `amount` ∈ `[0, 1]`: 0 = no taper, 1 = full pyramid (top collapses to a point).
    Taper(Expr),

    /// Applies an additional rotation to the scope (cumulative with existing rotation).
    /// Components are `(w, x, y, z)` in grammar order; the evaluated quaternion
    /// is normalized at derivation time.
    Rotate([Expr; 4]),

    /// Translates the scope origin in local space.
    Translate([Expr; 3]),

    /// Scales the scope size along each axis (multiplicative).
    Scale([Expr; 3]),

    /// Divides the scope along `axis` into ordered slots.
    ///
    /// When `snap` is `Some`, interior slot boundaries are snapped to the
    /// nearest registered snap-plane along `axis` (see [`SnapBinding`]).
    Split {
        axis: Axis,
        entries: Vec<SplitEntry>,
        snap: Option<SnapBinding>,
    },

    /// Divides the scope along `axis` by *target areas* instead of lengths.
    ///
    /// Slot sizes are read as areas: absolute = square units, relative (`'`)
    /// = fraction of the face area, floating (`~`) = share of the remaining
    /// area. Lengths are recovered by dividing through the cross-axis extent,
    /// so this is only meaningful on the horizontal axes of a footprint-like
    /// scope; `SplitArea(Y)` is rejected.
    ///
    /// Syntax: `SplitArea(X) { 30: Lot | ~1: Rest }`
    SplitArea { axis: Axis, slots: Vec<SplitSlot> },

    /// Size-fallback choice: invokes the first candidate whose minimum
    /// extent fits the scope along `axis`; candidates are tried in order and
    /// the scope vanishes when none fits (use a `0:` catch-all to avoid
    /// that).
    ///
    /// Syntax: `Fit(X) { 2.2: DoorBay | 1.2: WinBay | 0: Wall }`
    Fit {
        axis: Axis,
        candidates: Vec<FitCandidate>,
    },

    /// Tiles the scope along `axis` with child scopes drawn from `tile_sizes`.
    ///
    /// `tile_sizes` is a per-slot pattern that is cycled to fill the axis range.
    /// Tiles are appended greedily (next tile from the cycle is added while it
    /// still fits inside the remaining range), then **all** placed tiles are
    /// scaled by the same factor `total / Σ(placed)` so they fill the scope
    /// exactly with no gap and no overshoot.
    ///
    /// A single-element list `[t]` is the legacy uniform `Repeat(axis, t)`.
    /// A multi-element list `[a, b, c]` produces an `…, a, b, c, a, b, c, …`
    /// cadence where each tile's relative width is preserved.
    Repeat {
        axis: Axis,
        tile_sizes: Vec<Expr>,
        rule: RuleCall,
    },

    /// Decomposes the scope into its geometric components (faces, edges, vertices).
    Comp(CompTarget),

    /// Terminal: replace the scope with the named mesh asset.
    /// This is the "terminal symbol" — produces a `Terminal` node in the output model.
    I(String),

    /// Sets the material on the current work item.
    /// The material is propagated to the final `Terminal`, allowing downstream
    /// renderers to apply textures / shaders and physics consumers to derive
    /// volumetric mass properties without changing the scope.
    ///
    /// Syntax:
    /// - `Mat("Brick")` / `Mat(Brick)` — id-only material; no density.
    /// - `Mat("Brick", 1800)` — id + density in kg/m³; the interpreter computes
    ///   [`crate::model::MassProperties`] for terminals stamped with this material.
    Mat(Material),

    /// Calls a named sub-rule on the current scope unchanged, optionally
    /// passing call arguments (`Tier(depth + 1)`).
    /// Used for grammar rule references that don't transform the scope themselves.
    Rule(RuleCall),

    /// Sets the scope size to absolute world-unit values (CGA `s()` parity).
    /// Components must be finite and non-negative; `0` flattens the axis
    /// (face-scope semantics). Essential for sizing the zero-extent scopes
    /// produced by `Scatter` and `Comp(Edges)`.
    ///
    /// Syntax: `Size(2.1, 0.9, 0.12)` — expressions welcome:
    /// `Size(scope.x, 0.3, 0.3)`.
    Size([Expr; 3]),

    /// Re-centres the scope inside the axis-aligned bounds it occupied when
    /// the current rule was entered, along the masked axes. The scope must
    /// have been shrunk (e.g. by `Size`) for this to move anything.
    ///
    /// Syntax: `Center(X)`, `Center(XY)`, `Center(XYZ)` …
    Center { x: bool, y: bool, z: bool },

    /// Mirrors the *pending face profile* horizontally (Triangle peak,
    /// Trapezoid offset, Polygon points). Scope geometry is untouched —
    /// terminals carry rotations, not reflections, so a scope-level mirror
    /// cannot exist in this engine. Apply after the profile is set.
    ///
    /// Syntax: `Mirror(X)` (only X — profiles are 2-D, mirrored across
    /// their vertical centre line).
    Mirror,

    /// Carves an L footprint: a front bar of depth `front` (along local Z
    /// from the scope origin) plus a side leg of width `side` (along local X)
    /// over the remaining depth. The `Shape` selector receives both boxes;
    /// `Remainder` receives the cut-away rectangle.
    ///
    /// Syntax: `ShapeL(4, 3) { Shape: Wing | Remainder: Court }`
    ShapeL {
        front: Expr,
        side: Expr,
        cases: Vec<CarveCase>,
    },

    /// Carves a U footprint: a front bar plus left and right legs; the
    /// remainder is the inner court between the legs behind the bar.
    ///
    /// Syntax: `ShapeU(4, 3, 3) { Shape: Range | Remainder: Court }`
    ShapeU {
        front: Expr,
        left: Expr,
        right: Expr,
        cases: Vec<CarveCase>,
    },

    /// Rotates the scope so that the specified local axis points in the given world direction.
    ///
    /// Applies the shortest-arc rotation from the current world direction of `local_axis`
    /// to `target`. Useful for recovering from accumulated rotations.
    /// Syntax: `Align(Y, Up)`, `Align(Z, Forward)`, etc.
    /// Named targets: `Up`=(0,1,0), `Down`=(0,-1,0), `Right`=(1,0,0), `Left`=(-1,0,0),
    /// `Forward`=(0,0,-1), `Back`=(0,0,1).
    Align { local_axis: Axis, target: Vec3 },

    /// Creates an inset (`distance < 0`) frame on a 2D face scope.
    ///
    /// Produces up to two kinds of child scopes:
    /// - `Inside`: the inset rectangle.
    /// - `Border`: four surrounding strips (bottom, top, left, right), each invoking the same rule.
    ///
    /// Syntax: `Offset(-0.2) { Inside: Glass | Border: Frame }`
    Offset {
        distance: Expr,
        cases: Vec<OffsetCase>,
    },

    /// Generates a roof structure above the current scope using rich parametric configuration.
    ///
    /// Operates on a volume scope. The `config` contains the roof type, primary pitch angle,
    /// optional secondary pitch, overhang, ridge offset, fascia depth, and tier height.
    ///
    /// Syntax examples:
    /// - `Roof(Gable, 30) { Slope: Tiles | GableEnd: Bricks }` — basic Gable
    /// - `Roof(Hip, 30, 0.5) { Slope: Tiles }` — Hip with overhang
    /// - `Roof(Gambrel, 45, 20) { LowerSlope: Shingles | UpperSlope: Tiles }` — Gambrel
    /// - `Roof(Saltbox, 45, offset=0.3) { Slope: Tiles | GableEnd: Bricks }` — Saltbox
    /// - `Roof(DutchGable, 45, tier=0.7) { Slope: Tiles | GableEnd: Bricks }` — Dutch Gable
    Roof {
        spec: RoofSpec,
        cases: Vec<RoofCase>,
    },

    /// Registers all six face planes of the current scope as snap-planes
    /// under the given label. Subsequent `Split(snap="label")` ops can align
    /// their interior boundaries to these planes. Read-only with respect to
    /// the scope (the scope itself passes through unchanged).
    ///
    /// Syntax: `RegSnap("bays")`
    RegSnap(String),

    /// Conditionally invokes `rule` on the current scope only when no
    /// already-emitted terminal occludes the scope (true OBB overlap test).
    /// Useful for placing decorative elements that should only appear where
    /// no structural element has already been placed.
    ///
    /// The grammar author is responsible for ordering — terminals derived
    /// before this op participate in the test; later terminals do not.
    ///
    /// Syntax: `IfClear { Window }` / `IfClear("chimneys") { Window }` —
    /// the optional label restricts the test to terminals stamped with that
    /// `Label`.
    IfClear {
        rule: RuleCall,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        label: Option<String>,
    },

    /// Inverse of [`ShapeOp::IfClear`]: invokes `rule` only when the current
    /// scope **is** occluded by an already-emitted terminal.
    ///
    /// Syntax: `IfOccluded { Patch }` / `IfOccluded("roof") { Patch }`.
    IfOccluded {
        rule: RuleCall,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        label: Option<String>,
    },

    /// Graded occlusion: invokes `rule` only when the scope is FULLY inside
    /// a single already-emitted terminal (optionally of one label class).
    ///
    /// Syntax: `IfInside { Core }` / `IfInside("mass") { Core }`
    IfInside {
        rule: RuleCall,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        label: Option<String>,
    },

    /// Graded occlusion: invokes `rule` only when the scope is in surface
    /// contact with a terminal — overlapping at a hair's growth but not at a
    /// hair's shrinkage (optionally restricted to one label class).
    ///
    /// Syntax: `IfTouches { Trim }` / `IfTouches("walls") { Trim }`
    IfTouches {
        rule: RuleCall,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        label: Option<String>,
    },

    /// Coordination key: a weighted choice resolved once per derivation —
    /// every `Pick` with the same key picks the SAME index, wherever it
    /// appears in the tree. The poor man's CGA++ event: all floors agree on
    /// one window variant, front and back facades match.
    ///
    /// The choice is a pure function of `(interpreter seed, key)` — no
    /// derivation-order dependence.
    ///
    /// Syntax: `Pick("winStyle") { 60% WinA | 40% WinB }`
    Pick {
        key: String,
        /// `(weight, successor)` pairs; weights need not sum to 1.
        choices: Vec<(f64, RuleCall)>,
    },

    /// Stamps an occlusion label on subsequent terminals of this branch
    /// (propagates like `Mat`). Labelled terminals form a named class the
    /// occlusion conditionals can filter on.
    ///
    /// Syntax: `Label("chimneys")`
    Label(String),

    /// Scatters `count` zero-size point scopes uniformly over the scope's
    /// top face (`Top`) or through its volume (`Volume`), invoking `rule` on
    /// each. Points are drawn from the shape's RNG stream (seed-stable);
    /// give them extent with `Size(..)`. `count` is capped at 1024.
    ///
    /// Syntax: `Scatter(Top, 12) { Bush }`
    Scatter {
        volume: bool,
        count: Expr,
        rule: RuleCall,
    },

    /// Stamps an explicit polygonal `FaceProfile` on the next terminal in this rule.
    ///
    /// Mirrors how [`ShapeOp::Taper`] sets a profile override: the next `I(...)`
    /// (or implicit terminal) emits a `Terminal` whose `face_profile` is
    /// [`crate::model::FaceProfile::Polygon`] with the provided vertex list.
    /// Vertices are 2-D points in **normalized `[0, 1]²` scope coordinates**
    /// (X: 0 = left edge → 1 = right edge; Y: 0 = bottom → 1 = top of the
    /// face); the renderer triangulates and stretches them across the
    /// scope's extent. They are NOT world units.
    ///
    /// Syntax: `Polygon((0,0), (4,0), (4,2), (2,2), (2,4), (0,4))`
    /// (variadic `(x,y)` list, capped at 256 vertices for parser DoS hardening).
    Polygon(Vec<glam::DVec2>),

    /// Projects a new horizontal scope out of a sloped face for attaching dormers or details.
    ///
    /// `world_axis` defines the "up" direction for the attached scope (usually world Y).
    /// The resulting scope sits on the face's surface with its Y axis aligned to `world_axis`,
    /// inheriting the face's width and height but with depth = 0.
    ///
    /// Syntax: `Attach(Up) { Surface: DormerMass }`
    Attach {
        world_axis: Vec3,
        cases: Vec<AttachCase>,
    },
}