Skip to main content

sim_components/
base.rs

1//! A compliant base under any machine (effects.base_compliance): the frame or stand the whole machine stands on, a
2//! rigid body on springs in up to six directions, translation along x, y, z and a small tilt about x, y, z through
3//! `base.pivot_m`, in the frame of the tool pose (`FrameMomentum`). Each direction with a stiffness above zero is a
4//! mass (`base.mass_kg`, or `base.inertia_<x|y|z>_kgm2` for a tilt), a spring and a damper of its own:
5//!
6//!   M d'' + 2 zeta sqrt(k M) d' + k d = L
7//!
8//! where L is what the machine puts on the base: the rate of change of the momentum of what moves on it, taken back
9//! (the motors push on their stators as they push the load), the weight of what moves and an outside force on it (a
10//! process force from a workpiece on the floor), less those at rest at the start pose, at which the base was set up:
11//!
12//!   F = -dp/dt + m g + F_ext,   T = -dL/dt + c x g + r_ext x F_ext   (about the origin; about the pivot T - P x F)
13//!
14//! dp/dt is the momentum's change along the machine's own state rates, by central differences over +-1 us. The tool
15//! rides on the base and the workpiece stands on the floor, so the base's move at the tool (`Machine::base_shift`) is
16//! the tool's too; the motors' angles are measured on the base and do not see it.
17//!
18//! M is everything that sways with the base, the machine on it included: the base's natural frequency is
19//! sqrt(k / M) / 2 pi as configured.
20//!
21//! Without effects.base_reaction the coupling is one-way: the machine's own dynamics do not feel the base's
22//! acceleration (its motors neither see the sway in their following error nor hold against it); exact where the servo
23//! holds the axes stiffly to the base or the base is much heavier than what moves.
24//!
25//! With effects.base_reaction it is two-way. The machine's momentum is linear in its speeds v (the states that move a
26//! mass: `Reaction::speeds`), P = A(q) v (linear, then angular about the pivot), and A is the map that turns the
27//! base's acceleration a (translation, then tilt) into generalised forces on them, -A^T a, as it turns gravity into
28//! A_lin^T g. Its mass matrix over the speeds is the Hessian of its kinetic energy, M = d2E / dv2 (`Machine::energy`
29//! at the state with v set to unit speeds, by polarisation: exact, E being quadratic in v). With the machine's own
30//! accelerations v0'' (its derivatives, which do not know the base), the two are solved together each evaluation:
31//!
32//!   v'' = v0'' + M^-1 A^T (w - a),   (M_B - A M^-1 A^T) a = L - k d - c d' - A M^-1 A^T w
33//!
34//! L as above (its dp/dt along the machine's own rates), w = (g x theta, 0) the change of gravity in the machine's frame
35//! by the base's tilt theta. The base's kinetic energy 1/2 M_B d'^2 + d' . P, its spring's 1/2 k d^2 and the weight's
36//! work on its tilt, -theta . (c x g - c0 x g), are in `Machine::energy` and in the signals `energy.*`; its damping c d'^2
37//! is the signal `power.base`. The process force's work on the moving base, the outside force's wrench (about the pivot,
38//! less its value at the start pose) times the base's rates, is taken off that row (it is energy put in, so a negative
39//! loss), which closes the budget while a process force works on a swaying base.
40//!
41//! The gyroscopic and centrifugal terms of the base's tilt rates on the machine (second order in the small tilt), and
42//! the change of the base's inertia with the machine's pose, are left out. A gantry crate's and the machine files' own frame mode (effects.frame_compliance)
43//! is the coupled one along one axis: the portal's posts swaying under its beam; the base is what the whole machine
44//! stands on, in series with it.
45
46use sim_core::{
47    AxisInfo, BASE_AXES, BeltSection, Config, ConfigError, ENERGY_PARTS, FrameMomentum, FrictionContact, LOSS_PREFIX,
48    Machine, Mode, MotorInfo, RatingCheck, Scene, SignalInfo, ThermalPart,
49};
50
51/// The base's directions: translation along x, y, z, tilt about x, y, z.
52pub const DOFS: [&str; 6] = ["x", "y", "z", "rx", "ry", "rz"];
53
54/// The step of the central difference that takes the momentum's rate of change, s.
55const H: f64 = 1e-6;
56
57#[derive(Debug, Clone, Copy)]
58struct Dof {
59    /// Which of `DOFS`.
60    index: usize,
61    mass: f64,
62    stiffness: f64,
63    damping: f64,
64}
65
66/// A machine on a compliant base. Its state is the machine's, then the base's deflection in each compliant direction,
67/// then their rates.
68pub struct Based {
69    inner: Box<dyn Machine>,
70    dofs: Vec<Dof>,
71    pivot: [f64; 3],
72    /// The static load at the start pose (about the origin), which the base was set up under.
73    reference: [f64; 6],
74    /// The outside force's wrench at the start pose, about the origin (the part of `reference` that is not weight).
75    external_reference: [f64; 6],
76    /// How many of the machine's signals are its base signals.
77    inner_base_signals: usize,
78    /// effects.base_reaction.
79    reaction: Option<Reaction>,
80    /// An obstacle's push on the contact coordinates (`Machine::set_tool_force`), which the base's move shifts too: it
81    /// acts on the base as well (`pushed`). Empty for none.
82    push: Vec<f64>,
83}
84
85/// The two-way coupling (effects.base_reaction, see the module).
86struct Reaction {
87    /// The machine's states that are its speeds: those its momentum moves with, and whose change moves something but
88    /// speeds (a state held at zero, as a frame mode switched off, is none).
89    speeds: Vec<usize>,
90    /// Gravity in the machine's frame, and its weight as force and torque about the origin at the start pose.
91    gravity: [f64; 3],
92    weight: [f64; 6],
93    /// Where `energy.<ENERGY_PARTS>` sit among the machine's effect signals.
94    parts: Option<[usize; 3]>,
95}
96
97impl Reaction {
98    /// Found at the machine's state at rest `state` under `torque`, its momentum there `at_rest`.
99    fn new(m: &dyn Machine, state: &[f64], torque: &[f64], pivot: [f64; 3], at_rest: &FrameMomentum) -> Self {
100        let momentum_at = |s: &[f64]| m.frame_momentum(s).map(|f| momentum(&f, pivot));
101        let moved = |j: usize| {
102            let mut s = state.to_vec();
103            s[j] += 1e-3;
104            s
105        };
106        // At rest the momentum is zero whatever the positions: only a speed moves it.
107        let before = momentum_at(state);
108        let moving: Vec<usize> = (0..state.len())
109            .filter(|&j| {
110                momentum_at(&moved(j))
111                    .zip(before)
112                    .is_some_and(|(a, b)| a.iter().zip(&b).any(|(a, b)| (a - b).is_finite() && a != b))
113            })
114            .collect();
115        let mut rates = vec![0.0; state.len()];
116        m.derivatives(state, torque, &mut rates);
117        let speeds = moving
118            .iter()
119            .copied()
120            .filter(|&j| {
121                let mut out = vec![0.0; state.len()];
122                m.derivatives(&moved(j), torque, &mut out);
123                (0..state.len()).any(|i| !moving.contains(&i) && out[i] != rates[i])
124            })
125            .collect();
126        let infos = m.signal_infos();
127        let mut own = Vec::new();
128        m.base_signals(state, torque, &mut own);
129        let parts =
130            ENERGY_PARTS.map(|part| infos.iter().position(|s| s.id == format!("energy.{part}")).map(|i| i - own.len()));
131        Self {
132            speeds,
133            gravity: at_rest.gravity,
134            weight: weight(at_rest),
135            parts: parts.iter().all(Option::is_some).then(|| parts.map(Option::unwrap)),
136        }
137    }
138}
139
140/// Momentum and angular momentum about `pivot`.
141fn momentum(f: &FrameMomentum, pivot: [f64; 3]) -> [f64; 6] {
142    let about = cross(pivot, f.linear);
143    let l = f.angular;
144    [f.linear[0], f.linear[1], f.linear[2], l[0] - about[0], l[1] - about[1], l[2] - about[2]]
145}
146
147/// The weight of what moves, as force and torque about the origin.
148fn weight(f: &FrameMomentum) -> [f64; 6] {
149    let t = cross(f.first_moment, f.gravity);
150    let g = f.gravity.map(|g| f.mass * g);
151    [g[0], g[1], g[2], t[0], t[1], t[2]]
152}
153
154/// The machine on a compliant base with effects.base_compliance, as it is without. A config without the switch (one
155/// written before 14 November 2026) has a rigid base.
156pub fn mount(cfg: &Config, machine: Box<dyn Machine>) -> Result<Box<dyn Machine>, ConfigError> {
157    if cfg.get("effects.base_compliance").is_err() || !cfg.bool("effects.base_compliance")? {
158        return Ok(machine);
159    }
160    let mass = cfg.positive("base.mass_kg")?;
161    let mut dofs = Vec::new();
162    for (index, id) in DOFS.iter().enumerate() {
163        let axis = ["x", "y", "z"][index % 3];
164        let (m, k) = if index < 3 {
165            (mass, cfg.non_negative(&format!("base.stiffness_{axis}_n_m"))?)
166        } else {
167            (
168                cfg.positive(&format!("base.inertia_{axis}_kgm2"))?,
169                cfg.non_negative(&format!("base.tilt_stiffness_{axis}_nm_rad"))?,
170            )
171        };
172        let zeta = cfg.non_negative(&format!("base.damping_ratio_{id}"))?;
173        if k > 0.0 {
174            dofs.push(Dof { index, mass: m, stiffness: k, damping: 2.0 * zeta * (k * m).sqrt() });
175        }
176    }
177    let pivot = match cfg.f64s("base.pivot_m")?[..] {
178        [x, y, z] => [x, y, z],
179        _ => return Err(ConfigError::Invalid("base.pivot_m".into())),
180    };
181    let pose = crate::sim::start_pose(cfg, machine.as_ref())?;
182    let (mut state, mut torque) = (Vec::new(), vec![0.0; machine.motors().len()]);
183    machine.equilibrium(&pose, &mut state, &mut torque);
184    let at_rest =
185        machine.frame_momentum(&state).ok_or_else(|| ConfigError::Invalid("effects.base_compliance".into()))?;
186    let mut signals = Vec::new();
187    machine.base_signals(&state, &torque, &mut signals);
188    let reaction = (cfg.get("effects.base_reaction").is_ok() && cfg.bool("effects.base_reaction")?)
189        .then(|| Reaction::new(machine.as_ref(), &state, &torque, pivot, &at_rest));
190    let based = Based {
191        reference: static_load(&at_rest),
192        external_reference: external_wrench(&at_rest),
193        inner_base_signals: signals.len(),
194        inner: machine,
195        dofs,
196        pivot,
197        reaction,
198        push: Vec::new(),
199    };
200    // What sways must be heavier than what the machine moves on it along each direction: M_B - A M^-1 A^T > 0.
201    if let Some(r) = &based.reaction {
202        let (_, g) = based.coupling(r, &state);
203        if let Some(d) = based.dofs.iter().find(|d| !(d.mass - g[d.index][d.index] > 0.0)) {
204            let axis = ["x", "y", "z"][d.index % 3];
205            return Err(ConfigError::Invalid(if d.index < 3 {
206                "base.mass_kg".into()
207            } else {
208                format!("base.inertia_{axis}_kgm2")
209            }));
210        }
211    }
212    Ok(Box::new(based))
213}
214
215/// Adds a point mass `m` at `r` moving at `v` to a machine's `FrameMomentum`.
216pub fn add_point(f: &mut FrameMomentum, m: f64, r: [f64; 3], v: [f64; 3]) {
217    let l = cross(r, v);
218    for k in 0..3 {
219        f.linear[k] += m * v[k];
220        f.angular[k] += m * l[k];
221        f.first_moment[k] += m * r[k];
222    }
223    f.mass += m;
224}
225
226/// Adds a body that turns about a fixed joint at `joint`, at `speed`: its centre of mass lies along `dir` (a unit
227/// vector turning with it, `ddir` its derivative by the angle, so that the axis is dir x ddir), `moment` (kg m) its
228/// mass times that distance and `inertia` its inertia about the axis through the joint. Its mass at the joint does not
229/// change the load and is left out. Linear momentum moment speed ddir; angular inertia speed axis plus joint x that.
230pub fn add_turning(
231    f: &mut FrameMomentum,
232    joint: [f64; 3],
233    dir: [f64; 3],
234    ddir: [f64; 3],
235    speed: f64,
236    inertia: f64,
237    moment: f64,
238) {
239    let (axis, p) = (cross(dir, ddir), ddir.map(|d| moment * speed * d));
240    let about = cross(joint, p);
241    for k in 0..3 {
242        f.linear[k] += p[k];
243        f.angular[k] += inertia * speed * axis[k] + about[k];
244        f.first_moment[k] += moment * dir[k];
245    }
246}
247
248/// Adds a rotor (or any wheel whose centre stays put) spinning at `speed` with `inertia` about the unit `axis`.
249pub fn add_spin(f: &mut FrameMomentum, axis: [f64; 3], inertia: f64, speed: f64) {
250    (0..3).for_each(|k| f.angular[k] += inertia * speed * axis[k]);
251}
252
253fn cross(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
254    [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
255}
256
257/// The outside force alone, as force and torque about the origin.
258fn external_wrench(m: &FrameMomentum) -> [f64; 6] {
259    let t = cross(m.external_at, m.external);
260    [m.external[0], m.external[1], m.external[2], t[0], t[1], t[2]]
261}
262
263/// The weight and the outside force of what moves, as force and torque about the origin.
264fn static_load(m: &FrameMomentum) -> [f64; 6] {
265    let force: [f64; 3] = std::array::from_fn(|k| m.mass * m.gravity[k] + m.external[k]);
266    let (weight, outside) = (cross(m.first_moment, m.gravity), cross(m.external_at, m.external));
267    [force[0], force[1], force[2], weight[0] + outside[0], weight[1] + outside[1], weight[2] + outside[2]]
268}
269
270impl Based {
271    fn n(&self) -> usize {
272        self.inner.state_len()
273    }
274
275    /// The base's deflection (or rate, `rates`) in all six directions, zero where it is rigid.
276    fn full(&self, s: &[f64], rates: bool) -> [f64; 6] {
277        let at = self.n() + if rates { self.dofs.len() } else { 0 };
278        let mut d = [0.0; 6];
279        for (k, dof) in self.dofs.iter().enumerate() {
280            d[dof.index] = s[at + k];
281        }
282        d
283    }
284
285    /// What the machine at state `s` (its own), whose state changes at `rate`, puts on the base: force and torque
286    /// about the pivot, less what it put on it at rest at the start pose.
287    pub fn load(&self, s: &[f64], rate: &[f64]) -> [f64; 6] {
288        let at = |h: f64| {
289            let moved: Vec<f64> = s.iter().zip(rate).map(|(x, r)| x + h * r).collect();
290            self.inner.frame_momentum(&moved).unwrap_or_default()
291        };
292        let (before, now, after) = (at(-H), at(0.0), at(H));
293        let rest = static_load(&now);
294        let mut load: [f64; 6] = std::array::from_fn(|j| {
295            let (a, b) =
296                if j < 3 { (after.linear[j], before.linear[j]) } else { (after.angular[j - 3], before.angular[j - 3]) };
297            rest[j] - self.reference[j] - (a - b) / (2.0 * H)
298        });
299        let about_pivot = cross(self.pivot, [load[0], load[1], load[2]]);
300        (0..3).for_each(|k| load[3 + k] -= about_pivot[k]);
301        load
302    }
303
304    /// At the machine's state `s` (its own): X = M^-1 A^T (per speed, the six directions) and A M^-1 A^T (see the
305    /// module), from its momentum and its energy at unit speeds.
306    fn coupling(&self, r: &Reaction, s: &[f64]) -> (Vec<[f64; 6]>, [[f64; 6]; 6]) {
307        let n = r.speeds.len();
308        let mut at = s.to_vec();
309        r.speeds.iter().for_each(|&i| at[i] = 0.0);
310        let still = self.inner.energy(&at);
311        let (mut a, mut single) = (Vec::with_capacity(n), Vec::with_capacity(n));
312        for &i in &r.speeds {
313            at[i] = 1.0;
314            a.push(self.inner.frame_momentum(&at).map_or([f64::NAN; 6], |f| momentum(&f, self.pivot)));
315            single.push(self.inner.energy(&at) - still);
316            at[i] = 0.0;
317        }
318        let mut mass = vec![0.0; n * n];
319        for k in 0..n {
320            mass[k * n + k] = 2.0 * single[k];
321            for l in 0..k {
322                (at[r.speeds[k]], at[r.speeds[l]]) = (1.0, 1.0);
323                let both = self.inner.energy(&at) - still - single[k] - single[l];
324                (at[r.speeds[k]], at[r.speeds[l]]) = (0.0, 0.0);
325                (mass[k * n + l], mass[l * n + k]) = (both, both);
326            }
327        }
328        let mut x = vec![[0.0; 6]; n];
329        for j in 0..6 {
330            let rhs: Vec<f64> = a.iter().map(|c| c[j]).collect();
331            let column = crate::chain::solve(&mass, &rhs).unwrap_or_else(|| vec![f64::NAN; n]);
332            x.iter_mut().zip(column).for_each(|(x, c)| x[j] = c);
333        }
334        let g = std::array::from_fn(|i| std::array::from_fn(|j| (0..n).map(|k| a[k][i] * x[k][j]).sum()));
335        (x, g)
336    }
337
338    /// The base's share of the energy at state `s` with effects.base_reaction, as [kinetic, potential, elastic]: its
339    /// sway with the machine's momentum, the weight's work on its tilt, its springs.
340    fn reaction_energy(&self, r: &Reaction, s: &[f64]) -> [f64; 3] {
341        let (n, m) = (self.n(), self.dofs.len());
342        let f = self.inner.frame_momentum(&s[..n]).unwrap_or_default();
343        let (p, rate) = (momentum(&f, self.pivot), self.full(s, true));
344        let about = |w: [f64; 6]| {
345            let t = cross(self.pivot, [w[0], w[1], w[2]]);
346            [w[0], w[1], w[2], w[3] - t[0], w[4] - t[1], w[5] - t[2]]
347        };
348        let (now, then) = (about(weight(&f)), about(r.weight));
349        let mut parts = [(0..6).map(|j| rate[j] * p[j]).sum(), 0.0, 0.0];
350        for (k, d) in self.dofs.iter().enumerate() {
351            let (x, v) = (s[n + k], s[n + m + k]);
352            parts[0] += 0.5 * d.mass * v * v;
353            parts[1] -= x * (now[d.index] - then[d.index]);
354            parts[2] += 0.5 * d.stiffness * x * x;
355        }
356        parts
357    }
358
359    /// The base's row of the loss budget, W: its damping loss less the work the process force does on it as it moves.
360    fn damping_power(&self, s: &[f64]) -> f64 {
361        let at = self.n() + self.dofs.len();
362        let damping: f64 = self.dofs.iter().enumerate().map(|(k, d)| d.damping * s[at + k] * s[at + k]).sum();
363        let f = self.inner.frame_momentum(&s[..self.n()]).unwrap_or_default();
364        let now = external_wrench(&f);
365        let mut w: [f64; 6] = std::array::from_fn(|j| now[j] - self.external_reference[j]);
366        let about = cross(self.pivot, [w[0], w[1], w[2]]);
367        (0..3).for_each(|k| w[3 + k] -= about[k]);
368        let rate = self.full(s, true);
369        damping - (0..6).map(|j| rate[j] * w[j]).sum::<f64>()
370    }
371
372    /// An obstacle's push on each of the base's directions: the generalised forces `Sim` gives the base's own contact
373    /// coordinates (`contact_state`, after the machine's), its virtual work per unit of each wherever the parts touch.
374    /// Zero without a push.
375    fn pushed(&self, _state: &[f64]) -> Vec<f64> {
376        let m = self.dofs.len();
377        let k = self.inner.contact_axes();
378        if self.push.len() < k + m {
379            return vec![0.0; m];
380        }
381        self.push[k..k + m].to_vec()
382    }
383
384    /// The base's deflection at rest under the machine at state `s` (its own).
385    fn rest(&self, s: &[f64]) -> Vec<f64> {
386        let load = self.load(s, &vec![0.0; s.len()]);
387        self.dofs.iter().map(|d| load[d.index] / d.stiffness).collect()
388    }
389
390    /// The tool pose's move by the base's deflection `d` at the pose `pose` the machine alone has.
391    fn tool_shift(&self, pose: &[f64], d: &[f64; 6]) -> Vec<f64> {
392        let mut out = vec![0.0; pose.len()];
393        self.inner.base_shift(pose, self.pivot, d, &mut out);
394        out
395    }
396
397    /// The base's modes: frequency, damping, which direction.
398    fn base_modes(&self) -> impl Iterator<Item = (Mode, usize)> + '_ {
399        self.dofs.iter().enumerate().map(|(k, d)| {
400            let w = (d.stiffness / d.mass).sqrt();
401            (Mode { hz: w / std::f64::consts::TAU, damping: d.damping / (2.0 * d.mass * w) }, k)
402        })
403    }
404
405    /// Where the base's move (`scale` times) takes a point `p` of the scene: by the base's translation plus its tilt
406    /// about the pivot at the point's own place, p + t + theta x (p - pivot). The scene's axes are those of the
407    /// machine's frame up to the map the machine's `scene_point` makes (a permutation or a reflection): it is read
408    /// off from the scene move of a unit translation along each axis, and the tilt, a pseudovector, goes through it
409    /// with the sign of its determinant. The pivot in the scene lies where the tool's point lies, less its distance to
410    /// the pivot in the machine's frame. (A direction the scene point does not show is taken along the scene's own axis.)
411    fn scene_mover(&self, s: &[f64], scale: f64) -> Option<impl Fn([f64; 3]) -> [f64; 3]> {
412        let n = self.inner.axes().len();
413        let (mut pose, mut vel) = (vec![0.0; n], vec![0.0; n]);
414        self.inner.tool_state(&s[..self.n()], &mut pose, &mut vel);
415        let from = self.inner.scene_point(&pose)?;
416        // A millimetre along each axis, read back per metre.
417        const STEP: f64 = 1e-3;
418        let mut columns = [[0.0; 3]; 3];
419        for (k, column) in columns.iter_mut().enumerate() {
420            let mut unit = [0.0; 6];
421            unit[k] = STEP;
422            let moved: Vec<f64> = pose.iter().zip(self.tool_shift(&pose, &unit)).map(|(p, d)| p + d).collect();
423            let to = self.inner.scene_point(&moved)?;
424            *column = std::array::from_fn(|i| (to[i] - from[i]) / STEP);
425        }
426        // A direction the scene point does not show (a planar machine has no z axis): the scene's axis furthest from
427        // the directions it shows.
428        for k in 0..3 {
429            if columns[k].iter().all(|c| c.abs() < 1e-9) {
430                let shown = |i: usize| columns.iter().map(|c| c[i].abs()).sum::<f64>();
431                let free = (0..3).min_by(|&a, &b| shown(a).total_cmp(&shown(b))).unwrap_or(k);
432                columns[k] = std::array::from_fn(|i| if i == free { 1.0 } else { 0.0 });
433            }
434        }
435        let map = |v: [f64; 3]| -> [f64; 3] { std::array::from_fn(|i| (0..3).map(|k| columns[k][i] * v[k]).sum()) };
436        let det = {
437            let c = columns;
438            let x = cross(c[0], c[1]);
439            (0..3).map(|i| x[i] * c[2][i]).sum::<f64>().signum()
440        };
441        let d = self.full(s, false);
442        let t = map([d[0], d[1], d[2]]).map(|v| scale * v);
443        let theta = map([d[3], d[4], d[5]]).map(|v| scale * v * if det < 0.0 { -1.0 } else { 1.0 });
444        let axes = self.inner.axes();
445        let found = BASE_AXES[0].map(|id| axes.iter().position(|a| a.id == id));
446        let pivot: [f64; 3] = if found.iter().any(Option::is_some) {
447            let at_tool: [f64; 3] = std::array::from_fn(|k| found[k].map_or(0.0, |i| pose[i]) - self.pivot[k]);
448            let away = map(at_tool);
449            std::array::from_fn(|k| from[k] - away[k])
450        } else {
451            // Tool axes that are joints tell nothing of where the tool is in the frame: the scene's origin is the
452            // frame's (as the axes are where the scene shows no translation).
453            map(self.pivot)
454        };
455        Some(move |p: [f64; 3]| {
456            let turned = cross(theta, std::array::from_fn(|k| p[k] - pivot[k]));
457            std::array::from_fn(|k| p[k] + t[k] + turned[k])
458        })
459    }
460
461    /// The machine's capsules `capsules` as the base's sway moves them (`scene_mover`).
462    fn moved(&self, state: &[f64], mut capsules: Vec<sim_core::Capsule>) -> Vec<sim_core::Capsule> {
463        if let Some(mover) = self.scene_mover(state, 1.0) {
464            for c in &mut capsules {
465                (c.from, c.to) = (mover(c.from), mover(c.to));
466            }
467        }
468        capsules
469    }
470}
471
472impl Machine for Based {
473    fn frame_momentum(&self, state: &[f64]) -> Option<FrameMomentum> {
474        self.inner.frame_momentum(&state[..self.n()])
475    }
476    fn base_shift(&self, tool_pose: &[f64], pivot: [f64; 3], shift: &[f64; 6], out: &mut [f64]) {
477        self.inner.base_shift(tool_pose, pivot, shift, out)
478    }
479    fn rating_checks(&self) -> Vec<RatingCheck> {
480        self.inner.rating_checks()
481    }
482    fn axes(&self) -> &[AxisInfo] {
483        self.inner.axes()
484    }
485    fn motors(&self) -> &[MotorInfo] {
486        self.inner.motors()
487    }
488    fn motor_linear(&self, motor: usize) -> bool {
489        self.inner.motor_linear(motor)
490    }
491    fn inverse(&self, tool: &[f64], motors: &mut [f64]) {
492        self.inner.inverse(tool, motors)
493    }
494    fn forward(&self, motors: &[f64], tool: &mut [f64]) {
495        self.inner.forward(motors, tool)
496    }
497    fn state_len(&self) -> usize {
498        self.n() + 2 * self.dofs.len()
499    }
500    /// The tool, not the machine on a rigid base, at `tool`: the machine stands off by the base's deflection under it.
501    fn equilibrium(&self, tool: &[f64], state: &mut Vec<f64>, torque: &mut [f64]) {
502        let mut pose = tool.to_vec();
503        for _ in 0..2 {
504            self.inner.equilibrium(&pose, state, torque);
505            let mut d = [0.0; 6];
506            for (k, value) in self.rest(state).into_iter().enumerate() {
507                d[self.dofs[k].index] = value;
508            }
509            let shift = self.tool_shift(&pose, &d);
510            pose = tool.iter().zip(&shift).map(|(t, s)| t - s).collect();
511        }
512        self.inner.equilibrium(&pose, state, torque);
513        let rest = self.rest(state);
514        state.extend(rest);
515        state.extend(vec![0.0; self.dofs.len()]);
516    }
517    fn derivatives(&self, state: &[f64], torque: &[f64], out: &mut [f64]) {
518        let n = self.n();
519        self.inner.derivatives(&state[..n], torque, &mut out[..n]);
520        let load = self.load(&state[..n], &out[..n]);
521        let m = self.dofs.len();
522        let pushed = self.pushed(state);
523        let Some(r) = &self.reaction else {
524            for (k, d) in self.dofs.iter().enumerate() {
525                let (x, v) = (state[n + k], state[n + m + k]);
526                out[n + k] = v;
527                out[n + m + k] = (load[d.index] - d.stiffness * x - d.damping * v + pushed[k]) / d.mass;
528            }
529            return;
530        };
531        // Base and machine together (see the module): (M_B - G) a = L - k d - c d' - G w, then v'' += X (w - a).
532        let (x, g) = self.coupling(r, &state[..n]);
533        let d = self.full(state, false);
534        let tilt = cross(r.gravity, [d[3], d[4], d[5]]);
535        let w = [tilt[0], tilt[1], tilt[2], 0.0, 0.0, 0.0];
536        let (mut matrix, mut rhs) = (vec![0.0; m * m], vec![0.0; m]);
537        for (k, dk) in self.dofs.iter().enumerate() {
538            let (i, x, v) = (dk.index, state[n + k], state[n + m + k]);
539            rhs[k] =
540                load[i] - dk.stiffness * x - dk.damping * v - (0..6).map(|j| g[i][j] * w[j]).sum::<f64>() + pushed[k];
541            for (l, dl) in self.dofs.iter().enumerate() {
542                matrix[k * m + l] = if k == l { dk.mass } else { 0.0 } - g[i][dl.index];
543            }
544        }
545        let acc = crate::chain::solve(&matrix, &rhs).unwrap_or_else(|| vec![f64::NAN; m]);
546        let mut push = w;
547        for (k, dk) in self.dofs.iter().enumerate() {
548            push[dk.index] -= acc[k];
549            out[n + k] = state[n + m + k];
550            out[n + m + k] = acc[k];
551        }
552        for (k, &i) in r.speeds.iter().enumerate() {
553            out[i] += (0..6).map(|j| x[k][j] * push[j]).sum::<f64>();
554        }
555    }
556    fn tool_state(&self, state: &[f64], pos: &mut [f64], vel: &mut [f64]) {
557        self.inner.tool_state(&state[..self.n()], pos, vel);
558        let shift = self.tool_shift(pos, &self.full(state, false));
559        let rate = self.tool_shift(pos, &self.full(state, true));
560        pos.iter_mut().zip(shift).for_each(|(p, d)| *p += d);
561        vel.iter_mut().zip(rate).for_each(|(v, d)| *v += d);
562    }
563    /// The scale stands on the machine, so the base's deflection is not in it either.
564    fn scale_state(&self, state: &[f64], pos: &mut [f64], vel: &mut [f64]) {
565        self.inner.scale_state(&state[..self.n()], pos, vel)
566    }
567    fn set_tool_velocity(&self, state: &mut [f64], vel: &[f64]) {
568        let n = self.n();
569        self.inner.set_tool_velocity(&mut state[..n], vel)
570    }
571    fn motor_state(&self, state: &[f64], pos: &mut [f64], vel: &mut [f64]) {
572        self.inner.motor_state(&state[..self.n()], pos, vel)
573    }
574    fn feedforward_torque(&self, tool_pos: &[f64], tool_acc: &[f64], out: &mut [f64]) {
575        self.inner.feedforward_torque(tool_pos, tool_acc, out)
576    }
577    fn feedforward_torque_moving(&self, tool_pos: &[f64], tool_vel: &[f64], tool_acc: &[f64], out: &mut [f64]) {
578        self.inner.feedforward_torque_moving(tool_pos, tool_vel, tool_acc, out)
579    }
580    fn rigid_motor_torque(&self, angle: &[f64], speed: &[f64], acc: &[f64], out: &mut [f64]) {
581        self.inner.rigid_motor_torque(angle, speed, acc, out)
582    }
583    fn twist(&self, torque: &[f64], acc: &[f64], out: &mut [f64]) {
584        self.inner.twist(torque, acc, out)
585    }
586    fn twist_at(&self, angle: &[f64], torque: &[f64], acc: &[f64], out: &mut [f64]) {
587        self.inner.twist_at(angle, torque, acc, out)
588    }
589    fn rigid_split_torque(&self, angle: &[f64], speed: &[f64], acc: &[f64], rotor_acc: &[f64], out: &mut [f64]) {
590        self.inner.rigid_split_torque(angle, speed, acc, rotor_acc, out)
591    }
592    fn rigid_tensions(&self, tool_pos: &[f64], tool_acc: &[f64], out: &mut Vec<f64>) {
593        self.inner.rigid_tensions(tool_pos, tool_acc, out)
594    }
595    fn rigid_tensions_moving(&self, tool_pos: &[f64], tool_vel: &[f64], tool_acc: &[f64], out: &mut Vec<f64>) {
596        self.inner.rigid_tensions_moving(tool_pos, tool_vel, tool_acc, out)
597    }
598    fn tension_band(&self) -> Option<[f64; 2]> {
599        self.inner.tension_band()
600    }
601    fn rigid_guide_loads(&self, tool_pos: &[f64], tool_acc: &[f64], out: &mut Vec<[f64; 2]>) {
602        self.inner.rigid_guide_loads(tool_pos, tool_acc, out)
603    }
604    fn steady_friction(&self, tool_pos: &[f64], tool_vel: &[f64], out: &mut [f64]) {
605        self.inner.steady_friction(tool_pos, tool_vel, out)
606    }
607    fn rigid_friction(&self, tool_pos: &[f64], tool_dir: &[f64], out: &mut Vec<[f64; 2]>) {
608        self.inner.rigid_friction(tool_pos, tool_dir, out)
609    }
610    fn rigid_friction_rise(&self, tool_pos: &[f64], tool_dir: &[f64], out: &mut Vec<Vec<[f64; 2]>>) {
611        self.inner.rigid_friction_rise(tool_pos, tool_dir, out)
612    }
613    fn rigid_checks(&self, tool_pos: &[f64], tool_vel: &[f64], tool_acc: &[f64], out: &mut Vec<f64>) {
614        self.inner.rigid_checks(tool_pos, tool_vel, tool_acc, out)
615    }
616    /// The machine's, plus the base's kinetic and elastic energy (its potential energy in gravity left out: one-way the
617    /// machine's own energy is not conserved with it anyway). With effects.base_reaction the base's share as the module
618    /// has it, which the two together conserve.
619    fn energy(&self, state: &[f64]) -> f64 {
620        if let Some(r) = &self.reaction {
621            return self.inner.energy(&state[..self.n()]) + self.reaction_energy(r, state).iter().sum::<f64>();
622        }
623        let (n, m) = (self.n(), self.dofs.len());
624        let base: f64 = self
625            .dofs
626            .iter()
627            .enumerate()
628            .map(|(k, d)| 0.5 * d.mass * state[n + m + k].powi(2) + 0.5 * d.stiffness * state[n + k].powi(2))
629            .sum();
630        self.inner.energy(&state[..n]) + base
631    }
632    fn set_payload_attached(&mut self, attached: bool) {
633        self.inner.set_payload_attached(attached)
634    }
635    fn valves(&self) -> Vec<(String, f64)> {
636        self.inner.valves()
637    }
638    fn set_valve(&mut self, valve: usize, command: f64) {
639        self.inner.set_valve(valve, command)
640    }
641    fn end_sensors(&self, valve: usize) -> [bool; 2] {
642        self.inner.end_sensors(valve)
643    }
644    fn links(&self) -> Vec<String> {
645        self.inner.links()
646    }
647    fn set_link_change(&mut self, link: usize, factor: f64, moment: [f64; 3]) {
648        self.inner.set_link_change(link, factor, moment)
649    }
650    fn set_dwelling(&mut self, dwelling: bool) {
651        self.inner.set_dwelling(dwelling)
652    }
653    fn set_tool_force(&mut self, force: &[f64]) -> bool {
654        self.push.clear();
655        self.push.extend_from_slice(force);
656        let k = self.inner.contact_axes();
657        self.inner.set_tool_force(&force[..k.min(force.len())])
658    }
659    /// The machine's contact coordinates, then the base's deflections (`dofs`): the clearance's slopes along these
660    /// are those of whichever part touches, and the push's generalised forces on them act on the base directly
661    /// (`pushed`). Before, the push reached the base through the tool's move by the base's deflection (`tool_shift`),
662    /// which is the touching part's only where it is at the tool: a gantry whose leaning Z axis has contact
663    /// coordinates of its own (`x, z, q, u`) sprang back off a slab on its compliant base.
664    fn contact_axes(&self) -> usize {
665        self.inner.contact_axes() + self.dofs.len()
666    }
667    fn push_substeps(&self) -> u32 {
668        self.inner.push_substeps()
669    }
670    /// The machine's (`contact_axes`), then the base's deflections and their rates.
671    /// One-way (without effects.base_reaction) the base is outside the energy budget: neither its energy nor its
672    /// damping is booked (`effect_signals`, `loss_powers`), since the machine does not feel it and nothing in the budget
673    /// drives it. So there the base's rates are left out (0), and the crash row books the push's work on the machine
674    /// alone; its work on the base goes where the base's other loads' does (`pushed`). Two-way they are in.
675    fn contact_state(&self, state: &[f64], pos: &mut [f64], vel: &mut [f64]) {
676        let (n, m, k) = (self.n(), self.dofs.len(), self.inner.contact_axes());
677        self.inner.contact_state(&state[..n], &mut pos[..k], &mut vel[..k]);
678        for j in 0..m {
679            pos[k + j] = state[n + j];
680            vel[k + j] = if self.reaction.is_some() { state[n + m + j] } else { 0.0 };
681        }
682    }
683    /// The machine's parts placed at `at`'s first coordinates, the base deflected by the rest, its rates as they are.
684    fn contact_placed(&self, state: &[f64], at: &[f64], out: &mut Vec<f64>) {
685        let (n, m, k) = (self.n(), self.dofs.len(), self.inner.contact_axes());
686        self.inner.contact_placed(&state[..n], &at[..k], out);
687        out.truncate(n);
688        out.extend_from_slice(&at[k..k + m]);
689        out.extend_from_slice(&state[n + m..]);
690    }
691    fn set_brake_engaged(&mut self, engaged: bool) {
692        self.inner.set_brake_engaged(engaged)
693    }
694    fn substeps_wanted(&self, state: &[f64], torque: &[f64], dt: f64, substeps: u32) -> u32 {
695        self.inner.substeps_wanted(&state[..self.n()], torque, dt, substeps)
696    }
697    fn after_step(&mut self, state: &mut [f64], dt: f64) {
698        let n = self.n();
699        self.inner.after_step(&mut state[..n], dt)
700    }
701    fn memory(&self) -> Vec<f64> {
702        self.inner.memory()
703    }
704    fn set_memory(&mut self, memory: &[f64]) {
705        self.inner.set_memory(memory)
706    }
707    fn set_part_temperatures(&mut self, rises: &[f64]) {
708        self.inner.set_part_temperatures(rises)
709    }
710    /// The lower of the machine's resonance and the base's lowest mode that moves the tool along its first axis.
711    fn resonance_hz(&self, tool_pose: &[f64]) -> Option<f64> {
712        let base = self.mode_shape(tool_pose).map(|(hz, _)| hz);
713        match (base, self.inner.resonance_hz(tool_pose)) {
714            (Some(b), Some(i)) => Some(b.min(i)),
715            (b, i) => b.or(i),
716        }
717    }
718    fn mode_shape(&self, tool_pose: &[f64]) -> Option<(f64, Vec<f64>)> {
719        let len = self.state_len();
720        let inner = self.inner.mode_shape(tool_pose).map(|(hz, mut shape)| {
721            shape.resize(len, 0.0);
722            (hz, shape)
723        });
724        let base = self
725            .base_modes()
726            .filter_map(|(mode, k)| {
727                let mut unit = [0.0; 6];
728                unit[self.dofs[k].index] = 1.0;
729                let along = self.tool_shift(tool_pose, &unit)[0];
730                (along.abs() > 1e-12).then(|| {
731                    let mut shape = vec![0.0; len];
732                    shape[self.n() + k] = 1.0 / along;
733                    (mode.hz, shape)
734                })
735            })
736            .min_by(|a, b| a.0.total_cmp(&b.0));
737        match (inner, base) {
738            (Some(i), Some(b)) => Some(if b.0 < i.0 { b } else { i }),
739            (i, b) => i.or(b),
740        }
741    }
742    fn modes(&self, tool_pose: &[f64]) -> Vec<Mode> {
743        let mut modes = self.inner.modes(tool_pose);
744        modes.extend(self.base_modes().map(|(mode, _)| mode));
745        modes.sort_by(|a, b| a.hz.total_cmp(&b.hz));
746        modes
747    }
748    /// The machine's own with the base's, as `modes`.
749    fn sway_modes(&self, tool_pose: &[f64]) -> Vec<Mode> {
750        let mut modes = self.inner.sway_modes(tool_pose);
751        modes.extend(self.base_modes().map(|(mode, _)| mode));
752        modes.sort_by(|a, b| a.hz.total_cmp(&b.hz));
753        modes
754    }
755    fn trains(&self, tool_pose: &[f64]) -> Vec<Option<sim_core::Train>> {
756        self.inner.trains(tool_pose)
757    }
758    fn belt_wraps(&self, tool_pose: &[f64]) -> Vec<f64> {
759        self.inner.belt_wraps(tool_pose)
760    }
761    fn unreachable(&self, tool_pose: &[f64], slack: f64) -> Option<&'static str> {
762        self.inner.unreachable(tool_pose, slack)
763    }
764    fn refuses_pick(&self, tool_pose: &[f64]) -> Option<&'static str> {
765        self.inner.refuses_pick(tool_pose)
766    }
767    fn condition(&self, tool_pose: &[f64]) -> Option<f64> {
768        self.inner.condition(tool_pose)
769    }
770    fn setpoint_slack(&self) -> f64 {
771        self.inner.setpoint_slack()
772    }
773    fn cam(&self) -> Option<sim_core::CamMaster> {
774        self.inner.cam()
775    }
776    fn cam_at(&self, master: f64, out: &mut [[f64; 4]]) {
777        self.inner.cam_at(master, out)
778    }
779    fn cam_curve(&self) -> Option<sim_core::CamCurve> {
780        self.inner.cam_curve()
781    }
782    fn gantry_motors(&self) -> Option<[usize; 2]> {
783        self.inner.gantry_motors()
784    }
785    /// The machine's base signals, the base's deflections (`base.<dof>`, m or rad), then the machine's effect signals.
786    fn signal_infos(&self) -> Vec<SignalInfo> {
787        let mut infos = self.inner.signal_infos();
788        let base = self.dofs.iter().map(|d| {
789            let id = DOFS[d.index];
790            SignalInfo::new(format!("base.{id}"), "base", &format!("quantity-base-{id}"), ["m", "rad"][d.index / 3])
791        });
792        infos.splice(self.inner_base_signals..self.inner_base_signals, base);
793        if self.reaction.is_some() {
794            infos.push(SignalInfo::new(format!("{LOSS_PREFIX}base"), "base", "quantity-damping-power", "W"));
795        }
796        infos
797    }
798    fn base_signals(&self, state: &[f64], torque: &[f64], out: &mut Vec<f64>) {
799        let n = self.n();
800        self.inner.base_signals(&state[..n], torque, out);
801        out.extend_from_slice(&state[n..n + self.dofs.len()]);
802    }
803    /// The machine's, with effects.base_reaction the base's energy in its `energy.*` and its damping loss last.
804    fn effect_signals(&self, state: &[f64], torque: &[f64], out: &mut Vec<f64>) {
805        let start = out.len();
806        self.inner.effect_signals(&state[..self.n()], torque, out);
807        let Some(r) = &self.reaction else { return };
808        if let Some(parts) = r.parts {
809            let shares = self.reaction_energy(r, state);
810            parts.iter().zip(shares).for_each(|(&at, share)| out[start + at] += share);
811        }
812        out.push(self.damping_power(state));
813    }
814    fn loss_powers(&self, state: &[f64], torque: &[f64], out: &mut Vec<f64>) {
815        self.inner.loss_powers(&state[..self.n()], torque, out);
816        if self.reaction.is_some() {
817            out.push(self.damping_power(state));
818        }
819    }
820    /// The machine's scene, moved with the base times the exaggeration: every point (the parts, the ends of a belt's
821    /// strips, labels, arrows) by the base's translation and its tilt at its own place (`scene_mover`).
822    fn scene(&self, state: &[f64], out: &mut Scene) {
823        self.inner.scene(&state[..self.n()], out);
824        let Some(mover) = self.scene_mover(state, out.exaggeration) else { return };
825        for part in &mut out.parts {
826            part.pos = mover(part.pos);
827            if let sim_core::Shape::Segment { to, .. } = &mut part.shape {
828                *to = mover(*to);
829            }
830        }
831        out.labels.iter_mut().for_each(|l| l.pos = mover(l.pos));
832        out.arrows.iter_mut().for_each(|a| a.pos = mover(a.pos));
833    }
834    fn scene_point(&self, tool_pose: &[f64]) -> Option<[f64; 3]> {
835        self.inner.scene_point(tool_pose)
836    }
837    fn collision_bodies(&self, state: &[f64]) -> Vec<sim_core::Aabb> {
838        let mut bodies = self.inner.collision_bodies(&state[..self.n()]);
839        // (A box keeps its axes: only its centre goes with the tilt.)
840        if let Some(mover) = self.scene_mover(state, 1.0) {
841            bodies.iter_mut().for_each(|b| b.centre = mover(b.centre));
842        }
843        bodies
844    }
845    fn collision_capsules(&self, state: &[f64]) -> Vec<sim_core::Capsule> {
846        self.moved(state, self.inner.collision_capsules(&state[..self.n()]))
847    }
848    fn self_collision_capsules(&self, state: &[f64]) -> Vec<sim_core::Capsule> {
849        self.moved(state, self.inner.self_collision_capsules(&state[..self.n()]))
850    }
851    fn connected_bodies(&self, state: &[f64], boxes: usize, capsules: usize) -> Option<Vec<(usize, usize)>> {
852        self.inner.connected_bodies(&state[..self.n()], boxes, capsules)
853    }
854    fn friction_contacts(&self) -> Vec<FrictionContact> {
855        self.inner.friction_contacts()
856    }
857    fn friction_curve(&self, i: usize, speed: f64, load_scale: f64) -> [f64; 3] {
858        self.inner.friction_curve(i, speed, load_scale)
859    }
860    fn friction_rotary(&self, i: usize) -> bool {
861        self.inner.friction_rotary(i)
862    }
863    fn friction_speed_limit(&self, i: usize, motor_speed: &[f64]) -> Option<f64> {
864        self.inner.friction_speed_limit(i, motor_speed)
865    }
866    fn belt_sections(&self) -> Vec<BeltSection> {
867        self.inner.belt_sections()
868    }
869    fn thermal_parts(&self) -> Vec<ThermalPart> {
870        self.inner.thermal_parts()
871    }
872    fn thermal_values(&self, id: &str) -> Option<(f64, f64)> {
873        self.inner.thermal_values(id)
874    }
875}
876
877#[cfg(test)]
878mod tests {
879    use super::*;
880    use sim_core::{Rk4, advance};
881    use std::f64::consts::FRAC_PI_2;
882
883    /// A point mass on a frictionless guide along x, pushed by its motor's force (torque = force), with a process force
884    /// while it dwells, and a spring of `spring` N/m that holds it at x = 0.5: the smallest machine that stands on a
885    /// base.
886    struct Slider {
887        mass: f64,
888        process: f64,
889        spring: f64,
890        dwelling: bool,
891        resonance: Option<f64>,
892        /// The scene shows x the other way (a reflection).
893        flipped: bool,
894        axes: [AxisInfo; 1],
895        motors: [MotorInfo; 1],
896    }
897
898    fn slider() -> Slider {
899        Slider {
900            mass: 4.0,
901            process: 50.0,
902            spring: 0.0,
903            dwelling: false,
904            resonance: None,
905            flipped: false,
906            axes: [AxisInfo {
907                id: "x",
908                key: "",
909                unit: "m",
910                min: 0.0,
911                max: 1.0,
912                max_vel: 1.0,
913                max_acc: 10.0,
914                max_jerk: 100.0,
915            }],
916            motors: [MotorInfo { id: "a", key: "" }],
917        }
918    }
919
920    impl Machine for Slider {
921        fn frame_momentum(&self, s: &[f64]) -> Option<FrameMomentum> {
922            Some(FrameMomentum {
923                linear: [self.mass * s[1], 0.0, 0.0],
924                mass: self.mass,
925                first_moment: [self.mass * s[0], 0.0, 0.0],
926                external: [if self.dwelling { self.process } else { 0.0 }, 0.0, 0.0],
927                external_at: [s[0], 0.0, 0.0],
928                ..Default::default()
929            })
930        }
931        fn axes(&self) -> &[AxisInfo] {
932            &self.axes
933        }
934        fn motors(&self) -> &[MotorInfo] {
935            &self.motors
936        }
937        fn inverse(&self, tool: &[f64], motors: &mut [f64]) {
938            motors[0] = tool[0];
939        }
940        fn forward(&self, motors: &[f64], tool: &mut [f64]) {
941            tool[0] = motors[0];
942        }
943        fn state_len(&self) -> usize {
944            2
945        }
946        fn equilibrium(&self, tool: &[f64], state: &mut Vec<f64>, torque: &mut [f64]) {
947            *state = vec![tool[0], 0.0];
948            torque[0] = if self.dwelling { -self.process } else { 0.0 };
949        }
950        fn derivatives(&self, s: &[f64], torque: &[f64], out: &mut [f64]) {
951            let process = if self.dwelling { self.process } else { 0.0 };
952            out[0] = s[1];
953            out[1] = (torque[0] + process - self.spring * (s[0] - 0.5)) / self.mass;
954        }
955        fn tool_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
956            (pos[0], vel[0]) = (s[0], s[1]);
957        }
958        fn set_tool_velocity(&self, s: &mut [f64], vel: &[f64]) {
959            s[1] = vel[0];
960        }
961        fn motor_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
962            (pos[0], vel[0]) = (s[0], s[1]);
963        }
964        fn feedforward_torque(&self, _: &[f64], acc: &[f64], out: &mut [f64]) {
965            out[0] = self.mass * acc[0];
966        }
967        fn energy(&self, s: &[f64]) -> f64 {
968            0.5 * self.mass * s[1] * s[1] + 0.5 * self.spring * (s[0] - 0.5).powi(2)
969        }
970        fn set_payload_attached(&mut self, _: bool) {}
971        fn set_dwelling(&mut self, dwelling: bool) {
972            self.dwelling = dwelling;
973        }
974        fn resonance_hz(&self, _: &[f64]) -> Option<f64> {
975            self.resonance
976        }
977        fn motor_linear(&self, _: usize) -> bool {
978            true
979        }
980        fn signal_infos(&self) -> Vec<SignalInfo> {
981            Vec::new()
982        }
983        fn base_signals(&self, _: &[f64], _: &[f64], _: &mut Vec<f64>) {}
984        fn scene(&self, _: &[f64], _: &mut Scene) {}
985        fn scene_point(&self, tool: &[f64]) -> Option<[f64; 3]> {
986            Some([if self.flipped { -tool[0] } else { tool[0] }, 0.0, 0.0])
987        }
988    }
989
990    /// An arm in the x-z plane turning about the y axis at the origin, its angle a from x towards z: a point mass `mass`
991    /// at `length`, a rotor of `rotor` kg m^2 on its shaft (ratio 1), gravity `g` down z. Its energy parts are signals,
992    /// so that the loss budget can be checked on it.
993    struct Arm {
994        mass: f64,
995        length: f64,
996        rotor: f64,
997        g: f64,
998        axes: [AxisInfo; 1],
999        motors: [MotorInfo; 1],
1000    }
1001
1002    fn arm(g: f64) -> Arm {
1003        // Its middle hanging down, where it swings stably under a constant torque (the standard suite's checks hold it
1004        // so).
1005        let (min, max) = (-FRAC_PI_2 - 0.5, -FRAC_PI_2 + 0.5);
1006        let axes = [AxisInfo { id: "a", key: "", unit: "rad", min, max, max_vel: 1.0, max_acc: 10.0, max_jerk: 100.0 }];
1007        Arm { mass: 3.0, length: 0.4, rotor: 0.02, g, axes, motors: [MotorInfo { id: "a", key: "" }] }
1008    }
1009
1010    impl Arm {
1011        fn inertia(&self) -> f64 {
1012            self.mass * self.length * self.length + self.rotor
1013        }
1014        fn parts(&self, s: &[f64]) -> [f64; 3] {
1015            [0.5 * self.inertia() * s[1] * s[1], self.mass * self.g * self.length * s[0].sin(), 0.0]
1016        }
1017    }
1018
1019    impl Machine for Arm {
1020        fn frame_momentum(&self, s: &[f64]) -> Option<FrameMomentum> {
1021            let (sin, cos) = s[0].sin_cos();
1022            let mut f = FrameMomentum { gravity: [0.0, 0.0, -self.g], ..Default::default() };
1023            let (dir, ddir) = ([cos, 0.0, sin], [-sin, 0.0, cos]);
1024            let (l, m) = (self.length, self.mass);
1025            add_turning(&mut f, [0.0; 3], dir, ddir, s[1], m * l * l, m * l);
1026            add_spin(&mut f, [0.0, -1.0, 0.0], self.rotor, s[1]);
1027            Some(f)
1028        }
1029        fn axes(&self) -> &[AxisInfo] {
1030            &self.axes
1031        }
1032        fn motors(&self) -> &[MotorInfo] {
1033            &self.motors
1034        }
1035        fn inverse(&self, tool: &[f64], motors: &mut [f64]) {
1036            motors[0] = tool[0];
1037        }
1038        fn forward(&self, motors: &[f64], tool: &mut [f64]) {
1039            tool[0] = motors[0];
1040        }
1041        fn state_len(&self) -> usize {
1042            2
1043        }
1044        fn equilibrium(&self, tool: &[f64], state: &mut Vec<f64>, torque: &mut [f64]) {
1045            *state = vec![tool[0], 0.0];
1046            torque[0] = self.mass * self.g * self.length * tool[0].cos();
1047        }
1048        fn derivatives(&self, s: &[f64], torque: &[f64], out: &mut [f64]) {
1049            out[0] = s[1];
1050            out[1] = (torque[0] - self.mass * self.g * self.length * s[0].cos()) / self.inertia();
1051        }
1052        fn tool_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
1053            (pos[0], vel[0]) = (s[0], s[1]);
1054        }
1055        fn set_tool_velocity(&self, s: &mut [f64], vel: &[f64]) {
1056            s[1] = vel[0];
1057        }
1058        fn motor_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
1059            (pos[0], vel[0]) = (s[0], s[1]);
1060        }
1061        fn feedforward_torque(&self, pos: &[f64], acc: &[f64], out: &mut [f64]) {
1062            out[0] = self.inertia() * acc[0] + self.mass * self.g * self.length * pos[0].cos();
1063        }
1064        fn energy(&self, s: &[f64]) -> f64 {
1065            self.parts(s).iter().sum()
1066        }
1067        fn set_payload_attached(&mut self, _: bool) {}
1068        fn signal_infos(&self) -> Vec<SignalInfo> {
1069            ENERGY_PARTS.map(|p| SignalInfo::new(format!("energy.{p}"), "", "", "J")).to_vec()
1070        }
1071        fn base_signals(&self, _: &[f64], _: &[f64], _: &mut Vec<f64>) {}
1072        fn effect_signals(&self, s: &[f64], _: &[f64], out: &mut Vec<f64>) {
1073            out.extend(self.parts(s));
1074        }
1075        fn scene(&self, _: &[f64], _: &mut Scene) {}
1076    }
1077
1078    /// A base config with effects.base_reaction as `reaction`: 200 kg, 10 kg m^2 about each axis, the stiffnesses of
1079    /// `DOFS`, damping ratio `zeta`, the start pose `pose`.
1080    fn base_config(reaction: bool, pose: f64, stiffness: [f64; 6], zeta: f64, pivot: [f64; 3]) -> Config {
1081        // `Config::set_text` only changes keys that are there, so every key is written into the text.
1082        let mut text = format!(
1083            "format_version = 1\n[effects]\nbase_compliance = true\nbase_reaction = {reaction}\n[start]\n\
1084             pose = [{pose:?}]\n[base]\npivot_m = {pivot:?}\nmass_kg = 200.0\n"
1085        );
1086        for (k, axis) in ["x", "y", "z"].iter().enumerate() {
1087            text += &format!(
1088                "stiffness_{axis}_n_m = {:?}\ntilt_stiffness_{axis}_nm_rad = {:?}\ninertia_{axis}_kgm2 = 10.0\n",
1089                stiffness[k],
1090                stiffness[3 + k]
1091            );
1092        }
1093        for id in DOFS {
1094            text += &format!("damping_ratio_{id} = {zeta:?}\n");
1095        }
1096        Config::parse(&text).unwrap()
1097    }
1098
1099    /// A base along x of 200 kg on 8e5 N/m, damping ratio `zeta`, pivot at the origin.
1100    fn on_base(zeta: f64) -> Box<dyn Machine> {
1101        let stiffness = [8.0e5, 0.0, 0.0, 0.0, 0.0, 0.0];
1102        mount(&base_config(false, 0.5, stiffness, zeta, [0.0; 3]), Box::new(slider())).unwrap()
1103    }
1104
1105    #[test]
1106    fn the_base_adds_a_deflection_and_its_rate_per_compliant_direction() {
1107        let m = on_base(0.0);
1108        assert_eq!(m.state_len(), 4);
1109        assert_eq!(m.signal_infos()[0].id, "base.x");
1110        // f = sqrt(k / M) / 2 pi = sqrt(8e5 / 200) / 2 pi = 63.25 / 2 pi = 10.07 Hz.
1111        let modes = m.modes(&[0.5]);
1112        assert!((modes[0].hz - 63.245_553 / std::f64::consts::TAU).abs() < 1e-6, "{modes:?}");
1113        assert_eq!(m.resonance_hz(&[0.5]), Some(modes[0].hz));
1114    }
1115
1116    #[test]
1117    fn the_resonance_is_the_lower_of_the_machines_and_the_bases_and_the_motor_kind_is_forwarded() {
1118        // The base mode is 10.07 Hz (see above); a machine resonance of 0.35 Hz without a mode shape is the lower.
1119        let stiffness = [8.0e5, 0.0, 0.0, 0.0, 0.0, 0.0];
1120        let config = base_config(false, 0.5, stiffness, 0.0, [0.0; 3]);
1121        let m = mount(&config, Box::new(Slider { resonance: Some(0.35), ..slider() })).unwrap();
1122        assert_eq!(m.resonance_hz(&[0.5]), Some(0.35));
1123        assert!(m.motor_linear(0));
1124    }
1125
1126    #[test]
1127    fn a_force_held_at_rest_deflects_the_base_and_the_tool_by_force_over_stiffness() {
1128        let mut m = on_base(0.3);
1129        let (mut state, mut torque) = (Vec::new(), vec![0.0]);
1130        m.equilibrium(&[0.5], &mut state, &mut torque);
1131        assert_eq!(state[2], 0.0);
1132        // Now the process force of 50 N pushes the slider while its motor holds it with -50 N: the motor's stator
1133        // takes +50 N, and the base gives way by 50 / 8e5 = 62.5 um once its sway has died down (damping ratio 0.3,
1134        // 10 Hz: after 2 s it is down by exp(-0.3 * 63.2 * 2), nothing).
1135        m.set_dwelling(true);
1136        let mut rk = Rk4::new(state.len());
1137        for _ in 0..2000 {
1138            advance(m.as_ref(), &mut rk, &mut state, &[-50.0], 1e-3, 4);
1139        }
1140        assert!((state[2] - 62.5e-6).abs() < 1e-9, "base {}", state[2]);
1141        let (mut pos, mut vel) = ([0.0], [0.0]);
1142        m.tool_state(&state, &mut pos, &mut vel);
1143        assert!((pos[0] - (0.5 + 62.5e-6)).abs() < 1e-9, "tool {}", pos[0]);
1144    }
1145
1146    #[test]
1147    fn an_axis_stopping_on_a_soft_base_leaves_it_ringing_at_its_natural_frequency() {
1148        let m = on_base(0.0);
1149        let (mut state, mut torque) = (Vec::new(), vec![0.0]);
1150        m.equilibrium(&[0.5], &mut state, &mut torque);
1151        // 100 N for 50 ms, then -100 N for 50 ms: the slider (4 kg) moves and stops; the base, pushed back by -100 N
1152        // and then +100 N, rings on after. Undamped, its zero crossings come every half period, 1 / (2 f) =
1153        // pi sqrt(M / k) = pi sqrt(200 / 8e5) = 49.67 ms.
1154        let mut rk = Rk4::new(state.len());
1155        let dt = 1e-4;
1156        let mut crossings = Vec::new();
1157        let mut last = state[2];
1158        for step in 0..20_000 {
1159            let t = step as f64 * dt;
1160            let force = if t < 0.05 {
1161                100.0
1162            } else if t < 0.1 {
1163                -100.0
1164            } else {
1165                0.0
1166            };
1167            advance(m.as_ref(), &mut rk, &mut state, &[force], dt, 1);
1168            if t > 0.1 && last.signum() != state[2].signum() {
1169                // Where the line between the two samples crosses zero.
1170                crossings.push(t + dt * last / (last - state[2]));
1171            }
1172            last = state[2];
1173        }
1174        assert!((state[1]).abs() < 1e-12, "the slider stopped");
1175        let half = (crossings[crossings.len() - 1] - crossings[0]) / (crossings.len() - 1) as f64;
1176        assert!((half - std::f64::consts::PI * (200.0f64 / 8.0e5).sqrt()).abs() < 1e-6, "half period {half}");
1177    }
1178
1179    /// Two-way (effects.base_reaction), the drive off and the belt replaced by a spring: the slider of m = 4 kg held by
1180    /// k_c = 2e5 N/m to the base, the base 200 kg in all (M0 = 196 kg of its own) on k_b = 8e5 N/m along x. A two-mass
1181    /// system, the base x0 and the slider x1 over ground: M0 x0'' = -k_b x0 + k_c (x1 - x0), m x1'' = -k_c (x1 - x0).
1182    /// Its modes w^2 = (p -+ sqrt(p^2 - 4 q)) / 2 with p = (k_b + k_c) / M0 + k_c / m = 5102.04 + 50000 = 55102.04 and
1183    /// q = k_b k_c / (M0 m) = 2.0408e8: w^2 = 3993.07 and 51108.97, 10.057 Hz and 35.981 Hz; in each the slider moves
1184    /// r = k_c / (k_c - m w^2) times as far as the base, 1.0868 and -45.09. Started at rest in either shape, the base
1185    /// swings as A cos(w t) and the slider keeps the shape, to 1e-6 of A over 0.2 s (2 and 7 periods). One-way the base
1186    /// rings at sqrt(k_b / 200) = 10.066 Hz whatever the slider does.
1187    #[test]
1188    fn a_slider_on_a_spring_on_a_coupled_base_swings_in_the_two_mass_modes() {
1189        let (m, kb, kc): (f64, f64, f64) = (4.0, 8.0e5, 2.0e5);
1190        let m0 = 200.0 - m;
1191        let (p, q) = ((kb + kc) / m0 + kc / m, kb * kc / (m0 * m));
1192        let modes = [-1.0, 1.0].map(|sign: f64| (0.5 * (p + sign * (p * p - 4.0 * q).sqrt())).sqrt());
1193        let hz = modes.map(|w| w / std::f64::consts::TAU);
1194        assert!((hz[0] - 10.057).abs() < 1e-3 && (hz[1] - 35.981).abs() < 1e-3, "{hz:?}");
1195        let config = base_config(true, 0.5, [kb, 0.0, 0.0, 0.0, 0.0, 0.0], 0.0, [0.0; 3]);
1196        for w in modes {
1197            let machine = mount(&config, Box::new(Slider { spring: kc, ..slider() })).unwrap();
1198            let (r, a, dt) = (kc / (kc - m * w * w), 1e-6, 1e-5);
1199            let mut state = vec![0.5 + (r - 1.0) * a, 0.0, a, 0.0];
1200            let mut rk = Rk4::new(state.len());
1201            let (mut swing, mut shape) = (0f64, 0f64);
1202            for step in 1..=20_000 {
1203                advance(machine.as_ref(), &mut rk, &mut state, &[0.0], dt, 1);
1204                swing = swing.max((state[2] - a * (w * step as f64 * dt).cos()).abs());
1205                shape = shape.max((state[0] - 0.5 - (r - 1.0) * state[2]).abs() / (r - 1.0).abs());
1206            }
1207            assert!(swing < 1e-6 * a && shape < 1e-6 * a, "{w} rad/s: off by {swing} m, shape by {shape} m");
1208        }
1209    }
1210
1211    /// Two-way, the base free (springs at zero) along x and z and in tilt about y through the pivot (0.1, 0, -0.2),
1212    /// 20 kg and 2 kg m^2, no gravity and no outside force: a torque pulse swings the arm (3 kg at 0.4 m, rotor 0.02 kg
1213    /// m^2) from 0.3 rad. Nothing outside pushes base and arm, so their momentum stays what it was, zero: M_B d' + p along
1214    /// x and z and I_B theta' + L (about the pivot) about y, to 1e-9 of the arm's own while it swings. One-way keeps it
1215    /// too (the base takes dp/dt whatever the machine does); this checks that the two are solved as one: with the
1216    /// machine feeling the base but the base's equation left without A M^-1 A^T it fails.
1217    #[test]
1218    fn a_free_coupled_base_and_the_machine_on_it_keep_their_momentum() {
1219        let inner = arm(0.0);
1220        let (mut state, mut torque) = (Vec::new(), [0.0]);
1221        inner.equilibrium(&[0.3], &mut state, &mut torque);
1222        let pivot = [0.1, 0.0, -0.2];
1223        let at_rest = inner.frame_momentum(&state).unwrap();
1224        let reaction = Reaction::new(&inner, &state, &torque, pivot, &at_rest);
1225        assert_eq!(reaction.speeds, [1]);
1226        let free = |index, mass| Dof { index, mass, stiffness: 0.0, damping: 0.0 };
1227        let dofs = vec![free(0, 20.0), free(2, 20.0), free(4, 2.0)];
1228        let m = Based {
1229            inner: Box::new(inner),
1230            dofs: dofs.clone(),
1231            pivot,
1232            reference: static_load(&at_rest),
1233            external_reference: external_wrench(&at_rest),
1234            inner_base_signals: 0,
1235            reaction: Some(reaction),
1236            push: Vec::new(),
1237        };
1238        state.extend([0.0; 6]);
1239        let mut rk = Rk4::new(state.len());
1240        let (dt, mut own, mut total) = (1e-4, 0f64, 0f64);
1241        for step in 0..5000 {
1242            let t = step as f64 * dt;
1243            let pulse = if t < 0.2 { 4.0 * (std::f64::consts::PI * t / 0.2).sin().powi(2) } else { 0.0 };
1244            advance(&m, &mut rk, &mut state, &[pulse], dt, 1);
1245            let p = momentum(&m.frame_momentum(&state).unwrap(), pivot);
1246            for (k, d) in dofs.iter().enumerate() {
1247                own = own.max(p[d.index].abs());
1248                total = total.max((d.mass * state[5 + k] + p[d.index]).abs());
1249            }
1250        }
1251        assert!(own > 0.1 && total < 1e-9 * own, "the arm's momentum up to {own}, with the base's {total}");
1252    }
1253
1254    /// Two-way, losses off: the arm hanging in gravity on a base along x and z (8e5 N/m) and tilting about y through a
1255    /// pivot 0.3 m below the arm's joint (5e3 N m/rad, soft, so that the tilt turns gravity in the arm's frame by a
1256    /// measurable angle), undamped. The standard suite's energy check: the arm's energy and the base's (its sway with the
1257    /// arm's momentum, its springs, the arm's weight on its tilt) stay within 0.1 % of what the torque pulse put in over
1258    /// 10 s (without the tilt's turn of gravity on the arm 0.32 %; one-way more). With a damping ratio of 0.05 the loss
1259    /// budget closes with the base's damping loss `power.base` and its energy in the `energy.*` signals.
1260    #[test]
1261    fn a_coupled_base_keeps_the_energy_and_closes_the_loss_budget() {
1262        let stiffness = [8.0e5, 0.0, 8.0e5, 0.0, 5.0e3, 0.0];
1263        let config = |zeta: f64| base_config(true, -FRAC_PI_2, stiffness, zeta, [0.0, 0.0, -0.3]);
1264        let on = |zeta: f64| mount(&config(zeta), Box::new(arm(9.81)));
1265        sim_core::testkit::energy_conservation(on(0.0).unwrap().as_ref());
1266        let damped = on(0.05).unwrap();
1267        assert_eq!(damped.signal_infos().last().unwrap().id, "power.base");
1268        sim_core::testkit::loss_budget(damped.as_ref());
1269    }
1270
1271    /// The process force's work on the moving base is in the base's row. The slider dwells under 50 N along x on a base
1272    /// of 200 kg and 8e5 N/m (damping ratio 0.05: c = 2 * 0.05 * sqrt(8e5 * 200) = 1264.911 N s/m) moving at 0.3 m/s:
1273    /// the row is c v^2 - F v = 113.842 - 15 = 98.842 W (the force was not on at the start pose, so none is taken off).
1274    #[test]
1275    fn the_process_force_works_on_the_moving_base_in_its_row() {
1276        let config = base_config(true, 0.5, [8.0e5, 0.0, 0.0, 0.0, 0.0, 0.0], 0.05, [0.0; 3]);
1277        let mut machine = mount(&config, Box::new(slider())).unwrap();
1278        machine.set_dwelling(true);
1279        let state = [0.5, 0.0, 1e-4, 0.3];
1280        let mut rows = Vec::new();
1281        machine.loss_powers(&state, &[0.0], &mut rows);
1282        assert!((rows.last().unwrap() - 98.842).abs() < 1e-3, "{rows:?}");
1283    }
1284
1285    /// The budget closes with the process force on a moving base: the slider (dwelling under 50 N along x, its motor
1286    /// pushing 30 N back) on a coupled base along x (200 kg, 8e5 N/m, damping ratio 0.05), integrated by RK4 over 50 ms
1287    /// from rest. The motor's work and the process force's on the slider's own travel, int (tau + F) x' dt, equal the
1288    /// change of the energy plus the base's row, int (c d'^2 - F d') dt (trapezoid on 1 us steps).
1289    #[test]
1290    fn the_budget_closes_with_the_process_force_on_a_moving_base() {
1291        let config = base_config(true, 0.5, [8.0e5, 0.0, 0.0, 0.0, 0.0, 0.0], 0.05, [0.0; 3]);
1292        let mut machine = mount(&config, Box::new(slider())).unwrap();
1293        machine.set_dwelling(true);
1294        let (dt, tau, force) = (1e-6, [-30.0], 50.0);
1295        let mut s = vec![0.5, 0.0, 0.0, 0.0];
1296        let row = |s: &[f64]| {
1297            let mut rows = Vec::new();
1298            machine.loss_powers(s, &tau, &mut rows);
1299            *rows.last().unwrap()
1300        };
1301        let start = machine.energy(&s);
1302        let (mut work, mut lost, mut last, mut fastest) = (0.0, 0.0, ((tau[0] + force) * s[1], row(&s)), 0.0f64);
1303        let derivative = |s: &[f64]| {
1304            let mut out = vec![0.0; s.len()];
1305            machine.derivatives(s, &tau, &mut out);
1306            out
1307        };
1308        for _ in 0..50_000 {
1309            let k1 = derivative(&s);
1310            let at = |k: &[f64], h: f64| s.iter().zip(k).map(|(x, d)| x + h * d).collect::<Vec<_>>();
1311            let k2 = derivative(&at(&k1, 0.5 * dt));
1312            let k3 = derivative(&at(&k2, 0.5 * dt));
1313            let k4 = derivative(&at(&k3, dt));
1314            for i in 0..s.len() {
1315                s[i] += dt / 6.0 * (k1[i] + 2.0 * k2[i] + 2.0 * k3[i] + k4[i]);
1316            }
1317            let now = ((tau[0] + force) * s[1], row(&s));
1318            (work, lost) = (work + 0.5 * dt * (now.0 + last.0), lost + 0.5 * dt * (now.1 + last.1));
1319            last = now;
1320            fastest = fastest.max(s[3].abs());
1321        }
1322        let stored = machine.energy(&s) - start;
1323        assert!(fastest > 1e-3 && work > 0.01, "the base moves ({fastest} m/s), the slider is pushed ({work} J)");
1324        assert!((work - stored - lost).abs() < 1e-9, "work {work} J, stored {stored} J, base row {lost} J");
1325    }
1326
1327    /// The scene tilts with the base. The base is moved 2e-4 m along x and tilted 1e-3 rad about y through the origin;
1328    /// a part at (0.2, 0, 0.5) and a belt strip's far end at (0.8, 0, -0.25) move by t + theta x p, theta = (0, 1e-3, 0):
1329    /// (2e-4 + 1e-3 * 0.5, 0, -1e-3 * 0.2) = (7e-4, 0, -2e-4) and (2e-4 - 2.5e-4, 0, -8e-4) = (-5e-5, 0, -8e-4).
1330    #[test]
1331    fn the_scene_tilts_with_the_base_at_each_points_own_place() {
1332        let config = base_config(false, 0.5, [8.0e5, 0.0, 0.0, 0.0, 5.0e3, 0.0], 0.0, [0.0; 3]);
1333        let machine = mount(&config, Box::new(slider())).unwrap();
1334        let mut scene = Scene::default();
1335        let shape = sim_core::Shape::Segment { to: [0.8, 0.0, -0.25], width: 0.01 };
1336        scene.parts.push(sim_core::Part::new("belt", shape, [0.2, 0.0, 0.5], [1.0; 3]));
1337        // The slider at 0.5, then the base's x and tilt about y, then their rates.
1338        let state = [0.5, 0.0, 2e-4, 1e-3, 0.0, 0.0];
1339        machine.scene(&state, &mut scene);
1340        let part = &scene.parts[0];
1341        let sim_core::Shape::Segment { to, .. } = &part.shape else { unreachable!() };
1342        let (a, b) = ([7e-4, 0.0, -2e-4], [-5e-5, 0.0, -8e-4]);
1343        for k in 0..3 {
1344            assert!((part.pos[k] - [0.2, 0.0, 0.5][k] - a[k]).abs() < 1e-12, "{:?}", part.pos);
1345            assert!((to[k] - [0.8, 0.0, -0.25][k] - b[k]).abs() < 1e-12, "{to:?}");
1346        }
1347    }
1348
1349    /// The same base move on a scene that shows x the other way (a reflection, x -> -x): the point the scene shows at
1350    /// (-0.2, 0, 0.5) is the machine's (0.2, 0, 0.5), which moves by (7e-4, 0, -2e-4) as above; in the scene that is
1351    /// (-7e-4, 0, -2e-4). (Mapping the tilt as a plain vector, not as a pseudovector, gives +2e-4 in z.)
1352    #[test]
1353    fn the_scene_tilts_with_the_base_on_a_flipped_scene() {
1354        let config = base_config(false, 0.5, [8.0e5, 0.0, 0.0, 0.0, 5.0e3, 0.0], 0.0, [0.0; 3]);
1355        let machine = mount(&config, Box::new(Slider { flipped: true, ..slider() })).unwrap();
1356        let mut scene = Scene::default();
1357        scene.parts.push(sim_core::Part::new(
1358            "box",
1359            sim_core::Shape::Box { size: [0.1; 3] },
1360            [-0.2, 0.0, 0.5],
1361            [1.0; 3],
1362        ));
1363        machine.scene(&[0.5, 0.0, 2e-4, 1e-3, 0.0, 0.0], &mut scene);
1364        let moved: [f64; 3] = std::array::from_fn(|k| scene.parts[0].pos[k] - [-0.2, 0.0, 0.5][k]);
1365        for (m, want) in moved.iter().zip([-7e-4, 0.0, -2e-4]) {
1366            assert!((m - want).abs() < 1e-12, "{moved:?}");
1367        }
1368    }
1369
1370    /// A base lighter than what the machine moves on it cannot be: M_B - A M^-1 A^T would not be positive.
1371    #[test]
1372    fn a_coupled_base_must_be_heavier_than_what_moves_on_it() {
1373        let mut config = base_config(true, 0.5, [8.0e5, 0.0, 0.0, 0.0, 0.0, 0.0], 0.0, [0.0; 3]);
1374        config.set_text("base.mass_kg = 3.9").unwrap();
1375        assert!(matches!(mount(&config, Box::new(slider())), Err(ConfigError::Invalid(k)) if k == "base.mass_kg"));
1376        config.set_text("base.mass_kg = 4.1").unwrap();
1377        assert!(mount(&config, Box::new(slider())).is_ok());
1378    }
1379}