Skip to main content

qualia_core_db/bundle/
variant_matrix.rs

1//! Multi-Model Variant Matrix & Digital Twin Family Manifest for `.hmc` Bundles.
2//!
3//! Organizes model families (species with sexual dimorphism, ontogenetic life stages,
4//! functional trims, damage states, and LOD hierarchies) into a single cohesive,
5//! attestable `.hmc` bundle.
6//!
7//! Provides deterministic query resolution ($O(1)$) with principled fallback:
8//! `(phenotype, stage, lod, state) -> &ModelVariantDescriptor`.
9
10use serde::{Deserialize, Serialize};
11
12use super::format::BundleError;
13use crate::entity_view::entity_ontologies::LifecycleStage;
14
15/// Biological sexual dimorphism / reproductive phenotype.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
17#[serde(rename_all = "snake_case")]
18pub enum BiologicalPhenotype {
19    /// Distinct male morphology.
20    Male,
21    /// Distinct female morphology.
22    Female,
23    /// Sexually monomorphic taxon (males and females share indistinguishable morphology).
24    #[default]
25    Monomorphic,
26    /// Non-reproductive worker / sterile caste.
27    Neuter,
28    /// Simultaneous or sequential hermaphroditic morphology.
29    Hermaphroditic,
30    /// Not applicable (constructed inanimate object, vehicle, building) or unrecorded.
31    Unspecified,
32}
33
34/// Level of Detail (LOD) tier.
35#[derive(
36    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, Default,
37)]
38#[serde(rename_all = "snake_case")]
39pub enum LodTier {
40    /// Hero presentation asset (highest vertex density, full skeletal rigs).
41    #[default]
42    Lod0 = 0,
43    /// High-detail close-range asset.
44    Lod1 = 1,
45    /// Medium-detail mid-range asset.
46    Lod2 = 2,
47    /// Low-detail distance asset.
48    Lod3 = 3,
49    /// Billboard / octahedral impostor representation.
50    Impostor = 4,
51}
52
53/// Physical wear, weathering, or structural damage condition.
54#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
55#[serde(rename_all = "snake_case")]
56pub enum StructuralState {
57    /// Intact, pristine condition.
58    #[default]
59    Pristine,
60    /// Surface weathering, lichen, oxidation, patina, or wear.
61    Weathered,
62    /// Functional or localized structural damage (cracked, bent, punctured).
63    Damaged,
64    /// Terminal mechanical or physical fracture (split into sub-components).
65    Fractured,
66}
67
68/// Descriptor of a single model variant stored within the `.hmc` bundle.
69#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
70pub struct ModelVariantDescriptor {
71    /// Unique identifier within the family (e.g. `"male_adult_lod0"`).
72    pub variant_id: String,
73    /// Biological sexual dimorphism form.
74    pub phenotype: BiologicalPhenotype,
75    /// Ontogenetic or mechanical lifecycle stage.
76    pub stage: LifecycleStage,
77    /// Level of detail tier.
78    pub lod: LodTier,
79    /// Structural wear or damage condition.
80    pub state: StructuralState,
81    /// Key of the embedded 3D geometry file in the bundle (e.g. `"models/male_adult.10d"`).
82    pub asset_key: String,
83    /// Optional key of the associated entity ontology volume (e.g. `"ontology/male_adult.q42"`).
84    #[serde(
85        default,
86        alias = "personal_ontology_key",
87        skip_serializing_if = "Option::is_none"
88    )]
89    pub entity_ontology_key: Option<String>,
90    /// Optional seed for procedural micro-surface/allometry synthesis.
91    #[serde(default, skip_serializing_if = "Option::is_none")]
92    pub procedural_seed: Option<u64>,
93}
94
95/// Family manifest describing a biological taxon or constructed asset family.
96#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
97pub struct TwinFamilyManifest {
98    /// Stable URN or IRI (e.g. `"urn:taxon:phascolarctos_cinereus"`).
99    pub family_id: String,
100    /// Common or trade name (e.g. `"Koala"` or `"Centrifugal Pump V2"`).
101    pub common_name: String,
102    /// Taxonomic or asset domain classification (`"fauna"`, `"flora"`, `"funga"`, `"machinery"`, `"vehicle"`).
103    pub classification: String,
104    /// Set of declared model variants.
105    pub variants: Vec<ModelVariantDescriptor>,
106    /// Variant ID to select when no specific criteria are specified.
107    pub default_variant: String,
108}
109
110impl TwinFamilyManifest {
111    /// Create an empty family manifest; variants are added with
112    /// [`Self::add_variant`] and `default_variant` selects the fallback.
113    pub fn new(
114        family_id: impl Into<String>,
115        common_name: impl Into<String>,
116        classification: impl Into<String>,
117        default_variant: impl Into<String>,
118    ) -> Self {
119        Self {
120            family_id: family_id.into(),
121            common_name: common_name.into(),
122            classification: classification.into(),
123            variants: Vec::new(),
124            default_variant: default_variant.into(),
125        }
126    }
127
128    /// Add a model variant to the family manifest.
129    pub fn add_variant(&mut self, variant: ModelVariantDescriptor) {
130        if let Some(pos) = self
131            .variants
132            .iter()
133            .position(|v| v.variant_id == variant.variant_id)
134        {
135            self.variants[pos] = variant;
136        } else {
137            self.variants.push(variant);
138        }
139    }
140
141    /// Resolve the most appropriate model variant using a principled fallback policy:
142    /// 1. Exact match on `(phenotype, stage, lod, state)`
143    /// 2. Match on `(phenotype, stage, state)` with closest available LOD tier
144    /// 3. Fallback to `Monomorphic` if sexual dimorphism variant is missing
145    /// 4. Fallback to `default_variant`
146    pub fn resolve_variant(
147        &self,
148        phenotype: BiologicalPhenotype,
149        stage: LifecycleStage,
150        lod: LodTier,
151        state: StructuralState,
152    ) -> Option<&ModelVariantDescriptor> {
153        if self.variants.is_empty() {
154            return None;
155        }
156
157        // Tier 1: Exact match
158        if let Some(v) = self.variants.iter().find(|v| {
159            v.phenotype == phenotype && v.stage == stage && v.lod == lod && v.state == state
160        }) {
161            return Some(v);
162        }
163
164        // Tier 2: Match (phenotype, stage, state) with closest LOD
165        let candidate_lods: Vec<&ModelVariantDescriptor> = self
166            .variants
167            .iter()
168            .filter(|v| v.phenotype == phenotype && v.stage == stage && v.state == state)
169            .collect();
170
171        if !candidate_lods.is_empty() {
172            // Find variant with minimum LOD distance
173            let closest = candidate_lods
174                .into_iter()
175                .min_by_key(|v| (v.lod as i32 - lod as i32).abs());
176            if let Some(c) = closest {
177                return Some(c);
178            }
179        }
180
181        // Tier 3: Monomorphic fallback if looking for Male/Female
182        if phenotype != BiologicalPhenotype::Monomorphic {
183            if let Some(v) = self.variants.iter().find(|v| {
184                v.phenotype == BiologicalPhenotype::Monomorphic
185                    && v.stage == stage
186                    && v.lod == lod
187                    && v.state == state
188            }) {
189                return Some(v);
190            }
191        }
192
193        // Tier 4: Default variant fallback
194        self.variants
195            .iter()
196            .find(|v| v.variant_id == self.default_variant)
197            .or_else(|| self.variants.first())
198    }
199
200    /// Serialise the family manifest to CBOR bytes.
201    pub fn encode_to_cbor(&self) -> Result<Vec<u8>, BundleError> {
202        let mut buf = Vec::new();
203        ciborium::into_writer(self, &mut buf).map_err(|e| BundleError::Cbor(e.to_string()))?;
204        Ok(buf)
205    }
206
207    /// Deserialise a family manifest from CBOR bytes.
208    pub fn decode_from_cbor(bytes: &[u8]) -> Result<Self, BundleError> {
209        ciborium::from_reader(bytes).map_err(|e| BundleError::Cbor(e.to_string()))
210    }
211}
212
213pub const FAMILY_MANIFEST_ENTRY_KEY: &str = "manifest/entity_family.cbor";
214pub const FAMILY_MANIFEST_LEGACY_KEY: &str = "manifest/twin_family.cbor";
215pub const FAMILY_MANIFEST_KIND: &str = "family_manifest";
216
217/// Semantic alias reflecting ontological entity framing over legacy industrial "twin".
218pub type EntityFamilyManifest = TwinFamilyManifest;
219
220#[cfg(test)]
221mod tests {
222    use super::*;
223
224    #[test]
225    fn twin_family_manifest_roundtrips_and_resolves_variants() {
226        let mut manifest = TwinFamilyManifest::new(
227            "urn:taxon:phascolarctos_cinereus",
228            "Koala",
229            "fauna",
230            "male_adult_lod0",
231        );
232
233        manifest.add_variant(ModelVariantDescriptor {
234            variant_id: "male_adult_lod0".to_string(),
235            phenotype: BiologicalPhenotype::Male,
236            stage: LifecycleStage::Adult,
237            lod: LodTier::Lod0,
238            state: StructuralState::Pristine,
239            asset_key: "models/male_adult_lod0.10d".to_string(),
240            entity_ontology_key: Some("ontology/male_adult.q42".to_string()),
241            procedural_seed: Some(42),
242        });
243
244        manifest.add_variant(ModelVariantDescriptor {
245            variant_id: "female_adult_lod0".to_string(),
246            phenotype: BiologicalPhenotype::Female,
247            stage: LifecycleStage::Adult,
248            lod: LodTier::Lod0,
249            state: StructuralState::Pristine,
250            asset_key: "models/female_adult_lod0.10d".to_string(),
251            entity_ontology_key: Some("ontology/female_adult.q42".to_string()),
252            procedural_seed: Some(43),
253        });
254
255        manifest.add_variant(ModelVariantDescriptor {
256            variant_id: "monomorphic_juvenile_lod0".to_string(),
257            phenotype: BiologicalPhenotype::Monomorphic,
258            stage: LifecycleStage::Juvenile,
259            lod: LodTier::Lod0,
260            state: StructuralState::Pristine,
261            asset_key: "models/juvenile_lod0.10d".to_string(),
262            entity_ontology_key: None,
263            procedural_seed: Some(44),
264        });
265
266        // Exact resolution: Female Adult Lod0
267        let res1 = manifest
268            .resolve_variant(
269                BiologicalPhenotype::Female,
270                LifecycleStage::Adult,
271                LodTier::Lod0,
272                StructuralState::Pristine,
273            )
274            .unwrap();
275        assert_eq!(res1.variant_id, "female_adult_lod0");
276
277        // Closest LOD fallback: Male Adult Lod2 -> resolves to Lod0
278        let res2 = manifest
279            .resolve_variant(
280                BiologicalPhenotype::Male,
281                LifecycleStage::Adult,
282                LodTier::Lod2,
283                StructuralState::Pristine,
284            )
285            .unwrap();
286        assert_eq!(res2.variant_id, "male_adult_lod0");
287
288        // Monomorphic fallback: Female Juvenile Lod0 -> resolves to Monomorphic Juvenile
289        let res3 = manifest
290            .resolve_variant(
291                BiologicalPhenotype::Female,
292                LifecycleStage::Juvenile,
293                LodTier::Lod0,
294                StructuralState::Pristine,
295            )
296            .unwrap();
297        assert_eq!(res3.variant_id, "monomorphic_juvenile_lod0");
298
299        // Roundtrip CBOR
300        let cbor_bytes = manifest.encode_to_cbor().unwrap();
301        let decoded = TwinFamilyManifest::decode_from_cbor(&cbor_bytes).unwrap();
302        assert_eq!(decoded.family_id, manifest.family_id);
303        assert_eq!(decoded.variants.len(), 3);
304    }
305}