imaginu 0.4.0

AI-drivable procedural 3D asset compiler: JSON recipes -> beautiful game-ready GLB for Babylon.js
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
//! Monster rig: a data-driven creature skeleton + a fold-order-ranked set of
//! SDF primitives + a gait descriptor. This generalizes the fixed humanoid
//! `character::Rig` to arbitrary body plans. All eight `BodyPlan`s are modeled
//! (`plan_*`); each returns a [`MonsterRig`] fed to the same shared
//! body/skin/anim pipeline.

use glam::{Quat, Vec3};

use crate::gltf::{Joint, Skeleton};
use crate::recipe::{BodyPlan, MonsterParams};

use crate::generators::{range, rng};

/// Which SDF primitive a body part is built from.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PrimKind {
    RoundCone,
    Ellipsoid,
}

/// Coloring role of a primitive. `Body` uses the fold-rank region coloring
/// (torso/head/legs/tail); `Horn` paints a bone/armor tone (horns, spikes,
/// plates, teeth); `Eye` paints the emissive accent (glowing eyes).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PrimTint {
    Body,
    Horn,
    Eye,
}

/// One flesh primitive spanning two skeleton joints. `fold_rank` orders the
/// smooth-min compose (0 = core torso, higher = later/outer). `k` is the
/// smooth-min blend radius used when this primitive folds into its rank band.
#[derive(Clone, Copy, Debug)]
pub struct PrimitiveDesc {
    pub kind: PrimKind,
    pub joint_a: usize,
    pub joint_b: usize,
    pub r1: f32,
    pub r2: f32,
    pub fold_rank: u8,
    pub k: f32,
    /// Explicit per-axis half-radii for an anisotropic ellipsoid (centered at
    /// the midpoint of the two joints). `None` = derive the radius from the
    /// joint span (spheres / joint-elongated ellipsoids / round cones). Used
    /// to build genuinely FLAT sheets (thin on one axis) like flyer wings.
    pub radii: Option<Vec3>,
    /// Coloring role (feature knobs paint bone/eye tones; body prims default).
    pub tint: PrimTint,
}

/// Locomotion style — drives which procedural clip driver builds the
/// creature's movement clip and how idle behaves. Only `Walk` is emitted for
/// the M2-M5 quadruped scope; the other styles are consumed by the clip driver
/// and wired up as later body plans (serpent/flyer/ooze) land.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Gait {
    Walk,
    Slither,
    Fly,
    Crawl,
    Pulse,
}

/// The moving parts of a body plan, as joint-index chains. `legs` holds one
/// chain per leg (root..foot); `spine` runs hips..head; `tail`/`wings` are
/// optional chains; `head` is the head joint if the plan has a distinct one.
#[derive(Clone, Debug)]
pub struct GaitDesc {
    pub legs: Vec<Vec<usize>>,
    pub spine: Vec<usize>,
    pub wings: Vec<usize>,
    pub tail: Vec<usize>,
    pub head: Option<usize>,
    pub style: Gait,
}

/// A fully-planned monster: bind-pose skeleton, ranked flesh primitives, gait
/// descriptor, and a padded world-space bounding box for meshing.
#[derive(Clone, Debug)]
pub struct MonsterRig {
    pub skeleton: Skeleton,
    pub prims: Vec<PrimitiveDesc>,
    pub gait: GaitDesc,
    pub bounds: (Vec3, Vec3),
}

impl MonsterRig {
    /// World-space bind position of joint `i`.
    pub fn joint_world(&self, i: usize) -> Vec3 {
        self.skeleton.global(i).transform_point3(Vec3::ZERO)
    }

    /// World-space bind positions of every joint.
    pub fn world(&self) -> Vec<Vec3> {
        (0..self.skeleton.joints.len())
            .map(|i| self.joint_world(i))
            .collect()
    }
}

/// Dispatch on the body plan. Every plan builds a fold-ranked [`MonsterRig`]
/// fed to the same shared body/skin/anim pipeline.
pub fn build_rig(p: &MonsterParams) -> MonsterRig {
    let mut rig = match p.body {
        BodyPlan::QuadrupedBeast => plan_quadruped_beast(p),
        BodyPlan::Ooze => plan_ooze(p),
        BodyPlan::Serpent => plan_serpent(p),
        BodyPlan::BipedBrute => plan_biped_brute(p),
        BodyPlan::WingedFlyer => plan_winged_flyer(p),
        BodyPlan::Arachnid => plan_arachnid(p),
        BodyPlan::Insectoid => plan_insectoid(p),
        BodyPlan::Aberration => plan_aberration(p),
    };
    apply_knobs(&mut rig, p);
    rig
}

/// Incremental rig builder: joints are added by WORLD position (converted to
/// parent-relative local translations, valid because all bind rotations are
/// identity) and primitives reference joint indices. Keeps the data-driven
/// plans terse and readable.
pub(crate) struct RigBuilder {
    joints: Vec<(Option<usize>, String, Vec3)>,
    world: Vec<Vec3>,
    prims: Vec<PrimitiveDesc>,
}

impl RigBuilder {
    pub(crate) fn new() -> Self {
        Self {
            joints: Vec::new(),
            world: Vec::new(),
            prims: Vec::new(),
        }
    }

    /// Add a joint at `world_pos`; returns its index.
    pub(crate) fn joint(&mut self, parent: Option<usize>, name: &str, world_pos: Vec3) -> usize {
        let local = match parent {
            Some(p) => world_pos - self.world[p],
            None => world_pos,
        };
        let i = self.joints.len();
        self.joints.push((parent, name.into(), local));
        self.world.push(world_pos);
        i
    }

    /// World position of an already-added joint.
    pub(crate) fn wpos(&self, i: usize) -> Vec3 {
        self.world[i]
    }

    pub(crate) fn cone(&mut self, a: usize, b: usize, r1: f32, r2: f32, fold_rank: u8, k: f32) {
        self.prims.push(PrimitiveDesc {
            kind: PrimKind::RoundCone,
            joint_a: a,
            joint_b: b,
            r1,
            r2,
            fold_rank,
            k,
            radii: None,
            tint: PrimTint::Body,
        });
    }

    pub(crate) fn ellip(&mut self, a: usize, b: usize, r1: f32, r2: f32, fold_rank: u8, k: f32) {
        self.prims.push(PrimitiveDesc {
            kind: PrimKind::Ellipsoid,
            joint_a: a,
            joint_b: b,
            r1,
            r2,
            fold_rank,
            k,
            radii: None,
            tint: PrimTint::Body,
        });
    }

    /// A flat/anisotropic ellipsoid centered between `a` and `b` with explicit
    /// per-axis half-radii (thin on one axis = a sheet, e.g. a wing membrane).
    pub(crate) fn flat(&mut self, a: usize, b: usize, radii: Vec3, fold_rank: u8, k: f32) {
        self.prims.push(PrimitiveDesc {
            kind: PrimKind::Ellipsoid,
            joint_a: a,
            joint_b: b,
            r1: 0.0,
            r2: 0.0,
            fold_rank,
            k,
            radii: Some(radii),
            tint: PrimTint::Body,
        });
    }

    /// Finalize into a bounds-computed [`MonsterRig`].
    pub(crate) fn finish(self, gait: GaitDesc) -> MonsterRig {
        let skeleton = Skeleton {
            joints: self
                .joints
                .iter()
                .map(|(parent, name, t)| Joint {
                    name: name.clone(),
                    parent: *parent,
                    translation: *t,
                    rotation: Quat::IDENTITY,
                })
                .collect(),
        };
        let mut rig = MonsterRig {
            skeleton,
            prims: self.prims,
            gait,
            bounds: (Vec3::ZERO, Vec3::ZERO),
        };
        rig.bounds = compute_bounds(&rig);
        rig
    }
}

// ----- quadruped joint indices -----
const HIPS: usize = 0;
const SPINE1: usize = 1;
const SPINE2: usize = 2;
const NECK: usize = 3;
const HEAD: usize = 4;
const TAIL1: usize = 5;
const TAIL2: usize = 6;
// front-left / front-right / rear-left / rear-right legs, each (upper,lower,foot)
const FL_UP: usize = 7;
const FL_LO: usize = 8;
const FL_FT: usize = 9;
const FR_UP: usize = 10;
const FR_LO: usize = 11;
const FR_FT: usize = 12;
const RL_UP: usize = 13;
const RL_LO: usize = 14;
const RL_FT: usize = 15;
const RR_UP: usize = 16;
const RR_LO: usize = 17;
const RR_FT: usize = 18;
// appended leaf joints (kept at the end so leg indices stay stable)
const SNOUT: usize = 19; // muzzle tip, child of HEAD
const TAIL3: usize = 20; // tail point, child of TAIL2

/// Build the quadruped-beast template: a horizontal torso along +Z, a neck +
/// head reaching forward-up, a two-segment tail, and four three-joint legs.
pub fn plan_quadruped_beast(p: &MonsterParams) -> MonsterRig {
    let s = p.size.clamp(0.2, 4.0);
    // menace fattens/lowers the build a touch (0..1 -> +0..0.35 bulk).
    let menace = p.menace.clamp(0.0, 1.0);
    let bulk = 1.0 + 0.35 * menace;

    let hy = 0.62 * s; // hip/shoulder height
    let leg_seg = 0.21 * s; // per leg-segment drop (upper, lower)
    // The leg *swing* joints sit at the torso underside, NOT at the buried
    // shoulder/hip, so the exposed leg top rides its own pivot and motion
    // grows toward the foot — otherwise the whole visible leg swings a large
    // arc against the static belly and shatters the mesh (stretch probe).
    let fl_drop = -0.24 * s; // spine2 world y (~0.66s) -> ~0.42s
    let rl_drop = -0.20 * s; // hips world y (0.62s) -> ~0.42s

    // (parent, name, local translation). Parents always precede children.
    let joints: Vec<(Option<usize>, &str, Vec3)> = vec![
        (None, "hips", Vec3::new(0.0, hy, -0.35 * s)),
        (Some(HIPS), "spine1", Vec3::new(0.0, 0.02 * s, 0.30 * s)),
        (Some(SPINE1), "spine2", Vec3::new(0.0, 0.02 * s, 0.32 * s)),
        // neck reaches forward, head drops BELOW the back line (predatory)
        (Some(SPINE2), "neck", Vec3::new(0.0, 0.06 * s, 0.22 * s)),
        (Some(NECK), "head", Vec3::new(0.0, -0.06 * s, 0.20 * s)),
        // tapering tail chain sweeping back + down
        (Some(HIPS), "tail1", Vec3::new(0.0, 0.02 * s, -0.18 * s)),
        (Some(TAIL1), "tail2", Vec3::new(0.0, -0.03 * s, -0.22 * s)),
        // front-left leg (swing joint at the torso underside)
        (Some(SPINE2), "fl_upper", Vec3::new(0.18 * s, fl_drop, 0.0)),
        (Some(FL_UP), "fl_lower", Vec3::new(0.0, -leg_seg, 0.0)),
        (Some(FL_LO), "fl_foot", Vec3::new(0.0, -leg_seg, 0.04 * s)),
        // front-right leg
        (Some(SPINE2), "fr_upper", Vec3::new(-0.18 * s, fl_drop, 0.0)),
        (Some(FR_UP), "fr_lower", Vec3::new(0.0, -leg_seg, 0.0)),
        (Some(FR_LO), "fr_foot", Vec3::new(0.0, -leg_seg, 0.04 * s)),
        // rear-left leg
        (Some(HIPS), "rl_upper", Vec3::new(0.18 * s, rl_drop, 0.0)),
        (Some(RL_UP), "rl_lower", Vec3::new(0.0, -leg_seg, 0.0)),
        (Some(RL_LO), "rl_foot", Vec3::new(0.0, -leg_seg, -0.02 * s)),
        // rear-right leg
        (Some(HIPS), "rr_upper", Vec3::new(-0.18 * s, rl_drop, 0.0)),
        (Some(RR_UP), "rr_lower", Vec3::new(0.0, -leg_seg, 0.0)),
        (Some(RR_LO), "rr_foot", Vec3::new(0.0, -leg_seg, -0.02 * s)),
        // leaf joints (muzzle + tail point) drive geometry only
        (Some(HEAD), "snout", Vec3::new(0.0, -0.02 * s, 0.15 * s)),
        (Some(TAIL2), "tail3", Vec3::new(0.0, -0.05 * s, -0.20 * s)),
    ];

    let skeleton = Skeleton {
        joints: joints
            .iter()
            .map(|(parent, name, t)| Joint {
                name: (*name).into(),
                parent: *parent,
                translation: *t,
                rotation: Quat::IDENTITY,
            })
            .collect(),
    };

    // radii (scaled by size + menace bulk)
    let torso_r = 0.28 * s * bulk;
    let neck_r = 0.16 * s * bulk;
    let head_r = 0.16 * s;
    let leg_up_r = 0.14 * s * bulk; // beefy haunch
    let leg_lo_r = 0.08 * s;
    let foot_r = 0.055 * s;

    // fold ranks: 0 = core torso, 1 = neck/head, 2 = legs, 3 = tail. k is
    // large near the core (smooth flesh) and small at tips (crisp junctions).
    let rc = |a: usize, b: usize, r1: f32, r2: f32, fold_rank: u8, k: f32| PrimitiveDesc {
        kind: PrimKind::RoundCone,
        joint_a: a,
        joint_b: b,
        r1,
        r2,
        fold_rank,
        k,
        radii: None,
        tint: PrimTint::Body,
    };
    let el = |a: usize, b: usize, r1: f32, r2: f32, fold_rank: u8, k: f32| PrimitiveDesc {
        kind: PrimKind::Ellipsoid,
        joint_a: a,
        joint_b: b,
        r1,
        r2,
        fold_rank,
        k,
        radii: None,
        tint: PrimTint::Body,
    };
    let mut prims = vec![
        // rank 0: torso core (ellipsoid barrel + filling tube)
        el(HIPS, SPINE2, torso_r, 0.05 * s, 0, 0.11 * s),
        rc(HIPS, SPINE2, torso_r * 0.86, torso_r * 0.92, 0, 0.11 * s),
        // rank 1: thick neck bridge + head + elongated muzzle
        rc(SPINE2, NECK, torso_r * 0.6, neck_r * 1.05, 1, 0.06 * s),
        rc(NECK, HEAD, neck_r, head_r * 0.85, 1, 0.05 * s),
        el(HEAD, SNOUT, head_r, 0.015 * s, 1, 0.045 * s),
        // rank 3: 3-segment tapering tail
        rc(HIPS, TAIL1, torso_r * 0.5, 0.12 * s, 3, 0.03 * s),
        rc(TAIL1, TAIL2, 0.12 * s, 0.06 * s, 3, 0.028 * s),
        rc(TAIL2, TAIL3, 0.06 * s, 0.018 * s, 3, 0.022 * s),
    ];

    // rank 2: four legs (upper + lower round cones each). Small upper-leg k ->
    // a tight haunch/shoulder join (a defined crease, not a melted blob).
    let legs_joints = [
        (FL_UP, FL_LO, FL_FT),
        (FR_UP, FR_LO, FR_FT),
        (RL_UP, RL_LO, RL_FT),
        (RR_UP, RR_LO, RR_FT),
    ];
    for (up, lo, ft) in legs_joints {
        prims.push(rc(up, lo, leg_up_r, leg_lo_r * 1.15, 2, 0.018 * s));
        prims.push(rc(lo, ft, leg_lo_r, foot_r, 2, 0.026 * s));
    }

    let gait = GaitDesc {
        legs: legs_joints
            .iter()
            .map(|(u, l, f)| vec![*u, *l, *f])
            .collect(),
        spine: vec![HIPS, SPINE1, SPINE2, NECK, HEAD],
        wings: Vec::new(),
        tail: vec![TAIL1, TAIL2, TAIL3],
        head: Some(HEAD),
        style: Gait::Walk,
    };

    let mut rig = MonsterRig {
        skeleton,
        prims,
        gait,
        bounds: (Vec3::ZERO, Vec3::ZERO),
    };
    rig.bounds = compute_bounds(&rig);
    rig
}

/// Padded world-space AABB enclosing every primitive.
pub(crate) fn compute_bounds(rig: &MonsterRig) -> (Vec3, Vec3) {
    let world = rig.world();
    let mut lo = Vec3::splat(f32::INFINITY);
    let mut hi = Vec3::splat(f32::NEG_INFINITY);
    for d in &rig.prims {
        let r = match d.radii {
            Some(rv) => rv.max_element(),
            None => d.r1.max(d.r2),
        } + d.k;
        for j in [d.joint_a, d.joint_b] {
            let w = world[j];
            lo = lo.min(w - Vec3::splat(r));
            hi = hi.max(w + Vec3::splat(r));
        }
    }
    // ensure feet reach ground plane and a little air headroom
    lo.y = lo.y.min(0.0);
    let pad = Vec3::splat(0.06 * (hi - lo).length().max(1.0) * 0.1 + 0.05);
    (lo - pad, hi + pad)
}

// ===================== the other 7 body plans =====================
// All reuse the shared body/skin/anim pipeline; each just lays out joints +
// fold-ranked primitives + a gait descriptor. Coordinate convention: Y up,
// +Z forward, ground at y = 0.

use core::f32::consts::{PI, TAU};

/// M6a — Ooze/blob: a low wide gelatinous mound (crossed horizontal capsules +
/// a top bulge + a seeded lump). No limbs; pulses in place.
fn plan_ooze(p: &MonsterParams) -> MonsterRig {
    let s = p.size.clamp(0.2, 4.0);
    let v = Vec3::new;
    let mut r = RigBuilder::new();
    let core = r.joint(None, "core", v(0.0, 0.30 * s, 0.0));
    let top = r.joint(Some(core), "top", v(0.0, 0.48 * s, 0.05 * s));
    let left = r.joint(Some(core), "l", v(-0.32 * s, 0.30 * s, 0.0));
    let right = r.joint(Some(core), "r", v(0.32 * s, 0.30 * s, 0.0));
    let front = r.joint(Some(core), "f", v(0.0, 0.30 * s, 0.30 * s));
    let back = r.joint(Some(core), "b", v(0.0, 0.30 * s, -0.30 * s));
    let mut rr = rng(p.seed);
    let lump = r.joint(
        Some(core),
        "lump",
        v(
            range(&mut rr, -0.2, 0.2) * s,
            0.44 * s,
            range(&mut rr, -0.15, 0.15) * s,
        ),
    );
    // crossed horizontal capsules form a wide low blob; bulge + lump add mass
    r.cone(left, right, 0.33 * s, 0.33 * s, 0, 0.14 * s);
    r.cone(front, back, 0.30 * s, 0.30 * s, 0, 0.14 * s);
    r.ellip(top, top, 0.24 * s, 0.0, 0, 0.10 * s);
    r.ellip(lump, lump, 0.16 * s, 0.0, 0, 0.08 * s);
    r.finish(GaitDesc {
        legs: Vec::new(),
        spine: vec![core, top],
        wings: Vec::new(),
        tail: Vec::new(),
        head: None,
        style: Gait::Pulse,
    })
}

/// M6b — Serpent/wyrm (the fire-wyrm hero base): a thick tapered spine (12
/// joints) in a clear horizontal S with the front third REARED up, ending in a
/// broad blunt-snouted head with an underslung jaw.
fn plan_serpent(p: &MonsterParams) -> MonsterRig {
    let s = p.size.clamp(0.2, 4.0);
    let v = Vec3::new;
    let mut r = RigBuilder::new();
    let n = 12usize;
    let mut chain = Vec::new();
    let mut prev = None;
    for i in 0..n {
        let t = i as f32 / (n - 1) as f32; // 0 = tail .. 1 = head
        // body runs along +Z; the front third rears up off the ground
        let z = (t - 0.5) * 2.4 * s;
        let x = 0.42 * s * (t * PI * 2.2).sin(); // clear horizontal S
        let rear = (((t - 0.55) / 0.45).clamp(0.0, 1.0)).powi(2); // eased lift
        let y = 0.20 * s + 0.95 * s * rear;
        let idx = r.joint(prev, &format!("spine{i}"), v(x, y, z));
        chain.push(idx);
        prev = Some(idx);
    }
    // thick coil: fat mid-body (~0.28s) tapering to a pointed tail
    let rad = |t: f32| (0.28 * s * (1.0 - (2.0 * t - 1.0).powi(2) * 0.78)).max(0.04 * s);
    for i in 0..n - 1 {
        let ta = i as f32 / (n - 1) as f32;
        let tb = (i + 1) as f32 / (n - 1) as f32;
        r.cone(chain[i], chain[i + 1], rad(ta), rad(tb), 0, 0.05 * s);
    }
    // defined head: a broad blunt ellipsoid (distinctly wider than the neck)
    // pointing forward-down, plus an underslung lower jaw = a maw.
    let head = chain[n - 1];
    let hp = r.wpos(head);
    let snout = r.joint(Some(head), "snout", hp + v(0.0, -0.14 * s, 0.30 * s));
    let jaw = r.joint(Some(head), "jaw", hp + v(0.0, -0.20 * s, 0.20 * s));
    // wide/tall/long head block via explicit radii; centered a bit forward
    r.flat(head, snout, v(0.26 * s, 0.24 * s, 0.34 * s), 0, 0.05 * s);
    r.cone(head, jaw, 0.16 * s, 0.09 * s, 0, 0.04 * s); // lower jaw
    r.finish(GaitDesc {
        legs: Vec::new(),
        spine: chain,
        wings: Vec::new(),
        tail: Vec::new(),
        head: Some(head),
        style: Gait::Slither,
    })
}

/// M6c — Biped brute: hunched humanoid, 2 arms + 2 legs + torso + head. Arms
/// are their own skin families (connectivity); only the legs drive the walk.
fn plan_biped_brute(p: &MonsterParams) -> MonsterRig {
    let s = p.size.clamp(0.2, 4.0);
    let bulk = 1.0 + 0.4 * p.menace.clamp(0.0, 1.0);
    let v = Vec3::new;
    let mut r = RigBuilder::new();
    // hunched, heavy build in the base bind (menace/size stack on later)
    let hips = r.joint(None, "hips", v(0.0, 0.88 * s, 0.0));
    let spine = r.joint(Some(hips), "spine", v(0.0, 1.02 * s, 0.0));
    let chest = r.joint(Some(spine), "chest", v(0.0, 1.20 * s, -0.05 * s));
    let neck = r.joint(Some(chest), "neck", v(0.0, 1.30 * s, 0.06 * s));
    let head = r.joint(Some(neck), "head", v(0.0, 1.40 * s, 0.12 * s));
    r.ellip(hips, chest, 0.24 * s * bulk, 0.05 * s, 0, 0.10 * s); // thick barrel torso
    r.cone(hips, chest, 0.20 * s * bulk, 0.24 * s * bulk, 0, 0.10 * s);
    r.flat(
        chest,
        chest,
        v(0.36 * s * bulk, 0.22 * s, 0.24 * s),
        0,
        0.09 * s,
    ); // broad shoulders
    r.cone(chest, neck, 0.16 * s * bulk, 0.12 * s, 1, 0.06 * s); // thick neck
    r.cone(neck, head, 0.10 * s, 0.13 * s, 1, 0.05 * s);
    r.ellip(head, head, 0.15 * s, 0.0, 1, 0.05 * s);
    // arms (own families) — heavy limbs off the broad shoulders
    for side in [-1.0f32, 1.0] {
        let sh = r.joint(Some(chest), "upperarm", v(side * 0.34 * s, 1.18 * s, 0.0));
        let el = r.joint(Some(sh), "forearm", v(side * 0.46 * s, 0.90 * s, 0.06 * s));
        let hn = r.joint(Some(el), "hand", v(side * 0.50 * s, 0.64 * s, 0.10 * s));
        r.cone(sh, el, 0.16 * s * bulk, 0.12 * s * bulk, 2, 0.02 * s);
        r.cone(el, hn, 0.12 * s, 0.09 * s, 2, 0.026 * s);
        r.ellip(hn, hn, 0.11 * s, 0.0, 2, 0.02 * s); // big fists
    }
    // legs (thick thighs; swing joints at the torso underside)
    let mut legs = Vec::new();
    for side in [-1.0f32, 1.0] {
        let th = r.joint(Some(hips), "thigh", v(side * 0.16 * s, 0.70 * s, 0.0));
        let sn = r.joint(Some(th), "shin", v(side * 0.17 * s, 0.38 * s, 0.02 * s));
        let ft = r.joint(Some(sn), "foot", v(side * 0.18 * s, 0.05 * s, 0.14 * s));
        r.cone(th, sn, 0.18 * s * bulk, 0.12 * s, 2, 0.018 * s);
        r.cone(sn, ft, 0.12 * s, 0.07 * s, 2, 0.026 * s);
        legs.push(vec![th, sn, ft]);
    }
    r.finish(GaitDesc {
        legs,
        spine: vec![hips, spine, chest, neck, head],
        wings: Vec::new(),
        tail: Vec::new(),
        head: Some(head),
        style: Gait::Walk,
    })
}

/// M6d — Winged flyer: a slim biped core with two large wings (thin-cone frame
/// + membrane lobe, fold-ranked last) and small tucked legs.
fn plan_winged_flyer(p: &MonsterParams) -> MonsterRig {
    let s = p.size.clamp(0.2, 4.0);
    let v = Vec3::new;
    let mut r = RigBuilder::new();
    let hips = r.joint(None, "hips", v(0.0, 0.85 * s, 0.0));
    let chest = r.joint(Some(hips), "chest", v(0.0, 1.02 * s, 0.08 * s));
    let neck = r.joint(Some(chest), "neck", v(0.0, 1.10 * s, 0.20 * s));
    let head = r.joint(Some(neck), "head", v(0.0, 1.12 * s, 0.36 * s));
    let hp = r.wpos(head);
    let snout = r.joint(Some(head), "snout", hp + v(0.0, -0.02 * s, 0.16 * s));
    r.ellip(hips, chest, 0.17 * s, 0.04 * s, 0, 0.09 * s);
    r.cone(hips, chest, 0.15 * s, 0.15 * s, 0, 0.09 * s);
    r.cone(chest, neck, 0.11 * s, 0.09 * s, 1, 0.05 * s);
    r.cone(neck, head, 0.08 * s, 0.09 * s, 1, 0.045 * s);
    r.ellip(head, snout, 0.10 * s, 0.015 * s, 1, 0.04 * s);
    // small tucked legs
    let mut legs = Vec::new();
    for side in [-1.0f32, 1.0] {
        let th = r.joint(Some(hips), "thigh", v(side * 0.10 * s, 0.72 * s, -0.05 * s));
        let sn = r.joint(Some(th), "shin", v(side * 0.11 * s, 0.50 * s, 0.02 * s));
        let ft = r.joint(Some(sn), "foot", v(side * 0.12 * s, 0.16 * s, 0.14 * s));
        r.cone(th, sn, 0.07 * s, 0.05 * s, 2, 0.018 * s);
        r.cone(sn, ft, 0.05 * s, 0.035 * s, 2, 0.02 * s);
        legs.push(vec![th, sn, ft]);
    }
    // wings: each a large ellipsoid FLATTENED on the vertical axis (a genuine
    // thin sheet — wide span, ~0.045s thin, deep chord), spread wide from the
    // shoulders and swept slightly forward. Fold-ranked last and fused with a
    // LOW k (near hard-union) so smooth-min does NOT inflate them back to lobes.
    let mut wings = Vec::new();
    for side in [-1.0f32, 1.0] {
        let root = r.joint(Some(chest), "wing", v(side * 0.16 * s, 1.06 * s, 0.02 * s));
        // wingtip out to the side + slightly forward (swept leading edge)
        let tip = r.joint(
            Some(root),
            "wingtip",
            v(side * 1.15 * s, 1.14 * s, 0.12 * s),
        );
        // membrane center ~mid-span; radii = (half-span, thin, half-chord)
        r.flat(root, tip, v(0.62 * s, 0.045 * s, 0.42 * s), 4, 0.012 * s);
        // a thin leading-edge spar for a defined bone
        r.cone(root, tip, 0.05 * s, 0.02 * s, 4, 0.02 * s);
        wings.push(root);
    }
    r.finish(GaitDesc {
        legs,
        spine: vec![hips, chest, neck, head],
        wings,
        tail: Vec::new(),
        head: Some(head),
        style: Gait::Fly,
    })
}

/// M6e — Arachnid: two-part body (cephalothorax + abdomen) with 8 radial legs
/// bent up at the knee and planted wide on the ground.
fn plan_arachnid(p: &MonsterParams) -> MonsterRig {
    let s = p.size.clamp(0.2, 4.0);
    let v = Vec3::new;
    let mut r = RigBuilder::new();
    let ceph = r.joint(None, "cephalothorax", v(0.0, 0.34 * s, 0.18 * s));
    let abdo = r.joint(Some(ceph), "abdomen", v(0.0, 0.40 * s, -0.35 * s));
    r.ellip(ceph, ceph, 0.20 * s, 0.0, 0, 0.07 * s);
    r.ellip(abdo, abdo, 0.26 * s, 0.0, 0, 0.08 * s);
    r.cone(ceph, abdo, 0.13 * s, 0.15 * s, 0, 0.05 * s);
    let mut legs = Vec::new();
    for side in [-1.0f32, 1.0] {
        for kk in 0..4 {
            let zc = 0.30 * s - kk as f32 * 0.20 * s;
            let spread = 0.16 * s * (1.5 - kk as f32);
            let root = r.joint(Some(ceph), "coxa", v(side * 0.20 * s, 0.33 * s, zc));
            let knee = r.joint(
                Some(root),
                "knee",
                v(side * 0.52 * s, 0.58 * s, zc + spread * 0.4),
            );
            let foot = r.joint(Some(knee), "foot", v(side * 0.80 * s, 0.0, zc + spread));
            r.cone(root, knee, 0.06 * s, 0.05 * s, 2, 0.02 * s);
            r.cone(knee, foot, 0.05 * s, 0.03 * s, 2, 0.02 * s);
            legs.push(vec![root, knee, foot]);
        }
    }
    r.finish(GaitDesc {
        legs,
        spine: vec![ceph, abdo],
        wings: Vec::new(),
        tail: Vec::new(),
        head: None,
        style: Gait::Crawl,
    })
}

/// M6f — Insectoid: head + thorax + elongated abdomen, 6 legs off the thorax,
/// 2 antennae off the head.
fn plan_insectoid(p: &MonsterParams) -> MonsterRig {
    let s = p.size.clamp(0.2, 4.0);
    let v = Vec3::new;
    let mut r = RigBuilder::new();
    let thorax = r.joint(None, "thorax", v(0.0, 0.42 * s, 0.10 * s));
    let head = r.joint(Some(thorax), "head", v(0.0, 0.44 * s, 0.55 * s));
    let abdo = r.joint(Some(thorax), "abdomen", v(0.0, 0.44 * s, -0.55 * s));
    let abtip = r.joint(Some(abdo), "abtip", v(0.0, 0.40 * s, -1.05 * s));
    r.ellip(thorax, thorax, 0.20 * s, 0.0, 0, 0.06 * s);
    r.ellip(head, head, 0.15 * s, 0.0, 0, 0.05 * s);
    r.ellip(abdo, abtip, 0.18 * s, 0.02 * s, 0, 0.06 * s);
    r.cone(thorax, head, 0.10 * s, 0.12 * s, 0, 0.04 * s);
    r.cone(thorax, abdo, 0.11 * s, 0.14 * s, 0, 0.04 * s);
    // antennae (part of the trunk/head)
    let hp = r.wpos(head);
    let al = r.joint(Some(head), "antL", hp + v(0.10 * s, 0.28 * s, 0.20 * s));
    let ar = r.joint(Some(head), "antR", hp + v(-0.10 * s, 0.28 * s, 0.20 * s));
    r.cone(head, al, 0.03 * s, 0.012 * s, 1, 0.02 * s);
    r.cone(head, ar, 0.03 * s, 0.012 * s, 1, 0.02 * s);
    // 6 legs off the thorax
    let mut legs = Vec::new();
    for side in [-1.0f32, 1.0] {
        for kk in 0..3 {
            let zc = 0.28 * s - kk as f32 * 0.22 * s;
            let root = r.joint(Some(thorax), "coxa", v(side * 0.16 * s, 0.40 * s, zc));
            let knee = r.joint(
                Some(root),
                "knee",
                v(side * 0.42 * s, 0.55 * s, zc + 0.05 * s),
            );
            let foot = r.joint(
                Some(knee),
                "foot",
                v(side * 0.58 * s, 0.0, zc + 0.12 * s * (1.0 - kk as f32)),
            );
            r.cone(root, knee, 0.05 * s, 0.04 * s, 2, 0.018 * s);
            r.cone(knee, foot, 0.04 * s, 0.028 * s, 2, 0.02 * s);
            legs.push(vec![root, knee, foot]);
        }
    }
    r.finish(GaitDesc {
        legs,
        spine: vec![head, thorax, abdo, abtip],
        wings: Vec::new(),
        tail: Vec::new(),
        head: Some(head),
        style: Gait::Crawl,
    })
}

/// M6g — Aberration: a central mass with N drooping tentacle chains radiating
/// out (seeded angles). Tentacles bind like legs; the mass pulses.
fn plan_aberration(p: &MonsterParams) -> MonsterRig {
    let s = p.size.clamp(0.2, 4.0);
    let v = Vec3::new;
    let mut r = RigBuilder::new();
    let core = r.joint(None, "core", v(0.0, 0.60 * s, 0.0));
    let lower = r.joint(Some(core), "lower", v(0.0, 0.42 * s, 0.0));
    r.ellip(core, core, 0.34 * s, 0.0, 0, 0.10 * s);
    r.ellip(lower, lower, 0.26 * s, 0.0, 0, 0.09 * s);
    let mut rr = rng(p.seed);
    let ntent = 6usize;
    let mut legs = Vec::new();
    for i in 0..ntent {
        let ang = i as f32 / ntent as f32 * TAU + range(&mut rr, -0.3, 0.3);
        let dir = v(ang.cos(), 0.0, ang.sin());
        let h = 0.55 * s + range(&mut rr, -0.1, 0.1) * s;
        let p0 = v(0.0, h, 0.0) + dir * 0.30 * s;
        let j0 = r.joint(Some(core), "t0", p0);
        let p1 = p0 + dir * 0.28 * s + v(0.0, -0.18 * s, 0.0);
        let j1 = r.joint(Some(j0), "t1", p1);
        let p2 = p1 + dir * 0.24 * s + v(0.0, -0.28 * s, 0.0);
        let j2 = r.joint(Some(j1), "t2", p2);
        let p3 = p2 + dir * 0.18 * s + v(0.0, -0.30 * s, 0.0);
        let j3 = r.joint(Some(j2), "t3", p3);
        r.cone(j0, j1, 0.09 * s, 0.07 * s, 2, 0.02 * s);
        r.cone(j1, j2, 0.07 * s, 0.05 * s, 2, 0.02 * s);
        r.cone(j2, j3, 0.05 * s, 0.02 * s, 2, 0.02 * s);
        legs.push(vec![j0, j1, j2, j3]);
    }
    r.finish(GaitDesc {
        legs,
        spine: vec![core, lower],
        wings: Vec::new(),
        tail: Vec::new(),
        head: None,
        style: Gait::Pulse,
    })
}

// ===================== M8: composable feature knobs =====================
// Each knob appends fold-ranked-LAST primitives (and their own tiny joint
// chains) on top of a finished plan. Protruding features (horns, spikes,
// teeth, eyes) get a 2-joint chain parented under a trunk joint so they form
// their own clean skin family that rides that joint rigidly — never a web.
// Every knob value is clamped so hostile input cannot panic or explode the grid.

use std::collections::HashSet;

/// Sentinel-resolved, clamped knob values for a specific rig.
struct Knobs {
    horns: f32,
    spikes: f32,
    plates: f32,
    tail: f32,
    wings: f32,
    eyes: i32,
    maw: f32,
}

/// Resolve the `-1` "plan decides" sentinels to concrete values and clamp
/// everything to safe ranges. Plan defaults depend on what the rig actually
/// has (a tail chain, wings, a head joint).
fn resolve_knobs(rig: &MonsterRig, p: &MonsterParams) -> Knobs {
    let has_head = rig.gait.head.is_some();
    let tail = if p.tail < 0.0 {
        if rig.gait.tail.is_empty() { 0.0 } else { 1.0 }
    } else {
        p.tail.clamp(0.0, 1.0)
    };
    let wings = if p.wings < 0.0 {
        if rig.gait.wings.is_empty() { 0.0 } else { 1.0 }
    } else {
        p.wings.clamp(0.0, 1.0)
    };
    let eyes = if p.eyes < 0 {
        if has_head { 2 } else { 0 }
    } else {
        p.eyes.clamp(0, 12)
    };
    let maw = if p.maw < 0.0 {
        0.0
    } else {
        p.maw.clamp(0.0, 1.0)
    };
    Knobs {
        horns: p.horns.clamp(0.0, 1.0),
        spikes: p.spikes.clamp(0.0, 1.0),
        plates: p.plates.clamp(0.0, 1.0),
        tail,
        wings,
        eyes,
        maw,
    }
}

/// Append a leaf joint at `world_pos` under `parent`, returning its index.
pub(crate) fn add_joint(rig: &mut MonsterRig, parent: usize, name: &str, world_pos: Vec3) -> usize {
    let pw = rig.joint_world(parent);
    let i = rig.skeleton.joints.len();
    rig.skeleton.joints.push(Joint {
        name: name.into(),
        parent: Some(parent),
        translation: world_pos - pw,
        rotation: Quat::IDENTITY,
    });
    i
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn push_cone(
    rig: &mut MonsterRig,
    a: usize,
    b: usize,
    r1: f32,
    r2: f32,
    fold_rank: u8,
    k: f32,
    tint: PrimTint,
) {
    rig.prims.push(PrimitiveDesc {
        kind: PrimKind::RoundCone,
        joint_a: a,
        joint_b: b,
        r1,
        r2,
        fold_rank,
        k,
        radii: None,
        tint,
    });
}

pub(crate) fn push_flat(
    rig: &mut MonsterRig,
    a: usize,
    b: usize,
    radii: Vec3,
    fold_rank: u8,
    k: f32,
    tint: PrimTint,
) {
    rig.prims.push(PrimitiveDesc {
        kind: PrimKind::Ellipsoid,
        joint_a: a,
        joint_b: b,
        r1: 0.0,
        r2: 0.0,
        fold_rank,
        k,
        radii: Some(radii),
        tint,
    });
}

/// Sample a world point + its proximal spine joint at parameter `t` (0..1)
/// along the spine polyline. Returns `(point, proximal_joint)`.
pub(crate) fn spine_sample(rig: &MonsterRig, t: f32) -> (Vec3, usize) {
    let spine = &rig.gait.spine;
    if spine.len() < 2 {
        let j = *spine.first().unwrap_or(&0);
        return (rig.joint_world(j), j);
    }
    let segs = spine.len() - 1;
    let ft = (t.clamp(0.0, 1.0) * segs as f32).min(segs as f32 - 1e-4);
    let i = ft as usize;
    let f = ft - i as f32;
    let a = rig.joint_world(spine[i]);
    let b = rig.joint_world(spine[i + 1]);
    (a.lerp(b, f), spine[i])
}

/// Apply all M8 feature knobs to a finished rig, then recompute bounds.
fn apply_knobs(rig: &mut MonsterRig, p: &MonsterParams) {
    let s = p.size.clamp(0.2, 4.0);
    let k = resolve_knobs(rig, p);
    // ranks strictly above every plan prim so each knob folds LAST (crisp
    // attach, its own cross-band k) and cannot perturb existing bands.
    let base = rig.prims.iter().map(|d| d.fold_rank).max().unwrap_or(0);

    scale_tail(rig, k.tail);
    scale_wings(rig, k.wings);

    if k.horns > 0.0 {
        add_horns(rig, s, k.horns, base.saturating_add(1));
    }
    if k.spikes > 0.0 {
        add_spikes(rig, s, k.spikes, base.saturating_add(2));
    }
    if k.plates > 0.0 {
        add_plates(rig, s, k.plates, base.saturating_add(3));
    }
    if k.eyes > 0 {
        add_eyes(rig, s, k.eyes, base.saturating_add(4));
    }
    if k.maw > 0.0 {
        add_maw(rig, s, k.maw, base.saturating_add(5));
    }

    rig.bounds = compute_bounds(rig);
}

/// tail knob: 0 removes the tail chain's prims; other values scale thickness.
fn scale_tail(rig: &mut MonsterRig, v: f32) {
    if rig.gait.tail.is_empty() {
        return;
    }
    let set: HashSet<usize> = rig.gait.tail.iter().copied().collect();
    let touches = |d: &PrimitiveDesc| set.contains(&d.joint_a) || set.contains(&d.joint_b);
    if v <= 0.0 {
        rig.prims.retain(|d| !touches(d));
        rig.gait.tail.clear();
    } else if (v - 1.0).abs() > 1e-3 {
        for d in rig.prims.iter_mut().filter(|d| touches(d)) {
            d.r1 *= v;
            d.r2 *= v;
            if let Some(r) = d.radii.as_mut() {
                *r *= v;
            }
        }
    }
}

/// wings knob: 0 removes the wing prims (and clears the gait); else scales.
fn scale_wings(rig: &mut MonsterRig, v: f32) {
    if rig.gait.wings.is_empty() {
        return;
    }
    let set: HashSet<usize> = rig.gait.wings.iter().copied().collect();
    let touches = |d: &PrimitiveDesc| set.contains(&d.joint_a) || set.contains(&d.joint_b);
    if v <= 0.0 {
        rig.prims.retain(|d| !touches(d));
        rig.gait.wings.clear();
    } else if (v - 1.0).abs() > 1e-3 {
        for d in rig.prims.iter_mut().filter(|d| touches(d)) {
            d.r1 *= v;
            d.r2 *= v;
            if let Some(r) = d.radii.as_mut() {
                *r *= v;
            }
        }
    }
}

/// Two tapered horns curving up and back off the head, scaled by `v`.
fn add_horns(rig: &mut MonsterRig, s: f32, v: f32, rank: u8) {
    let Some(head) = rig.gait.head else {
        return; // no head joint (ooze / aberration) -> nothing to mount on
    };
    let hp = rig.joint_world(head);
    for side in [-1.0f32, 1.0] {
        let base_w = hp + Vec3::new(side * 0.07 * s, 0.09 * s, -0.02 * s);
        // mid + tip sweep up and back, growing with the knob value
        let mid_w = base_w
            + Vec3::new(
                side * 0.04 * s,
                (0.10 + 0.10 * v) * s,
                -(0.06 + 0.08 * v) * s,
            );
        let tip_w = mid_w
            + Vec3::new(
                side * 0.05 * s,
                (0.04 + 0.06 * v) * s,
                -(0.08 + 0.12 * v) * s,
            );
        let b0 = add_joint(rig, head, "horn", base_w);
        let b1 = add_joint(rig, b0, "horn_mid", mid_w);
        let b2 = add_joint(rig, b1, "horn_tip", tip_w);
        let r0 = (0.05 * s * (0.5 + 0.5 * v)).max(0.012);
        let r1 = r0 * 0.6;
        push_cone(rig, b0, b1, r0, r1, rank, 0.02 * s, PrimTint::Horn);
        push_cone(rig, b1, b2, r1, 0.008 * s, rank, 0.015 * s, PrimTint::Horn);
    }
}

/// A dorsal ridge of small spikes along the spine, count + size scaled by `v`.
fn add_spikes(rig: &mut MonsterRig, s: f32, v: f32, rank: u8) {
    let count = (2.0 + 6.0 * v).round() as usize;
    if count == 0 {
        return;
    }
    let height = (0.08 + 0.16 * v) * s;
    let rad = (0.028 + 0.03 * v) * s;
    for i in 0..count {
        let t = 0.18 + 0.62 * (i as f32 / (count.max(2) - 1) as f32);
        let (pt, parent) = spine_sample(rig, t);
        // taper spikes toward the tail end of the run
        let scale = 1.0 - 0.4 * (i as f32 / count as f32);
        let base_w = pt + Vec3::new(0.0, 0.16 * s, 0.0);
        let tip_w = base_w + Vec3::new(0.0, height * scale, -0.03 * s);
        let b0 = add_joint(rig, parent, "spike", base_w);
        let b1 = add_joint(rig, b0, "spike_tip", tip_w);
        push_cone(
            rig,
            b0,
            b1,
            rad * scale,
            0.006 * s,
            rank,
            0.012 * s,
            PrimTint::Horn,
        );
    }
}

/// A few flattened ellipsoid armor plates over the back/shoulders.
fn add_plates(rig: &mut MonsterRig, s: f32, v: f32, rank: u8) {
    let count = (1.0 + 2.0 * v).round() as usize;
    if count == 0 {
        return;
    }
    let w = (0.16 + 0.10 * v) * s;
    for i in 0..count {
        let t = 0.28 + 0.44 * (i as f32 / (count.max(2) - 1) as f32);
        let (pt, parent) = spine_sample(rig, t);
        let base_w = pt + Vec3::new(0.0, 0.14 * s, 0.0);
        let tip_w = base_w + Vec3::new(0.0, 0.0, -0.02 * s);
        let b0 = add_joint(rig, parent, "plate", base_w);
        let b1 = add_joint(rig, b0, "plate_b", tip_w);
        let radii = Vec3::new(w, 0.045 * s, w * 0.85);
        push_flat(rig, b0, b1, radii, rank, 0.02 * s, PrimTint::Horn);
    }
}

/// Emissive eyes on the head, placed symmetrically (clustered for many).
fn add_eyes(rig: &mut MonsterRig, s: f32, count: i32, rank: u8) {
    let Some(head) = rig.gait.head else {
        return; // guard: headless plans get no eyes
    };
    let hp = rig.joint_world(head);
    let er = (0.05 * s).max(0.012);
    // rows of pairs down the face; an odd count adds a central eye
    let pairs = count / 2;
    let center = count % 2 == 1;
    let r = er * (1.0 - 0.03 * count as f32).clamp(0.5, 1.0);
    for i in 0..pairs {
        let row = i as f32;
        let dy = 0.05 * s - row * 0.06 * s;
        let dz = 0.10 * s;
        let dx = (0.06 + 0.02 * row) * s;
        for side in [-1.0f32, 1.0] {
            let base_w = hp + Vec3::new(side * dx, dy, dz);
            let out_w = base_w + Vec3::new(side * 0.01 * s, 0.0, 0.02 * s);
            let b0 = add_joint(rig, head, "eye", base_w);
            let b1 = add_joint(rig, b0, "eye_out", out_w);
            push_cone(rig, b0, b1, r, r * 0.7, rank, 0.006 * s, PrimTint::Eye);
        }
    }
    if center {
        let base_w = hp + Vec3::new(0.0, 0.09 * s, 0.11 * s);
        let out_w = base_w + Vec3::new(0.0, 0.0, 0.02 * s);
        let b0 = add_joint(rig, head, "eye", base_w);
        let b1 = add_joint(rig, b0, "eye_out", out_w);
        push_cone(rig, b0, b1, r, r * 0.7, rank, 0.006 * s, PrimTint::Eye);
    }
}

/// Widen and lower the head's jaw; add small teeth cones at high values.
fn add_maw(rig: &mut MonsterRig, s: f32, v: f32, rank: u8) {
    let Some(head) = rig.gait.head else {
        return; // guard: headless plans have no jaw
    };
    let hp = rig.joint_world(head);
    // a broad lower jaw jutting forward-down, widening with the knob
    let jaw_base = hp + Vec3::new(0.0, -0.10 * s, 0.04 * s);
    let jaw_tip = hp + Vec3::new(0.0, -(0.12 + 0.06 * v) * s, (0.14 + 0.10 * v) * s);
    let j0 = add_joint(rig, head, "jaw", jaw_base);
    let j1 = add_joint(rig, j0, "jaw_tip", jaw_tip);
    let jr = (0.10 + 0.08 * v) * s;
    push_cone(rig, j0, j1, jr, 0.05 * s, rank, 0.03 * s, PrimTint::Body);
    // teeth appear once the maw is prominent
    if v > 0.5 {
        let n = (2.0 + 4.0 * v).round() as usize;
        for i in 0..n {
            let f = if n > 1 {
                i as f32 / (n - 1) as f32
            } else {
                0.5
            };
            let side = (f - 0.5) * 2.0;
            let root = jaw_base.lerp(jaw_tip, 0.4) + Vec3::new(side * jr * 0.7, 0.02 * s, 0.0);
            let tip = root + Vec3::new(0.0, 0.05 * s, 0.01 * s);
            let t0 = add_joint(rig, head, "tooth", root);
            let t1 = add_joint(rig, t0, "tooth_tip", tip);
            push_cone(
                rig,
                t0,
                t1,
                0.018 * s,
                0.003 * s,
                rank,
                0.006 * s,
                PrimTint::Horn,
            );
        }
    }
}

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

    fn params_from(json: &str) -> MonsterParams {
        serde_json::from_str(json).unwrap()
    }

    #[test]
    fn horns_and_eyes_add_geometry() {
        let base = build_rig(&params_from(
            r#"{"kind":"monster","body":"quadruped_beast"}"#,
        ));
        let horned = build_rig(&params_from(
            r#"{"kind":"monster","body":"quadruped_beast","horns":1.0,"eyes":4}"#,
        ));
        assert!(
            horned.prims.len() > base.prims.len(),
            "horns/eyes add prims"
        );
    }

    #[test]
    fn hostile_knob_input_cannot_panic() {
        // absurd values must clamp, never panic or explode the joint count
        let rig = build_rig(&params_from(
            r#"{"kind":"monster","body":"biped_brute","horns":-5.0,"spikes":1e30,
                "plates":-1.0,"eyes":999999,"maw":1e30,"tail":-9.0,"wings":50.0}"#,
        ));
        let n = rig.skeleton.joints.len();
        assert!(rig.prims.iter().all(|d| d.joint_a < n && d.joint_b < n));
        assert!(n < 400, "eye count clamp keeps joints bounded: {n}");
    }

    #[test]
    fn tail_zero_disables_chain() {
        let with = build_rig(&params_from(
            r#"{"kind":"monster","body":"quadruped_beast"}"#,
        ));
        let without = build_rig(&params_from(
            r#"{"kind":"monster","body":"quadruped_beast","tail":0.0}"#,
        ));
        assert!(without.gait.tail.is_empty());
        assert!(without.prims.len() < with.prims.len(), "tail prims removed");
    }

    #[test]
    fn quadruped_rig_is_wellformed() {
        let p = MonsterParams::default(); // body = QuadrupedBeast
        let rig = build_rig(&p);
        assert_eq!(rig.gait.legs.len(), 4, "quadruped has 4 legs");
        assert!(matches!(rig.gait.style, Gait::Walk));
        // fold ranks: at least one core prim (rank 0) exists
        assert!(rig.prims.iter().any(|d| d.fold_rank == 0));
        // every prim references valid joints
        let n = rig.skeleton.joints.len();
        assert!(rig.prims.iter().all(|d| d.joint_a < n && d.joint_b < n));
    }

    fn rig_for(body: &str) -> MonsterRig {
        let p: MonsterParams = serde_json::from_str(&format!("{{\"body\":\"{body}\"}}")).unwrap();
        build_rig(&p)
    }

    /// Every plan must reference only valid joints and have a rank-0 core.
    fn assert_wellformed(rig: &MonsterRig) {
        let n = rig.skeleton.joints.len();
        assert!(rig.prims.iter().all(|d| d.joint_a < n && d.joint_b < n));
        assert!(rig.prims.iter().any(|d| d.fold_rank == 0));
        for chain in &rig.gait.legs {
            assert!(chain.iter().all(|&j| j < n));
        }
        assert!(rig.gait.spine.iter().all(|&j| j < n));
    }

    #[test]
    fn ooze_plan() {
        let rig = rig_for("ooze");
        assert!(rig.gait.legs.is_empty());
        assert!(matches!(rig.gait.style, Gait::Pulse));
        assert_wellformed(&rig);
    }

    #[test]
    fn serpent_plan() {
        let rig = rig_for("serpent");
        assert!(rig.gait.spine.len() >= 8, "spine {}", rig.gait.spine.len());
        assert!(matches!(rig.gait.style, Gait::Slither));
        assert_wellformed(&rig);
    }

    #[test]
    fn biped_plan() {
        let rig = rig_for("biped_brute");
        assert_eq!(rig.gait.legs.len(), 2);
        assert!(matches!(rig.gait.style, Gait::Walk));
        assert_wellformed(&rig);
    }

    #[test]
    fn flyer_plan() {
        let rig = rig_for("winged_flyer");
        assert!(!rig.gait.wings.is_empty());
        assert!(matches!(rig.gait.style, Gait::Fly));
        assert_wellformed(&rig);
    }

    #[test]
    fn arachnid_plan() {
        let rig = rig_for("arachnid");
        assert!(rig.gait.legs.len() >= 6, "legs {}", rig.gait.legs.len());
        assert!(matches!(rig.gait.style, Gait::Crawl));
        assert_wellformed(&rig);
    }

    #[test]
    fn insectoid_plan() {
        let rig = rig_for("insectoid");
        assert_eq!(rig.gait.legs.len(), 6);
        assert!(matches!(rig.gait.style, Gait::Crawl));
        assert_wellformed(&rig);
    }

    #[test]
    fn aberration_plan() {
        let rig = rig_for("aberration");
        assert!(
            rig.gait.legs.len() >= 4,
            "tentacles {}",
            rig.gait.legs.len()
        );
        assert!(matches!(rig.gait.style, Gait::Pulse));
        assert_wellformed(&rig);
    }
}