Skip to main content

vibe/physics/
laws.rs

1//! Interaction Laws — physical transformation rules and evaluation engine.
2//!
3//! Evaluates interaction conditions when ambient fields, material signatures,
4//! and spatial continuants meet, producing deterministic transformation events.
5//!
6//! Reference: `docs/plans/vibe-design/20260819_fields-materials-and-creator-physics.md` §2.3.
7
8use crate::physics::fields::FieldDeclaration;
9use crate::physics::materials::MaterialSignature;
10use crate::value::Pose;
11
12/// State of an embodied continuant in the physical simulation.
13#[derive(Debug, Clone, PartialEq)]
14pub struct ContinuantState {
15    pub id: String,
16    pub pose: Pose,
17    pub material: MaterialSignature,
18    pub mass_kg: f64,
19    pub is_solid: bool,
20    pub is_crushed: bool,
21    pub current_temperature_k: f64,
22}
23
24/// Physical interaction event resulting from law evaluation.
25#[derive(Debug, Clone, PartialEq)]
26pub enum InteractionEvent {
27    /// Object exceeded its mechanical yield strength under ambient pressure.
28    YieldExceeded {
29        continuant_id: String,
30        ambient_pressure_kpa: f64,
31        yield_threshold_kpa: f64,
32        crush_ratio: f64,
33    },
34    /// Thermal energy caused a phase transition (e.g. melting).
35    PhaseChange {
36        continuant_id: String,
37        temperature_k: f64,
38        melt_threshold_k: f64,
39        new_phase: &'static str,
40    },
41    /// Solute dissolving in solvent over delta time.
42    DissolutionStep {
43        solute_id: String,
44        solvent_id: String,
45        dissolved_mass_kg: f64,
46        remaining_mass_kg: f64,
47        mass_fraction: f64,
48    },
49    /// Immiscible materials meeting at an interface without blending (e.g. oil/water).
50    ImmiscibleBarrier {
51        body_a: String,
52        body_b: String,
53        interface_area_m2: f64,
54    },
55}
56
57/// Evaluates ambient field interaction laws against a continuant.
58pub fn evaluate_field_interactions(
59    continuant: &mut ContinuantState,
60    fields: &[FieldDeclaration],
61    events: &mut Vec<InteractionEvent>,
62) {
63    for field in fields {
64        let sample = field.sample_at(&continuant.pose.position);
65
66        match field.quantity {
67            crate::physics::fields::FieldQuantity::Pressure => {
68                if let Some(mech) = &continuant.material.mechanical {
69                    if sample > mech.yield_kpa && !continuant.is_crushed {
70                        continuant.is_crushed = true;
71                        let ratio = sample / mech.yield_kpa;
72                        events.push(InteractionEvent::YieldExceeded {
73                            continuant_id: continuant.id.clone(),
74                            ambient_pressure_kpa: sample,
75                            yield_threshold_kpa: mech.yield_kpa,
76                            crush_ratio: ratio,
77                        });
78                    }
79                }
80            }
81            crate::physics::fields::FieldQuantity::Temperature => {
82                continuant.current_temperature_k = sample;
83                if let Some(thermal) = &continuant.material.thermal {
84                    if let Some(melt_k) = thermal.melt_point_k {
85                        if sample >= melt_k && continuant.is_solid {
86                            continuant.is_solid = false;
87                            events.push(InteractionEvent::PhaseChange {
88                                continuant_id: continuant.id.clone(),
89                                temperature_k: sample,
90                                melt_threshold_k: melt_k,
91                                new_phase: "Liquid",
92                            });
93                        }
94                    }
95                }
96            }
97            crate::physics::fields::FieldQuantity::ChemicalSpecies(ref species_iri) => {
98                if let Some(chem) = &continuant.material.chemical {
99                    if chem.soluble_in.as_deref() == Some(species_iri) && sample > 0.0 {
100                        // Rate law: dm/dt = k * m * dt (with default dt=1.0 for single eval step)
101                        let dt = 1.0;
102                        let dissolve_delta = (chem.dissolve_rate_per_s * continuant.mass_kg * dt)
103                            .min(continuant.mass_kg);
104                        continuant.mass_kg -= dissolve_delta;
105                        let fraction = if continuant.mass_kg > 0.0 {
106                            continuant.mass_kg / (continuant.mass_kg + dissolve_delta)
107                        } else {
108                            0.0
109                        };
110
111                        events.push(InteractionEvent::DissolutionStep {
112                            solute_id: continuant.id.clone(),
113                            solvent_id: species_iri.clone(),
114                            dissolved_mass_kg: dissolve_delta,
115                            remaining_mass_kg: continuant.mass_kg,
116                            mass_fraction: fraction,
117                        });
118                    }
119                }
120            }
121            _ => {}
122        }
123    }
124}
125
126/// Evaluates pairwise proximity interactions between two continuants (solvation, immiscibility).
127pub fn evaluate_pairwise_interactions(
128    body_a: &mut ContinuantState,
129    body_b: &mut ContinuantState,
130    dt: f64,
131    events: &mut Vec<InteractionEvent>,
132) {
133    // Proximity / contact distance check
134    let dx =
135        body_a.pose.position.first().unwrap_or(&0.0) - body_b.pose.position.first().unwrap_or(&0.0);
136    let dy = body_a.pose.position.get(1).unwrap_or(&0.0) - body_b.pose.get_coord(1);
137    let dz = body_a.pose.position.get(2).unwrap_or(&0.0) - body_b.pose.get_coord(2);
138    let dist_sq = dx * dx + dy * dy + dz * dz;
139
140    // Contact threshold (e.g. radius < 0.5m)
141    if dist_sq > 0.25 {
142        return;
143    }
144
145    // Check Immiscibility Barrier (e.g. Oil & Water)
146    if let Some(chem_a) = &body_a.material.chemical {
147        if chem_a.immiscible_with.contains(&body_b.material.id) {
148            events.push(InteractionEvent::ImmiscibleBarrier {
149                body_a: body_a.id.clone(),
150                body_b: body_b.id.clone(),
151                interface_area_m2: 0.01,
152            });
153            return;
154        }
155    }
156
157    // Check Solvation / Dissolution (e.g. Sugar in Water)
158    if let Some(chem_a) = &body_a.material.chemical {
159        if chem_a.soluble_in.as_deref() == Some(&body_b.material.id) && body_a.mass_kg > 0.0 {
160            let dm = (chem_a.dissolve_rate_per_s * body_a.mass_kg * dt).min(body_a.mass_kg);
161            body_a.mass_kg -= dm;
162            let frac = body_a.mass_kg / (body_a.mass_kg + dm);
163
164            events.push(InteractionEvent::DissolutionStep {
165                solute_id: body_a.id.clone(),
166                solvent_id: body_b.id.clone(),
167                dissolved_mass_kg: dm,
168                remaining_mass_kg: body_a.mass_kg,
169                mass_fraction: frac,
170            });
171        }
172    }
173}
174
175trait PoseExt {
176    fn get_coord(&self, idx: usize) -> f64;
177}
178
179impl PoseExt for Pose {
180    fn get_coord(&self, idx: usize) -> f64 {
181        self.position.get(idx).copied().unwrap_or(0.0)
182    }
183}
184
185#[cfg(test)]
186mod tests {
187    use super::*;
188    use crate::ast::{FieldRepresentation, FieldSupport};
189    use crate::physics::fields::{AnalyticFieldProfile, FieldQuantity, FieldUnit};
190
191    fn make_test_pose(x: f64, y: f64, z: f64) -> Pose {
192        Pose {
193            position: vec![x, y, z],
194            orientation: vec![1.0, 0.0, 0.0, 0.0],
195            frame: None,
196        }
197    }
198
199    #[test]
200    fn test_yield_law_under_deep_pressure() {
201        let mut sugar = ContinuantState {
202            id: "sugar_01".to_string(),
203            pose: make_test_pose(0.0, 0.0, 0.0),
204            material: MaterialSignature::sugar_cube(),
205            mass_kg: 0.01,
206            is_solid: true,
207            is_crushed: false,
208            current_temperature_k: 293.0,
209        };
210
211        // Extreme pressure field (100 kPa > 50 kPa yield threshold)
212        let deep_pressure = FieldDeclaration {
213            id: "field:deep_pressure".to_string(),
214            quantity: FieldQuantity::Pressure,
215            unit: FieldUnit::KiloPascal,
216            support: FieldSupport::Region,
217            representation: FieldRepresentation::Analytic,
218            profile: AnalyticFieldProfile::Uniform(100.0),
219        };
220
221        let mut events = Vec::new();
222        evaluate_field_interactions(&mut sugar, &[deep_pressure], &mut events);
223
224        assert!(sugar.is_crushed);
225        assert_eq!(events.len(), 1);
226        match &events[0] {
227            InteractionEvent::YieldExceeded { crush_ratio, .. } => {
228                assert!((crush_ratio - 2.0).abs() < 1e-4);
229            }
230            _ => panic!("expected YieldExceeded event"),
231        }
232    }
233
234    #[test]
235    fn test_sugar_dissolution_in_water() {
236        let mut sugar = ContinuantState {
237            id: "sugar_01".to_string(),
238            pose: make_test_pose(0.0, 0.0, 0.0),
239            material: MaterialSignature::sugar_cube(),
240            mass_kg: 0.01,
241            is_solid: true,
242            is_crushed: false,
243            current_temperature_k: 293.0,
244        };
245
246        let mut water = ContinuantState {
247            id: "water_glass".to_string(),
248            pose: make_test_pose(0.05, 0.0, 0.0), // Close contact
249            material: MaterialSignature::liquid_water(),
250            mass_kg: 0.25,
251            is_solid: false,
252            is_crushed: false,
253            current_temperature_k: 293.0,
254        };
255
256        let mut events = Vec::new();
257        evaluate_pairwise_interactions(&mut sugar, &mut water, 0.5, &mut events);
258
259        assert_eq!(events.len(), 1);
260        match &events[0] {
261            InteractionEvent::DissolutionStep {
262                dissolved_mass_kg,
263                remaining_mass_kg,
264                ..
265            } => {
266                // Rate = 0.5/s, dt = 0.5s => dm = 0.5 * 0.01 * 0.5 = 0.0025 kg
267                assert!((dissolved_mass_kg - 0.0025).abs() < 1e-6);
268                assert!((remaining_mass_kg - 0.0075).abs() < 1e-6);
269            }
270            _ => panic!("expected DissolutionStep event"),
271        }
272    }
273
274    #[test]
275    fn test_oil_water_immiscibility() {
276        let mut oil = ContinuantState {
277            id: "oil_drop".to_string(),
278            pose: make_test_pose(0.0, 0.0, 0.0),
279            material: MaterialSignature::mineral_oil(),
280            mass_kg: 0.02,
281            is_solid: false,
282            is_crushed: false,
283            current_temperature_k: 293.0,
284        };
285
286        let mut water = ContinuantState {
287            id: "water_glass".to_string(),
288            pose: make_test_pose(0.05, 0.0, 0.0),
289            material: MaterialSignature::liquid_water(),
290            mass_kg: 0.25,
291            is_solid: false,
292            is_crushed: false,
293            current_temperature_k: 293.0,
294        };
295
296        let mut events = Vec::new();
297        evaluate_pairwise_interactions(&mut oil, &mut water, 1.0, &mut events);
298
299        assert_eq!(events.len(), 1);
300        match &events[0] {
301            InteractionEvent::ImmiscibleBarrier { .. } => {}
302            _ => panic!("expected ImmiscibleBarrier event"),
303        }
304    }
305}