Skip to main content

qualia_core_db/render/skeletal/
fauna_rig.rs

1//! Hardware GPU PGA Motor Dual-Quaternion Skinning, Multi-Layer ABSM,
2//! 2D Delaunay Blend Space & Constrained Motor IK for Australian Fauna.
3//!
4//! Harnesses:
5//! - **Epic 3**: Hardware GPU PGA `Motor` Dual-Quaternion Skinning, `PROC1` Motor Oscillation
6//!   (harmonic respiration pitch & caudal undulation) & 8-Channel Pre-Skinning GPU Morph Targets.
7//! - **Epic 4**: Zero-Heap Multi-Layer ABSM (`BaseLocomotion`, `UpperBodyVocalizeForage`,
8//!   `HeadLookAtPosture`), `EONT1` Ontogenetic/Metabolic Posture Modulation, 2D Bowyer-Watson
9//!   Delaunay Blend Spaces, Seam-Preserving Root Motion & Constrained Motor IK (Analytical
10//!   Two-Bone + Constrained FABRIK with `ConeLimit` and `HingeLimit`).
11//!
12//! Covers 164 East Coast Australian fauna species organized into 13 biomechanical archetypes.
13
14use crate::container_10d::skeletal_section::{
15    KinematicSolverRegime, SkeletalSectionPayload, Skl2JointDescriptorV2, SwingTwistConeLimits,
16    SKL2_JOINT_FLAG_EXOSKELETAL, SKL2_JOINT_FLAG_HYDROSTATIC, SKL2_JOINT_FLAG_SYMMETRIC,
17    SKL2_NONE_INDEX,
18};
19use crate::q_hash;
20use crate::render::skeletal::{
21    compute_ontogenetic_morph_weights_zero_heap, evaluate_morph_deltas_zero_heap,
22    evaluate_skinning_motor_palette_zero_heap, gpu_shader_skin_vertex_reference,
23    sample_blend_space_2d_zero_heap, solve_constrained_fabrik_motor_ik_zero_heap,
24    solve_two_bone_motor_ik_zero_heap, AbsmLayer, AbsmMachine, AbsmParameter, AbsmStateNode,
25    AbsmStateSource, BlendSample2D, BlendSpace2D, BoneLayerMask, EontPostureConfig,
26    GpuInstanceMorphWeights, GpuJointMotorPair, GpuMorphDelta, GpuSkinnedVertex, Joint,
27    JointConstraint, LayerBlendMode, Motor, RootMotionDelta, RootMotionExtractor, SignalQueue,
28    SignalTrigger, SkeletalError, TransitionCondition, TwoBoneIkResult,
29};
30use qualia_cooperative_core::contextual_evidence::{EpistemicTier, ObservationMethod};
31use serde::{Deserialize, Serialize};
32
33/// Maximum joints in the Australian fauna skeletal rig (fits in fixed stack buffer).
34pub const FAUNA_MAX_JOINTS: usize = 24;
35
36// ── Cardinal Joint Indices (24 Joints) ───────────────────────────────────────
37pub const JOINT_PELVIS_ROOT: usize = 0;
38pub const JOINT_SPINE: usize = 1;
39pub const JOINT_CHEST: usize = 2;
40pub const JOINT_NECK: usize = 3;
41pub const JOINT_HEAD: usize = 4;
42pub const JOINT_JAW: usize = 5;
43
44// Hindlimbs (saltatorial propulsion / bipedal cursorial / quadrupedal hind):
45pub const JOINT_LEFT_HIP: usize = 6;
46pub const JOINT_LEFT_KNEE: usize = 7;
47pub const JOINT_LEFT_ANKLE: usize = 8;
48pub const JOINT_RIGHT_HIP: usize = 9;
49pub const JOINT_RIGHT_KNEE: usize = 10;
50pub const JOINT_RIGHT_ANKLE: usize = 11;
51
52// Left Forelimb / Wing / Flipper / Claw:
53pub const JOINT_LEFT_SHOULDER: usize = 12;
54pub const JOINT_LEFT_ELBOW: usize = 13;
55pub const JOINT_LEFT_WRIST_WING: usize = 14;
56
57// Articulated Tail (macropod balance, reptile undulation, avian steering):
58pub const JOINT_TAIL_BASE: usize = 15;
59pub const JOINT_TAIL_MID: usize = 16;
60pub const JOINT_TAIL_TIP: usize = 17;
61
62// Symmetric Right Forelimb, Mandible, Thoracic & Distal Tail Extension (18..23):
63pub const JOINT_RIGHT_SHOULDER: usize = 18;
64pub const JOINT_RIGHT_ELBOW: usize = 19;
65pub const JOINT_RIGHT_WRIST_WING: usize = 20;
66pub const JOINT_JAW_MANDIBLE: usize = 21;
67pub const JOINT_MID_THORACIC: usize = 22;
68pub const JOINT_TAIL_DISTAL_TIP: usize = 23;
69
70/// Canonical joint names for SKL2 descriptor hashing and diagnostics.
71pub const FAUNA_JOINT_NAMES: [&str; FAUNA_MAX_JOINTS] = [
72    "pelvis_root",
73    "spine",
74    "chest",
75    "neck",
76    "head",
77    "jaw",
78    "left_hip",
79    "left_knee",
80    "left_ankle",
81    "right_hip",
82    "right_knee",
83    "right_ankle",
84    "left_shoulder",
85    "left_elbow",
86    "left_wrist_wing",
87    "tail_base",
88    "tail_mid",
89    "tail_tip",
90    "right_shoulder",
91    "right_elbow",
92    "right_wrist_wing",
93    "jaw_mandible",
94    "mid_thoracic",
95    "tail_distal_tip",
96];
97
98/// Canonical topological parent array for the 24-joint fauna rig (`parent < 0` for root).
99pub const FAUNA_PARENT_INDICES: [i32; FAUNA_MAX_JOINTS] = [
100    -1, // 0: PelvisRoot
101    0,  // 1: Spine
102    1,  // 2: Chest
103    2,  // 3: Neck
104    3,  // 4: Head
105    4,  // 5: Jaw
106    0,  // 6: LeftHip
107    6,  // 7: LeftKnee
108    7,  // 8: LeftAnkle
109    0,  // 9: RightHip
110    9,  // 10: RightKnee
111    10, // 11: RightAnkle
112    2,  // 12: LeftShoulder (Chest)
113    12, // 13: LeftElbow
114    13, // 14: LeftWristWing
115    0,  // 15: TailBase (Pelvis)
116    15, // 16: TailMid
117    16, // 17: TailTip
118    2,  // 18: RightShoulder (Chest)
119    18, // 19: RightElbow
120    19, // 20: RightWristWing
121    4,  // 21: JawMandible (Head)
122    1,  // 22: MidThoracic (Spine)
123    17, // 23: TailDistalTip (TailTip)
124];
125
126// ── Cardinal Clip Indices (5 Cardinal Clips) ─────────────────────────────────
127pub const CLIP_IDLE: usize = 0;
128pub const CLIP_WALK_STALK: usize = 1;
129pub const CLIP_CRUISE_TROT_GLIDE: usize = 2;
130pub const CLIP_SPRINT_HOP_DIVE: usize = 3;
131pub const CLIP_TURN: usize = 4;
132pub const FAUNA_CLIP_COUNT: usize = 5;
133
134// ── Animation Signal IDs ─────────────────────────────────────────────────────
135pub const SIG_FOOTSTEP_LEFT: u32 = 1001;
136pub const SIG_FOOTSTEP_RIGHT: u32 = 1002;
137pub const SIG_WINGBEAT: u32 = 1003;
138pub const SIG_VOCAL_CALL: u32 = 2001;
139
140// ── Biomechanical Archetypes ─────────────────────────────────────────────────
141
142/// 13 Primary Australian Biomechanical Archetypes covering all 164 catalogued species.
143#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
144pub enum FaunaBiomechanicalArchetype {
145    /// Eastern Grey Kangaroo, Red Kangaroo, Wallabies, Pademelons, Potoroos, Bettongs.
146    MacropodSaltatorial,
147    /// Common Wombat, Northern Hairy-Nosed Wombat.
148    VombatidFossorial,
149    /// Koala, Lumholtz's Tree-Kangaroo.
150    PhascolarctidArboreal,
151    /// Greater Glider, Sugar Glider, Squirrel Glider, Feathertail Glider, Brushtail Possum.
152    PetauridGlider,
153    /// Spotted-Tail Quoll, Eastern Quoll, Tasmanian Devil, Antechinus, Bandicoots, Dunnarts.
154    DasyuridPredator,
155    /// Grey-Headed Flying-Fox, Black Flying-Fox, Little Red Flying-Fox, Gould's Wattled Bat.
156    PteropodidChiroptera,
157    /// Australian Fur Seal, Indo-Pacific Bottlenose Dolphin.
158    MarinePinnipedCetacean,
159    /// Emu, Southern Cassowary.
160    RatiteBipedal,
161    /// Wedge-Tailed Eagle, White-Bellied Sea-Eagle, Eastern Osprey, Powerful Owl, Sooty Owl.
162    RaptorSoaring,
163    /// Superb Lyrebird, Sulphur-Crested Cockatoo, Gang-Gang, Kookaburra, Fairywren, Magpie.
164    PasserinePsittacine,
165    /// Lace Monitor, Gould's Goanna, Frill-Necked Lizard, Bearded Dragon, Shingleback, Estuarine Crocodile.
166    SquamateSprawling,
167    /// Red-Bellied Black Snake, Tiger Snake, Coastal Carpet Python, Green Tree Python.
168    SerpentineUndulatory,
169    /// Platypus, Short-Beaked Echidna, Murray Cod, Southern Corroboree Frog, Green Tree Frog.
170    MonotremeTeleostAmphibian,
171}
172
173impl FaunaBiomechanicalArchetype {
174    /// String identifier matching the fauna catalog representation.
175    pub const fn as_str(&self) -> &'static str {
176        match self {
177            Self::MacropodSaltatorial => "macropod_saltatorial",
178            Self::VombatidFossorial => "vombatid_fossorial",
179            Self::PhascolarctidArboreal => "phascolarctid_arboreal",
180            Self::PetauridGlider => "petaurid_glider",
181            Self::DasyuridPredator => "dasyurid_predator",
182            Self::PteropodidChiroptera => "pteropodid_chiroptera",
183            Self::MarinePinnipedCetacean => "marine_pinniped_cetacean",
184            Self::RatiteBipedal => "ratite_bipedal",
185            Self::RaptorSoaring => "raptor_soaring",
186            Self::PasserinePsittacine => "passerine_psittacine",
187            Self::SquamateSprawling => "squamate_sprawling",
188            Self::SerpentineUndulatory => "serpentine_undulatory",
189            Self::MonotremeTeleostAmphibian => "monotreme_teleost_amphibian",
190        }
191    }
192
193    /// Resolves an archetype from its canonical string name.
194    pub fn from_archetype_str(s: &str) -> Option<Self> {
195        match s {
196            "macropod_saltatorial" | "macropod" => Some(Self::MacropodSaltatorial),
197            "vombatid_fossorial" | "wombat" => Some(Self::VombatidFossorial),
198            "phascolarctid_arboreal" | "koala" => Some(Self::PhascolarctidArboreal),
199            "petaurid_glider" | "glider_possum" => Some(Self::PetauridGlider),
200            "dasyurid_predator" | "quoll_dasyurid" => Some(Self::DasyuridPredator),
201            "pteropodid_chiroptera" | "flying_fox" | "chiroptera" => {
202                Some(Self::PteropodidChiroptera)
203            }
204            "marine_pinniped_cetacean" | "pinniped_cetacean" | "cetacean" | "pinniped" => {
205                Some(Self::MarinePinnipedCetacean)
206            }
207            "ratite_bipedal" | "ratite" => Some(Self::RatiteBipedal),
208            "raptor_soaring" | "raptor" => Some(Self::RaptorSoaring),
209            "passerine_psittacine"
210            | "songbird"
211            | "lyrebird"
212            | "cockatoo_parrot"
213            | "kookaburra_kingfisher" => Some(Self::PasserinePsittacine),
214            "squamate_sprawling" | "goanna_skink" | "crocodilian" => Some(Self::SquamateSprawling),
215            "serpentine_undulatory" | "snake" => Some(Self::SerpentineUndulatory),
216            "monotreme_teleost_amphibian"
217            | "frog"
218            | "fish"
219            | "turtle"
220            | "crayfish"
221            | "moth_insect"
222            | "platypus"
223            | "echidna" => Some(Self::MonotremeTeleostAmphibian),
224            _ => None,
225        }
226    }
227
228    /// Resolves species metadata from `(archetype, gait, class_name)` tuple records.
229    pub fn from_species_taxonomy(archetype: &str, gait: &str, class_name: &str) -> Self {
230        if let Some(arch) = Self::from_archetype_str(archetype) {
231            return arch;
232        }
233        match class_name {
234            "Aves" => {
235                if gait == "soaring_flight" {
236                    Self::RaptorSoaring
237                } else if archetype == "ratite"
238                    || gait == "bipedal_walk" && archetype.contains("casuarius")
239                {
240                    Self::RatiteBipedal
241                } else {
242                    Self::PasserinePsittacine
243                }
244            }
245            "Reptilia" => {
246                if archetype == "snake" || gait == "lateral_undulation" {
247                    Self::SerpentineUndulatory
248                } else {
249                    Self::SquamateSprawling
250                }
251            }
252            "Amphibia" | "Actinopterygii" | "Sarcopterygii" | "Malacostraca" | "Insecta"
253            | "Arachnida" => Self::MonotremeTeleostAmphibian,
254            _ => {
255                if gait == "bipedal_saltatorial" {
256                    Self::MacropodSaltatorial
257                } else if gait == "quadrupedal_waddle" {
258                    Self::VombatidFossorial
259                } else if gait == "arboreal_climb" {
260                    Self::PhascolarctidArboreal
261                } else if gait == "patagial_glide" {
262                    Self::PetauridGlider
263                } else if gait == "flapping_flight" {
264                    Self::PteropodidChiroptera
265                } else if gait == "aquatic_swim" {
266                    Self::MarinePinnipedCetacean
267                } else {
268                    Self::DasyuridPredator
269                }
270            }
271        }
272    }
273
274    /// Returns the active joint count for this archetype (`<= FAUNA_MAX_JOINTS`).
275    #[inline]
276    pub const fn joint_count(&self) -> usize {
277        match self {
278            Self::SerpentineUndulatory
279            | Self::SquamateSprawling
280            | Self::MacropodSaltatorial
281            | Self::DasyuridPredator
282            | Self::VombatidFossorial
283            | Self::PhascolarctidArboreal
284            | Self::PetauridGlider
285            | Self::MarinePinnipedCetacean => FAUNA_MAX_JOINTS,
286            Self::MonotremeTeleostAmphibian
287            | Self::RatiteBipedal
288            | Self::RaptorSoaring
289            | Self::PasserinePsittacine
290            | Self::PteropodidChiroptera => 22,
291        }
292    }
293
294    /// Canonical anatomical pelvic girdle classification for this biomechanical archetype.
295    #[inline]
296    pub const fn pelvic_girdle_class(&self) -> PelvicGirdleClass {
297        match self {
298            Self::RatiteBipedal | Self::RaptorSoaring | Self::PasserinePsittacine => {
299                PelvicGirdleClass::AvianSynsacrum
300            }
301            Self::MarinePinnipedCetacean => PelvicGirdleClass::CetaceanVestigial,
302            Self::SerpentineUndulatory => PelvicGirdleClass::SerpentineReduced,
303            Self::MacropodSaltatorial
304            | Self::VombatidFossorial
305            | Self::PhascolarctidArboreal
306            | Self::PetauridGlider
307            | Self::DasyuridPredator
308            | Self::PteropodidChiroptera
309            | Self::SquamateSprawling
310            | Self::MonotremeTeleostAmphibian => PelvicGirdleClass::TetrapodEndoskeletal,
311        }
312    }
313
314    /// Default locomotor stance associated with this biomechanical archetype.
315    #[inline]
316    pub const fn default_stance(&self) -> FaunaStance {
317        match self {
318            Self::MacropodSaltatorial => FaunaStance::SaltatorialBiped,
319            Self::VombatidFossorial
320            | Self::PhascolarctidArboreal
321            | Self::PetauridGlider
322            | Self::MonotremeTeleostAmphibian => FaunaStance::PlantigradeQuadruped,
323            Self::DasyuridPredator => FaunaStance::DigitigradeQuadruped,
324            Self::PteropodidChiroptera | Self::RaptorSoaring | Self::PasserinePsittacine => {
325                FaunaStance::VolantWinged
326            }
327            Self::MarinePinnipedCetacean => FaunaStance::PinnipedAquatic,
328            Self::RatiteBipedal => FaunaStance::CursorialBiped,
329            Self::SquamateSprawling => FaunaStance::SprawlingQuadruped,
330            Self::SerpentineUndulatory => FaunaStance::UndulatoryApodal,
331        }
332    }
333
334    /// Whether this archetype possesses active wings / aerial patagium.
335    #[inline]
336    pub const fn has_wings(&self) -> bool {
337        matches!(
338            self,
339            Self::RaptorSoaring
340                | Self::PasserinePsittacine
341                | Self::PteropodidChiroptera
342                | Self::PetauridGlider
343        )
344    }
345
346    /// Returns authored dimensional scales `(body_length_m, hip_height_m)`.
347    pub const fn default_dimensions(&self) -> (f32, f32) {
348        match self {
349            Self::MacropodSaltatorial => (1.20, 0.85),
350            Self::VombatidFossorial => (0.95, 0.35),
351            Self::PhascolarctidArboreal => (0.75, 0.40),
352            Self::PetauridGlider => (0.45, 0.15),
353            Self::DasyuridPredator => (0.65, 0.25),
354            Self::PteropodidChiroptera => (0.35, 0.20),
355            Self::MarinePinnipedCetacean => (1.80, 0.50),
356            Self::RatiteBipedal => (1.60, 1.30),
357            Self::RaptorSoaring => (0.80, 0.50),
358            Self::PasserinePsittacine => (0.35, 0.20),
359            Self::SquamateSprawling => (1.10, 0.20),
360            Self::SerpentineUndulatory => (1.60, 0.08),
361            Self::MonotremeTeleostAmphibian => (0.45, 0.18),
362        }
363    }
364}
365
366// ── Pelvic Girdle, Stance, Multi-Tier LOD & Biological Metadata ──────────────
367
368/// Anatomical pelvic / structural anchorage classification across vertebrate,
369/// arthropod exoskeletal, and hydrostatic continuum clades.
370#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
371pub enum PelvicGirdleClass {
372    /// Endoskeletal ilium-ischium-pubis tetrapod girdle.
373    TetrapodEndoskeletal,
374    /// Fused synsacrum + pygostyle avian girdle.
375    AvianSynsacrum,
376    /// Vestigial free-floating pelvic rudiments in cetaceans/pinnipeds.
377    CetaceanVestigial,
378    /// Reduced or absent apodal pelvic girdle (serpentine clades).
379    SerpentineReduced,
380    /// Decoupled arthropod / crustacean / arachnid exoskeletal cuticle shell.
381    ExoskeletalCuticle,
382    /// Pressurized muscular / coelomic hydrostatic continuum (annelid, cephalopod, gastropod).
383    HydrostaticContinuum,
384}
385
386/// Primary locomotor stance and body-support modality.
387#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
388pub enum FaunaStance {
389    PlantigradeQuadruped,
390    DigitigradeQuadruped,
391    SaltatorialBiped,
392    CursorialBiped,
393    SprawlingQuadruped,
394    UndulatoryApodal,
395    VolantWinged,
396    PinnipedAquatic,
397    ArthropodHexapod,
398    HydrostaticSoftBody,
399}
400
401impl FaunaStance {
402    /// Maps locomotor stance to canonical pelvic / structural girdle class.
403    #[inline]
404    pub const fn pelvic_girdle_class(self) -> PelvicGirdleClass {
405        match self {
406            Self::ArthropodHexapod => PelvicGirdleClass::ExoskeletalCuticle,
407            Self::HydrostaticSoftBody => PelvicGirdleClass::HydrostaticContinuum,
408            Self::VolantWinged | Self::CursorialBiped => PelvicGirdleClass::AvianSynsacrum,
409            Self::PinnipedAquatic => PelvicGirdleClass::CetaceanVestigial,
410            Self::UndulatoryApodal => PelvicGirdleClass::SerpentineReduced,
411            Self::PlantigradeQuadruped
412            | Self::DigitigradeQuadruped
413            | Self::SaltatorialBiped
414            | Self::SprawlingQuadruped => PelvicGirdleClass::TetrapodEndoskeletal,
415        }
416    }
417
418    /// Maps locomotor stance to canonical `SKL2` kinematic solver regime.
419    #[inline]
420    pub const fn default_solver_regime(self) -> KinematicSolverRegime {
421        match self {
422            Self::ArthropodHexapod => KinematicSolverRegime::ExoskeletalCuticleShell,
423            Self::HydrostaticSoftBody => KinematicSolverRegime::HydrostaticMuscularContinuum,
424            Self::UndulatoryApodal => KinematicSolverRegime::CosseratRodContinuum,
425            Self::PlantigradeQuadruped
426            | Self::DigitigradeQuadruped
427            | Self::SaltatorialBiped
428            | Self::CursorialBiped
429            | Self::SprawlingQuadruped
430            | Self::VolantWinged
431            | Self::PinnipedAquatic => KinematicSolverRegime::ArticulatedRigidBodyDca,
432        }
433    }
434}
435
436/// Hierarchical skeletal rig level-of-detail tier per Section 8.4.
437#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
438pub enum RigLodTier {
439    /// Tier 0: Full biomechanical reference rig (up to 256 articulated elements).
440    Tier0FullBiomechanical,
441    /// Tier 1: Interactive simulation rig (32-64 elements).
442    Tier1Interactive,
443    /// Tier 2: Real-time game / crowd GPU palette rig (18-24 elements).
444    Tier2GameRuntime,
445}
446
447impl RigLodTier {
448    #[inline]
449    pub const fn max_elements(self) -> usize {
450        match self {
451            Self::Tier0FullBiomechanical => 256,
452            Self::Tier1Interactive => 64,
453            Self::Tier2GameRuntime => FAUNA_MAX_JOINTS,
454        }
455    }
456}
457
458/// Decoupled descriptor for exoskeletal arthropod / hexapod / arachnid cuticle rigs,
459/// preserving compatibility with the 13 vertebrate `FaunaBiomechanicalArchetype` variants.
460#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
461pub struct ExoskeletalCuticularArchetype {
462    pub stance: FaunaStance,
463    pub pelvic_girdle: PelvicGirdleClass,
464    pub solver_regime: KinematicSolverRegime,
465    pub podomere_segments_per_limb: u8,
466    pub cuticle_modulus_gpa: f32,
467    pub resilin_joint_compliance: f32,
468    pub active_joint_count: usize,
469}
470
471impl ExoskeletalCuticularArchetype {
472    #[inline]
473    pub const fn hexapod_insect() -> Self {
474        Self {
475            stance: FaunaStance::ArthropodHexapod,
476            pelvic_girdle: FaunaStance::ArthropodHexapod.pelvic_girdle_class(),
477            solver_regime: KinematicSolverRegime::ExoskeletalCuticleShell,
478            podomere_segments_per_limb: 5,
479            cuticle_modulus_gpa: 6.5,
480            resilin_joint_compliance: 0.35,
481            active_joint_count: FAUNA_MAX_JOINTS,
482        }
483    }
484}
485
486/// Per-joint biological structural, mechanical, and epistemic metadata aligned to `SKL2`.
487#[derive(Clone, Copy, Debug, PartialEq)]
488pub struct JointBioMetadata {
489    pub joint_index: u16,
490    pub joint_name: &'static str,
491    pub solver_regime: KinematicSolverRegime,
492    pub swing_twist: SwingTwistConeLimits,
493    pub cortical_bmd_mg_cm3: f32,
494    pub trabecular_bv_tv: f32,
495    pub bone_length_m: f32,
496    pub segment_mass_kg: f32,
497    pub epistemic_tier: EpistemicTier,
498    pub observation_method: ObservationMethod,
499    pub confidence_q8: u8,
500    pub flags: u8,
501}
502
503impl JointBioMetadata {
504    pub fn to_skl2_descriptor(&self, parent_index: i32) -> Skl2JointDescriptorV2 {
505        let mut desc = Skl2JointDescriptorV2::new(
506            q_hash(self.joint_name),
507            if parent_index < 0 {
508                SKL2_NONE_INDEX
509            } else {
510                parent_index as u16
511            },
512            self.swing_twist,
513            self.solver_regime,
514            self.cortical_bmd_mg_cm3,
515            self.trabecular_bv_tv,
516            self.bone_length_m,
517            self.segment_mass_kg,
518            self.epistemic_tier.rank(),
519            self.observation_method as u16,
520            self.confidence_q8,
521        );
522        desc.flags = self.flags;
523        desc.with_sealed_crc()
524    }
525}
526
527// ── Kinematics Helpers (Zero Heap) ───────────────────────────────────────────
528
529/// Zero-heap forward kinematics computing world-space `Motor`s from local transforms.
530#[inline]
531pub fn forward_kinematics_zero_heap(
532    parent_indices: &[i32],
533    local_pose: &[Motor],
534    out_world: &mut [Motor],
535) {
536    let count = parent_indices
537        .len()
538        .min(local_pose.len())
539        .min(out_world.len());
540    for j in 0..count {
541        let p = parent_indices[j];
542        out_world[j] = if p >= 0 && (p as usize) < count {
543            out_world[p as usize].mul(&local_pose[j]).normalize()
544        } else {
545            local_pose[j].normalize()
546        };
547    }
548}
549
550/// Computes the relative local `Motor` between a parent and child world transform.
551#[inline]
552pub fn world_to_local_motor(parent_world: &Motor, child_world: &Motor) -> Motor {
553    parent_world.conjugate().mul(child_world).normalize()
554}
555
556// ── 10D Fauna Skeletal Rig ───────────────────────────────────────────────────
557
558/// Complete 10D Articulated Fauna Skeletal Rig.
559///
560/// Encapsulates the PGA Motor joint hierarchy, 2D Bowyer–Watson Delaunay blend space,
561/// multi-layer ABSM, procedural motor oscillators, two-bone + FABRIK IK solvers,
562/// and GPU skinning palette / morph target evaluation buffers.
563#[derive(Clone, Copy, Debug)]
564pub struct FaunaSkeletalRig10d {
565    /// Biomechanical archetype.
566    pub archetype: FaunaBiomechanicalArchetype,
567    /// Active joint count (`<= FAUNA_MAX_JOINTS`).
568    pub joint_count: usize,
569    /// Up to 24 skeletal joints with authored rest transforms and inverse-bind motors.
570    pub joints: [Joint; FAUNA_MAX_JOINTS],
571    /// Parent index lookup table (`parent < 0` for root).
572    pub parent_indices: [i32; FAUNA_MAX_JOINTS],
573    /// Authored rest pose in local space.
574    pub rest_pose: [Motor; FAUNA_MAX_JOINTS],
575    /// 5 cardinal clips for 2D blend space locomotion and state machine generation.
576    pub clip_poses: [[Motor; FAUNA_MAX_JOINTS]; FAUNA_CLIP_COUNT],
577    /// 2D Bowyer-Watson Delaunay blend space parameterized by `(forward_speed, turn_rate)`.
578    pub blend_space_2d: BlendSpace2D<16, 32>,
579    /// Multi-layer zero-heap Animation Blending State Machine.
580    pub absm: AbsmMachine<4, 16, 32>,
581    /// Previous-frame skinning motors for exact TAA velocity vector evaluation.
582    pub prev_skin_motors: [Motor; FAUNA_MAX_JOINTS],
583    /// Current-frame skinning motors.
584    pub current_skin_motors: [Motor; FAUNA_MAX_JOINTS],
585    /// 64-byte GPU storage records (`GpuJointMotorPair`) ready for direct SSBO upload.
586    pub gpu_palette: [GpuJointMotorPair; FAUNA_MAX_JOINTS],
587    /// Event ring buffer for timeline animation signals.
588    pub signal_queue: SignalQueue<16>,
589}
590
591impl FaunaSkeletalRig10d {
592    /// Constructs a fully authored 10D fauna rig for the specified biomechanical archetype.
593    pub fn new(archetype: FaunaBiomechanicalArchetype) -> Self {
594        let joint_count = archetype.joint_count();
595        let parent_indices = FAUNA_PARENT_INDICES;
596        let (body_len, hip_height) = archetype.default_dimensions();
597
598        // 1. Author archetype rest local motors based on physical proportions
599        let mut rest_pose = [Motor::identity(); FAUNA_MAX_JOINTS];
600        let half_width = (body_len * 0.16).max(0.04) as f64;
601        let upper_leg = (hip_height * 0.48).max(0.05) as f64;
602        let lower_leg = (hip_height * 0.52).max(0.05) as f64;
603        let spine_len = (body_len * 0.28).max(0.06) as f64;
604        let neck_len = (body_len * 0.18).max(0.04) as f64;
605        let tail_seg = (body_len * 0.32).max(0.06) as f64;
606
607        // Pelvis / Root
608        rest_pose[JOINT_PELVIS_ROOT] = Motor::from_translation(0.0, hip_height as f64, 0.0);
609        // Spine & Chest (forward along +Z)
610        rest_pose[JOINT_SPINE] = Motor::from_translation(0.0, 0.04, spine_len * 0.5);
611        rest_pose[JOINT_CHEST] = Motor::from_translation(0.0, 0.03, spine_len * 0.5);
612        // Neck, Head, Jaw (forward + upward)
613        rest_pose[JOINT_NECK] = Motor::from_translation(0.0, neck_len * 0.6, neck_len * 0.6);
614        rest_pose[JOINT_HEAD] = Motor::from_translation(0.0, neck_len * 0.3, neck_len * 0.5);
615        rest_pose[JOINT_JAW] = Motor::from_translation(0.0, -0.04, neck_len * 0.2);
616
617        // Hindlimbs (Left & Right Hips, Knees, Ankles)
618        rest_pose[JOINT_LEFT_HIP] = Motor::from_translation(-half_width, -0.02, -0.02);
619        rest_pose[JOINT_LEFT_KNEE] = Motor::from_translation(0.0, -upper_leg, 0.04);
620        rest_pose[JOINT_LEFT_ANKLE] = Motor::from_translation(0.0, -lower_leg, -0.04);
621
622        rest_pose[JOINT_RIGHT_HIP] = Motor::from_translation(half_width, -0.02, -0.02);
623        rest_pose[JOINT_RIGHT_KNEE] = Motor::from_translation(0.0, -upper_leg, 0.04);
624        rest_pose[JOINT_RIGHT_ANKLE] = Motor::from_translation(0.0, -lower_leg, -0.04);
625
626        // Forelimbs / Wings (Left & Symmetric Right)
627        let fore_upper = upper_leg * 0.8;
628        let fore_lower = lower_leg * 0.8;
629        rest_pose[JOINT_LEFT_SHOULDER] = Motor::from_translation(-half_width * 0.9, -0.04, 0.04);
630        rest_pose[JOINT_LEFT_ELBOW] = Motor::from_translation(0.0, -fore_upper, -0.02);
631        rest_pose[JOINT_LEFT_WRIST_WING] = Motor::from_translation(0.0, -fore_lower, 0.02);
632
633        rest_pose[JOINT_RIGHT_SHOULDER] = Motor::from_translation(half_width * 0.9, -0.04, 0.04);
634        rest_pose[JOINT_RIGHT_ELBOW] = Motor::from_translation(0.0, -fore_upper, -0.02);
635        rest_pose[JOINT_RIGHT_WRIST_WING] = Motor::from_translation(0.0, -fore_lower, 0.02);
636
637        // Secondary Mandible, Mid-Thoracic & Distal Tail Extension
638        rest_pose[JOINT_JAW_MANDIBLE] = Motor::from_translation(0.0, -0.045, neck_len * 0.18);
639        rest_pose[JOINT_MID_THORACIC] = Motor::from_translation(0.0, 0.02, spine_len * 0.25);
640
641        // Articulated Tail (backward along -Z)
642        rest_pose[JOINT_TAIL_BASE] = Motor::from_translation(0.0, -0.02, -tail_seg * 0.6);
643        rest_pose[JOINT_TAIL_MID] = Motor::from_translation(0.0, -0.04, -tail_seg * 0.8);
644        rest_pose[JOINT_TAIL_TIP] = Motor::from_translation(0.0, -0.04, -tail_seg * 0.8);
645        rest_pose[JOINT_TAIL_DISTAL_TIP] = Motor::from_translation(0.0, -0.02, -tail_seg * 0.55);
646
647        // 2. Compute World Rest and Inverse Bind Motors across all 24 canonical joints
648        let mut world_rest = [Motor::identity(); FAUNA_MAX_JOINTS];
649        forward_kinematics_zero_heap(&parent_indices, &rest_pose, &mut world_rest);
650
651        let mut joints = [Joint {
652            parent: None,
653            rest_local: Motor::identity(),
654            inverse_bind: Motor::identity(),
655        }; FAUNA_MAX_JOINTS];
656
657        for j in 0..FAUNA_MAX_JOINTS {
658            let p = parent_indices[j];
659            joints[j] = Joint {
660                parent: if p >= 0 { Some(p as u16) } else { None },
661                rest_local: rest_pose[j],
662                inverse_bind: world_rest[j].conjugate().normalize(),
663            };
664        }
665
666        // 3. Synthesize 5 Cardinal Locomotion Clips
667        let mut clip_poses = [rest_pose; FAUNA_CLIP_COUNT];
668
669        // CLIP 0: Idle (rest pose with baseline postural tension)
670        clip_poses[CLIP_IDLE] = rest_pose;
671
672        // CLIP 1: Walk / Stalk (subtle alternating stride, spine yaw, tail counterbalance)
673        let mut walk_pose = rest_pose;
674        let walk_hip_rot =
675            Motor::from_rotation_translation([0.98, 0.18, 0.0, 0.0], [0.0, 0.0, 0.0]);
676        let walk_hip_rev =
677            Motor::from_rotation_translation([0.98, -0.18, 0.0, 0.0], [0.0, 0.0, 0.0]);
678        let walk_spine_yaw =
679            Motor::from_rotation_translation([0.99, 0.0, 0.08, 0.0], [0.0, 0.0, 0.0]);
680        let walk_tail_sway =
681            Motor::from_rotation_translation([0.99, 0.0, -0.12, 0.0], [0.0, 0.0, 0.0]);
682
683        walk_pose[JOINT_LEFT_HIP] = walk_pose[JOINT_LEFT_HIP].mul(&walk_hip_rot).normalize();
684        walk_pose[JOINT_RIGHT_HIP] = walk_pose[JOINT_RIGHT_HIP].mul(&walk_hip_rev).normalize();
685        walk_pose[JOINT_LEFT_SHOULDER] = walk_pose[JOINT_LEFT_SHOULDER]
686            .mul(&walk_hip_rev)
687            .normalize();
688        walk_pose[JOINT_RIGHT_SHOULDER] = walk_pose[JOINT_RIGHT_SHOULDER]
689            .mul(&walk_hip_rot)
690            .normalize();
691        walk_pose[JOINT_SPINE] = walk_pose[JOINT_SPINE].mul(&walk_spine_yaw).normalize();
692        walk_pose[JOINT_TAIL_MID] = walk_pose[JOINT_TAIL_MID].mul(&walk_tail_sway).normalize();
693        clip_poses[CLIP_WALK_STALK] = walk_pose;
694
695        // CLIP 2: Cruise / Trot / Glide (deeper stride or wing expansion)
696        let mut cruise_pose = rest_pose;
697        let cruise_hip_rot =
698            Motor::from_rotation_translation([0.94, 0.34, 0.0, 0.0], [0.0, 0.0, 0.0]);
699        let cruise_hip_rev =
700            Motor::from_rotation_translation([0.94, -0.34, 0.0, 0.0], [0.0, 0.0, 0.0]);
701        let cruise_chest_pitch =
702            Motor::from_rotation_translation([0.99, -0.10, 0.0, 0.0], [0.0, 0.0, 0.0]);
703
704        cruise_pose[JOINT_LEFT_HIP] = cruise_pose[JOINT_LEFT_HIP].mul(&cruise_hip_rot).normalize();
705        cruise_pose[JOINT_RIGHT_HIP] = cruise_pose[JOINT_RIGHT_HIP]
706            .mul(&cruise_hip_rev)
707            .normalize();
708        cruise_pose[JOINT_LEFT_SHOULDER] = cruise_pose[JOINT_LEFT_SHOULDER]
709            .mul(&cruise_hip_rev)
710            .normalize();
711        cruise_pose[JOINT_RIGHT_SHOULDER] = cruise_pose[JOINT_RIGHT_SHOULDER]
712            .mul(&cruise_hip_rot)
713            .normalize();
714        cruise_pose[JOINT_CHEST] = cruise_pose[JOINT_CHEST]
715            .mul(&cruise_chest_pitch)
716            .normalize();
717        clip_poses[CLIP_CRUISE_TROT_GLIDE] = cruise_pose;
718
719        // CLIP 3: Sprint / Saltatorial Hop / Dive (synchronous limb flex or rapid propulsion)
720        let mut sprint_pose = rest_pose;
721        let sprint_hip_rot =
722            Motor::from_rotation_translation([0.88, 0.48, 0.0, 0.0], [0.0, 0.0, 0.0]);
723        let sprint_knee_rot =
724            Motor::from_rotation_translation([0.92, -0.38, 0.0, 0.0], [0.0, 0.0, 0.0]);
725        let sprint_spine_pitch =
726            Motor::from_rotation_translation([0.97, 0.22, 0.0, 0.0], [0.0, 0.0, 0.0]);
727
728        sprint_pose[JOINT_LEFT_HIP] = sprint_pose[JOINT_LEFT_HIP].mul(&sprint_hip_rot).normalize();
729        sprint_pose[JOINT_LEFT_KNEE] = sprint_pose[JOINT_LEFT_KNEE]
730            .mul(&sprint_knee_rot)
731            .normalize();
732        sprint_pose[JOINT_RIGHT_HIP] = sprint_pose[JOINT_RIGHT_HIP]
733            .mul(&sprint_hip_rot)
734            .normalize();
735        sprint_pose[JOINT_RIGHT_KNEE] = sprint_pose[JOINT_RIGHT_KNEE]
736            .mul(&sprint_knee_rot)
737            .normalize();
738        sprint_pose[JOINT_SPINE] = sprint_pose[JOINT_SPINE]
739            .mul(&sprint_spine_pitch)
740            .normalize();
741        clip_poses[CLIP_SPRINT_HOP_DIVE] = sprint_pose;
742
743        // CLIP 4: Turn (asymmetric yaw on spine, neck and tail)
744        let mut turn_pose = rest_pose;
745        let turn_spine_yaw =
746            Motor::from_rotation_translation([0.95, 0.0, 0.31, 0.0], [0.0, 0.0, 0.0]);
747        let turn_neck_yaw =
748            Motor::from_rotation_translation([0.93, 0.0, 0.36, 0.0], [0.0, 0.0, 0.0]);
749        let turn_tail_counter =
750            Motor::from_rotation_translation([0.94, 0.0, -0.34, 0.0], [0.0, 0.0, 0.0]);
751
752        turn_pose[JOINT_SPINE] = turn_pose[JOINT_SPINE].mul(&turn_spine_yaw).normalize();
753        turn_pose[JOINT_NECK] = turn_pose[JOINT_NECK].mul(&turn_neck_yaw).normalize();
754        turn_pose[JOINT_TAIL_MID] = turn_pose[JOINT_TAIL_MID]
755            .mul(&turn_tail_counter)
756            .normalize();
757        clip_poses[CLIP_TURN] = turn_pose;
758
759        // 4. Build 2D Delaunay Blend Space
760        let mut blend_space_2d = BlendSpace2D::<16, 32>::new();
761        // 5 cardinal points forming non-collinear Delaunay triangles
762        blend_space_2d.add_point(0.0, 0.0, CLIP_IDLE as u16);
763        blend_space_2d.add_point(0.35, -0.7, CLIP_WALK_STALK as u16);
764        blend_space_2d.add_point(0.70, 0.0, CLIP_CRUISE_TROT_GLIDE as u16);
765        blend_space_2d.add_point(1.00, 0.0, CLIP_SPRINT_HOP_DIVE as u16);
766        blend_space_2d.add_point(0.35, 0.7, CLIP_TURN as u16);
767        blend_space_2d.build_triangulation();
768
769        // 5. Build Multi-Layer ABSM
770        let mut absm = AbsmMachine::<4, 16, 32>::new();
771        absm.blend_spaces_2d[0] = blend_space_2d;
772
773        // Layer 0: BaseLocomotion (Full body locomotion driven by 2D blend space)
774        let mut base_layer = AbsmLayer::new(BoneLayerMask::ALL, LayerBlendMode::Override, 1.0);
775        let mut loco_node = AbsmStateNode::default();
776        loco_node.source = AbsmStateSource::Blend2D {
777            space_index: 0,
778            param_idx: 0, // Vec2: [forward_speed_norm, turn_rate_rad]
779        };
780        loco_node.duration = 1.0;
781        loco_node.speed = 1.0;
782        loco_node.looping = true;
783        loco_node.triggers[0] = SignalTrigger {
784            active: true,
785            signal_id: SIG_FOOTSTEP_LEFT,
786            normalized_time: 0.25,
787            sonic_archetype: 1,
788            payload_f32: 0.5,
789        };
790        loco_node.triggers[1] = SignalTrigger {
791            active: true,
792            signal_id: SIG_FOOTSTEP_RIGHT,
793            normalized_time: 0.75,
794            sonic_archetype: 1,
795            payload_f32: 0.5,
796        };
797        base_layer.add_state(loco_node);
798
799        let mut idle_node = AbsmStateNode::default();
800        idle_node.source = AbsmStateSource::SingleClip {
801            clip_index: CLIP_IDLE as u16,
802        };
803        idle_node.duration = 2.0;
804        idle_node.looping = true;
805        base_layer.add_state(idle_node);
806
807        // Transitions between Idle (state 1) and Locomotion (state 0) driven by scalar speed param (idx 1)
808        base_layer.add_transition(
809            1,
810            0,
811            0.15,
812            TransitionCondition::ParamGt {
813                param_idx: 1,
814                threshold: 0.05,
815            },
816        );
817        base_layer.add_transition(
818            0,
819            1,
820            0.25,
821            TransitionCondition::ParamLt {
822                param_idx: 1,
823                threshold: 0.05,
824            },
825        );
826        absm.add_layer(base_layer);
827
828        // Layer 1: UpperBodyVocalizeForage (Masked layer covering Chest, Neck, Head, Jaw, Forelimbs)
829        let upper_body_mask = BoneLayerMask::from_joint_subtree(&parent_indices, JOINT_CHEST);
830        let mut upper_layer = AbsmLayer::new(upper_body_mask, LayerBlendMode::Override, 0.0);
831
832        let mut forage_node = AbsmStateNode::default();
833        forage_node.source = AbsmStateSource::SingleClip {
834            clip_index: CLIP_WALK_STALK as u16,
835        };
836        forage_node.duration = 1.5;
837        forage_node.looping = true;
838        upper_layer.add_state(forage_node);
839
840        let mut vocal_node = AbsmStateNode::default();
841        vocal_node.source = AbsmStateSource::SingleClip {
842            clip_index: CLIP_TURN as u16,
843        };
844        vocal_node.duration = 1.2;
845        vocal_node.looping = false;
846        vocal_node.triggers[0] = SignalTrigger {
847            active: true,
848            signal_id: SIG_VOCAL_CALL,
849            normalized_time: 0.50,
850            sonic_archetype: 10,
851            payload_f32: 1.0,
852        };
853        upper_layer.add_state(vocal_node);
854
855        // Transition on bool parameter 2 (is_vocalizing)
856        upper_layer.add_transition(
857            0,
858            1,
859            0.10,
860            TransitionCondition::ParamEqBool {
861                param_idx: 2,
862                expected: true,
863            },
864        );
865        upper_layer.add_transition(
866            1,
867            0,
868            0.20,
869            TransitionCondition::ParamEqBool {
870                param_idx: 2,
871                expected: false,
872            },
873        );
874        absm.add_layer(upper_layer);
875
876        // Layer 2: HeadLookAtPosture (Additive neck/head modulation)
877        let neck_mask = BoneLayerMask::from_joint_subtree(&parent_indices, JOINT_NECK);
878        let mut head_layer = AbsmLayer::new(neck_mask, LayerBlendMode::Additive, 0.5);
879        let mut head_node = AbsmStateNode::default();
880        head_node.source = AbsmStateSource::SingleClip {
881            clip_index: CLIP_IDLE as u16,
882        };
883        head_node.duration = 1.0;
884        head_layer.add_state(head_node);
885        absm.add_layer(head_layer);
886
887        // Configure EONT1 Posture Fatigue / Age Droop
888        absm.eont_posture = EontPostureConfig {
889            enabled: true,
890            spine_mask: BoneLayerMask::from_joint_subtree(&parent_indices, JOINT_SPINE),
891            stage: 2, // Adult baseline
892            energy_permill: 1000,
893            damage_permill: 0,
894            hydration_permill: 1000,
895            max_droop_rad: 0.35,
896        };
897
898        // Configure Root Motion Extractor on root pelvis joint
899        absm.root_motion = Some(RootMotionExtractor::new(
900            JOINT_PELVIS_ROOT,
901            rest_pose[JOINT_PELVIS_ROOT],
902            rest_pose[JOINT_PELVIS_ROOT],
903        ));
904
905        // 6. Initialize GPU Palette & Tracking
906        let prev_skin_motors = [Motor::identity(); FAUNA_MAX_JOINTS];
907        let current_skin_motors = [Motor::identity(); FAUNA_MAX_JOINTS];
908        let gpu_palette = [GpuJointMotorPair::identity(); FAUNA_MAX_JOINTS];
909        let signal_queue = SignalQueue::new();
910
911        Self {
912            archetype,
913            joint_count,
914            joints,
915            parent_indices,
916            rest_pose,
917            clip_poses,
918            blend_space_2d,
919            absm,
920            prev_skin_motors,
921            current_skin_motors,
922            gpu_palette,
923            signal_queue,
924        }
925    }
926
927    /// Sets an ABSM control parameter (e.g. idx 0: Vec2 `[speed, turn]`, idx 1: Float `speed`, idx 2: Bool `is_vocalizing`).
928    #[inline]
929    pub fn set_parameter(&mut self, idx: usize, param: AbsmParameter) {
930        self.absm.set_parameter(idx, param);
931    }
932
933    /// Samples the 2D Bowyer–Watson Delaunay blend space at `(forward_speed_norm, turn_rate_rad)`
934    /// blending cardinal clip poses directly with `Motor::sclerp` (zero heap allocations).
935    pub fn sample_blend_space(
936        &self,
937        forward_speed_norm: f32,
938        turn_rate_rad: f32,
939        out_pose: &mut [Motor],
940    ) -> Result<BlendSample2D, SkeletalError> {
941        let clip_refs: [&[Motor]; FAUNA_CLIP_COUNT] = [
942            &self.clip_poses[0][..self.joint_count],
943            &self.clip_poses[1][..self.joint_count],
944            &self.clip_poses[2][..self.joint_count],
945            &self.clip_poses[3][..self.joint_count],
946            &self.clip_poses[4][..self.joint_count],
947        ];
948        let (sample, _) = sample_blend_space_2d_zero_heap(
949            &self.blend_space_2d,
950            [forward_speed_norm, turn_rate_rad],
951            &clip_refs,
952            out_pose,
953        )?;
954        Ok(sample)
955    }
956
957    /// Advances the multi-layer ABSM by `dt` seconds, evaluating layer blending, EONT1
958    /// posture modulation, and root motion extraction while pushing crossed timeline signals
959    /// into `self.signal_queue` (`HotZeroHeap`).
960    pub fn step_absm(
961        &mut self,
962        dt: f32,
963        out_local_pose: &mut [Motor],
964    ) -> Result<RootMotionDelta, SkeletalError> {
965        let clip_refs: [&[Motor]; FAUNA_CLIP_COUNT] = [
966            &self.clip_poses[0][..self.joint_count],
967            &self.clip_poses[1][..self.joint_count],
968            &self.clip_poses[2][..self.joint_count],
969            &self.clip_poses[3][..self.joint_count],
970            &self.clip_poses[4][..self.joint_count],
971        ];
972
973        let delta = self.absm.step_and_evaluate_zero_heap(
974            dt,
975            &self.rest_pose[..self.joint_count],
976            &clip_refs,
977            &mut out_local_pose[..self.joint_count],
978            &mut self.signal_queue,
979        )?;
980
981        Ok(delta)
982    }
983
984    // ── Epic 3: PROC1 Motor Oscillation ──────────────────────────────────────
985
986    /// Applies procedural respiration breathing pitch oscillation onto the Chest and Spine joints.
987    pub fn apply_proc1_respiration_oscillation(
988        &self,
989        pose: &mut [Motor],
990        time_sec: f32,
991        amplitude_rad: f32,
992    ) {
993        const RESPIRATION_HZ: f32 = 0.35;
994        let angle =
995            (amplitude_rad * (std::f32::consts::TAU * RESPIRATION_HZ * time_sec).sin()) as f64;
996        let half = angle * 0.5;
997        let pitch_rotor =
998            Motor::from_rotation_translation([half.cos(), half.sin(), 0.0, 0.0], [0.0, 0.0, 0.0]);
999
1000        if JOINT_CHEST < pose.len() {
1001            pose[JOINT_CHEST] = pose[JOINT_CHEST].mul(&pitch_rotor).normalize();
1002        }
1003        if JOINT_MID_THORACIC < pose.len() {
1004            let half_mid = half * 0.75;
1005            let mid_rotor = Motor::from_rotation_translation(
1006                [half_mid.cos(), half_mid.sin(), 0.0, 0.0],
1007                [0.0, 0.0, 0.0],
1008            );
1009            pose[JOINT_MID_THORACIC] = pose[JOINT_MID_THORACIC].mul(&mid_rotor).normalize();
1010        }
1011        if JOINT_SPINE < pose.len() {
1012            let half_spine = half * 0.5;
1013            let spine_rotor = Motor::from_rotation_translation(
1014                [half_spine.cos(), half_spine.sin(), 0.0, 0.0],
1015                [0.0, 0.0, 0.0],
1016            );
1017            pose[JOINT_SPINE] = pose[JOINT_SPINE].mul(&spine_rotor).normalize();
1018        }
1019    }
1020
1021    /// Applies continuous procedural caudal (tail) undulation along the Tail Base, Mid, Tip, and Distal Tip joints.
1022    pub fn apply_proc1_tail_undulation(
1023        &self,
1024        pose: &mut [Motor],
1025        time_sec: f32,
1026        frequency_hz: f32,
1027        amplitude_rad: f32,
1028    ) {
1029        let tail_joints = [
1030            JOINT_TAIL_BASE,
1031            JOINT_TAIL_MID,
1032            JOINT_TAIL_TIP,
1033            JOINT_TAIL_DISTAL_TIP,
1034        ];
1035        for (i, &j_idx) in tail_joints.iter().enumerate() {
1036            if j_idx < pose.len() {
1037                let phase = (i as f32) * 0.85;
1038                let yaw_angle = (amplitude_rad
1039                    * (std::f32::consts::TAU * frequency_hz * time_sec - phase).sin())
1040                    as f64;
1041                let half = yaw_angle * 0.5;
1042                let yaw_rotor = Motor::from_rotation_translation(
1043                    [half.cos(), 0.0, half.sin(), 0.0],
1044                    [0.0, 0.0, 0.0],
1045                );
1046                pose[j_idx] = pose[j_idx].mul(&yaw_rotor).normalize();
1047            }
1048        }
1049    }
1050
1051    // ── Epic 4: Inverse Kinematics ───────────────────────────────────────────
1052
1053    /// Solves analytical Two-Bone Motor IK for both hindlimbs (Left and Right Hip-Knee-Ankle)
1054    /// to adapt foot placement to sloped East Coast terrain elevations (`HotZeroHeap`).
1055    pub fn solve_hindlimb_terrain_ik(
1056        &self,
1057        local_pose: &mut [Motor],
1058        left_foot_target: [f32; 3],
1059        right_foot_target: [f32; 3],
1060    ) -> Result<(TwoBoneIkResult, TwoBoneIkResult), SkeletalError> {
1061        let mut world_motors = [Motor::identity(); FAUNA_MAX_JOINTS];
1062        forward_kinematics_zero_heap(
1063            &self.parent_indices,
1064            local_pose,
1065            &mut world_motors[..self.joint_count],
1066        );
1067
1068        // Left Hindlimb
1069        let (_, _p_l_hip) = world_motors[JOINT_LEFT_HIP].to_rotation_translation();
1070        let (_, p_l_knee) = world_motors[JOINT_LEFT_KNEE].to_rotation_translation();
1071        let left_pole = [
1072            p_l_knee[0] as f32,
1073            p_l_knee[1] as f32,
1074            (p_l_knee[2] + 0.6) as f32,
1075        ];
1076
1077        let left_res = solve_two_bone_motor_ik_zero_heap(
1078            world_motors[JOINT_LEFT_HIP],
1079            world_motors[JOINT_LEFT_KNEE],
1080            world_motors[JOINT_LEFT_ANKLE],
1081            0.0,
1082            0.0,
1083            left_foot_target,
1084            left_pole,
1085            0.1,
1086            std::f32::consts::PI - 0.05,
1087        )?;
1088
1089        world_motors[JOINT_LEFT_HIP] = left_res.world_motors[0];
1090        world_motors[JOINT_LEFT_KNEE] = left_res.world_motors[1];
1091        world_motors[JOINT_LEFT_ANKLE] = left_res.world_motors[2];
1092
1093        let p_pelvis = world_motors[JOINT_PELVIS_ROOT];
1094        local_pose[JOINT_LEFT_HIP] = world_to_local_motor(&p_pelvis, &world_motors[JOINT_LEFT_HIP]);
1095        local_pose[JOINT_LEFT_KNEE] = left_res.local_motors[1];
1096        local_pose[JOINT_LEFT_ANKLE] = left_res.local_motors[2];
1097
1098        // Right Hindlimb
1099        let (_, _p_r_hip) = world_motors[JOINT_RIGHT_HIP].to_rotation_translation();
1100        let (_, p_r_knee) = world_motors[JOINT_RIGHT_KNEE].to_rotation_translation();
1101        let right_pole = [
1102            p_r_knee[0] as f32,
1103            p_r_knee[1] as f32,
1104            (p_r_knee[2] + 0.6) as f32,
1105        ];
1106
1107        let right_res = solve_two_bone_motor_ik_zero_heap(
1108            world_motors[JOINT_RIGHT_HIP],
1109            world_motors[JOINT_RIGHT_KNEE],
1110            world_motors[JOINT_RIGHT_ANKLE],
1111            0.0,
1112            0.0,
1113            right_foot_target,
1114            right_pole,
1115            0.1,
1116            std::f32::consts::PI - 0.05,
1117        )?;
1118
1119        world_motors[JOINT_RIGHT_HIP] = right_res.world_motors[0];
1120        world_motors[JOINT_RIGHT_KNEE] = right_res.world_motors[1];
1121        world_motors[JOINT_RIGHT_ANKLE] = right_res.world_motors[2];
1122
1123        local_pose[JOINT_RIGHT_HIP] =
1124            world_to_local_motor(&p_pelvis, &world_motors[JOINT_RIGHT_HIP]);
1125        local_pose[JOINT_RIGHT_KNEE] = right_res.local_motors[1];
1126        local_pose[JOINT_RIGHT_ANKLE] = right_res.local_motors[2];
1127
1128        Ok((left_res, right_res))
1129    }
1130
1131    /// Solves Constrained Motor FABRIK on the articulated tail chain (Tail Base, Mid, Tip)
1132    /// enforcing conical swing limits and hinge constraints (`HotZeroHeap`).
1133    pub fn solve_tail_fabrik_ik(
1134        &self,
1135        local_pose: &mut [Motor],
1136        target_tip: [f32; 3],
1137    ) -> Result<f32, SkeletalError> {
1138        let mut world_motors = [Motor::identity(); FAUNA_MAX_JOINTS];
1139        forward_kinematics_zero_heap(
1140            &self.parent_indices,
1141            local_pose,
1142            &mut world_motors[..self.joint_count],
1143        );
1144
1145        let tail_world = [
1146            world_motors[JOINT_TAIL_BASE],
1147            world_motors[JOINT_TAIL_MID],
1148            world_motors[JOINT_TAIL_TIP],
1149        ];
1150
1151        let constraints = [
1152            JointConstraint::ConeLimit {
1153                max_half_angle_rad: 0.52, // 30 deg cone limit
1154            },
1155            JointConstraint::HingeLimit {
1156                axis: [0.0, 1.0, 0.0],
1157                min_angle_rad: -0.78, // 45 deg lateral hinge
1158                max_angle_rad: 0.78,
1159            },
1160            JointConstraint::Unconstrained,
1161        ];
1162
1163        let mut out_world = [Motor::identity(); 3];
1164        let mut out_local = [Motor::identity(); 3];
1165
1166        let err = solve_constrained_fabrik_motor_ik_zero_heap(
1167            &tail_world,
1168            &constraints,
1169            target_tip,
1170            1e-3,
1171            16,
1172            &mut out_world,
1173            &mut out_local,
1174        )?;
1175
1176        let pelvis_world = world_motors[JOINT_PELVIS_ROOT];
1177        local_pose[JOINT_TAIL_BASE] = world_to_local_motor(&pelvis_world, &out_world[0]);
1178        local_pose[JOINT_TAIL_MID] = out_local[1];
1179        local_pose[JOINT_TAIL_TIP] = out_local[2];
1180
1181        Ok(err)
1182    }
1183
1184    // ── Epic 3: GPU Skinning Palette & Morph Target Evaluation ────────────────
1185
1186    /// Evaluates the GPU dual-quaternion skinning palette into `self.gpu_palette` (`GpuJointMotorPair`),
1187    /// computing $M_{\text{skin}} = M_{\text{world}} \circ M_{\text{inv\_bind}}$ and updating previous-frame
1188    /// motors for exact TAA velocity vector evaluation (`HotZeroHeap`).
1189    pub fn evaluate_gpu_palette(&mut self, local_pose: &[Motor]) -> usize {
1190        let mut world_motors = [Motor::identity(); FAUNA_MAX_JOINTS];
1191        forward_kinematics_zero_heap(
1192            &self.parent_indices,
1193            local_pose,
1194            &mut world_motors[..self.joint_count],
1195        );
1196
1197        let mut bind_inv = [Motor::identity(); FAUNA_MAX_JOINTS];
1198        for j in 0..self.joint_count {
1199            bind_inv[j] = self.joints[j].inverse_bind;
1200        }
1201
1202        let count = evaluate_skinning_motor_palette_zero_heap(
1203            &bind_inv[..self.joint_count],
1204            &world_motors[..self.joint_count],
1205            &self.prev_skin_motors[..self.joint_count],
1206            &mut self.gpu_palette[..self.joint_count],
1207            &mut self.current_skin_motors[..self.joint_count],
1208        );
1209
1210        for j in 0..count {
1211            self.prev_skin_motors[j] = self.current_skin_motors[j];
1212        }
1213
1214        count
1215    }
1216
1217    /// Computes 48-byte `GpuInstanceMorphWeights` combining explicit facial/vocal blend shape
1218    /// weights with `.10d` `EONT1` metabolic damage, hydration, and lifecycle growth factors (`HotZeroHeap`).
1219    pub fn compute_morph_weights(
1220        &self,
1221        explicit_weights: &[f32],
1222        stage: u8,
1223        damage_permill: u16,
1224        hydration_permill: u16,
1225    ) -> GpuInstanceMorphWeights {
1226        compute_ontogenetic_morph_weights_zero_heap(
1227            explicit_weights,
1228            4, // 4 active morph targets (respiration, vocal_gular, ontogenetic_growth, hydration_condition)
1229            1, // vertex_stride
1230            stage,
1231            damage_permill,
1232            hydration_permill,
1233        )
1234    }
1235
1236    /// Displaces authored bind-pose vertex positions and normals by pre-skinning GPU morph deltas (`HotZeroHeap`).
1237    pub fn evaluate_morph_deltas(
1238        &self,
1239        base_positions: &[[f32; 3]],
1240        base_normals: &[[f32; 3]],
1241        morph_deltas: &[GpuMorphDelta],
1242        weights: &GpuInstanceMorphWeights,
1243        out_positions: &mut [[f32; 3]],
1244        out_normals: &mut [[f32; 3]],
1245    ) -> Result<usize, SkeletalError> {
1246        evaluate_morph_deltas_zero_heap(
1247            base_positions,
1248            base_normals,
1249            morph_deltas,
1250            weights,
1251            out_positions,
1252            out_normals,
1253        )
1254    }
1255
1256    /// Software reference execution of the GPU WGSL dual-quaternion skinning vertex shader,
1257    /// returning `(skinned_pos, skinned_normal, skinned_tangent, taa_motion_vector)`.
1258    pub fn verify_vertex_skinning(
1259        &self,
1260        pos: [f32; 3],
1261        normal: [f32; 3],
1262        tangent: [f32; 4],
1263        skin_attr: &GpuSkinnedVertex,
1264    ) -> ([f32; 3], [f32; 3], [f32; 4], [f32; 3]) {
1265        gpu_shader_skin_vertex_reference(
1266            pos,
1267            normal,
1268            tangent,
1269            skin_attr,
1270            &self.gpu_palette[..self.joint_count],
1271        )
1272    }
1273
1274    /// Returns the pelvic / structural girdle classification for this rig's archetype.
1275    #[inline]
1276    pub const fn pelvic_girdle_class(&self) -> PelvicGirdleClass {
1277        self.archetype.pelvic_girdle_class()
1278    }
1279
1280    /// Derives per-joint biomechanical & epistemic metadata across all 24 canonical joints.
1281    pub fn joint_bio_metadata(&self) -> [JointBioMetadata; FAUNA_MAX_JOINTS] {
1282        let (body_len, hip_height) = self.archetype.default_dimensions();
1283        let default_regime = self.archetype.default_stance().default_solver_regime();
1284        let girdle = self.archetype.pelvic_girdle_class();
1285        let is_serpentine = self.archetype == FaunaBiomechanicalArchetype::SerpentineUndulatory;
1286        let is_avian = matches!(
1287            girdle,
1288            PelvicGirdleClass::AvianSynsacrum
1289        );
1290        let default_bmd = if is_avian { 920.0 } else { 1160.0 };
1291        let default_bv_tv = if is_avian { 0.22 } else { 0.31 };
1292
1293        core::array::from_fn(|idx| {
1294            let (_, t) = self.rest_pose[idx].to_rotation_translation();
1295            let bone_len = ((t[0] * t[0] + t[1] * t[1] + t[2] * t[2]).sqrt() as f32)
1296                .max(0.02 * body_len.min(1.0));
1297            let regime = if is_serpentine && matches!(idx, JOINT_SPINE | JOINT_TAIL_BASE..=JOINT_TAIL_TIP | JOINT_TAIL_DISTAL_TIP) {
1298                KinematicSolverRegime::CosseratRodContinuum
1299            } else {
1300                default_regime
1301            };
1302            let flags = match idx {
1303                JOINT_LEFT_HIP..=JOINT_LEFT_WRIST_WING
1304                | JOINT_RIGHT_SHOULDER..=JOINT_RIGHT_WRIST_WING => SKL2_JOINT_FLAG_SYMMETRIC,
1305                _ => 0,
1306            } | match girdle {
1307                PelvicGirdleClass::ExoskeletalCuticle => SKL2_JOINT_FLAG_EXOSKELETAL,
1308                PelvicGirdleClass::HydrostaticContinuum => SKL2_JOINT_FLAG_HYDROSTATIC,
1309                _ => 0,
1310            };
1311            let swing_twist = match idx {
1312                JOINT_PELVIS_ROOT => SwingTwistConeLimits::symmetric(0.35, 0.25),
1313                JOINT_JAW | JOINT_JAW_MANDIBLE => SwingTwistConeLimits::new(0.65, 0.15, -0.05, 0.05),
1314                JOINT_LEFT_KNEE | JOINT_RIGHT_KNEE | JOINT_LEFT_ELBOW | JOINT_RIGHT_ELBOW => {
1315                    SwingTwistConeLimits::new(1.35, 0.20, -0.15, 0.15)
1316                }
1317                JOINT_TAIL_BASE..=JOINT_TAIL_TIP | JOINT_TAIL_DISTAL_TIP => {
1318                    SwingTwistConeLimits::symmetric(0.75, 0.45)
1319                }
1320                _ => SwingTwistConeLimits::default(),
1321            };
1322            let segment_mass_kg = (body_len * hip_height * 2.5).max(0.05) / (FAUNA_MAX_JOINTS as f32);
1323
1324            JointBioMetadata {
1325                joint_index: idx as u16,
1326                joint_name: FAUNA_JOINT_NAMES[idx],
1327                solver_regime: regime,
1328                swing_twist,
1329                cortical_bmd_mg_cm3: default_bmd,
1330                trabecular_bv_tv: default_bv_tv,
1331                bone_length_m: bone_len,
1332                segment_mass_kg,
1333                epistemic_tier: EpistemicTier::PhylogeneticallyBracketed,
1334                observation_method: ObservationMethod::PublishedScientificLiterature,
1335                confidence_q8: 204,
1336                flags,
1337            }
1338        })
1339    }
1340
1341    /// Exports this rig's active joints as a validated `SKL2` v2 `SkeletalSectionPayload`.
1342    pub fn to_skl2_payload(&self) -> SkeletalSectionPayload {
1343        let meta = self.joint_bio_metadata();
1344        let joints = (0..self.joint_count)
1345            .map(|idx| meta[idx].to_skl2_descriptor(self.parent_indices[idx]))
1346            .collect();
1347        SkeletalSectionPayload::new(joints)
1348    }
1349}
1350
1351// ── Unit Tests ───────────────────────────────────────────────────────────────
1352
1353#[cfg(test)]
1354mod tests {
1355    use super::*;
1356
1357    const ALL_13_ARCHETYPES: [FaunaBiomechanicalArchetype; 13] = [
1358        FaunaBiomechanicalArchetype::MacropodSaltatorial,
1359        FaunaBiomechanicalArchetype::VombatidFossorial,
1360        FaunaBiomechanicalArchetype::PhascolarctidArboreal,
1361        FaunaBiomechanicalArchetype::PetauridGlider,
1362        FaunaBiomechanicalArchetype::DasyuridPredator,
1363        FaunaBiomechanicalArchetype::PteropodidChiroptera,
1364        FaunaBiomechanicalArchetype::MarinePinnipedCetacean,
1365        FaunaBiomechanicalArchetype::RatiteBipedal,
1366        FaunaBiomechanicalArchetype::RaptorSoaring,
1367        FaunaBiomechanicalArchetype::PasserinePsittacine,
1368        FaunaBiomechanicalArchetype::SquamateSprawling,
1369        FaunaBiomechanicalArchetype::SerpentineUndulatory,
1370        FaunaBiomechanicalArchetype::MonotremeTeleostAmphibian,
1371    ];
1372
1373    #[test]
1374    fn test_rig_construction_all_13_archetypes() {
1375        for archetype in ALL_13_ARCHETYPES {
1376            let mut rig = FaunaSkeletalRig10d::new(archetype);
1377            assert!(
1378                rig.joint_count >= 15 && rig.joint_count <= FAUNA_MAX_JOINTS,
1379                "archetype {:?} has joint count {}",
1380                archetype,
1381                rig.joint_count
1382            );
1383            assert_eq!(rig.blend_space_2d.point_count, 5);
1384            assert!(rig.blend_space_2d.tri_count > 0);
1385            assert_eq!(rig.absm.layer_count, 3);
1386
1387            // Verify bind inverse cancels rest pose: skinning in bind pose produces identity motors
1388            let local_pose = rig.rest_pose;
1389            let count = rig.evaluate_gpu_palette(&local_pose);
1390            assert_eq!(count, rig.joint_count);
1391
1392            for j in 0..count {
1393                let pair = rig.gpu_palette[j];
1394                // In bind pose, M_skin = M_world * M_inv_bind = Identity
1395                assert!(
1396                    (pair.current_r[0].abs() - 1.0).abs() < 1e-3,
1397                    "archetype {:?} joint {} scalar rotor = {}",
1398                    archetype,
1399                    j,
1400                    pair.current_r[0]
1401                );
1402                assert!(
1403                    pair.current_d[0].abs() < 1e-3
1404                        && pair.current_d[1].abs() < 1e-3
1405                        && pair.current_d[2].abs() < 1e-3
1406                        && pair.current_d[3].abs() < 1e-3,
1407                    "archetype {:?} joint {} dual translation must be near 0 in bind pose",
1408                    archetype,
1409                    j
1410                );
1411            }
1412        }
1413    }
1414
1415    #[test]
1416    fn test_blend_space_2d_delaunay_sampling() {
1417        let rig = FaunaSkeletalRig10d::new(FaunaBiomechanicalArchetype::MacropodSaltatorial);
1418        let mut out_pose = [Motor::identity(); FAUNA_MAX_JOINTS];
1419
1420        // Sample at origin (Idle)
1421        let sample_idle = rig.sample_blend_space(0.0, 0.0, &mut out_pose).unwrap();
1422        assert_eq!(sample_idle.clips[0], CLIP_IDLE as u16);
1423        assert!((sample_idle.weights[0] - 1.0).abs() < 1e-4);
1424
1425        // Sample at max sprint
1426        let sample_sprint = rig.sample_blend_space(1.0, 0.0, &mut out_pose).unwrap();
1427        let sprint_idx = sample_sprint
1428            .clips
1429            .iter()
1430            .position(|&c| c == CLIP_SPRINT_HOP_DIVE as u16);
1431        assert!(sprint_idx.is_some());
1432        let w = sample_sprint.weights[sprint_idx.unwrap()];
1433        assert!(w > 0.8, "Sprint weight must dominate at speed=1.0: w={w}");
1434
1435        // Sample at intermediate coordinate (0.5, 0.1)
1436        let sample_mid = rig.sample_blend_space(0.5, 0.1, &mut out_pose).unwrap();
1437        let weight_sum = sample_mid.weights[0] + sample_mid.weights[1] + sample_mid.weights[2];
1438        assert!((weight_sum - 1.0).abs() < 1e-4);
1439    }
1440
1441    #[test]
1442    fn test_absm_stepping_transitions_and_signal_emission() {
1443        let mut rig = FaunaSkeletalRig10d::new(FaunaBiomechanicalArchetype::MacropodSaltatorial);
1444        let mut local_pose = rig.rest_pose;
1445
1446        // Start stationary: speed = 0.0
1447        rig.set_parameter(0, AbsmParameter::Vec2([0.0, 0.0]));
1448        rig.set_parameter(1, AbsmParameter::Float(0.0));
1449        let _ = rig.step_absm(0.05, &mut local_pose).unwrap();
1450
1451        // Accelerate into locomotion: speed = 0.6
1452        rig.set_parameter(0, AbsmParameter::Vec2([0.6, 0.0]));
1453        rig.set_parameter(1, AbsmParameter::Float(0.6));
1454
1455        // Step through full cycle (1.0 sec in steps of 0.1)
1456        let mut saw_signals = false;
1457        for _ in 0..15 {
1458            let delta = rig.step_absm(0.1, &mut local_pose).unwrap();
1459            assert!(delta.delta_rotor[0].is_finite());
1460            while let Some(sig) = rig.signal_queue.pop() {
1461                if sig.signal_id == SIG_FOOTSTEP_LEFT || sig.signal_id == SIG_FOOTSTEP_RIGHT {
1462                    saw_signals = true;
1463                }
1464            }
1465        }
1466        assert!(
1467            saw_signals,
1468            "Locomotion ABSM layer must emit footstep signals"
1469        );
1470    }
1471
1472    #[test]
1473    fn test_two_bone_and_constrained_fabrik_ik() {
1474        let rig = FaunaSkeletalRig10d::new(FaunaBiomechanicalArchetype::MacropodSaltatorial);
1475        let mut pose = rig.rest_pose;
1476
1477        // Sloped East Coast terrain targets
1478        let left_target = [-0.15f32, 0.05, 0.0];
1479        let right_target = [0.15f32, -0.05, 0.0];
1480
1481        let (left_res, right_res) = rig
1482            .solve_hindlimb_terrain_ik(&mut pose, left_target, right_target)
1483            .unwrap();
1484        assert!(left_res.target_error < 0.05);
1485        assert!(right_res.target_error < 0.05);
1486
1487        // Constrained FABRIK tail adaptation (within 30-degree cone limit)
1488        let tail_target = [0.0f32, 0.72, -0.82];
1489        let tail_err = rig.solve_tail_fabrik_ik(&mut pose, tail_target).unwrap();
1490        assert!(
1491            tail_err < 0.15,
1492            "Tail FABRIK error must converge: {tail_err}"
1493        );
1494    }
1495
1496    #[test]
1497    fn test_gpu_palette_evaluation_and_taa_motion_vectors() {
1498        let mut rig = FaunaSkeletalRig10d::new(FaunaBiomechanicalArchetype::DasyuridPredator);
1499        let mut pose = rig.rest_pose;
1500
1501        // Initial frame evaluation
1502        rig.evaluate_gpu_palette(&pose);
1503
1504        // Perturb root translation by +0.10 m in Z for frame 2
1505        pose[JOINT_PELVIS_ROOT] = Motor::from_translation(0.0, 0.25, 0.10);
1506        rig.evaluate_gpu_palette(&pose);
1507
1508        let test_vertex = [0.0f32, 0.25, 0.0];
1509        let test_normal = [0.0f32, 1.0, 0.0];
1510        let test_tangent = [1.0f32, 0.0, 0.0, 1.0];
1511        let skin_attr = GpuSkinnedVertex {
1512            joint_indices: [JOINT_PELVIS_ROOT as u16, 0, 0, 0],
1513            joint_weights: [1.0, 0.0, 0.0, 0.0],
1514        };
1515
1516        let (curr_p, _, _, motion_vec) =
1517            rig.verify_vertex_skinning(test_vertex, test_normal, test_tangent, &skin_attr);
1518
1519        // Motion vector = curr_p - prev_p. Since root moved +0.10 in Z, motion_vec[2] should be ~0.10
1520        assert!(
1521            (motion_vec[2] - 0.10).abs() < 1e-2,
1522            "TAA velocity vector Z must capture +0.10m displacement: actual={}",
1523            motion_vec[2]
1524        );
1525        assert!(curr_p[2].is_finite());
1526    }
1527
1528    #[test]
1529    fn test_ontogenetic_morph_weights_and_deltas() {
1530        let rig = FaunaSkeletalRig10d::new(FaunaBiomechanicalArchetype::SquamateSprawling);
1531        let explicit = [0.3f32, 0.7, 0.0, 0.0];
1532
1533        // Stage 1 (Juvenile), 200 damage permill, 800 hydration permill
1534        let weights = rig.compute_morph_weights(&explicit, 1, 200, 800);
1535        assert_eq!(weights.weights[0], 0.3);
1536        assert_eq!(weights.weights[1], 0.7);
1537        assert_eq!(weights.weights[5], 0.50); // Juvenile growth factor
1538        assert_eq!(weights.weights[6], 0.20); // 200 permill damage
1539        assert!((weights.weights[7] - 0.20).abs() < 1e-4); // 1.0 - 0.8 hydration
1540
1541        // Displace base vertex via morph deltas
1542        let base_pos = [[0.0f32, 1.0, 0.0]];
1543        let base_norm = [[0.0f32, 1.0, 0.0]];
1544        let mut deltas = [GpuMorphDelta::default(); 8];
1545        deltas[0] = GpuMorphDelta::new([0.0, 0.1, 0.0], [0.0, 0.0, 0.0]); // Respiration expansion
1546
1547        let mut out_pos = [[0.0f32; 3]];
1548        let mut out_norm = [[0.0f32; 3]];
1549        let n = rig
1550            .evaluate_morph_deltas(
1551                &base_pos,
1552                &base_norm,
1553                &deltas,
1554                &weights,
1555                &mut out_pos,
1556                &mut out_norm,
1557            )
1558            .unwrap();
1559        assert_eq!(n, 1);
1560        // Displaced by 0.3 * 0.1 = 0.03 in Y
1561        assert!((out_pos[0][1] - 1.03).abs() < 1e-4);
1562    }
1563
1564    #[test]
1565    fn test_24_joint_topology_symmetry_and_skl2_export() {
1566        assert_eq!(FAUNA_MAX_JOINTS, 24);
1567        assert_eq!(JOINT_RIGHT_SHOULDER, 18);
1568        assert_eq!(JOINT_RIGHT_ELBOW, 19);
1569        assert_eq!(JOINT_RIGHT_WRIST_WING, 20);
1570        assert_eq!(JOINT_JAW_MANDIBLE, 21);
1571        assert_eq!(JOINT_MID_THORACIC, 22);
1572        assert_eq!(JOINT_TAIL_DISTAL_TIP, 23);
1573
1574        for (j, &p) in FAUNA_PARENT_INDICES.iter().enumerate() {
1575            if j == 0 {
1576                assert!(p < 0);
1577            } else {
1578                assert!(p >= 0 && (p as usize) < j, "joint {j} has non-topological parent {p}");
1579            }
1580        }
1581
1582        let rig = FaunaSkeletalRig10d::new(FaunaBiomechanicalArchetype::DasyuridPredator);
1583        assert_eq!(rig.joint_count, 24);
1584
1585        let (_, left_shoulder_t) = rig.rest_pose[JOINT_LEFT_SHOULDER].to_rotation_translation();
1586        let (_, right_shoulder_t) = rig.rest_pose[JOINT_RIGHT_SHOULDER].to_rotation_translation();
1587        assert!((left_shoulder_t[0] + right_shoulder_t[0]).abs() < 1e-6);
1588
1589        let skl2 = rig.to_skl2_payload();
1590        assert_eq!(skl2.joints.len(), 24);
1591        let bytes = skl2.to_bytes_v2().expect("encode skl2 v2");
1592        let decoded = SkeletalSectionPayload::from_bytes(&bytes).expect("decode skl2 v2");
1593        assert_eq!(decoded.joints, skl2.joints);
1594    }
1595
1596    #[test]
1597    fn test_pelvic_girdle_class_arthropod_and_hydrostatic_mapping() {
1598        assert_eq!(
1599            FaunaStance::ArthropodHexapod.pelvic_girdle_class(),
1600            PelvicGirdleClass::ExoskeletalCuticle
1601        );
1602        assert_eq!(
1603            FaunaStance::ArthropodHexapod.default_solver_regime(),
1604            KinematicSolverRegime::ExoskeletalCuticleShell
1605        );
1606        assert_eq!(
1607            FaunaStance::HydrostaticSoftBody.pelvic_girdle_class(),
1608            PelvicGirdleClass::HydrostaticContinuum
1609        );
1610        assert_eq!(
1611            FaunaStance::HydrostaticSoftBody.default_solver_regime(),
1612            KinematicSolverRegime::HydrostaticMuscularContinuum
1613        );
1614
1615        let exo = ExoskeletalCuticularArchetype::hexapod_insect();
1616        assert_eq!(exo.pelvic_girdle, PelvicGirdleClass::ExoskeletalCuticle);
1617        assert_eq!(exo.solver_regime, KinematicSolverRegime::ExoskeletalCuticleShell);
1618        assert_eq!(RigLodTier::Tier2GameRuntime.max_elements(), FAUNA_MAX_JOINTS);
1619    }
1620}