Skip to main content

vibe/physics/
materials.rs

1//! Material Signatures — physical continuant properties and response traits.
2//!
3//! Encodes mechanical, optical, acoustic, chemical, and thermal facets on continuants
4//! as unit-bearing signed records without polluting 10D tensor coordinates.
5//!
6//! Reference: `docs/plans/vibe-design/20260819_fields-materials-and-creator-physics.md` §2.2.
7
8/// Mechanical response facet.
9#[derive(Debug, Clone, PartialEq)]
10pub struct MechanicalFacet {
11    /// Elastic yield strength threshold (kPa).
12    pub yield_kpa: f64,
13    /// Young's modulus of elasticity (GPa).
14    pub youngs_modulus_gpa: f64,
15    /// Mass density (kg/m³).
16    pub density_kg_m3: f64,
17    /// Poisson's ratio (dimensionless, typically 0.0 to 0.5).
18    pub poisson_ratio: f64,
19}
20
21/// Optical response facet — the **colour** reading of the one EMF spectrum axis
22/// in the 10D structure.
23///
24/// Colour and sound are two readings of that same axis. They are not two
25/// materials, and they are not place or spatial axes. This facet reads the
26/// axis. It does not invent a second spectrum and it does not write into
27/// spatial coordinates. A stressed or failed look is a change in this reading
28/// (see [`MaterialSignature::with_spectrum_stress`]), not a swapped baked
29/// texture. The game stays an editable construct (cells + records); a baked
30/// picture or frame is not the construct.
31#[derive(Debug, Clone, PartialEq)]
32pub struct OpticalFacet {
33    /// Surface diffuse albedo / reflectance in [0.0, 1.0].
34    pub albedo: f64,
35    /// Refractive index (IOR).
36    pub ior: f64,
37    /// Optical absorption coefficient (1/m).
38    pub absorption: f64,
39}
40
41/// Acoustic response facet — the **sound** reading of the same EMF spectrum
42/// axis that [`OpticalFacet`] reads as colour.
43///
44/// Not a second spectrum, not a second material, and not a spatial axis.
45/// Stress changes this reading together with the optical reading; it does not
46/// swap a baked texture or write spatial coordinates.
47#[derive(Debug, Clone, PartialEq)]
48pub struct AcousticFacet {
49    /// Characteristic acoustic impedance (Pa·s/m or Rayls).
50    pub impedance_rayls: f64,
51    /// Acoustic absorption coefficient in [0.0, 1.0].
52    pub absorption_coeff: f64,
53}
54
55/// Chemical and dissolution response facet.
56#[derive(Debug, Clone, PartialEq)]
57pub struct ChemicalFacet {
58    /// Solvent species IRI in which this material dissolves (e.g. `did:q42:species:H2O`).
59    pub soluble_in: Option<String>,
60    /// Dissolution rate constant (1/s) under standard reference conditions.
61    pub dissolve_rate_per_s: f64,
62    /// Resulting solution/dissolved species IRI (e.g. `did:q42:species:sucrose(aq)`).
63    pub dissolve_products: Option<String>,
64    /// List of immiscible species/materials (e.g. oil vs water interface barrier).
65    pub immiscible_with: Vec<String>,
66}
67
68/// Thermal response facet.
69#[derive(Debug, Clone, PartialEq)]
70pub struct ThermalFacet {
71    /// Thermal conductivity (W/(m·K)).
72    pub conductivity_w_mk: f64,
73    /// Specific heat capacity (J/(kg·K)).
74    pub specific_heat_j_kgk: f64,
75    /// Melting point (Kelvin).
76    pub melt_point_k: Option<f64>,
77    /// Boiling / vaporization point (Kelvin).
78    pub boil_point_k: Option<f64>,
79}
80
81/// Which facet of a [`MaterialSignature`] a cell is using.
82///
83/// The words are `mechanical`, `thermal`, `optical`, `acoustic`, and
84/// `chemical`. `optical` is the colour reading and `acoustic` is the sound
85/// reading of one EMF spectrum axis — not two materials, and not spatial axes.
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub enum SignatureFacet {
88    Mechanical,
89    Thermal,
90    Optical,
91    Acoustic,
92    Chemical,
93}
94
95impl SignatureFacet {
96    /// Parse the facet word a cell names. Only the five stack facets.
97    pub fn parse(name: &str) -> Option<Self> {
98        match name.trim().to_ascii_lowercase().as_str() {
99            "mechanical" => Some(Self::Mechanical),
100            "thermal" => Some(Self::Thermal),
101            "optical" => Some(Self::Optical),
102            "acoustic" => Some(Self::Acoustic),
103            "chemical" => Some(Self::Chemical),
104            _ => None,
105        }
106    }
107
108    /// `str` form.
109    pub fn as_str(self) -> &'static str {
110        match self {
111            Self::Mechanical => "mechanical",
112            Self::Thermal => "thermal",
113            Self::Optical => "optical",
114            Self::Acoustic => "acoustic",
115            Self::Chemical => "chemical",
116        }
117    }
118
119    /// Colour (`optical`) and sound (`acoustic`) read the EMF spectrum axis.
120    pub fn reads_emf_spectrum(self) -> bool {
121        matches!(self, Self::Optical | Self::Acoustic)
122    }
123
124    /// The named reading for this slot, if it is a spectrum reading.
125    pub fn spectrum_reading(self) -> Option<SpectrumReading> {
126        match self {
127            Self::Optical => Some(SpectrumReading::Colour),
128            Self::Acoustic => Some(SpectrumReading::Sound),
129            _ => None,
130        }
131    }
132}
133
134/// One number or string on a facet, so a cell record can carry the reading
135/// without a second materials system.
136#[derive(Debug, Clone, PartialEq)]
137pub enum FacetField {
138    /// Scalar in the facet's own unit.
139    Num(f64),
140    /// IRI or other text.
141    Text(String),
142    /// List of IRIs (immiscible-with, and similar).
143    Texts(Vec<String>),
144}
145
146/// Water *conditions* (natural, collected, potable, salt, grey, black).
147///
148/// Shared physics vocabulary for Poet and every Qualia app — not a town or
149/// game dialect. These names are not [`MaterialSignature`] records.
150/// `liquid_water` is species H2O only and does not subsume them.
151pub const GAME_WATER_FORMS: &[&str] = &["natural", "collected", "potable", "salt", "grey", "black"];
152
153/// True when `name` names a game water form rather than the H2O species signature.
154pub fn is_game_water_form(name: &str) -> bool {
155    let n = name.trim().to_ascii_lowercase().replace('-', "_");
156    if matches!(
157        n.as_str(),
158        "water" | "liquid_water" | "h2o" | "did:q42:species:h2o"
159    ) {
160        return false;
161    }
162    if GAME_WATER_FORMS.contains(&n.as_str()) {
163        return true;
164    }
165    const ALIASES: &[&str] = &[
166        "natural_water",
167        "collected_water",
168        "potable_water",
169        "salt_water",
170        "grey_water",
171        "gray_water",
172        "black_water",
173        "water_natural",
174        "water_collected",
175        "water_potable",
176        "water_salt",
177        "water_grey",
178        "water_gray",
179        "water_black",
180        "greywater",
181        "graywater",
182        "blackwater",
183        "saltwater",
184        "potablewater",
185        "gray",
186    ];
187    ALIASES.contains(&n.as_str())
188}
189
190/// Flora, fauna, and funga are living kinds. They are not sugar, water, or oil
191/// material signatures. Same rule in every Qualia app.
192pub fn is_living_kingdom(name: &str) -> bool {
193    matches!(
194        name.trim().to_ascii_lowercase().as_str(),
195        "flora" | "fauna" | "funga"
196    )
197}
198
199/// Colour or sound: the two readings of one EMF spectrum axis.
200///
201/// A cell names which reading. `optical` / `acoustic` are the facet slots;
202/// they do not hide whether the reading is colour or sound. Not a second
203/// spectrum, and not a spatial axis. Shared words for Poet and every Qualia app.
204#[derive(Debug, Clone, Copy, PartialEq, Eq)]
205pub enum SpectrumReading {
206    /// Colour reading. Facet slot: optical.
207    Colour,
208    /// Sound reading. Facet slot: acoustic.
209    Sound,
210}
211
212impl SpectrumReading {
213    /// Parses.
214    pub fn parse(name: &str) -> Option<Self> {
215        match name.trim().to_ascii_lowercase().as_str() {
216            "colour" | "color" => Some(Self::Colour),
217            "sound" => Some(Self::Sound),
218            _ => None,
219        }
220    }
221
222    /// `str` form.
223    pub fn as_str(self) -> &'static str {
224        match self {
225            Self::Colour => "colour",
226            Self::Sound => "sound",
227        }
228    }
229
230    /// Facet.
231    pub fn facet(self) -> SignatureFacet {
232        match self {
233            Self::Colour => SignatureFacet::Optical,
234            Self::Sound => SignatureFacet::Acoustic,
235        }
236    }
237}
238
239/// Why a part/signature bind did not attach.
240#[derive(Debug, Clone, PartialEq, Eq)]
241pub enum PartBindError {
242    /// `part` was empty. A part is its own continuant id.
243    EmptyPart,
244    /// Facet word was not one of the five.
245    UnknownFacet,
246    /// Name is a game water form, not the liquid-water signature.
247    WaterFormNotSignature,
248    /// Name is not in this physics stack's signature catalog.
249    UnknownSignature,
250    /// The signature has no data for the facet the cell named.
251    FacetAbsent,
252    /// Flora, fauna, or funga was used where a material signature belongs.
253    LivingKingdomNotMaterial,
254    /// `reading` was not colour or sound.
255    UnknownReading,
256    /// Colour/sound did not match the facet, or was set on a non-spectrum facet.
257    ReadingMismatch,
258    /// Neither facet nor reading was named.
259    MissingSelector,
260}
261
262impl PartBindError {
263    /// Message.
264    pub fn message(&self) -> String {
265        match self {
266            Self::EmptyPart => {
267                "part must name a continuant id; the whole object does not subsume the part"
268                    .into()
269            }
270            Self::UnknownFacet => {
271                "facet must be mechanical, thermal, optical, acoustic, or chemical".into()
272            }
273            Self::WaterFormNotSignature => {
274                "a water condition (natural, collected, potable, salt, grey, black) is not the liquid_water signature"
275                    .into()
276            }
277            Self::UnknownSignature => {
278                "signature is not a material record on this physics stack".into()
279            }
280            Self::FacetAbsent => "signature has no data for that facet".into(),
281            Self::LivingKingdomNotMaterial => {
282                "flora, fauna, and funga are not sugar, water, or oil material signatures".into()
283            }
284            Self::UnknownReading => "reading must be colour or sound".into(),
285            Self::ReadingMismatch => {
286                "colour and sound are the two readings of one EMF spectrum axis; they do not replace mechanical, thermal, or chemical, and they must match the facet"
287                    .into()
288            }
289            Self::MissingSelector => {
290                "name a facet, or name reading as colour or sound".into()
291            }
292        }
293    }
294}
295
296/// A part continuant with its own material signature and the facet in use.
297///
298/// The whole object does not own this signature. Optical and acoustic facets
299/// read the EMF spectrum axis; binding a part does not bake a frame.
300#[derive(Debug, Clone, PartialEq)]
301pub struct PartContinuant {
302    /// Continuant id of the part (not the whole object).
303    pub part_id: String,
304    /// Signature attached to this part.
305    pub signature: MaterialSignature,
306    /// Facet slot in use (mechanical, thermal, optical, acoustic, chemical).
307    pub facet: SignatureFacet,
308    /// Which spectrum reading, when the facet is optical (colour) or acoustic (sound).
309    ///
310    /// Absent for mechanical, thermal, and chemical. Never a single hidden
311    /// "spectrum" facet.
312    pub reading: Option<SpectrumReading>,
313}
314
315impl PartContinuant {
316    /// Bind `part` to a catalog signature and select one facet.
317    ///
318    /// Optical names the colour reading. Acoustic names the sound reading.
319    pub fn bind(part_id: &str, signature: &str, facet: &str) -> Result<Self, PartBindError> {
320        Self::bind_with(part_id, signature, Some(facet), None)
321    }
322
323    /// Bind `part` + `signature` plus a facet and/or a colour|sound reading.
324    ///
325    /// Shared words for Poet and every Qualia app. A colour or sound reading
326    /// selects the optical or acoustic slot of the one EMF spectrum axis.
327    pub fn bind_with(
328        part_id: &str,
329        signature: &str,
330        facet: Option<&str>,
331        reading: Option<&str>,
332    ) -> Result<Self, PartBindError> {
333        let part_id = part_id.trim();
334        if part_id.is_empty() {
335            return Err(PartBindError::EmptyPart);
336        }
337        let signature = MaterialSignature::lookup(signature)?;
338        let named_reading = match reading.map(str::trim).filter(|s| !s.is_empty()) {
339            Some(word) => Some(SpectrumReading::parse(word).ok_or(PartBindError::UnknownReading)?),
340            None => None,
341        };
342        let named_facet = match facet.map(str::trim).filter(|s| !s.is_empty()) {
343            Some(word) => Some(SignatureFacet::parse(word).ok_or(PartBindError::UnknownFacet)?),
344            None => None,
345        };
346        let (facet, reading) = match (named_facet, named_reading) {
347            (Some(facet), Some(reading)) => {
348                if facet.spectrum_reading() != Some(reading) {
349                    return Err(PartBindError::ReadingMismatch);
350                }
351                (facet, Some(reading))
352            }
353            (None, Some(reading)) => (reading.facet(), Some(reading)),
354            (Some(facet), None) => (facet, facet.spectrum_reading()),
355            (None, None) => return Err(PartBindError::MissingSelector),
356        };
357        if !signature.has_facet(facet) {
358            return Err(PartBindError::FacetAbsent);
359        }
360        Ok(Self {
361            part_id: part_id.to_string(),
362            signature,
363            facet,
364            reading,
365        })
366    }
367
368    /// Apply a spectrum-stress reading. Spatial coordinates are untouched.
369    pub fn with_stress(mut self, stress: f64) -> Self {
370        self.signature = self.signature.with_spectrum_stress(stress);
371        self
372    }
373
374    /// Editable construct record (cells import this; a baked frame is not it).
375    pub fn to_record(&self) -> crate::value::Value {
376        use crate::value::Value;
377        use std::collections::BTreeMap;
378
379        let mut reading = BTreeMap::new();
380        for (key, field) in self.signature.facet_fields(self.facet) {
381            reading.insert(key.to_string(), facet_field_value(field));
382        }
383        let mut rec = BTreeMap::new();
384        rec.insert("part".to_string(), Value::String(self.part_id.clone()));
385        rec.insert(
386            "signature".to_string(),
387            Value::String(self.signature.id.clone()),
388        );
389        rec.insert(
390            "signature_name".to_string(),
391            Value::String(self.signature.name.clone()),
392        );
393        rec.insert(
394            "facet".to_string(),
395            Value::String(self.facet.as_str().to_string()),
396        );
397        rec.insert("continuant".to_string(), Value::String("part".to_string()));
398        rec.insert("subsumes_whole".to_string(), Value::Bool(false));
399        // Poet imports cells + records. A baked picture is not this construct.
400        rec.insert(
401            "construct".to_string(),
402            Value::String("editable".to_string()),
403        );
404        rec.insert("baked_frame".to_string(), Value::Bool(false));
405        rec.insert(
406            "reads_emf_spectrum".to_string(),
407            Value::Bool(self.facet.reads_emf_spectrum()),
408        );
409        rec.insert("writes_spatial".to_string(), Value::Bool(false));
410        if self.facet.reads_emf_spectrum() {
411            rec.insert(
412                "spectrum_axis".to_string(),
413                Value::String("emf".to_string()),
414            );
415        }
416        if let Some(reading_name) = self.reading {
417            rec.insert(
418                "reading".to_string(),
419                Value::String(reading_name.as_str().to_string()),
420            );
421        }
422        rec.insert("fields".to_string(), Value::Record(reading));
423        Value::Record(rec)
424    }
425}
426
427fn facet_field_value(field: FacetField) -> crate::value::Value {
428    use crate::value::Value;
429    match field {
430        FacetField::Num(n) => Value::F64(n),
431        FacetField::Text(s) => Value::String(s),
432        FacetField::Texts(xs) => Value::List(xs.into_iter().map(Value::String).collect()),
433    }
434}
435
436/// A complete, multi-faceted Material Signature attached to a Continuant.
437#[derive(Debug, Clone, PartialEq)]
438pub struct MaterialSignature {
439    /// Canonical material signature IRI (e.g. `<did:q42:material:sucrose-cube-v1>`).
440    pub id: String,
441    /// Human-readable material name.
442    pub name: String,
443    /// Mechanical properties.
444    pub mechanical: Option<MechanicalFacet>,
445    /// Optical & EM properties.
446    pub optical: Option<OpticalFacet>,
447    /// Acoustic properties.
448    pub acoustic: Option<AcousticFacet>,
449    /// Chemical solubility & miscibility traits.
450    pub chemical: Option<ChemicalFacet>,
451    /// Thermal & thermodynamic properties.
452    pub thermal: Option<ThermalFacet>,
453}
454
455impl MaterialSignature {
456    /// Sugar Cube (Sucrose) canonical specification from primer §2.2.
457    pub fn sugar_cube() -> Self {
458        Self {
459            id: "did:q42:material:sucrose-cube-v1".to_string(),
460            name: "Sucrose Cube".to_string(),
461            mechanical: Some(MechanicalFacet {
462                yield_kpa: 50.0,
463                youngs_modulus_gpa: 10.0,
464                density_kg_m3: 1580.0,
465                poisson_ratio: 0.28,
466            }),
467            optical: Some(OpticalFacet {
468                albedo: 0.85,
469                ior: 1.537,
470                absorption: 0.05,
471            }),
472            acoustic: Some(AcousticFacet {
473                impedance_rayls: 2.3e6,
474                absorption_coeff: 0.15,
475            }),
476            chemical: Some(ChemicalFacet {
477                soluble_in: Some("did:q42:species:H2O".to_string()),
478                dissolve_rate_per_s: 0.5,
479                dissolve_products: Some("did:q42:species:sucrose(aq)".to_string()),
480                immiscible_with: Vec::new(),
481            }),
482            thermal: Some(ThermalFacet {
483                conductivity_w_mk: 0.58,
484                specific_heat_j_kgk: 1250.0,
485                melt_point_k: Some(459.0), // 186 °C
486                boil_point_k: None,
487            }),
488        }
489    }
490
491    /// Liquid Water canonical specification.
492    pub fn liquid_water() -> Self {
493        Self {
494            id: "did:q42:species:H2O".to_string(),
495            name: "Liquid Water".to_string(),
496            mechanical: Some(MechanicalFacet {
497                yield_kpa: 0.0,
498                youngs_modulus_gpa: 2.2, // Bulk modulus
499                density_kg_m3: 1000.0,
500                poisson_ratio: 0.5,
501            }),
502            optical: Some(OpticalFacet {
503                albedo: 0.05,
504                ior: 1.333,
505                absorption: 0.01,
506            }),
507            acoustic: Some(AcousticFacet {
508                impedance_rayls: 1.48e6,
509                absorption_coeff: 0.01,
510            }),
511            chemical: Some(ChemicalFacet {
512                soluble_in: None,
513                dissolve_rate_per_s: 0.0,
514                dissolve_products: None,
515                immiscible_with: vec!["did:q42:material:mineral-oil-v1".to_string()],
516            }),
517            thermal: Some(ThermalFacet {
518                conductivity_w_mk: 0.6,
519                specific_heat_j_kgk: 4184.0,
520                melt_point_k: Some(273.15),
521                boil_point_k: Some(373.15),
522            }),
523        }
524    }
525
526    /// Mineral Oil specification (immiscible with water).
527    pub fn mineral_oil() -> Self {
528        Self {
529            id: "did:q42:material:mineral-oil-v1".to_string(),
530            name: "Mineral Oil".to_string(),
531            mechanical: Some(MechanicalFacet {
532                yield_kpa: 0.0,
533                youngs_modulus_gpa: 1.5,
534                density_kg_m3: 850.0,
535                poisson_ratio: 0.5,
536            }),
537            optical: Some(OpticalFacet {
538                albedo: 0.1,
539                ior: 1.47,
540                absorption: 0.02,
541            }),
542            acoustic: Some(AcousticFacet {
543                impedance_rayls: 1.2e6,
544                absorption_coeff: 0.02,
545            }),
546            chemical: Some(ChemicalFacet {
547                soluble_in: None,
548                dissolve_rate_per_s: 0.0,
549                dissolve_products: None,
550                immiscible_with: vec!["did:q42:species:H2O".to_string()],
551            }),
552            thermal: Some(ThermalFacet {
553                conductivity_w_mk: 0.14,
554                specific_heat_j_kgk: 2000.0,
555                melt_point_k: Some(243.0),
556                boil_point_k: Some(573.0),
557            }),
558        }
559    }
560
561    /// HDPE shell of a water tank — a **part** continuant, not the water it holds.
562    ///
563    /// Order-of-magnitude polymer figures on this same signature stack, not a
564    /// second materials system. `liquid_water` is species H2O only: it is not
565    /// this shell, and it is not any of the six game water forms (natural,
566    /// collected, potable, salt, grey, black). The whole tank does not subsume
567    /// the shell's signature.
568    pub fn water_tank_shell() -> Self {
569        Self {
570            id: "did:q42:material:hdpe-tank-shell-v1".to_string(),
571            name: "HDPE water-tank shell".to_string(),
572            mechanical: Some(MechanicalFacet {
573                yield_kpa: 25_000.0,
574                youngs_modulus_gpa: 0.8,
575                density_kg_m3: 950.0,
576                poisson_ratio: 0.42,
577            }),
578            optical: Some(OpticalFacet {
579                albedo: 0.18,
580                ior: 1.54,
581                absorption: 0.40,
582            }),
583            acoustic: Some(AcousticFacet {
584                impedance_rayls: 1.7e6,
585                absorption_coeff: 0.08,
586            }),
587            chemical: Some(ChemicalFacet {
588                soluble_in: None,
589                dissolve_rate_per_s: 0.0,
590                dissolve_products: None,
591                immiscible_with: Vec::new(),
592            }),
593            thermal: Some(ThermalFacet {
594                conductivity_w_mk: 0.45,
595                specific_heat_j_kgk: 1900.0,
596                melt_point_k: Some(403.0),
597                boil_point_k: None,
598            }),
599        }
600    }
601
602    /// Catalog lookup on this one physics stack.
603    ///
604    /// Game water forms return [`PartBindError::WaterFormNotSignature`] and
605    /// never alias to [`Self::liquid_water`].
606    pub fn lookup(name: &str) -> Result<Self, PartBindError> {
607        if is_living_kingdom(name) {
608            return Err(PartBindError::LivingKingdomNotMaterial);
609        }
610        if is_game_water_form(name) {
611            return Err(PartBindError::WaterFormNotSignature);
612        }
613        let n = name.trim().to_ascii_lowercase();
614        Ok(match n.as_str() {
615            "sugar"
616            | "sugar_cube"
617            | "sucrose"
618            | "sucrose_cube"
619            | "did:q42:material:sucrose-cube-v1" => Self::sugar_cube(),
620            "water" | "liquid_water" | "h2o" | "did:q42:species:h2o" => Self::liquid_water(),
621            "oil" | "mineral_oil" | "did:q42:material:mineral-oil-v1" => Self::mineral_oil(),
622            "hdpe_tank_shell"
623            | "water_tank_shell"
624            | "tank_shell"
625            | "did:q42:material:hdpe-tank-shell-v1" => Self::water_tank_shell(),
626            _ => return Err(PartBindError::UnknownSignature),
627        })
628    }
629
630    /// `true` when it has facet.
631    pub fn has_facet(&self, facet: SignatureFacet) -> bool {
632        match facet {
633            SignatureFacet::Mechanical => self.mechanical.is_some(),
634            SignatureFacet::Thermal => self.thermal.is_some(),
635            SignatureFacet::Optical => self.optical.is_some(),
636            SignatureFacet::Acoustic => self.acoustic.is_some(),
637            SignatureFacet::Chemical => self.chemical.is_some(),
638        }
639    }
640
641    /// Fields of one facet. Empty when that facet is absent.
642    pub fn facet_fields(&self, facet: SignatureFacet) -> Vec<(&'static str, FacetField)> {
643        match facet {
644            SignatureFacet::Mechanical => {
645                let Some(m) = &self.mechanical else {
646                    return Vec::new();
647                };
648                vec![
649                    ("yield_kpa", FacetField::Num(m.yield_kpa)),
650                    ("youngs_modulus_gpa", FacetField::Num(m.youngs_modulus_gpa)),
651                    ("density_kg_m3", FacetField::Num(m.density_kg_m3)),
652                    ("poisson_ratio", FacetField::Num(m.poisson_ratio)),
653                ]
654            }
655            SignatureFacet::Optical => {
656                let Some(o) = &self.optical else {
657                    return Vec::new();
658                };
659                vec![
660                    ("albedo", FacetField::Num(o.albedo)),
661                    ("ior", FacetField::Num(o.ior)),
662                    ("absorption", FacetField::Num(o.absorption)),
663                ]
664            }
665            SignatureFacet::Acoustic => {
666                let Some(a) = &self.acoustic else {
667                    return Vec::new();
668                };
669                vec![
670                    ("impedance_rayls", FacetField::Num(a.impedance_rayls)),
671                    ("absorption_coeff", FacetField::Num(a.absorption_coeff)),
672                ]
673            }
674            SignatureFacet::Chemical => {
675                let Some(c) = &self.chemical else {
676                    return Vec::new();
677                };
678                let mut fields = Vec::new();
679                if let Some(s) = &c.soluble_in {
680                    fields.push(("soluble_in", FacetField::Text(s.clone())));
681                }
682                fields.push((
683                    "dissolve_rate_per_s",
684                    FacetField::Num(c.dissolve_rate_per_s),
685                ));
686                if let Some(p) = &c.dissolve_products {
687                    fields.push(("dissolve_products", FacetField::Text(p.clone())));
688                }
689                fields.push((
690                    "immiscible_with",
691                    FacetField::Texts(c.immiscible_with.clone()),
692                ));
693                fields
694            }
695            SignatureFacet::Thermal => {
696                let Some(t) = &self.thermal else {
697                    return Vec::new();
698                };
699                let mut fields = vec![
700                    ("conductivity_w_mk", FacetField::Num(t.conductivity_w_mk)),
701                    (
702                        "specific_heat_j_kgk",
703                        FacetField::Num(t.specific_heat_j_kgk),
704                    ),
705                ];
706                if let Some(m) = t.melt_point_k {
707                    fields.push(("melt_point_k", FacetField::Num(m)));
708                }
709                if let Some(b) = t.boil_point_k {
710                    fields.push(("boil_point_k", FacetField::Num(b)));
711                }
712                fields
713            }
714        }
715    }
716
717    /// Shift the colour and sound readings of the one EMF spectrum axis.
718    ///
719    /// `stress` is clamped to [0, 1]. Optical albedo falls and absorption
720    /// rises; acoustic absorption rises with the same stress. Mechanical
721    /// numbers, the signature id, and spatial coordinates are unchanged.
722    /// There is no texture id to swap — a stressed look is this reading.
723    pub fn with_spectrum_stress(&self, stress: f64) -> Self {
724        let t = stress.clamp(0.0, 1.0);
725        let mut out = self.clone();
726        if let Some(o) = out.optical.as_mut() {
727            o.albedo = (o.albedo * (1.0 - 0.65 * t)).clamp(0.0, 1.0);
728            o.absorption += 0.5 * t;
729        }
730        if let Some(a) = out.acoustic.as_mut() {
731            a.absorption_coeff = (a.absorption_coeff + 0.4 * t).clamp(0.0, 1.0);
732        }
733        out
734    }
735}
736
737#[cfg(test)]
738mod tests {
739    use super::*;
740
741    #[test]
742    fn test_sugar_cube_signature() {
743        let sugar = MaterialSignature::sugar_cube();
744        assert_eq!(sugar.name, "Sucrose Cube");
745        let mech = sugar.mechanical.as_ref().unwrap();
746        assert_eq!(mech.yield_kpa, 50.0);
747        let chem = sugar.chemical.as_ref().unwrap();
748        assert_eq!(chem.soluble_in.as_deref(), Some("did:q42:species:H2O"));
749        assert_eq!(chem.dissolve_rate_per_s, 0.5);
750    }
751
752    #[test]
753    fn test_immiscibility_relation() {
754        let water = MaterialSignature::liquid_water();
755        let oil = MaterialSignature::mineral_oil();
756
757        let water_chem = water.chemical.as_ref().unwrap();
758        let oil_chem = oil.chemical.as_ref().unwrap();
759
760        assert!(water_chem.immiscible_with.contains(&oil.id));
761        assert!(oil_chem.immiscible_with.contains(&water.id));
762    }
763
764    #[test]
765    fn tank_shell_is_not_liquid_water_or_a_water_form() {
766        let shell = MaterialSignature::water_tank_shell();
767        let water = MaterialSignature::liquid_water();
768        assert_ne!(shell.id, water.id);
769        assert!(shell.id.contains("hdpe-tank-shell"));
770        for form in GAME_WATER_FORMS {
771            assert!(is_game_water_form(form));
772            assert!(matches!(
773                MaterialSignature::lookup(form),
774                Err(PartBindError::WaterFormNotSignature)
775            ));
776        }
777        assert!(!is_game_water_form("liquid_water"));
778        assert!(!is_game_water_form("hdpe_tank_shell"));
779        let looked = MaterialSignature::lookup("hdpe_tank_shell").unwrap();
780        assert_eq!(looked.id, shell.id);
781        let species = MaterialSignature::lookup("liquid_water").unwrap();
782        assert_eq!(species.id, water.id);
783    }
784
785    #[test]
786    fn part_bind_does_not_subsume_into_the_whole_object() {
787        let a = PartContinuant::bind(
788            "did:q42:part:water-tank-shell",
789            "hdpe_tank_shell",
790            "mechanical",
791        )
792        .unwrap();
793        let b = PartContinuant::bind(
794            "did:q42:part:water-tank-shell-b",
795            "hdpe_tank_shell",
796            "mechanical",
797        )
798        .unwrap();
799        assert_ne!(a.part_id, b.part_id);
800        assert_eq!(a.signature.id, b.signature.id);
801        assert!(matches!(
802            PartContinuant::bind("did:q42:part:x", "grey", "chemical"),
803            Err(PartBindError::WaterFormNotSignature)
804        ));
805    }
806
807    #[test]
808    fn spectrum_stress_is_one_axis_two_readings_not_a_texture() {
809        let shell = MaterialSignature::water_tank_shell();
810        let stressed = shell.with_spectrum_stress(1.0);
811        let o0 = shell.optical.unwrap();
812        let o1 = stressed.optical.unwrap();
813        let a0 = shell.acoustic.unwrap();
814        let a1 = stressed.acoustic.unwrap();
815        assert!(o1.albedo < o0.albedo);
816        assert!(o1.absorption > o0.absorption);
817        assert!(a1.absorption_coeff > a0.absorption_coeff);
818        assert_eq!(
819            shell.mechanical.unwrap().density_kg_m3,
820            stressed.mechanical.unwrap().density_kg_m3
821        );
822        assert_eq!(shell.id, stressed.id);
823        assert!(SignatureFacet::Optical.reads_emf_spectrum());
824        assert!(SignatureFacet::Acoustic.reads_emf_spectrum());
825        assert!(!SignatureFacet::Mechanical.reads_emf_spectrum());
826        let rec = PartContinuant::bind(
827            "did:q42:part:water-tank-shell",
828            "hdpe_tank_shell",
829            "optical",
830        )
831        .unwrap()
832        .with_stress(1.0)
833        .to_record();
834        match rec {
835            crate::value::Value::Record(m) => {
836                assert_eq!(
837                    m.get("spectrum_axis"),
838                    Some(&crate::value::Value::String("emf".into()))
839                );
840                assert_eq!(
841                    m.get("writes_spatial"),
842                    Some(&crate::value::Value::Bool(false))
843                );
844                assert_eq!(
845                    m.get("baked_frame"),
846                    Some(&crate::value::Value::Bool(false))
847                );
848                assert_eq!(
849                    m.get("construct"),
850                    Some(&crate::value::Value::String("editable".into()))
851                );
852                assert!(!m.contains_key("texture"));
853                assert_eq!(
854                    m.get("reading"),
855                    Some(&crate::value::Value::String("colour".into()))
856                );
857                match m.get("fields") {
858                    Some(crate::value::Value::Record(fields)) => {
859                        assert!(fields.contains_key("albedo"));
860                    }
861                    other => panic!("fields {other:?}"),
862                }
863            }
864            other => panic!("{other:?}"),
865        }
866    }
867
868    #[test]
869    fn flora_fauna_funga_are_not_sugar_water_or_oil() {
870        for name in ["flora", "fauna", "funga"] {
871            assert!(is_living_kingdom(name));
872            assert!(matches!(
873                MaterialSignature::lookup(name),
874                Err(PartBindError::LivingKingdomNotMaterial)
875            ));
876            assert_ne!(
877                MaterialSignature::sugar_cube().name.to_ascii_lowercase(),
878                name
879            );
880        }
881        let colour = PartContinuant::bind_with(
882            "did:q42:part:polymer-shell",
883            "hdpe_tank_shell",
884            None,
885            Some("colour"),
886        )
887        .unwrap();
888        let sound = PartContinuant::bind_with(
889            "did:q42:part:polymer-shell",
890            "hdpe_tank_shell",
891            None,
892            Some("sound"),
893        )
894        .unwrap();
895        assert_eq!(colour.reading, Some(SpectrumReading::Colour));
896        assert_eq!(colour.facet, SignatureFacet::Optical);
897        assert_eq!(sound.reading, Some(SpectrumReading::Sound));
898        assert_eq!(sound.facet, SignatureFacet::Acoustic);
899        assert_eq!(colour.signature.id, sound.signature.id);
900        assert!(matches!(
901            PartContinuant::bind_with(
902                "did:q42:part:polymer-shell",
903                "hdpe_tank_shell",
904                Some("mechanical"),
905                Some("colour"),
906            ),
907            Err(PartBindError::ReadingMismatch)
908        ));
909    }
910}