Skip to main content

machine_t_gantry/
lib.rs

1//! T-gantry: transformation, belt routing, assembly, scene description.
2//!
3//! Two fixed motors A (left) and B (right) at the ends of the X beam drive one belt. The belt ends are
4//! clamped at the top of the Z axis and it runs around an idler at the bottom of the Z axis:
5//!
6//! clamp -> carriage idler -> motor A -> carriage idler -> Z-bottom idler -> carriage idler -> motor B
7//! -> carriage idler -> clamp
8//!
9//! With pulley angles a and b after the gearbox: x = r/2 (a + b), z = r/2 (a - b).
10//! Both motors the same way moves X, against each other moves Z.
11//!
12//! The two motor pulleys cut the belt into three sections of uniform tension:
13//!
14//! | section | from -> to            | geometric length      | belt fed in by |
15//! | ------- | --------------------- | --------------------- | -------------- |
16//! | 1       | clamp -> motor A      | const + x + z         | + r a          |
17//! | 2       | motor A -> motor B    | const - 2 z           | - r a + r b    |
18//! | 3       | motor B -> clamp      | const - x + z         | - r b          |
19//!
20//! Belt forces: Fx = T3 - T1, Fz = 2 T2 - T1 - T3, pulley A: r (T1 - T2), pulley B: r (T2 - T3).
21//!
22//! Belt speed past the idlers, as each idler sees it. The top of pulley A moves at vx + vz, the carriage
23//! at vx, so belt passes the two upper carriage idlers at vz (it only follows the clamp up and down). The
24//! lower run comes back from the pulleys at vx + vz and vx - vz against the carriage, so belt passes the
25//! lower carriage idlers at 2 vx + vz (left) and 2 vx - vz (right), and the Z-bottom idler, which rises
26//! with z, at 2 vx.
27
28use sim_components::mech::{
29    Belt, CableChain, Gearbox, HardStop, HoldingBrake, JUMP_STATES, Lugre, Ripple, SectionForce, ShaftFriction,
30    ThermalFeedback, ToothJump, ToothMesh, drive_excitations, span_detuning, span_frequency, wrap_angle,
31};
32use sim_core::{
33    Arrow, AxisInfo, BeltSection, Config, ConfigError, ENERGY_PARTS, FRICTION_SIGNALS, FrictionContact, LOSS_PREFIX,
34    Label, Machine, MachineEntry, Mode, MotorInfo, Part, Scene, Shape, SignalInfo, TORQUE_PARTS, ThermalPart,
35};
36
37pub static ENTRY: MachineEntry = MachineEntry {
38    id: "t-gantry",
39    key: "machine-t-gantry",
40    default_config: include_str!("../default.toml"),
41    i18n: &[("en", include_str!("../i18n/en.ftl")), ("de", include_str!("../i18n/de.ftl"))],
42    build,
43    suite_configs,
44};
45
46const G: f64 = 9.80665;
47
48/// A real machine as a config for `--config`: a Festo EXCT-30 with Siemens 1FK2 motors on SINAMICS S210.
49pub const EXCT_30_CONFIG: &str = include_str!("../exct-30.toml");
50
51/// Effects that take energy out or put it in; the standard suite runs with them off.
52pub const LOSSY_EFFECTS: [&str; 13] = [
53    "belt_damping",
54    "guide_friction",
55    "load_dependent_friction",
56    "motor_friction",
57    "gearbox_drag",
58    "gearbox_lost_motion",
59    "gearbox_efficiency",
60    "torque_ripple",
61    "tooth_meshing",
62    "temperature",
63    "process_force",
64    "holding_brake",
65    "beam_vertical_mode",
66];
67
68fn build(cfg: &Config) -> Result<Box<dyn Machine>, ConfigError> {
69    sim_components::base::mount(cfg, Box::new(TGantry::new(cfg)?))
70}
71
72/// The default config with every loss switched off.
73pub fn lossless_config() -> Config {
74    let mut cfg = ENTRY.config();
75    for effect in LOSSY_EFFECTS {
76        cfg.set_text(&format!("effects.{effect} = false")).unwrap();
77    }
78    cfg.set_text("gearbox.damping_nm_s_rad = 0.0").unwrap();
79    cfg.set_text("frame.damping_n_s_m = 0.0").unwrap();
80    cfg.set_text("tool_flex.damping_n_s_m = 0.0").unwrap();
81    cfg.set_text("idler.friction_nm = 0.0").unwrap();
82    cfg.set_text("cable_chain.drag_n = 0.0").unwrap();
83    cfg.set_text("hard_stop.damping_n_s_m = 0.0").unwrap();
84    cfg.set_text("beam.damping_ratio = 0.0").unwrap();
85    cfg
86}
87
88/// Loss-free rigid reference, loss-free full model, and the full model with the loss-free parts of the
89/// belt details and loads on top.
90fn suite_configs() -> Vec<Config> {
91    let mut rigid = lossless_config();
92    rigid.set_text("effects.belt_stretch = false").unwrap();
93    let mut loaded = lossless_config();
94    for effect in [
95        "belt_tooth_stiffness",
96        "idlers",
97        "cable_chain",
98        "part_heating",
99        "thermal_feedback",
100        "belt_tooth_jump",
101        "belt_span_vibration",
102        "belt_wrap",
103    ] {
104        loaded.set_text(&format!("effects.{effect} = true")).unwrap();
105    }
106    vec![rigid, lossless_config(), loaded]
107}
108
109pub struct TGantry {
110    elastic: bool,
111    r: f64,
112    /// Unstretched belt fed per radian of pulley. The pulley radius holds at pretension, where the
113    /// belt is already stretched, so that the kinematics are exact for an evenly tensioned belt.
114    r_mat: f64,
115    span_min: f64,
116    z_com_drop: f64,
117    z_tool_drop: f64,
118    guide_spacing: f64,
119    m_carriage: f64,
120    m_z_axis: f64,
121    m_payload: f64,
122    j_rotor: f64,
123    /// Pulley inertia including its share of the belt mass.
124    j_pulley: f64,
125    /// The belt lumped on each motor pulley, J = mu L / 2 r^2 (in `j_pulley`): its energy at the pulley's speed, not a spin
126    /// about the pulley (the runs carry the belt's angular momentum, `belt_angular`).
127    j_lump: f64,
128    g: f64,
129    belt: Belt,
130    /// Unstretched belt per section at x = z = 0 with the pulleys at angle 0.
131    mat0: [f64; 3],
132    friction_x: Lugre,
133    friction_z: Lugre,
134    shaft: [ShaftFriction; 2],
135    ripple: Ripple,
136    mesh: ToothMesh,
137    gearbox: Gearbox,
138    /// The gearbox of each motor: `gearbox` with its own efficiency once that follows its temperature
139    /// (effects.thermal_feedback).
140    gears: [Gearbox; 2],
141    /// With effects.thermal_feedback: the law, and the X and Z guides' viscous coefficients at the reference temperature.
142    thermal: Option<(ThermalFeedback, [f64; 2])>,
143    /// With effects.belt_tooth_jump (elastic model only): the law, and the energy the last step's jumps took, J/s.
144    jump: Option<ToothJump>,
145    jump_loss: f64,
146    /// With effects.belt_span_vibration: the belt's mass per metre, for the spans' string frequencies.
147    span_mass: Option<f64>,
148    /// With effects.belt_wrap: the carriage idlers' radius, for the belt's wrap at the motor pulleys (`belt_wraps`).
149    wrap_idler: Option<f64>,
150    /// The idlers' radius (`idler.radius_m`), where the belt's runs lie (`belt_angular`).
151    idler_radius: f64,
152    frame: Option<Frame>,
153    flex: Option<ToolFlex>,
154    /// With effects.beam_sag: the X beam sagging under the carriage.
155    beam: Option<Beam>,
156    /// Idler inertia as mass on [X, Z]: with m = J / r^2 per idler and the belt speeds of the module
157    /// comment, 1/2 m (2 vz^2 + (2 vx + vz)^2 + (2 vx - vz)^2 + (2 vx)^2) = 1/2 (12 m) vx^2 + 1/2 (4 m) vz^2.
158    m_idlers: [f64; 2],
159    /// One idler's inertia over its radius, kg m (0 with the effect off): the idlers' angular momentum is this times the
160    /// belt's speed past them over their radius (`idler_angular`).
161    idler_spin: f64,
162    /// Belt force that one idler's bearing friction takes, and the belt speed below which it fades out.
163    idler_drag: f64,
164    idler_smoothing: f64,
165    chain: CableChain,
166    /// Force on the tool in [X, Z] while the cycle dwells.
167    process: [f64; 2],
168    dwelling: bool,
169    /// An obstacle's push on the contact coordinates (`Machine::set_tool_force`): the tool's [X, Z], or with the lean the
170    /// elastic model's `coordinates`. Held until changed.
171    push: Stack<f64, MAX_COORDINATES>,
172    stops: HardStop,
173    /// Holding brake of one motor shaft.
174    brake: HoldingBrake,
175    brake_engaged: bool,
176    payload_attached: bool,
177    axes: [AxisInfo; 2],
178    motors: [MotorInfo; 2],
179}
180
181struct Frame {
182    mass: f64,
183    stiffness: f64,
184    damping: f64,
185}
186
187/// The Z axis leaning against the carriage: its centre of mass moves sideways by u against a spring.
188/// The guide gives way sideways (lateral) and in tilt; a force at the distance h from the carriage
189/// tilts with the arm h, so the compliance at the centre of mass is 1 / lateral + h^2 / tilt. With
190/// effects.z_axis_bending the Z axis bends too, a cantilever from the carriage of bending stiffness EI: h^3 / (3 EI)
191/// more at its centre of mass, and a force there moves the tool, at h_t, by h^2 (3 h_t - h) / (6 EI). With
192/// effects.tool_flex off the guide is rigid (infinite stiffnesses) and the Z axis only bends.
193struct ToolFlex {
194    lateral: f64,
195    tilt: f64,
196    damping: f64,
197    ei: f64,
198    /// How far the belt's two upper vertical runs (sections 1 and 3) reach the clamp to either side of the Z axis's line,
199    /// m (`TGantry::lean_offset`).
200    belt_offset: f64,
201}
202
203/// The X beam between the posts (effects.beam_sag, effects.beam_vertical_mode): a simple span of `span` m and bending
204/// stiffness `ei` N m^2, the carriage `start` m from the left post at x = 0. The carriage and the Z axis with what it
205/// carries, m g, sag it under the carriage at a by m g a^2 b^2 / (3 EI L) (`beam::span_compliance`), which lowers the tool.
206/// With `mode` the beam is not quasi-static: its deflection under the carriage w is a state (`BeamMode`).
207struct Beam {
208    span: f64,
209    start: f64,
210    ei: f64,
211    mode: Option<BeamMode>,
212}
213
214/// The beam's first vertical mode with the carriage on it (effects.beam_vertical_mode), one more coordinate w, the
215/// beam's deflection under the carriage, down. Its shape is the beam's static deflection under a point load at the
216/// carriage, taken to 1 under it: stiffness k = 1 / `span_compliance` (so that m g / k is the quasi-static sag, exactly),
217/// modal mass M = mu integral of the shape squared (`Beam::modal_mass`: 17 / 35 mu L in the middle) and the damping
218/// c = 2 zeta sqrt(k (m_c + m_z + M)), so that zeta is the mode's damping ratio with the carriage on the beam. The carriage, the Z axis and the payload move with w (mass m_c + m_z + M; the Z axis's own z is
219/// relative to the carriage, so its speed over ground is z' - w'), so a Z move's acceleration drives it, and the carriage's
220/// weight, riding along the beam, drives it as k(x) changes (V = 1/2 k(x) w^2 - m g w, a force on x of -1/2 k' w^2).
221/// The Lagrangian keeps T = 1/2 M(x) w'^2 and drops what the shape's change with x adds: the coupling 1/2 M' w x' w'
222/// (w / L = 5e-5 of the kept terms at the 59 um sag) and 1/2 mu integral of (phi_x w x')^2 (1e-9). The belt rides on w
223/// too (`belt_on_beam`, since 21 November 2026): its vertical runs, mu (4 s + 2 sz) = 0.16 kg, go down with the carriage
224/// whole (their speed over ground z' - w' as the Z axis's), and its horizontal runs, from the posts' pulleys to the
225/// carriage's idlers, tilt with it: a third of them, 0.087 kg, in the kinetic energy, half in the weight. That lowers
226/// the mode by 0.93 % (59.32 to 58.77 Hz in the middle). The runs' lengths change with w only to second order (w^2 / 2l),
227/// which is left out.
228struct BeamMode {
229    mass_per_m: f64,
230    damping_ratio: f64,
231}
232
233impl Beam {
234    /// The carriage's distance from the left post at x, kept off the posts where the span's stiffness is infinite.
235    fn at(&self, x: f64) -> f64 {
236        (self.start + x).clamp(1e-3 * self.span, (1.0 - 1e-3) * self.span)
237    }
238    /// The stiffness under the carriage at x, N/m.
239    fn stiffness(&self, x: f64) -> f64 {
240        1.0 / sim_components::beam::span_compliance(self.ei, self.span, self.at(x))
241    }
242    /// The modal mass at x for the mass per metre `mu`: mu times the integral of the static shape squared, phi = 1 under
243    /// the load at a (b = L - a): phi = s (L^2 - b^2 - s^2) / (2 a^2 b) left of it, mirrored right of it. With
244    /// I(a, c) = integral over 0..a of s^2 (c - s^2)^2 = c^2 a^3 / 3 - 2 c a^5 / 5 + a^7 / 7:
245    /// M = mu (I(a, L^2 - b^2) / (4 a^4 b^2) + I(b, L^2 - a^2) / (4 a^2 b^4)). In the middle 17 mu L / 35.
246    fn modal_mass(&self, mu: f64, x: f64) -> f64 {
247        let (a, l) = (self.at(x), self.span);
248        let b = l - a;
249        let i = |a: f64, c: f64| c * c * a.powi(3) / 3.0 - 2.0 * c * a.powi(5) / 5.0 + a.powi(7) / 7.0;
250        mu * (i(a, l * l - b * b) / (4.0 * a.powi(4) * b * b) + i(b, l * l - a * a) / (4.0 * a * a * b.powi(4)))
251    }
252    /// The beam's own moments of its shape at x for the mass per metre `mu`, [mu integral of phi, mu integral of s phi]
253    /// (s from the left post): its vertical momentum is the first times -w', and its points s along it move by -phi w.
254    /// Left of the load int_0^a s (c - s^2) = c a^2 / 2 - a^4 / 4 and int_0^a s^2 (c - s^2) = c a^3 / 3 - a^5 / 5 over
255    /// 2 a^2 b (c = L^2 - b^2); right of it the same in s' = L - s over 2 a b^2 (c = L^2 - a^2). In the middle 5 mu L / 8.
256    fn shape_moments(&self, mu: f64, x: f64) -> [f64; 2] {
257        let (a, l) = (self.at(x), self.span);
258        let b = l - a;
259        let (c_left, c_right) = (l * l - b * b, l * l - a * a);
260        let (one, two) = (
261            |a: f64, c: f64| c * a * a / 2.0 - a.powi(4) / 4.0,
262            |a: f64, c: f64| c * a.powi(3) / 3.0 - a.powi(5) / 5.0,
263        );
264        let (left, right) = (2.0 * a * a * b, 2.0 * a * b * b);
265        [
266            mu * (one(a, c_left) / left + one(b, c_right) / right),
267            mu * (two(a, c_left) / left + (l * one(b, c_right) - two(b, c_right)) / right),
268        ]
269    }
270}
271
272/// The slope of `f` at x by a central difference.
273fn slope(f: impl Fn(f64) -> f64, x: f64) -> f64 {
274    (f(x + 1e-6) - f(x - 1e-6)) / 2e-6
275}
276
277// Elastic state: positions [x, z, a, b, pa, pb, q, u, w], their rates, the friction states [sx, sz], the
278// seconds a belt section has spent without tension, and the friction states of the two brakes.
279// a, b: pulley angles. pa, pb: motor shaft angles. q: frame deflection in X; x is the carriage relative to
280// the frame. u: the Z axis's centre of mass in X relative to the carriage. w: with effects.beam_vertical_mode the
281// beam's deflection under the carriage, down (z is then relative to the carriage); 0 without derivative otherwise.
282const X: usize = 0;
283const Z: usize = 1;
284const A: usize = 2;
285const PA: usize = 4;
286const Q: usize = 6;
287const U: usize = 7;
288const W: usize = 8;
289const V: usize = 9;
290const S: usize = 18;
291const SLACK: usize = 20;
292const BRAKE: usize = 21;
293const N_ELASTIC: usize = 23;
294// With effects.belt_tooth_jump the elastic state goes on with the slip states of pulley A, then of pulley B
295// (`JUMP_STATES` each).
296const JUMP: usize = N_ELASTIC;
297// Rigid state: [x, z, vx, vz, sx, sz], and the deflections of the two brakes.
298const RIGID_BRAKE: usize = 6;
299const N_RIGID: usize = 8;
300/// The most coordinates that carry mass in the elastic model: x, z, the sway q, the lean u and the beam's deflection w.
301const MAX_COORDINATES: usize = 5;
302
303/// A short list on the stack (the elastic model's per-step vectors are at most `MAX_COORDINATES` squared long), which
304/// reads as a slice of what has been pushed.
305#[derive(Clone, Copy)]
306struct Stack<T, const N: usize> {
307    items: [T; N],
308    len: usize,
309}
310
311impl<T: Copy + Default, const N: usize> Stack<T, N> {
312    fn new() -> Self {
313        Self { items: [T::default(); N], len: 0 }
314    }
315
316    /// `len` default entries (zeros for numbers).
317    fn of_len(len: usize) -> Self {
318        Self { items: [T::default(); N], len }
319    }
320
321    fn push(&mut self, item: T) {
322        self.items[self.len] = item;
323        self.len += 1;
324    }
325}
326
327impl<T: std::fmt::Debug, const N: usize> std::fmt::Debug for Stack<T, N> {
328    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
329        (**self).fmt(f)
330    }
331}
332
333impl<T, const N: usize> std::ops::Deref for Stack<T, N> {
334    type Target = [T];
335    fn deref(&self) -> &[T] {
336        &self.items[..self.len]
337    }
338}
339
340impl<T, const N: usize> std::ops::DerefMut for Stack<T, N> {
341    fn deref_mut(&mut self) -> &mut [T] {
342        &mut self.items[..self.len]
343    }
344}
345
346/// The eigenpairs of K x = w2 M x for the symmetric n x n matrices `m` (positive definite) and `k`, row by row, lowest
347/// w2 first, each x scaled to x'Mx = 1: the eigenvalues of L^-1 K L^-T (M = L L') by Jacobi rotations, x = L^-T y. Empty
348/// where M is not positive definite.
349fn generalised_eigen(m: &[f64], k: &[f64], n: usize) -> Vec<(f64, Vec<f64>)> {
350    let mut l = vec![0.0; n * n];
351    for i in 0..n {
352        for j in 0..=i {
353            let sum = m[i * n + j] - (0..j).map(|p| l[i * n + p] * l[j * n + p]).sum::<f64>();
354            if i == j {
355                if !(sum > 0.0) {
356                    return Vec::new();
357                }
358                l[i * n + i] = sum.sqrt();
359            } else {
360                l[i * n + j] = sum / l[j * n + j];
361            }
362        }
363    }
364    // w = L^-1, by forward substitution column by column.
365    let mut w = vec![0.0; n * n];
366    for j in 0..n {
367        for i in 0..n {
368            let sum = f64::from(u8::from(i == j)) - (0..i).map(|p| l[i * n + p] * w[p * n + j]).sum::<f64>();
369            w[i * n + j] = sum / l[i * n + i];
370        }
371    }
372    let mut a: Vec<f64> = (0..n * n)
373        .map(|rc| {
374            let (r, c) = (rc / n, rc % n);
375            (0..n).map(|p| (0..n).map(|q| w[r * n + p] * k[p * n + q] * w[c * n + q]).sum::<f64>()).sum()
376        })
377        .collect();
378    let mut v: Vec<f64> = (0..n * n).map(|rc| f64::from(u8::from(rc / n == rc % n))).collect();
379    for _ in 0..100 {
380        let off: f64 = (0..n * n).filter(|rc| rc / n != rc % n).map(|rc| a[rc] * a[rc]).sum();
381        let diag: f64 = (0..n).map(|i| a[i * n + i] * a[i * n + i]).sum();
382        if !(off > 1e-30 * diag) {
383            break;
384        }
385        for p in 0..n {
386            for q in p + 1..n {
387                if a[p * n + q] == 0.0 {
388                    continue;
389                }
390                let theta = (a[q * n + q] - a[p * n + p]) / (2.0 * a[p * n + q]);
391                let t = theta.signum() / (theta.abs() + (theta * theta + 1.0).sqrt());
392                let (cs, sn) = (1.0 / (t * t + 1.0).sqrt(), t / (t * t + 1.0).sqrt());
393                for r in 0..n {
394                    let (rp, rq) = (a[r * n + p], a[r * n + q]);
395                    (a[r * n + p], a[r * n + q]) = (cs * rp - sn * rq, sn * rp + cs * rq);
396                }
397                for r in 0..n {
398                    let (pr, qr) = (a[p * n + r], a[q * n + r]);
399                    (a[p * n + r], a[q * n + r]) = (cs * pr - sn * qr, sn * pr + cs * qr);
400                }
401                for r in 0..n {
402                    let (rp, rq) = (v[r * n + p], v[r * n + q]);
403                    (v[r * n + p], v[r * n + q]) = (cs * rp - sn * rq, sn * rp + cs * rq);
404                }
405            }
406        }
407    }
408    let mut pairs: Vec<(f64, Vec<f64>)> = (0..n)
409        .map(|i| (a[i * n + i], (0..n).map(|r| (0..n).map(|p| w[p * n + r] * v[p * n + i]).sum()).collect()))
410        .collect();
411    pairs.sort_by(|x, y| x.0.total_cmp(&y.0));
412    pairs
413}
414
415impl TGantry {
416    pub fn new(cfg: &Config) -> Result<Self, ConfigError> {
417        let axis = |id: &'static str, key: &'static str, stroke: f64| -> Result<AxisInfo, ConfigError> {
418            Ok(AxisInfo {
419                id,
420                key,
421                unit: "m",
422                min: 0.0,
423                max: stroke,
424                max_vel: cfg.positive(&format!("axis.{id}.max_velocity_m_s"))?,
425                max_acc: cfg.positive(&format!("axis.{id}.max_acceleration_m_s2"))?,
426                max_jerk: cfg.positive(&format!("axis.{id}.max_jerk_m_s3"))?,
427            })
428        };
429        let belt = Belt::from_config(cfg)?;
430        let r = cfg.positive("geometry.pulley_radius_m")?;
431        let frame = if cfg.bool("effects.frame_compliance")? {
432            Some(Frame {
433                mass: cfg.positive("frame.mass_kg")?,
434                stiffness: cfg.positive("frame.stiffness_n_m")?,
435                damping: cfg.non_negative("frame.damping_n_s_m")?,
436            })
437        } else {
438            None
439        };
440        let (lean, bend) = (cfg.bool("effects.tool_flex")?, cfg.bool("effects.z_axis_bending")?);
441        let flex = if lean || bend {
442            let stiff =
443                |on: bool, key: &str| Ok::<f64, ConfigError>(if on { cfg.positive(key)? } else { f64::INFINITY });
444            Some(ToolFlex {
445                lateral: stiff(lean, "tool_flex.lateral_stiffness_n_m")?,
446                tilt: stiff(lean, "tool_flex.tilt_stiffness_nm_rad")?,
447                damping: cfg.non_negative("tool_flex.damping_n_s_m")?,
448                ei: stiff(bend, "tool_flex.z_axis_bending_stiffness_nm2")?,
449                belt_offset: if lean && cfg.bool("effects.belt_run_offset")? {
450                    cfg.non_negative("tool_flex.belt_offset_m")?
451                } else {
452                    0.0
453                },
454            })
455        } else {
456            None
457        };
458        let vertical = cfg.bool("effects.beam_vertical_mode")?;
459        let beam = if cfg.bool("effects.beam_sag")? || vertical {
460            Some(Beam {
461                span: cfg.positive("beam.span_m")?,
462                start: cfg.non_negative("beam.carriage_at_zero_m")?,
463                ei: cfg.positive("beam.bending_stiffness_nm2")?,
464                mode: if vertical {
465                    Some(BeamMode {
466                        mass_per_m: cfg.positive("beam.mass_kg_m")?,
467                        damping_ratio: cfg.non_negative("beam.damping_ratio")?,
468                    })
469                } else {
470                    None
471                },
472            })
473        } else {
474            None
475        };
476        let on = |effect: &str, value: f64| -> Result<f64, ConfigError> {
477            Ok(if cfg.bool(&format!("effects.{effect}"))? { value } else { 0.0 })
478        };
479        let idler_radius = cfg.positive("idler.radius_m")?;
480        let shaft = ShaftFriction::from_config(cfg)?;
481        // The gearbox's own inertia turns with the rotor.
482        let j_rotor = cfg.positive("motor.rotor_inertia_kgm2")? + cfg.non_negative("gearbox.inertia_at_input_kgm2")?;
483        let brake = HoldingBrake::from_config(cfg, j_rotor)?;
484        let idler_mass = on("idlers", cfg.non_negative("idler.inertia_kgm2")? / (idler_radius * idler_radius))?;
485        let mut m = Self {
486            elastic: cfg.bool("effects.belt_stretch")?,
487            r,
488            r_mat: belt.rest_length(r),
489            span_min: cfg.positive("geometry.span_min_m")?,
490            z_com_drop: cfg.f64("geometry.z_com_drop_m")?,
491            z_tool_drop: cfg.f64("geometry.z_tool_drop_m")?,
492            guide_spacing: cfg.positive("geometry.guide_spacing_m")?,
493            m_carriage: cfg.positive("mass.carriage_kg")?,
494            m_z_axis: cfg.positive("mass.z_axis_kg")?,
495            m_payload: if cfg.bool("effects.payload")? { cfg.non_negative("mass.payload_kg")? } else { 0.0 },
496            j_rotor,
497            j_pulley: cfg.positive("pulley.inertia_kgm2")?,
498            j_lump: 0.0,
499            g: if cfg.bool("effects.gravity")? { G } else { 0.0 },
500            mat0: [0.0; 3],
501            friction_x: Lugre::from_config(cfg, "friction_x")?,
502            friction_z: Lugre::from_config(cfg, "friction_z")?,
503            m_idlers: [12.0 * idler_mass, 4.0 * idler_mass],
504            idler_spin: on("idlers", cfg.non_negative("idler.inertia_kgm2")? / idler_radius)?,
505            idler_drag: on("idlers", cfg.non_negative("idler.friction_nm")? / idler_radius)?,
506            idler_smoothing: shaft.smoothing * idler_radius,
507            chain: CableChain::from_config(cfg)?,
508            process: [
509                on("process_force", cfg.f64("process.force_x_n")?)?,
510                on("process_force", cfg.f64("process.force_z_n")?)?,
511            ],
512            dwelling: false,
513            push: Stack::of_len(2),
514            stops: HardStop::from_config(cfg)?,
515            brake,
516            brake_engaged: false,
517            shaft: [shaft.clone(), shaft],
518            ripple: Ripple::from_config(cfg)?,
519            mesh: ToothMesh::from_config(cfg)?,
520            gearbox: Gearbox::from_config(cfg)?,
521            gears: [Gearbox::from_config(cfg)?, Gearbox::from_config(cfg)?],
522            thermal: match ThermalFeedback::from_config(cfg)? {
523                Some(law) => Some((
524                    law,
525                    [cfg.non_negative("friction_x.viscous_n_s_m")?, cfg.non_negative("friction_z.viscous_n_s_m")?],
526                )),
527                None => None,
528            },
529            jump: None,
530            jump_loss: 0.0,
531            span_mass: if cfg.bool("effects.belt_span_vibration")? {
532                Some(cfg.positive("belt.mass_kg_m")?)
533            } else {
534                None
535            },
536            wrap_idler: if cfg.bool("effects.belt_wrap")? { Some(idler_radius) } else { None },
537            idler_radius,
538            frame,
539            flex,
540            beam,
541            payload_attached: true,
542            axes: [
543                axis("x", "axis-x", cfg.positive("geometry.stroke_x_m")?)?,
544                axis("z", "axis-z", cfg.positive("geometry.stroke_z_m")?)?,
545            ],
546            motors: [MotorInfo { id: "a", key: "motor-a" }, MotorInfo { id: "b", key: "motor-b" }],
547            belt,
548        };
549        let geo = m.geo(0.0, 0.0);
550        m.mat0 = geo.map(|g| m.belt.rest_length(g));
551        if m.elastic {
552            // Half the belt's mass is lumped on each motor pulley (below).
553            m.jump = ToothJump::from_config(
554                cfg,
555                r,
556                0.5 * m.belt.mass_per_m * (geo.iter().sum::<f64>() - 4.0 * m.belt.tooth_length),
557            )?;
558        }
559        // Belt mass: the belt's horizontal runs move at pulley surface speed, so half of the free belt is lumped on each
560        // pulley; what the vertical runs have more is `belt_mass`.
561        m.j_lump = 0.5 * m.belt.mass_per_m * (geo.iter().sum::<f64>() - 4.0 * m.belt.tooth_length) * r * r;
562        m.j_pulley += m.j_lump;
563        Ok(m)
564    }
565
566    fn payload(&self) -> f64 {
567        if self.payload_attached { self.m_payload } else { 0.0 }
568    }
569    /// Everything that moves in Z: the vertical axis and what it carries.
570    fn m_z(&self) -> f64 {
571        self.m_z_axis + self.payload()
572    }
573    /// The weight the belt holds the Z axis up against: its own and that of the belt's vertical runs. Those hang from
574    /// the clamp, s + z long down to the upper idlers, and from the lower idlers down to the Z bottom, s + sz - z long,
575    /// so the belt's potential is mu g ((s + z)^2 - (s + sz - z)^2) + const = mu g (2 s + sz)(2 z - sz) + const, whose
576    /// rate in z is mu (4 s + 2 sz) g (`belt_sway`'s cross mass, 0.16 kg by default), whatever x: the horizontal runs
577    /// keep their heights. Up the runs the tension grows by mu g per metre, so the sections' tensions where they leave
578    /// the pulleys hold it: 2 T2 - T1 - T3 = (m_z + mu (4 s + 2 sz)) g at rest.
579    fn z_weight(&self) -> f64 {
580        (self.m_z() + self.belt_sway().0) * self.g
581    }
582    /// Everything that moves in X: the carriage and the whole Z axis on it.
583    fn m_x(&self) -> f64 {
584        self.m_carriage + self.m_z()
585    }
586    /// Inertia per motor at the pulley: pulley plus rotor seen through the gearbox.
587    fn j(&self) -> f64 {
588        self.j_pulley + self.gearbox.ratio * self.gearbox.ratio * self.j_rotor
589    }
590    /// Both motors reflected onto one tool axis: 2 J / r^2.
591    fn m_motors(&self) -> f64 {
592        2.0 * self.j() / (self.r * self.r)
593    }
594
595    /// What the belt's kinetic energy has beyond the half of it lumped on each pulley, as a mass matrix on the carriage's
596    /// speed vx along the beam and the Z axis's vz: (xx, xz) of T = 1/2 xx vx^2 + xz vx vz (zz stays at the lumps').
597    ///
598    /// Run by run along the belt path of the module comment, the carriage at s + x from motor A (at 0) and s + sx - x from
599    /// motor B, the clamp s + z above the beam, the Z-bottom idler s + sz - z below it. Each straight run moves as a
600    /// whole: across itself with the wheels at its ends, along itself at the belt's speed there, which keeps through
601    /// each wrap relative to the wheel's own body. Over ground:
602    ///
603    /// | run                                   | length     | velocity (X, Z)     |
604    /// | ------------------------------------- | ---------- | ------------------- |
605    /// | 1: clamp down to upper left idler     | s + z      | (vx, vz)            |
606    /// | 1: upper left idler to motor A        | s + x      | (vx + vz, 0)        |
607    /// | 2: motor A to lower left idler        | s + x      | (-(vx + vz), 0)     |
608    /// | 2: lower left idler down to Z bottom  | s + sz - z | (vx, 2 vx + vz)     |
609    /// | 2: Z bottom up to lower right idler   | s + sz - z | (vx, -(2 vx - vz))  |
610    /// | 2: lower right idler to motor B       | s + sx - x | (-(vx - vz), 0)     |
611    /// | 3: motor B to upper right idler       | s + sx - x | (vx - vz, 0)        |
612    /// | 3: upper right idler up to clamp      | s + z      | (vx, vz)            |
613    ///
614    /// (Belt material leaves the clamp at its speed (vx, vz): relative to the carriage it slides up at vz, so the upper
615    /// left run moves at vx + vz, which is pulley A's surface speed, as x = r/2 (a + b), z = r/2 (a - b) say; the lower run
616    /// comes back from A at -(vx + vz), 2 vx + vz past the carriage, which it keeps up the Z axis's left run; round the
617    /// bottom idler, rising at vz, at 2 vx; down the right run at vz - 2 vx; and back to B at -(vx - vz).) So
618    /// 2 T / mu = 2 (s + z)(vx^2 + vz^2) + 2 (s + x)(vx + vz)^2 + 2 (s + sx - x)(vx - vz)^2 + (s + sz - z)(10 vx^2 + 2 vz^2)
619    ///           = L (vx^2 + vz^2) + 8 (s + sz - z) vx^2 + 4 (2 x - sx) vx vz,
620    /// L = 8 s + 2 sx + 2 sz the free belt. The lumps, mu L / 2 r^2 on each pulley turning at (vx +- vz) / r, are
621    /// 1/2 mu L (vx^2 + vz^2): what is left is xx = 8 mu (s + sz - z) (the X coefficient mu (L + 8 (s + sz - z)) in all)
622    /// and the cross term 2 mu (2 x - sx) vx vz of T, xz = 2 mu (2 x - sx). (The 4 mu of the audit is that of 2 T / mu.)
623    fn belt_mass(&self, x: f64, z: f64) -> (f64, f64) {
624        let (mu, s) = (self.belt.mass_per_m, self.span_min);
625        (8.0 * mu * (s + self.axes[1].max - z), 2.0 * mu * (2.0 * x - self.axes[0].max))
626    }
627    /// With effects.beam_vertical_mode: the belt's runs that ride on the beam's mode w (`BeamMode`), as (inertia,
628    /// weight) in kg. The vertical runs, mu (4 s + 2 sz) (`belt_sway`'s cross mass), go down with w whole; the horizontal
629    /// ones, mu (4 s + 2 sx) from the posts' pulleys to the carriage's idlers, tilt with it, their point at the share xi of
630    /// the way to the carriage going down by xi w: a third of their mass in the kinetic energy, half in the weight and the
631    /// first moment. Default gantry: 0.16 + 0.26 / 3 and 0.16 + 0.26 / 2. The weight sags the beam quasi-statically too
632    /// (effects.beam_sag, `sag`).
633    fn belt_on_beam(&self) -> (f64, f64) {
634        let (mu, s, sx) = (self.belt.mass_per_m, self.span_min, self.axes[0].max);
635        let (vertical, flat) = (self.belt_sway().0, mu * (4.0 * s + 2.0 * sx));
636        (vertical + flat / 3.0, vertical + flat / 2.0)
637    }
638
639    /// The belt's runs when the frame sways at q' along X (effects.frame_compliance): everything on the frame sways with
640    /// it, the belt too, so its speed over ground is the table's plus (q', 0). That adds q' mu sum(length x X speed) =
641    /// mu (4 s + 2 sz) q' vx (the horizontal runs cancel; the vertical ones, 4 s + 2 sz long, move at vx) and
642    /// 1/2 mu L q'^2: (cross, sway) = (mu (4 s + 2 sz), mu L). Constant, so they bring no speed terms.
643    fn belt_sway(&self) -> (f64, f64) {
644        let (mu, s, sx, sz) = (self.belt.mass_per_m, self.span_min, self.axes[0].max, self.axes[1].max);
645        (mu * (4.0 * s + 2.0 * sz), mu * (8.0 * s + 2.0 * sx + 2.0 * sz))
646    }
647    /// The speed terms of `belt_mass`'s Lagrange equations at the carriage's speed vx along the beam and the Z axis's vz,
648    /// as forces on the right side of the X and the Z equation. With dxx/dz = -8 mu and dxz/dx = 4 mu:
649    /// d/dt dT/dvx - dT/dx = xx ax + xz az - 8 mu vz vx (the 4 mu vx vz of d xz / dt and of dT/dx cancel), and
650    /// d/dt dT/dvz - dT/dz = xz ax + 4 mu vx^2 + 4 mu vx^2: (8 mu vx vz, -8 mu vx^2).
651    fn belt_speed_terms(&self, vx: f64, vz: f64) -> (f64, f64) {
652        let mu = self.belt.mass_per_m;
653        (8.0 * mu * vx * vz, -8.0 * mu * vx * vx)
654    }
655
656    /// The elastic model's coordinates that carry mass, in the order of `elastic_mass`: x (the carriage on the frame), z,
657    /// with effects.frame_compliance the frame's sway q, with a flexible Z axis its lean u.
658    fn coordinates(&self) -> Stack<usize, MAX_COORDINATES> {
659        let mut at = Stack::new();
660        at.push(X);
661        at.push(Z);
662        if self.frame.is_some() {
663            at.push(Q);
664        }
665        if self.flex.is_some() {
666            at.push(U);
667        }
668        if self.vertical().is_some() {
669            at.push(W);
670        }
671        at
672    }
673
674    /// The elastic model's mass matrix over `coordinates` at (x, z), row by row: T = 1/2 v' M v of all but the pulleys
675    /// and rotors, which turn on their own states. With w = x' + q' the carriage's speed over ground:
676    ///   1/2 (mc + chain) w^2 + 1/2 mz (w + u')^2 + 1/2 (mz + idlers' Z share) z'^2 + 1/2 mf q'^2 + 1/2 (idlers' X share) x'^2,
677    /// exactly: the chain's moving run goes with the carriage over ground (w, and its growth m' of the Lagrange
678    /// equations is in `elastic_derivatives`), but an idler's spin follows the belt's speed past the carriage (module
679    /// comment), the difference of two speeds over ground in which the frame's sway q' cancels, so the idlers ride on x'.
680    ///   and the belt's 1/2 xx x'^2 + xz x' z' + cross q' x' + 1/2 sway q'^2   (`belt_mass`, `belt_sway`)
681    /// (without the lean mz rides on w). The derivatives, the energy, the modes and the frame's momentum all take this.
682    fn elastic_mass(&self, x: f64, z: f64) -> Stack<f64, { MAX_COORDINATES * MAX_COORDINATES }> {
683        let at = self.coordinates();
684        let n = at.len();
685        let index = |coordinate: usize| at.iter().position(|&c| c == coordinate);
686        let mut mass = Stack::of_len(n * n);
687        // v v' times `weight`, v given by the (coordinate, factor) of its non-zero entries; and a cross term.
688        let add = |mass: &mut [f64], v: &[(usize, f64)], weight: f64| {
689            for &(i, a) in v {
690                for &(j, b) in v {
691                    mass[i * n + j] += weight * a * b;
692                }
693            }
694        };
695        let cross = |mass: &mut [f64], i: usize, j: usize, value: f64| {
696            mass[i * n + j] += value;
697            mass[j * n + i] += value;
698        };
699        let mut carriage: Stack<(usize, f64), 3> = Stack::new();
700        carriage.push((0, 1.0));
701        if let Some(q) = index(Q) {
702            carriage.push((q, 1.0));
703        }
704        add(&mut mass, &carriage, self.m_x() - self.m_z() + self.chain.mass(x).0);
705        // The idlers spin with the belt's speed past the carriage, which the frame's sway does not change: x' alone.
706        add(&mut mass, &[(0, 1.0)], self.m_idlers[0]);
707        if let Some(u) = index(U) {
708            carriage.push((u, 1.0));
709        }
710        add(&mut mass, &carriage, self.m_z());
711        add(&mut mass, &[(1, 1.0)], self.m_z() + self.m_idlers[1]);
712        let (xx, xz) = self.belt_mass(x, z);
713        add(&mut mass, &[(0, 1.0)], xx);
714        cross(&mut mass, 0, 1, xz);
715        if let (Some(f), Some(q)) = (&self.frame, index(Q)) {
716            let (belt_cross, belt) = self.belt_sway();
717            add(&mut mass, &[(q, 1.0)], f.mass + belt);
718            cross(&mut mass, 0, q, belt_cross);
719        }
720        // The beam's mode: the carriage, the Z axis and the payload move with w, the Z axis's z is relative to the carriage
721        // (its speed over ground z' - w'), and the beam's own modal mass.
722        // The belt's vertical runs move at z' - w' in Z with the Z axis (their x-speeds cancel: `belt_mass`'s table).
723        if let Some(w) = index(W) {
724            add(&mut mass, &[(w, 1.0)], self.m_carriage + self.m_z() + self.beam_mode(x)[1] + self.belt_on_beam().0);
725            cross(&mut mass, 1, w, -self.m_z() - self.belt_sway().0);
726        }
727        mass
728    }
729
730    /// The small oscillations of the elastic model about the pose, lowest first, with each one's shape in the layout of
731    /// the state: the generalised eigenvalues K v = w^2 M v over `coordinates`, x (the carriage on the frame), z, with
732    /// effects.frame_compliance the frame's sway q, with a flexible Z axis its lean u. The pulleys are taken as held, so
733    /// their inertia and the belt lumped on them are not in M; the belt's runs beyond the lumps are (`elastic_mass`).
734    ///   V = 1/2 sum k_i (g_i . (x, z))^2 + 1/2 kf q^2 + 1/2 kz u^2, the belt's three sections, k_i = EA / l_i (l_i the
735    ///   section's unstretched belt at rest there), with g_1 = (1, 1), g_2 = (0, -2), g_3 = (-1, 1) (the sections'
736    ///   lengths change with x + z, -2 z, -x + z),
737    /// so K_xx = k_1 + k_3, K_xz = k_1 - k_3, K_zz = k_1 + 4 k_2 + k_3. Each one's damping ratio is that of its shape v
738    /// in the same coordinates, v'Cv / (2 w v'Mv), with C the belt's sections (`belt.damping_n_s_m` each, or with
739    /// effects.belt_material_damping `belt.damping_time_s` k_i more) on the same g_i, `frame.damping_n_s_m` on q and
740    /// `tool_flex.damping_n_s_m` on u; the cross terms of a damping that is not proportional are left out.
741    ///
742    /// K also carries what the lean's own dynamics have beyond the spring (second order in the deflection, exact at the
743    /// pose): the Z axis hangs like a pendulum, its weight rising as it leans (`lean_weight_stiffness`), the belt runs'
744    /// geometric stiffness (`lean_runs`, at the sections' tensions at rest) and the process force's vertical part riding
745    /// the leaning axis (`rise_coefficients`: the tip rises by a u^2, V = -F_z a u^2) are on the lean's spring k: k_u(z).
746    /// All of it changes with z, and so does the tip's travel per u, so at the lean u0 = tip F_x / k_u that the pose's
747    /// sideways process force holds, K_uz = k_u' u0 - F_x tip' and K_zz = k_u'' u0^2 / 2 - F_x tip'' u0.
748    /// With effects.beam_vertical_mode the beam's deflection w is a
749    /// coordinate: V = 1/2 k(x) w^2 - m g w, so at the pose's w0 = m g / k: K_ww = k, K_xw = k' w0, K_xx += k'' w0^2 / 2;
750    /// the tool moves by z - w in Z.
751    fn modal(&self, tool_pose: &[f64]) -> Vec<(Mode, Vec<f64>)> {
752        if !self.elastic {
753            return Vec::new();
754        }
755        // At rest at the pose, as `equilibrium` has it: the Z axis on its belt above the beam's sag, each section's
756        // unstretched belt what carries the weight; dT/dL = EA / l of `Belt::section` with l that belt.
757        let (x, z) = (tool_pose[0], tool_pose[1] + self.sag(tool_pose[0]).0);
758        let geo = self.geo(x, z);
759        let rest = self.belt.static_material(&geo, &[0.0, self.z_weight() / 2.0, 0.0], self.mat0.iter().sum());
760        let at = self.coordinates();
761        let n = at.len();
762        let index = |coordinate: usize| at.iter().position(|&c| c == coordinate);
763        // v v' times `weight`, v given by the (coordinate, factor) of its non-zero entries.
764        let add = |matrix: &mut [f64], v: &[(usize, f64)], weight: f64| {
765            for &(i, a) in v {
766                for &(j, b) in v {
767                    matrix[i * n + j] += weight * a * b;
768                }
769            }
770        };
771        let mass = self.elastic_mass(x, z);
772        let (mut stiffness, mut damping) = (vec![0.0; n * n], vec![0.0; n * n]);
773        // With the lean, sections 1 and 3 change with u by -+ the runs' offset (`lean_offset`).
774        let offset = index(U).map(|u| (u, self.lean_offset(z)));
775        let side = |sign: f64| offset.map(|(u, e)| (u, sign * e));
776        let one: Vec<(usize, f64)> = [(0, 1.0), (1, 1.0)].into_iter().chain(side(-1.0)).collect();
777        let three: Vec<(usize, f64)> = [(0, -1.0), (1, 1.0)].into_iter().chain(side(1.0)).collect();
778        let sections = [one.as_slice(), &[(1, -2.0)], three.as_slice()];
779        for (g, length) in sections.into_iter().zip(rest.iter().copied()) {
780            let k = self.belt.ea / length;
781            add(&mut stiffness, g, k);
782            add(&mut damping, g, self.belt.damping + self.belt.damping_time * k);
783        }
784        if let (Some(f), Some(q)) = (&self.frame, index(Q)) {
785            add(&mut stiffness, &[(q, 1.0)], f.stiffness);
786            add(&mut damping, &[(q, 1.0)], f.damping);
787        }
788        if let (Some(f), Some(u)) = (&self.flex, index(U)) {
789            add(&mut damping, &[(u, 1.0)], f.damping);
790            let [process_x, process_z] = self.process_force();
791            // The lean's own stiffness at height z: its spring, the weight's pendulum stiffness, the belt runs' geometric
792            // stiffness (at the tensions of the pose) and the process force's vertical part on the tip's rise, so that
793            // V = 1/2 k_u(z) u^2 - F_x tip(z) u. At the lean u0 = tip F_x / k_u that the pose's sideways process force
794            // holds: K_uu = k_u, K_uz = k_u' u0 - F_x tip', K_zz = 1/2 k_u'' u0^2 - F_x tip'' u0 (central differences
795            // over 1e-4 m).
796            let tensions: [f64; 3] = std::array::from_fn(|i| self.belt.section(geo[i], rest[i], 0.0, 0.0).tension);
797            let k_u = |z: f64| {
798                let runs = self.lean_runs(z);
799                self.flex_at(z).0 + self.lean_weight_stiffness(z) + (0..3).map(|i| tensions[i] * runs[i]).sum::<f64>()
800                    - 2.0 * process_z * self.rise_coefficients(z)[0]
801            };
802            let (here, ahead, behind, step) = (k_u(z), k_u(z + 1e-4), k_u(z - 1e-4), 1e-4);
803            let (u0, [dtip, ddtip]) = (self.flex_at(z).2 * process_x / here, self.tip_slope(z));
804            let uz = (ahead - behind) / (2.0 * step) * u0 - process_x * dtip;
805            stiffness[u * n + u] += here;
806            stiffness[u * n + 1] += uz;
807            stiffness[n + u] += uz;
808            stiffness[n + 1] += 0.5 * (ahead - 2.0 * here + behind) / (step * step) * u0 * u0 - process_x * ddtip * u0;
809        }
810        if let (Some(w), Some(_)) = (index(W), self.vertical()) {
811            let [k, _, c, dk, _] = self.beam_mode(x);
812            let w0 = self.on_beam_weight() / k;
813            let ddk = (self.beam_mode(x + 1e-4)[3] - self.beam_mode(x - 1e-4)[3]) / 2e-4;
814            add(&mut stiffness, &[(w, 1.0)], k);
815            add(&mut damping, &[(w, 1.0)], c);
816            stiffness[w * n] += dk * w0;
817            stiffness[w] += dk * w0;
818            stiffness[0] += 0.5 * ddk * w0 * w0;
819        }
820        // Only modes the tool moves in, along X by x + q + tip u (`tool_state`) or along Z: one it stands still in is
821        // neither seen nor shaped at the tool (it does at a single height, where tip u cancels x + q).
822        let tip = self.flex_at(z).2;
823        let moves_tool = |v: &[f64]| {
824            let get = |c: usize| index(c).map_or(0.0, |i| v[i]);
825            let largest = v.iter().fold(0.0, |a: f64, b| a.max(b.abs()));
826            (get(X) + get(Q) + tip * get(U)).hypot(get(Z) - get(W)) > 1e-9 * largest
827        };
828        generalised_eigen(&mass, &stiffness, n)
829            .into_iter()
830            .filter(|(w2, v)| *w2 > 0.0 && w2.is_finite() && moves_tool(v))
831            .map(|(w2, v)| {
832                let quadratic = |m: &[f64]| (0..n * n).map(|rc| v[rc / n] * m[rc] * v[rc % n]).sum::<f64>();
833                let w = w2.sqrt();
834                let damping = quadratic(&damping) / (2.0 * w * quadratic(&mass));
835                let mut shape = vec![0.0; self.state_len()];
836                for (c, value) in at.iter().zip(v) {
837                    shape[*c] = value;
838                }
839                (Mode { hz: w / std::f64::consts::TAU, damping }, shape)
840            })
841            .collect()
842    }
843
844    /// How far a point at distance `d` below the carriage rises as the Z axis leans under a sideways force F at its
845    /// centre of mass, `h` below the carriage, per F^2: 1/2 times the integral of theta(s)^2 ds over 0..d (a hanging bar
846    /// turned by theta is shortened by theta^2 / 2 per length). theta(s) / F is the guide's tilt h / tilt plus the
847    /// bending's F (h s - s^2 / 2) / EI up to the load (s' = clamp(s, 0, h)), constant beyond it; the integrand is a
848    /// polynomial of degree 4, which the 3-point Gauss rule integrates exactly.
849    fn lean_rise(&self, d: f64, h: f64) -> f64 {
850        let Some(f) = &self.flex else { return 0.0 };
851        let (a, b, hb) = (h / f.tilt, 1.0 / f.ei, h.max(0.0));
852        let theta = |s: f64| {
853            let s = s.clamp(0.0, hb);
854            a + b * (hb * s - 0.5 * s * s)
855        };
856        let m = d.min(hb);
857        let spread = 0.5 * 0.6_f64.sqrt();
858        let inner: f64 = [(0.5 - spread, 5.0 / 18.0), (0.5, 8.0 / 18.0), (0.5 + spread, 5.0 / 18.0)]
859            .iter()
860            .map(|&(node, weight)| weight * m * theta(node * m).powi(2))
861            .sum();
862        0.5 * (inner + (d - m).max(0.0) * theta(hb).powi(2))
863    }
864
865    /// The weight's geometric stiffness of the lean: the Z axis's weight m_z g at its centre of mass rises by F^2
866    /// `lean_rise` as the spring's force F = k u holds it out, V = m_z g F^2 r = 1/2 c u^2 with c = 2 k^2 m_z g r, the
867    /// Z axis hanging like a pendulum (c > 0 where its centre of mass is below the carriage). 0 without the lean or gravity.
868    fn lean_weight_stiffness(&self, z: f64) -> f64 {
869        let (k, h) = (self.flex_at(z).0, self.z_com_drop - z);
870        2.0 * k * k * self.m_z() * self.g * self.lean_rise(h, h)
871    }
872
873    /// d c / d z of `lean_weight_stiffness`, by central difference (the force on Z of the lean's weight term).
874    fn lean_weight_rise_with_z(&self, z: f64) -> f64 {
875        if self.flex.is_none() || self.g == 0.0 {
876            return 0.0;
877        }
878        let step = 1e-6;
879        (self.lean_weight_stiffness(z + step) - self.lean_weight_stiffness(z - step)) / (2.0 * step)
880    }
881
882    /// The spring that holds the Z axis upright at height z: (stiffness k at the centre of mass, dk/dz,
883    /// tool-tip travel per u). All zero with the effect off.
884    fn flex_at(&self, z: f64) -> (f64, f64, f64) {
885        let Some(f) = &self.flex else { return (0.0, 0.0, 0.0) };
886        let (h, h_tool) = (self.z_com_drop - z, self.z_tool_drop - z);
887        let b = h.max(0.0);
888        let k = 1.0 / (1.0 / f.lateral + h * h / f.tilt + b.powi(3) / (3.0 * f.ei));
889        // The force k u shifts the guide by k u / lateral and tilts it by k u h / tilt, and bends the Z axis.
890        (
891            k,
892            k * k * (2.0 * h / f.tilt + b * b / f.ei),
893            k * (1.0 / f.lateral + h * h_tool / f.tilt + b * b * (3.0 * h_tool - b) / (6.0 * f.ei)),
894        )
895    }
896
897    /// How the tool tip's travel per u (`flex_at`) changes with z: [d tip / dz, d2 tip / dz2] by central differences over
898    /// 1e-4 m. The process force's sideways part works on tip(z) u, so it pushes on Z with F_x tip' u.
899    fn tip_slope(&self, z: f64) -> [f64; 2] {
900        let (step, tip) = (1e-4, |z: f64| self.flex_at(z).2);
901        let (here, ahead, behind) = (tip(z), tip(z + step), tip(z - step));
902        [(ahead - behind) / (2.0 * step), (ahead - 2.0 * here + behind) / (step * step)]
903    }
904
905    /// The weight on the beam under the carriage (N): the carriage, the Z axis with its payload and the belt's share riding
906    /// on it (`belt_on_beam`; since 21 November 2026, 0.29 kg of 11.29 on the default gantry).
907    fn on_beam_weight(&self) -> f64 {
908        (self.m_carriage + self.m_z() + self.belt_on_beam().1) * self.g
909    }
910
911    /// With effects.beam_sag: how far the beam sags under the carriage at x, and its rate of change with x.
912    fn sag(&self, x: f64) -> (f64, f64) {
913        let Some(beam) = &self.beam else { return (0.0, 0.0) };
914        let weight = self.on_beam_weight();
915        let at = |x: f64| weight * sim_components::beam::span_compliance(beam.ei, beam.span, beam.start + x);
916        (at(x), (at(x + 1e-6) - at(x - 1e-6)) / 2e-6)
917    }
918
919    /// With effects.beam_vertical_mode (elastic model): the beam and its mode, whose deflection w is a state.
920    fn vertical(&self) -> Option<(&Beam, &BeamMode)> {
921        let beam = self.beam.as_ref()?;
922        if self.elastic { beam.mode.as_ref().map(|mode| (beam, mode)) } else { None }
923    }
924
925    /// The beam mode at x: (stiffness k, modal mass M, damping c, dk/dx, dM/dx), 0 without the mode.
926    fn beam_mode(&self, x: f64) -> [f64; 5] {
927        let Some((beam, mode)) = self.vertical() else { return [0.0; 5] };
928        let (k, mass) = (beam.stiffness(x), beam.modal_mass(mode.mass_per_m, x));
929        // The key is the mode's damping ratio, the carriage and the Z axis on it.
930        let riding = self.m_carriage + self.m_z() + self.belt_on_beam().0;
931        let damping = 2.0 * mode.damping_ratio * (k * (mass + riding)).sqrt();
932        [k, mass, damping, slope(|x| beam.stiffness(x), x), slope(|x| beam.modal_mass(mode.mass_per_m, x), x)]
933    }
934
935    /// The beam mode's damping loss, W: c w'^2.
936    fn beam_loss(&self, s: &[f64]) -> f64 {
937        self.beam_mode(s[X])[2] * s[V + W].powi(2)
938    }
939
940    /// How far a point at the signed distance `d` below the carriage (above it where negative) is out sideways, per newton
941    /// at the Z axis's centre of mass, `h` below the carriage: the guide's give 1 / lateral, the guide's tilt h d / tilt
942    /// (a rigid bar, above the carriage too) and, below it, the cantilever's bending, (h d^2 / 2 - d^3 / 6) / EI up to the load
943    /// and (h^2 d / 2 - h^3 / 6) / EI beyond (the angle h^2 / (2 EI) stays). At the tool, d = z_tool_drop - z, it is
944    /// `flex_at`'s tip travel per u over k.
945    fn lean_reach(&self, d: f64, h: f64) -> f64 {
946        let Some(f) = &self.flex else { return 0.0 };
947        let b = h.max(0.0);
948        let bend = if d <= 0.0 {
949            0.0
950        } else if d <= b {
951            0.5 * b * d * d - d.powi(3) / 6.0
952        } else {
953            0.5 * b * b * d - b.powi(3) / 6.0
954        };
955        1.0 / f.lateral + h * d / f.tilt + bend / f.ei
956    }
957
958    /// The belt runs' geometric stiffness (`lean_runs`): how much longer the Z axis's vertical runs get as it leans, to second
959    /// order. A run goes from a carriage idler (at the carriage's height, where the guide tilts) to a point of the Z axis at
960    /// the signed distance d below the carriage: the clamp (d = -(s + z), the upper runs of sections 1 and 3) or the bottom
961    /// idler (d = s + sz - z, the two lower runs of section 2). Under the spring's force F = k u that point is out sideways
962    /// by delta = F `lean_reach`(d) and has risen by F^2 `lean_rise`(d) along the Z axis, so the run of length |d| is longer
963    /// by delta^2 / (2 |d|) - sign(d) rise: c = k^2 (reach^2 / |d| - 2 sign(d) lean_rise) per 1/2 u^2. A guide that only
964    /// tilts turns the end about the run's other end and leaves the run as long as it was (reach = h d / tilt, rise =
965    /// (h / tilt)^2 d / 2: c = 0); what is left is the guide's sideways give, 1 / lateral, and the Z axis's bending. The energy
966    /// of the belt (its tension, its force on the lean and on Z, its damping) follows from the lengths. Zero without the
967    /// leaning Z axis.
968    fn lean_runs(&self, z: f64) -> [f64; 3] {
969        if self.flex.is_none() {
970            return [0.0; 3];
971        }
972        let (s, sz) = (self.span_min, self.axes[1].max);
973        let (k, h) = (self.flex_at(z).0, self.z_com_drop - z);
974        let run = |d: f64| k * k * (self.lean_reach(d, h).powi(2) / d.abs() - 2.0 * d.signum() * self.lean_rise(d, h));
975        let upper = run(-(s + z));
976        [upper, 2.0 * run(s + sz - z), upper]
977    }
978
979    /// The belt's upper vertical runs off the Z axis's line (`ToolFlex::belt_offset` e, to either side): the clamp, above
980    /// the carriage where the leaning Z axis is a rigid bar turned by the guide's tilt theta = F h / tilt (F = k u the
981    /// spring's force, h = z_com_drop - z), lifts the right run's end (section 3) by e theta and lowers the left one's
982    /// (section 1): section 3 longer by e theta, section 1 shorter, first order in u. Per u: e k h / tilt (0 with a rigid
983    /// guide or without the lean). The tensions then put the moment (T1 - T3) e theta' on the lean, the energy, modes and
984    /// damping following from the lengths.
985    fn lean_offset(&self, z: f64) -> f64 {
986        let Some(f) = &self.flex else { return 0.0 };
987        f.belt_offset * self.flex_at(z).0 * (self.z_com_drop - z) / f.tilt
988    }
989
990    /// How much longer `lean_runs` and `lean_offset` make the three belt sections at the state's lean u and height z, and
991    /// the rate of that.
992    fn lean_lengths(&self, s: &[f64]) -> ([f64; 3], [f64; 3]) {
993        if self.flex.is_none() {
994            return ([0.0; 3], [0.0; 3]);
995        }
996        let (u, z) = (s[U], s[Z]);
997        let (c, ahead, behind) = (self.lean_runs(z), self.lean_runs(z + 1e-6), self.lean_runs(z - 1e-6));
998        let (e, de) = (self.lean_offset(z), (self.lean_offset(z + 1e-6) - self.lean_offset(z - 1e-6)) / 2e-6);
999        let side = [-1.0, 0.0, 1.0];
1000        let longer = std::array::from_fn(|i| 0.5 * c[i] * u * u + side[i] * e * u);
1001        let rate = std::array::from_fn(|i| {
1002            c[i] * u * s[V + U]
1003                + 0.5 * (ahead[i] - behind[i]) / 2e-6 * s[V + Z] * u * u
1004                + side[i] * (e * s[V + U] + de * s[V + Z] * u)
1005        });
1006        (longer, rate)
1007    }
1008
1009    /// The tool's rise as the Z axis leans: the tip, `z_tool_drop - z` below the carriage, rises by (k u)^2 `lean_rise`
1010    /// (the leaning bar is shortened, the same rise as the weight's `lean_weight_stiffness` has). rho = a(z) u^2:
1011    /// [a, da/dz, d2a/dz2], 0 without the leaning Z axis.
1012    fn rise_coefficients(&self, z: f64) -> [f64; 3] {
1013        if self.flex.is_none() {
1014            return [0.0; 3];
1015        }
1016        let a = |z: f64| {
1017            let k = self.flex_at(z).0;
1018            k * k * self.lean_rise(self.z_tool_drop - z, self.z_com_drop - z)
1019        };
1020        let step = 1e-4;
1021        let (here, ahead, behind) = (a(z), a(z + step), a(z - step));
1022        [here, (ahead - behind) / (2.0 * step), (ahead - 2.0 * here + behind) / (step * step)]
1023    }
1024
1025    /// The Z axis and what hangs from it, as `scene` draws them before the frame sways, and their lean: with
1026    /// effects.tool_flex they turn about the carriage so that the tool moves by its flex travel, `exaggeration` times
1027    /// (`Scene::exaggeration`; deflections are micrometres).
1028    fn hanging(&self, s: &[f64], exaggeration: f64) -> (Vec<Part>, f64) {
1029        let (x, z, span) = (s[0], s[1], self.span_min);
1030        let (y, cx, half) = (-0.05, span + x, 0.03);
1031        let (top, bottom) = (span + z, z - self.axes[1].max - span);
1032        let part = Part::new;
1033        let mut hanging = vec![
1034            part(
1035                "z-axis",
1036                Shape::Box { size: [0.04, 0.03, top - bottom] },
1037                [cx, y, (top + bottom) / 2.0],
1038                [0.78, 0.8, 0.84],
1039            ),
1040            part("clamp", Shape::Box { size: [0.09, 0.035, 0.03] }, [cx, y, top + 0.015], [0.85, 0.3, 0.2]),
1041            // The tool: drawn where `scene_point` says, at the carriage's place on the beam.
1042            part(
1043                "flange",
1044                Shape::Box { size: [0.07, 0.05, 0.02] },
1045                self.scene_point(&[x, z]).unwrap_or_default(),
1046                [0.3, 0.3, 0.33],
1047            ),
1048        ];
1049        if self.payload() > 0.0 {
1050            hanging.push(part(
1051                "payload",
1052                Shape::Box { size: [0.1, 0.1, 0.1] },
1053                [cx, y, bottom - half - 0.072],
1054                [0.2, 0.7, 0.3],
1055            ));
1056        }
1057        sim_core::scene::idler(&mut hanging, [cx, bottom], y, half - 0.002, -2.0 * x / half);
1058        let u = if self.elastic { s[U] } else { 0.0 };
1059        let tool_arm = -self.scene_point(&[x, z]).unwrap_or_default()[2];
1060        let lean = (exaggeration * self.flex_at(z).2 * u / tool_arm.max(0.05)).clamp(-0.5, 0.5).asin();
1061        let (sin, cos) = lean.sin_cos();
1062        for p in &mut hanging {
1063            [p.pos[0], p.pos[2]] =
1064                [cx + (p.pos[0] - cx) * cos - p.pos[2] * sin, (p.pos[0] - cx) * sin + p.pos[2] * cos];
1065            p.angle += lean;
1066        }
1067        (hanging, lean)
1068    }
1069
1070    /// Whether an obstacle's push acts on the elastic model's coordinates themselves (`contact_state`): with the lean,
1071    /// whose parts stand back from the tool's point each by its own lever (the payload 0.06 m below the flange, the Z
1072    /// axis's foot above it), so that no one point is where they touch. On the coordinates the clearance's slopes along
1073    /// each are those of whichever part touches, and so are the generalised forces.
1074    fn pushes_on_coordinates(&self) -> bool {
1075        self.elastic && self.flex.is_some()
1076    }
1077
1078    /// Bearing friction of the idlers as forces opposing (vx, vz): each idler holds back the belt that
1079    /// passes it (see the module comment for the speeds).
1080    fn idler_friction(&self, vx: f64, vz: f64) -> (f64, f64) {
1081        let sign = |v: f64| (v / self.idler_smoothing).tanh();
1082        let (left, right) = (sign(2.0 * vx + vz), sign(2.0 * vx - vz));
1083        (2.0 * self.idler_drag * (left + right + sign(2.0 * vx)), self.idler_drag * (2.0 * sign(vz) + left - right))
1084    }
1085
1086    /// The five idlers' angular momentum about y (positive as x grows, the sense of the pulleys' `spin`), N m s. An idler
1087    /// turns with the belt's speed past it over its radius, signed by which way the belt turns round it along the belt
1088    /// path of the module comment (+ for a right turn seen with the path's heading, the pulleys' sense): the upper left
1089    /// one -vz / r (path down, then left), the lower left -(2 vx + vz) / r (right, then down), the Z-bottom one
1090    /// +2 vx / r (down, round, up), the lower right -(2 vx - vz) / r (up, then right), the upper right +vz / r (left,
1091    /// then up). Their sum is -2 vx / r: with J / r = `idler_spin`, -2 idler_spin vx. (The same rule gives motor pulley A
1092    /// (vx + vz) / r, its angle's rate.) vx is along the beam, relative to the frame.
1093    fn idler_angular(&self, vx: f64) -> f64 {
1094        -2.0 * self.idler_spin * vx
1095    }
1096
1097    /// The belt's runs' angular momentum about y, all of the belt's (the lumps on the pulleys, `j_lump`, are not in their
1098    /// `spin` in `frame_momentum`), for the carriage at `xc` over ground along the beam (the frame swayed by `sway`), the Z axis's point at
1099    /// (xc, z) where the belt's ends
1100    /// are clamped, with the carriage's speed along the beam vx, the Z axis's vz and the frame's sway speed vq. Each run's
1101    /// mass, mu times its length of `belt_mass` (the clamp to an upper idler s + z, an upper idler to its motor pulley
1102    /// s + x and s + sx - x, a motor pulley to a lower idler alike, a lower idler to the bottom idler s + sz - z), at the
1103    /// middle of its straight piece between the wheels (`runs`), moves at its speed of `belt_mass` with the sway's vq
1104    /// along the beam: m (Z Vx - X Vz) each. The wheels stand as `belt_wraps` has them (and the 3D view and the machine
1105    /// file draw them): the motor pulleys at the posts, level with the carriage's idlers' middle, the four carriage idlers
1106    /// 0.03 m + r_i beside the carriage and r + r_i above and below that level, so the runs from them to the pulleys leave
1107    /// level at +-r; the bottom idler 0.08 m under the Z axis's point. That level is the Z axis's at z = 0, the place the
1108    /// frame's momentum takes moments about (the machine file's carriage, its centre of mass `z_com_drop` above it).
1109    fn belt_angular(&self, xc: f64, sway: f64, z: f64, v: [f64; 3]) -> f64 {
1110        let (mu, s, sx, sz) = (self.belt.mass_per_m, self.span_min, self.axes[0].max, self.axes[1].max);
1111        let ([vx, vz, vq], x) = (v, xc - sway);
1112        let (lengths, velocity): ([f64; 8], [[f64; 2]; 8]) = (
1113            [s + z, s + x, s + x, s + sz - z, s + sz - z, s + sx - x, s + sx - x, s + z],
1114            [
1115                [vx, vz],
1116                [vx + vz, 0.0],
1117                [-(vx + vz), 0.0],
1118                [vx, 2.0 * vx + vz],
1119                [vx, -(2.0 * vx - vz)],
1120                [-(vx - vz), 0.0],
1121                [vx - vz, 0.0],
1122                [vx, vz],
1123            ],
1124        );
1125        self.runs(xc, sway, z)
1126            .iter()
1127            .zip(lengths.iter().zip(velocity))
1128            .map(|([a, b], (length, [ux, uz]))| {
1129                let middle = [0.5 * (a[0] + b[0]), 0.5 * (a[1] + b[1])];
1130                mu * length * (middle[1] * (ux + vq) - middle[0] * uz)
1131            })
1132            .sum()
1133    }
1134
1135    /// How far the carriage's idlers stand to its sides, centre from the carriage's x: 0.03 m and their radius, as the 3D
1136    /// view draws them.
1137    fn idler_side(&self) -> f64 {
1138        0.03 + self.idler_radius
1139    }
1140
1141    /// The belt's eight straight runs, each from where it leaves one wheel to where it meets the next, (x, height) over
1142    /// ground along the beam, for the carriage at `xc` with the frame swayed by `sway` and the Z axis's point at height
1143    /// `z` (`belt_angular`), in the order of the belt's path: the clamp to the upper left idler to motor pulley A to the
1144    /// lower left idler to the bottom idler to the lower right idler to motor pulley B to the upper right idler to the
1145    /// clamp. A run touches a wheel where the wheel's centre lies to its left (the belt round it anticlockwise, the
1146    /// pulleys and the bottom idler) or right (clockwise, the carriage idlers): with the run's direction t and l it turned
1147    /// left by 90 degrees, at c - rho l, rho the radius signed by that sense.
1148    fn runs(&self, xc: f64, sway: f64, z: f64) -> [[[f64; 2]; 2]; 8] {
1149        let (r, ri, s, sx) = (self.r, self.idler_radius, self.span_min, self.axes[0].max);
1150        let (side, up) = (self.idler_side(), r + ri);
1151        let wheel = |x: f64, h: f64, rho: f64| ([x, h], rho);
1152        let clamp = wheel(xc, z, 0.0);
1153        let path = [
1154            clamp,
1155            wheel(xc - side, up, -ri),
1156            wheel(sway - s, 0.0, r),
1157            wheel(xc - side, -up, -ri),
1158            wheel(xc, z - 0.08, ri),
1159            wheel(xc + side, -up, -ri),
1160            wheel(sway + s + sx, 0.0, r),
1161            wheel(xc + side, up, -ri),
1162            clamp,
1163        ];
1164        std::array::from_fn(|k| {
1165            let ((ca, ra), (cb, rb)) = (path[k], path[k + 1]);
1166            let d = [cb[0] - ca[0], cb[1] - ca[1]];
1167            let length = d[0].hypot(d[1]);
1168            let e = [d[0] / length, d[1] / length];
1169            let sin = (-(rb - ra) / length).clamp(-1.0, 1.0);
1170            let cos = (1.0 - sin * sin).sqrt();
1171            let t = [cos * e[0] - sin * e[1], cos * e[1] + sin * e[0]];
1172            let left = [-t[1], t[0]];
1173            [[ca[0] - ra * left[0], ca[1] - ra * left[1]], [cb[0] - rb * left[0], cb[1] - rb * left[1]]]
1174        })
1175    }
1176
1177    /// Chain drag opposing vx; it fades out at rest like the guide friction's Stribeck speed.
1178    fn chain_drag(&self, vx: f64) -> f64 {
1179        self.chain.drag(vx, self.friction_x.stribeck_v)
1180    }
1181
1182    fn process_force(&self) -> [f64; 2] {
1183        if self.dwelling { self.process } else { [0.0; 2] }
1184    }
1185
1186    /// Force of the end stops on an axis.
1187    fn stop_force(&self, axis: usize, pos: f64, vel: f64) -> f64 {
1188        self.stops.force(pos, vel, self.axes[axis].max)
1189    }
1190    fn stop_energy(&self, x: f64, z: f64) -> f64 {
1191        self.stops.energy(x, self.axes[0].max) + self.stops.energy(z, self.axes[1].max)
1192    }
1193
1194    /// Geometric length of the three belt sections. Sections 1 and 3 end at one motor pulley, section 2
1195    /// at both; the teeth in mesh there count as more belt (see `Belt::tooth_length`).
1196    fn geo(&self, x: f64, z: f64) -> [f64; 3] {
1197        let (sx, sz, s, teeth) = (self.axes[0].max, self.axes[1].max, self.span_min, self.belt.tooth_length);
1198        [2.0 * s + x + z + teeth, 4.0 * s + sx + 2.0 * sz - 2.0 * z + 2.0 * teeth, 2.0 * s + sx - x + z + teeth]
1199    }
1200
1201    /// Unstretched belt in the three sections for pulley angles a and b.
1202    fn mat(&self, a: f64, b: f64) -> [f64; 3] {
1203        let r = self.r_mat;
1204        [self.mat0[0] + r * a, self.mat0[1] - r * a + r * b, self.mat0[2] - r * b]
1205    }
1206
1207    /// The pulley angles as far as the belt sections see them: each pulley's angle plus the belt's slip over it
1208    /// (effects.belt_tooth_jump) over the radius, and their rates.
1209    fn fed_angles(&self, s: &[f64]) -> ([f64; 2], [f64; 2]) {
1210        let mut out = ([s[A], s[A + 1]], [s[V + A], s[V + A + 1]]);
1211        if self.jump.is_some() {
1212            for k in 0..2 {
1213                out.0[k] += s[JUMP + JUMP_STATES * k] / self.r;
1214                out.1[k] += s[JUMP + JUMP_STATES * k + 1] / self.r;
1215            }
1216        }
1217        out
1218    }
1219
1220    fn sections(&self, s: &[f64]) -> [SectionForce; 3] {
1221        let ([a, b], [va, vb]) = self.fed_angles(s);
1222        let (mut geo, mat, r) = (self.geo(s[X], s[Z]), self.mat(a, b), self.r_mat);
1223        let (vx, vz) = (s[V + X], s[V + Z]);
1224        let (longer, longer_rate) = self.lean_lengths(s);
1225        let mut geo_rate = [vx + vz, -2.0 * vz, vz - vx];
1226        for i in 0..3 {
1227            geo[i] += longer[i];
1228            geo_rate[i] += longer_rate[i];
1229        }
1230        let mat_rate = [r * va, r * (vb - va), -r * vb];
1231        std::array::from_fn(|i| self.belt.section(geo[i], mat[i], geo_rate[i], mat_rate[i]))
1232    }
1233
1234    /// Loads on the X and the Z guide at an X acceleration of the Z axis.
1235    ///
1236    /// The X guide carries the weight and the tilting moment of the overhanging Z axis; the Z guide
1237    /// carries the side force that drags the Z axis along and the same moment.
1238    fn guide_loads(&self, z: f64, ax: f64) -> (f64, f64) {
1239        let side = self.m_z() * ax;
1240        let tilt = 2.0 * side * (self.z_com_drop - z) / self.guide_spacing;
1241        (self.m_x() * self.g + tilt.abs(), side.abs() + tilt.abs())
1242    }
1243
1244    /// Friction level factors for the X and Z guides at an X acceleration of the Z axis.
1245    fn load_scales(&self, z: f64, ax: f64) -> (f64, f64) {
1246        let (load_x, load_z) = self.guide_loads(z, ax);
1247        (
1248            self.friction_x.load_scale(load_x, (self.m_carriage + self.m_z_axis) * self.g),
1249            self.friction_z.load_scale(load_z, 0.0),
1250        )
1251    }
1252
1253    /// The X acceleration that the motor torques would give a loss-free rigid machine at (x, z): what the guide
1254    /// loads are worked out with. Over the rigid model's mass matrix (`rigid_solve` with no losses): the moved masses,
1255    /// idlers, chain, rotors and pulleys, and the belt's runs with their coupling to Z. With the Z axis's weight, as
1256    /// `rigid_solve` has it (M a = F + gravity): through the belt runs' coupling the torque that holds the Z axis up would
1257    /// else accelerate X.
1258    fn commanded_ax(&self, x: f64, z: f64, torque: &[f64]) -> f64 {
1259        let k = self.gearbox.ratio / self.r;
1260        let (fx, fz) = (k * (torque[0] + torque[1]), k * (torque[0] - torque[1]) - self.z_weight());
1261        let (xx, xz) = self.belt_mass(x, z);
1262        let mx = self.m_x() + self.m_motors() + self.m_idlers[0] + self.chain.mass(x).0 + xx;
1263        let mz = self.m_z() + self.m_motors() + self.m_idlers[1];
1264        (fx * mz - xz * fz) / (mx * mz - xz * xz)
1265    }
1266
1267    /// Guide friction forces and friction state rates: (fx, fz, dsx, dsz).
1268    ///
1269    /// The guide load uses the X acceleration that the motor torques would give a loss-free rigid
1270    /// machine. The true acceleration would make friction depend on itself, and its absolute value
1271    /// would turn every belt vibration into extra friction.
1272    fn guide_friction(&self, x: f64, z: f64, v: [f64; 2], sx: f64, sz: f64, torque: &[f64]) -> (f64, f64, f64, f64) {
1273        let ([vx, vz], (scale_x, scale_z)) = (v, self.load_scales(z, self.commanded_ax(x, z, torque)));
1274        let (fx, dsx) = self.friction_x.eval(vx, sx, scale_x);
1275        let (fz, dsz) = self.friction_z.eval(vz, sz, scale_z);
1276        (fx, fz, dsx, dsz)
1277    }
1278
1279    fn elastic_derivatives(&self, s: &[f64], torque: &[f64], out: &mut [f64]) {
1280        let r = self.r;
1281        let sec = self.sections(s);
1282        let fx_belt = sec[2].tension - sec[0].tension;
1283        let fz_belt = 2.0 * sec[1].tension - sec[0].tension - sec[2].tension;
1284        let (ffx, ffz, dsx, dsz) = self.guide_friction(s[X], s[Z], [s[V + X], s[V + Z]], s[S], s[S + 1], torque);
1285        out[..V].copy_from_slice(&s[V..S]);
1286        let (vx, vz) = (s[V + X], s[V + Z]);
1287        let (idler_x, idler_z) = self.idler_friction(vx, vz);
1288        let [process_x, process_z] = self.process_force();
1289        // Belt, guide, idlers, chain and end stop act between the carriage and the beam.
1290        let fx = fx_belt - ffx - idler_x - self.chain_drag(vx) + self.stop_force(0, s[X], vx);
1291        // The chain's mass m(x) grows as the carriage moves: of 1/2 m w^2, d/dt (m w) - m' w^2 / 2 on x and d/dt (m w) on
1292        // the frame's q, which leaves m' w (w / 2 - vx) and -m' vx w on their right sides.
1293        let chain_growth = self.chain.mass(s[X]).1;
1294        let w = vx + s[V + Q];
1295        let (belt_x, belt_z) = self.belt_speed_terms(vx, vz);
1296        let (k, dk_dz, tip) = self.flex_at(s[Z]);
1297        // Lagrange's equations over `coordinates`, M a = F (`elastic_mass`). The process force acts at the tool tip, at
1298        // x + q + tip(z) u: on each of them, and with tip' u on z. The lean's spring acts between the carriage and the Z axis, on u alone; it gets
1299        // stiffer as the Z axis rises, which pushes back on Z: -dV/dz of k u^2 / 2. The idlers add inertia in Z but no
1300        // weight.
1301        //
1302        // The belt runs' geometric stiffness (`lean_runs`) is in the section tensions through the lengths: it holds the lean
1303        // back with sum T_i c_i u and pushes on Z with -1/2 u^2 sum T_i c_i'. The process force's vertical part works on the
1304        // tip's rise rho = a u^2 (`rise_coefficients`): 2 a u on the lean, a' u^2 on Z.
1305        let [rise, d_rise, _] = self.rise_coefficients(s[Z]);
1306        let tensions: [f64; 3] = std::array::from_fn(|i| sec[i].tension);
1307        let (runs, ahead, behind) = (self.lean_runs(s[Z]), self.lean_runs(s[Z] + 1e-6), self.lean_runs(s[Z] - 1e-6));
1308        // The runs' offset (`lean_offset`, sections 3 longer and 1 shorter by e u): (T3 - T1) e on the lean, its change
1309        // with z on Z.
1310        let (offset, offset_dz) =
1311            (self.lean_offset(s[Z]), (self.lean_offset(s[Z] + 1e-6) - self.lean_offset(s[Z] - 1e-6)) / 2e-6);
1312        let on_lean: f64 =
1313            (0..3).map(|i| tensions[i] * runs[i]).sum::<f64>() * s[U] + (tensions[2] - tensions[0]) * offset;
1314        let on_z: f64 = (0..3).map(|i| tensions[i] * (ahead[i] - behind[i]) / 2e-6).sum::<f64>() * 0.5 * s[U] * s[U]
1315            + (tensions[2] - tensions[0]) * offset_dz * s[U];
1316        // The beam mode (`BeamMode`): M(x) w'' + M' x' w' + c w' + k w = W - F_z, W the weight on it (`on_beam_weight`:
1317        // carriage, Z axis and the belt riding on it), and on x the speed term
1318        // 1/2 M' w'^2 less the stiffness's change with x, 1/2 k' w^2.
1319        let [beam_k, _, beam_c, beam_dk, beam_dm] = self.beam_mode(s[X]);
1320        let beam_x = if self.vertical().is_some() {
1321            0.5 * beam_dm * s[V + W].powi(2) - 0.5 * beam_dk * s[W] * s[W]
1322        } else {
1323            0.0
1324        };
1325        let mut force: Stack<f64, MAX_COORDINATES> = Stack::new();
1326        force.push(fx + process_x + chain_growth * w * (0.5 * w - vx) + belt_x + beam_x);
1327        force.push(
1328            fz_belt - on_z - ffz - 0.5 * s[U] * s[U] * (dk_dz + self.lean_weight_rise_with_z(s[Z])) - idler_z
1329                + process_z * (1.0 + d_rise * s[U] * s[U])
1330                + process_x * self.tip_slope(s[Z])[0] * s[U]
1331                + self.stop_force(1, s[Z], vz)
1332                - self.z_weight()
1333                + belt_z,
1334        );
1335        if let Some(f) = &self.frame {
1336            force.push(-f.stiffness * s[Q] - f.damping * s[V + Q] + process_x - chain_growth * vx * w);
1337        }
1338        if let Some(f) = &self.flex {
1339            force.push(
1340                tip * process_x + 2.0 * process_z * rise * s[U]
1341                    - on_lean
1342                    - (k + self.lean_weight_stiffness(s[Z])) * s[U]
1343                    - f.damping * s[V + U],
1344            );
1345        }
1346        if self.vertical().is_some() {
1347            force.push(self.on_beam_weight() - process_z - beam_k * s[W] - beam_c * s[V + W] - beam_dm * vx * s[V + W]);
1348        }
1349        let at = self.coordinates();
1350        // An obstacle's push at the tool (`Machine::set_tool_force`): its virtual power per unit of each coordinate's rate,
1351        // through the tip's place on all of them as `tool_state` has it (lean, sway, rise, the beam's deflection).
1352        if let Some(push) = sim_core::tool_force_on_rates(self, s, &self.push, V..S) {
1353            force.iter_mut().zip(at.iter()).for_each(|(f, c)| *f += push[*c]);
1354        }
1355        // `chain::solve` without its copies: the same elimination on the stack.
1356        let mut mass = self.elastic_mass(s[X], s[Z]);
1357        let mut acc = force;
1358        if !sim_components::chain::solve_in_place(&mut mass, &mut acc) {
1359            acc.iter_mut().for_each(|a| *a = f64::NAN);
1360        }
1361        for c in [Q, U, W] {
1362            (out[c], out[V + c]) = (0.0, 0.0);
1363        }
1364        for (&c, &a) in at.iter().zip(acc.iter()) {
1365            (out[c], out[V + c]) = (s[V + c], a);
1366        }
1367        let belt_torque =
1368            [self.r_mat * (sec[0].material - sec[1].material), self.r_mat * (sec[1].material - sec[2].material)];
1369        for k in 0..2 {
1370            let (theta, w_theta, phi, w_phi) = (s[A + k], s[V + A + k], s[PA + k], s[V + PA + k]);
1371            let gear = self.gears[k].torque(phi, w_phi, theta, w_theta);
1372            let (brake, brake_rate) = self.brake.torque(self.brake_engaged, w_phi, s[BRAKE + k]);
1373            // While its teeth are out of mesh the pulley feels only the ridge it holds the sliding belt back with.
1374            let on_pulley = self
1375                .jump
1376                .as_ref()
1377                .map_or(belt_torque[k], |j| j.pulley_torque(&s[JUMP + JUMP_STATES * k..], belt_torque[k], r));
1378            let j_pulley = self
1379                .jump
1380                .as_ref()
1381                .map_or(self.j_pulley, |j| j.pulley_inertia(&s[JUMP + JUMP_STATES * k..], self.j_pulley, r));
1382            out[V + A + k] = (gear.output + on_pulley + r * self.mesh.force(r * theta)) / j_pulley;
1383            if let Some(jump) = &self.jump {
1384                let at = JUMP + JUMP_STATES * k;
1385                jump.rates(&s[at..], belt_torque[k] / r, r * out[V + A + k], &mut out[at..]);
1386            }
1387            out[V + PA + k] =
1388                (self.ripple.apply(torque[k], phi) - gear.rotor - self.shaft[k].torque(w_phi) - brake) / self.j_rotor;
1389            out[BRAKE + k] = brake_rate;
1390        }
1391        out[S] = dsx;
1392        out[S + 1] = dsz;
1393        out[SLACK] = if sec.iter().any(|f| f.tension <= 0.0) { 1.0 } else { 0.0 };
1394    }
1395
1396    /// Rigid model: accelerations, guide friction forces, friction state rates, the torques at the two
1397    /// gearbox outputs and the torques that go into them before their losses,
1398    /// [ax, az, ffx, ffz, dsx, dsz, gear a, gear b, into gear a, into gear b].
1399    ///
1400    /// The gearbox loses torque only on what it transmits, which is the motor torque minus what
1401    /// accelerates the rotor itself. That depends on the acceleration being solved for: the loss factors are taken at
1402    /// their fixed point (`mech::settled_loss`).
1403    fn rigid_solve(&self, s: &[f64], torque: &[f64]) -> [f64; 10] {
1404        let (r, ratio) = (self.r, self.gearbox.ratio);
1405        let (mut pos, mut vel) = ([0.0; 2], [0.0; 2]);
1406        self.inverse(&s[0..2], &mut pos);
1407        self.inverse(&s[2..4], &mut vel);
1408        // Belt force each motor would give with a loss-free gearbox and a massless rotor; a brake holds the rotor.
1409        let brake: [f64; 2] =
1410            std::array::from_fn(|k| self.brake.torque(self.brake_engaged, vel[k], s[RIGID_BRAKE + k]).0);
1411        let drive: [f64; 2] = std::array::from_fn(|k| {
1412            ratio * (self.ripple.apply(torque[k], pos[k]) - self.shaft[k].torque(vel[k]) - brake[k]) / r
1413        });
1414        let mesh: [f64; 2] = std::array::from_fn(|k| self.mesh.force(r * pos[k] / ratio));
1415        let rotor = ratio * ratio * self.j_rotor / (r * r);
1416        let pulleys = 2.0 * self.j_pulley / (r * r);
1417        let (chain_mass, chain_growth) = self.chain.mass(s[0]);
1418        let (belt_xx, belt_xz) = self.belt_mass(s[0], s[1]);
1419        let (mx, mz) =
1420            (self.m_x() + pulleys + self.m_idlers[0] + chain_mass + belt_xx, self.m_z() + pulleys + self.m_idlers[1]);
1421        let (belt_x, belt_z) = self.belt_speed_terms(s[2], s[3]);
1422        let (ffx, ffz, dsx, dsz) = self.guide_friction(s[0], s[1], [s[2], s[3]], s[4], s[5], torque);
1423        // Idlers, chain, process and end stops; the growing chain takes m' vx^2 / 2 (see the elastic model).
1424        let (idler_x, idler_z) = self.idler_friction(s[2], s[3]);
1425        let [process_x, process_z] = self.process_force();
1426        let extra_x = process_x + self.push[0] + self.stop_force(0, s[0], s[2])
1427            - idler_x
1428            - self.chain_drag(s[2])
1429            - 0.5 * chain_growth * s[2] * s[2];
1430        let extra_z = process_z + self.push[1] + self.stop_force(1, s[1], s[3]) - idler_z;
1431        // One pass with the loss factors `loss`: the solution, and the factors of the torques it puts into the gearboxes.
1432        let pass = |loss: &[f64; 2]| -> ([f64; 10], [f64; 2]) {
1433            let bx = loss[0] * drive[0] + loss[1] * drive[1] + mesh[0] + mesh[1] - ffx + extra_x + belt_x;
1434            let bz =
1435                loss[0] * drive[0] - loss[1] * drive[1] + mesh[0] - mesh[1] - ffz - self.z_weight() + extra_z + belt_z;
1436            // (mx + p) ax + q az = bx,  q ax + (mz + p) az = bz
1437            let (p, q) = (rotor * (loss[0] + loss[1]), rotor * (loss[0] - loss[1]) + belt_xz);
1438            let det = (mx + p) * (mz + p) - q * q;
1439            let (ax, az) = ((bx * (mz + p) - q * bz) / det, ((mx + p) * bz - q * bx) / det);
1440            let through_gear = [drive[0] - rotor * (ax + az), drive[1] - rotor * (ax - az)];
1441            // The gearbox outputs carry what the rotors' own acceleration and the losses of this pass leave.
1442            let out = [
1443                ax,
1444                az,
1445                ffx,
1446                ffz,
1447                dsx,
1448                dsz,
1449                loss[0] * through_gear[0] * r,
1450                loss[1] * through_gear[1] * r,
1451                through_gear[0] * r,
1452                through_gear[1] * r,
1453            ];
1454            (out, std::array::from_fn(|k| self.gears[k].loss_factor(through_gear[k] * r, vel[k] / ratio)))
1455        };
1456        // The loss factors at their fixed point (`mech::settled_loss`); three passes left up to 1.5e-4 of the acceleration
1457        // on the shipped configs' rigid model.
1458        pass(&sim_components::mech::settled_loss([1.0; 2], |loss| pass(loss).1)).0
1459    }
1460
1461    fn rigid_derivatives(&self, s: &[f64], torque: &[f64], out: &mut [f64]) {
1462        let [ax, az, _, _, dsx, dsz, ..] = self.rigid_solve(s, torque);
1463        let (mut vel, mut brake) = ([0.0; 2], [0.0; 2]);
1464        self.inverse(&s[2..4], &mut vel);
1465        for k in 0..2 {
1466            brake[k] = self.brake.torque(self.brake_engaged, vel[k], s[RIGID_BRAKE + k]).1;
1467        }
1468        out.copy_from_slice(&[s[2], s[3], ax, az, dsx, dsz, brake[0], brake[1]]);
1469    }
1470
1471    /// Kinetic, potential and elastic energy (see `ENERGY_PARTS`).
1472    fn energy_parts(&self, s: &[f64]) -> [f64; 3] {
1473        let potential = self.z_weight() * s[Z];
1474        if !self.elastic {
1475            let (belt_xx, belt_xz) = self.belt_mass(s[0], s[1]);
1476            let kinetic = 0.5
1477                * (self.m_x() + self.m_motors() + self.m_idlers[0] + self.chain.mass(s[0]).0 + belt_xx)
1478                * s[2]
1479                * s[2]
1480                + 0.5 * (self.m_z() + self.m_motors() + self.m_idlers[1]) * s[3] * s[3]
1481                + belt_xz * s[2] * s[3];
1482            return [kinetic, potential, self.stop_energy(s[0], s[1])];
1483        }
1484        let ([a, b], _) = self.fed_angles(s);
1485        let (geo, mat, longer) = (self.geo(s[X], s[Z]), self.mat(a, b), self.lean_lengths(s).0);
1486        let belt: f64 = (0..3).map(|i| self.belt.energy(geo[i] + longer[i], mat[i])).sum();
1487        let gears: f64 = (0..2).map(|k| self.gears[k].energy(s[PA + k], s[A + k])).sum();
1488        let slip = self
1489            .jump
1490            .as_ref()
1491            .map_or(0.0, |j| (0..2).map(|k| j.slip_energy(&s[JUMP + JUMP_STATES * k..], self.r * s[V + A + k])).sum());
1492        let turning: f64 = slip
1493            + (0..2)
1494                .map(|k| 0.5 * self.j_pulley * s[V + A + k].powi(2) + 0.5 * self.j_rotor * s[V + PA + k].powi(2))
1495                .sum::<f64>();
1496        let frame = self.frame.as_ref().map_or(0.0, |f| 0.5 * f.stiffness * s[Q].powi(2));
1497        let at = self.coordinates();
1498        let mut speeds: Stack<f64, MAX_COORDINATES> = Stack::new();
1499        at.iter().for_each(|&c| speeds.push(s[V + c]));
1500        let mass = self.elastic_mass(s[X], s[Z]);
1501        let n = speeds.len();
1502        let kinetic = 0.5 * (0..n * n).map(|rc| speeds[rc / n] * mass[rc] * speeds[rc % n]).sum::<f64>() + turning;
1503        let mut potential = potential + 0.5 * self.lean_weight_stiffness(s[Z]) * s[U] * s[U];
1504        let mut elastic =
1505            0.5 * self.flex_at(s[Z]).0 * s[U] * s[U] + self.stop_energy(s[X], s[Z]) + belt + gears + frame;
1506        if let Some((beam, mode)) = self.vertical() {
1507            // The Z axis's weight at z - w, the carriage's at -w, the beam's own at -phi w (its first moment, -p0 w,
1508            // `frame_momentum`); the beam's spring, which holds the stress of the beam's own sag: its cross term with
1509            // the mode is +g p0 w by virtual work (EI u'''' = mu g), so the beam's weight does no work on w in all.
1510            let own = self.g * beam.shape_moments(mode.mass_per_m, s[X])[0] * s[W];
1511            potential -= self.on_beam_weight() * s[W] + own;
1512            elastic += 0.5 * self.beam_mode(s[X])[0] * s[W] * s[W] + own;
1513        }
1514        [kinetic, potential, elastic]
1515    }
1516
1517    /// The loss powers in the order of `effect_infos`, and per motor the gearbox loss as a torque at the rotor and the
1518    /// brake torque, which the torque breakdown takes too. No derivatives: cheap enough for every step.
1519    fn losses(&self, s: &[f64], torque: &[f64]) -> ([f64; 13], [f64; 2], [f64; 2]) {
1520        let (r, ratio) = (self.r, self.gearbox.ratio);
1521        let v = if self.elastic { V } else { 2 };
1522        let (z, vx, vz) = (s[Z], s[v + X], s[v + Z]);
1523        let (sx, sz) = if self.elastic { (s[S], s[S + 1]) } else { (s[4], s[5]) };
1524        let (ffx, ffz, ..) = self.guide_friction(s[X], z, [vx, vz], sx, sz, torque);
1525        let (idler_x, idler_z) = self.idler_friction(vx, vz);
1526        let drag = self.chain_drag(vx);
1527        let [process_x, process_z] = self.process_force();
1528        let (mut angle, mut speed) = ([0.0; 2], [0.0; 2]);
1529        self.motor_state(s, &mut angle, &mut speed);
1530        // Per motor: gearbox loss as a torque at the rotor and as a power, brake torque, and the power the tooth
1531        // meshing puts in; the damping losses.
1532        let (mut gear_loss, mut gear_power, mut brake, mut mesh_in) = ([0.0; 2], [0.0; 2], [0.0; 2], 0.0);
1533        let (process_in, damping) = if self.elastic {
1534            for k in 0..2 {
1535                let (theta, w_theta, phi, w_phi) = (s[A + k], s[V + A + k], s[PA + k], s[V + PA + k]);
1536                let gear = self.gears[k].torque(phi, w_phi, theta, w_theta);
1537                gear_loss[k] = gear.rotor - gear.output / ratio;
1538                gear_power[k] = self.gears[k].loss_power(phi, w_phi, theta, w_theta);
1539                brake[k] = self.brake.torque(self.brake_engaged, w_phi, s[BRAKE + k]).0;
1540                mesh_in += r * self.mesh.force(r * theta) * w_theta;
1541            }
1542            // The rates of `sections`.
1543            let ([a, b], [va, vb]) = self.fed_angles(s);
1544            let (rm, (mut geo, mat)) = (self.r_mat, (self.geo(s[X], z), self.mat(a, b)));
1545            let (mut geo_rate, mat_rate) = ([vx + vz, -2.0 * vz, vz - vx], [rm * va, rm * (vb - va), -rm * vb]);
1546            let (longer, longer_rate) = self.lean_lengths(s);
1547            for i in 0..3 {
1548                geo[i] += longer[i];
1549                geo_rate[i] += longer_rate[i];
1550            }
1551            let belt: f64 = (0..3).map(|i| self.belt.loss_power(geo[i], mat[i], geo_rate[i], mat_rate[i])).sum();
1552            let frame = self.frame.as_ref().map_or(0.0, |f| f.damping * s[V + Q].powi(2));
1553            let flex = self.flex.as_ref().map_or(0.0, |f| f.damping * s[V + U].powi(2));
1554            // The tool's velocity (`tool_state`): along X with the sway and the lean, along Z with the beam's deflection
1555            // and the leaning tip's rise.
1556            let tool_vx = vx + s[V + Q] + self.flex_at(z).2 * s[V + U] + self.tip_slope(z)[0] * s[U] * vz;
1557            let [rise, d_rise, _] = self.rise_coefficients(z);
1558            let tool_vz = vz + 2.0 * rise * s[U] * s[V + U] + d_rise * s[U] * s[U] * vz
1559                - if self.vertical().is_some() { s[V + W] } else { 0.0 };
1560            (process_x * tool_vx + process_z * tool_vz, [belt, frame, flex])
1561        } else {
1562            let solved = self.rigid_solve(s, torque);
1563            for k in 0..2 {
1564                let sign = [1.0, -1.0][k];
1565                brake[k] = self.brake.torque(self.brake_engaged, speed[k], s[RIGID_BRAKE + k]).0;
1566                gear_loss[k] = (solved[8 + k] - solved[6 + k]) / ratio;
1567                gear_power[k] = gear_loss[k] * speed[k];
1568                mesh_in += self.mesh.force(r * angle[k] / ratio) * (vx + sign * vz);
1569            }
1570            (process_x * vx + process_z * vz, [0.0; 3])
1571        };
1572        // The gearboxes' drag acts on the rotors but is the gearboxes' loss.
1573        let gear_drag: [f64; 2] = std::array::from_fn(|k| self.shaft[k].drag_power(speed[k]));
1574        let shaft: [f64; 2] =
1575            std::array::from_fn(|k| (self.shaft[k].torque(speed[k]) + brake[k]) * speed[k] - gear_drag[k]);
1576        let ripple: f64 = (0..2).map(|k| (torque[k] - self.ripple.apply(torque[k], angle[k])) * speed[k]).sum();
1577        let stops = self.stops.loss_power(s[X], vx, self.axes[0].max) + self.stops.loss_power(z, vz, self.axes[1].max);
1578        let [belt, frame, flex] = damping;
1579        let powers = [
1580            ffx * vx,
1581            ffz * vz,
1582            idler_x * vx + idler_z * vz,
1583            drag * vx,
1584            shaft[0],
1585            shaft[1],
1586            gear_power[0] + gear_drag[0],
1587            gear_power[1] + gear_drag[1],
1588            belt,
1589            frame,
1590            flex,
1591            stops,
1592            ripple - mesh_in - process_in,
1593        ];
1594        (powers, gear_loss, brake)
1595    }
1596
1597    /// The signals of the effect views, in the order of `effect_infos`: per motor the parts of its torque, the
1598    /// loss powers, the energy parts and per guide its friction split.
1599    ///
1600    /// Torque parts. Per motor k = A, B with s_k = +1, -1 and the rigid model's transpose k_r = r / (2 i):
1601    /// inertia = k_r (I_x + s_k I_z), with I what accelerates every moved mass at its own acceleration (carriage,
1602    /// leaning Z axis, idlers, chain with what picking it up costs) and both rotors and pulleys at the acceleration
1603    /// of the carriage along the beam and of the Z axis, as a rigid machine would turn them;
1604    /// gravity = s_k k_r W_z (`z_weight`);
1605    /// friction = shaft friction + brake + gearbox loss at the rotor + k_r (F_x + s_k F_z), F the guide, idler and
1606    /// chain drag forces; rest = motor torque less these. So rotors and pulleys ringing against the load on the belt
1607    /// and in the gearbox backlash are in the rest.
1608    fn view_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
1609        let kr = self.r / (2.0 * self.gearbox.ratio);
1610        let v = if self.elastic { V } else { 2 };
1611        let (z, vx, vz) = (s[Z], s[v + X], s[v + Z]);
1612        let (sx, sz) = if self.elastic { (s[S], s[S + 1]) } else { (s[4], s[5]) };
1613        let (scales, (ffx, ffz, ..)) = (
1614            self.load_scales(z, self.commanded_ax(s[X], z, torque)),
1615            self.guide_friction(s[X], z, [vx, vz], sx, sz, torque),
1616        );
1617        let (idler_x, idler_z) = self.idler_friction(vx, vz);
1618        let drag = self.chain_drag(vx);
1619        let (chain_mass, chain_growth) = self.chain.mass(s[X]);
1620        let (mut angle, mut speed) = ([0.0; 2], [0.0; 2]);
1621        self.motor_state(s, &mut angle, &mut speed);
1622        let (powers, gear_loss, brake) = self.losses(s, torque);
1623        // The inertia forces in X and Z.
1624        let (motors, idlers) = (self.m_motors(), self.m_idlers);
1625        let inertia = if self.elastic {
1626            let mut d = [0.0; N_ELASTIC + 2 * JUMP_STATES];
1627            self.elastic_derivatives(s, torque, &mut d[..self.state_len()]);
1628            // The X and the Z rows of M a (`elastic_mass`), the rotors and pulleys at ax and az, less the speed terms.
1629            let (at, mass) = (self.coordinates(), self.elastic_mass(s[X], z));
1630            let row = |i: usize| at.iter().enumerate().map(|(j, &c)| mass[i * at.len() + j] * d[V + c]).sum::<f64>();
1631            let w = vx + s[V + Q];
1632            let (belt_x, belt_z) = self.belt_speed_terms(vx, vz);
1633            [
1634                row(0) + motors * d[V + X] + chain_growth * w * (vx - 0.5 * w) - belt_x,
1635                row(1) + motors * d[V + Z] - belt_z,
1636            ]
1637        } else {
1638            let solved = self.rigid_solve(s, torque);
1639            let (belt_xx, belt_xz) = self.belt_mass(s[X], z);
1640            let (belt_x, belt_z) = self.belt_speed_terms(vx, vz);
1641            let inertia_x = (self.m_x() + motors + idlers[0] + chain_mass + belt_xx) * solved[0]
1642                + belt_xz * solved[1]
1643                + 0.5 * chain_growth * vx * vx
1644                - belt_x;
1645            [inertia_x, (self.m_z() + motors + idlers[1]) * solved[1] + belt_xz * solved[0] - belt_z]
1646        };
1647        let friction = [ffx + idler_x + drag, ffz + idler_z];
1648        for k in 0..2 {
1649            let sign = [1.0, -1.0][k];
1650            let parts = [
1651                kr * (inertia[0] + sign * inertia[1]),
1652                sign * kr * self.z_weight(),
1653                self.shaft[k].torque(speed[k]) + brake[k] + gear_loss[k] + kr * (friction[0] + sign * friction[1]),
1654            ];
1655            out.extend(parts);
1656            out.push(torque[k] - parts.iter().sum::<f64>());
1657        }
1658        out.extend(powers);
1659        if self.jump.is_some() {
1660            out.push(self.jump_loss);
1661        }
1662        if self.vertical().is_some() {
1663            out.push(self.beam_loss(s));
1664        }
1665        out.extend(self.energy_parts(s));
1666        for (friction, v, state, scale) in [(&self.friction_x, vx, sx, scales.0), (&self.friction_z, vz, sz, scales.1)]
1667        {
1668            out.push(v);
1669            out.extend(friction.split(v, state, scale));
1670            out.push(scale);
1671        }
1672        // Stretch per belt section: its length less its unstretched belt; in the rigid model that of pretension.
1673        let geo = self.geo(s[X], z);
1674        let mat = if self.elastic {
1675            let ([a, b], _) = self.fed_angles(s);
1676            self.mat(a, b)
1677        } else {
1678            geo.map(|g| self.belt.rest_length(g))
1679        };
1680        out.extend((0..3).map(|i| geo[i] - mat[i]));
1681    }
1682
1683    /// The first-mode frequency of each free belt span (`span_frequency`) and how far the nearest of them is from what
1684    /// the two drives excite (`span_detuning`). The spans run between the clamps, the idlers and the motor pulleys, in
1685    /// the order of the belt from the left clamp: 1 and 2 are section 1, 3 to 6 section 2, 7 and 8 section 3; their
1686    /// lengths are those of `geo` without the teeth in mesh.
1687    fn span_signals(&self, s: &[f64], mass: f64, out: &mut Vec<f64>) {
1688        let (x, z, sx, sz, span) = (s[X], s[Z], self.axes[0].max, self.axes[1].max, self.span_min);
1689        let t = if self.elastic { self.sections(s).map(|f| f.tension) } else { [self.belt.pretension; 3] };
1690        let (down, left, right) = (span + sz - z, span + x, span + sx - x);
1691        let spans = [
1692            (span + z, t[0]),
1693            (left, t[0]),
1694            (left, t[1]),
1695            (down, t[1]),
1696            (down, t[1]),
1697            (right, t[1]),
1698            (right, t[2]),
1699            (span + z, t[2]),
1700        ];
1701        let (mut angle, mut speed) = ([0.0; 2], [0.0; 2]);
1702        self.motor_state(s, &mut angle, &mut speed);
1703        let mut excitations = Vec::with_capacity(6);
1704        for k in 0..2 {
1705            let pulley = if self.elastic { s[V + A + k] } else { speed[k] / self.gearbox.ratio };
1706            drive_excitations(self.mesh.pitch, self.r * pulley, &self.ripple, speed[k], &mut excitations);
1707        }
1708        let frequencies = spans.map(|(length, tension)| span_frequency(length, tension, mass));
1709        out.extend(frequencies);
1710        out.push(frequencies.iter().map(|f| span_detuning(*f, &excitations)).fold(1.0, f64::min));
1711    }
1712
1713    /// The signal list of `effect_signals`.
1714    fn effect_infos(&self, out: &mut Vec<SignalInfo>) {
1715        for motor in &self.motors {
1716            out.extend(TORQUE_PARTS.map(|part| {
1717                SignalInfo::new(
1718                    format!("motor.{}.torque_{part}", motor.id),
1719                    motor.key,
1720                    &format!("quantity-torque-{part}"),
1721                    "N m",
1722                )
1723            }));
1724        }
1725        let friction = "quantity-friction-power";
1726        let mut powers = vec![
1727            ("guide_x", "axis-x", friction),
1728            ("guide_z", "axis-z", friction),
1729            ("idlers", "group-idler", friction),
1730            ("cable_chain", "group-cable_chain", friction),
1731        ];
1732        powers.extend([
1733            ("shaft_a", "motor-a", "quantity-shaft-friction-power"),
1734            ("shaft_b", "motor-b", "quantity-shaft-friction-power"),
1735        ]);
1736        let gear =
1737            if self.gearbox.is_coupling() { "quantity-coupling-loss-power" } else { "quantity-gearbox-loss-power" };
1738        powers.extend([("gearbox_a", "motor-a", gear), ("gearbox_b", "motor-b", gear)]);
1739        let damping = "quantity-damping-power";
1740        powers.extend([
1741            ("belt", "group-belt", damping),
1742            ("frame", "frame", damping),
1743            ("tool_flex", "group-tool_flex", damping),
1744            ("hard_stops", "group-hard_stop", damping),
1745        ]);
1746        powers.push(("other", "loss-other", "quantity-power-given-off"));
1747        if self.jump.is_some() {
1748            powers.push(("tooth_jump", "group-belt", "quantity-tooth-jump-power"));
1749        }
1750        if self.vertical().is_some() {
1751            powers.push(("beam", "group-beam", damping));
1752        }
1753        out.extend(
1754            powers
1755                .into_iter()
1756                .map(|(id, owner, quantity)| SignalInfo::new(format!("{LOSS_PREFIX}{id}"), owner, quantity, "W")),
1757        );
1758        out.extend(ENERGY_PARTS.map(|part| {
1759            SignalInfo::new(format!("energy.{part}"), "group-energy", &format!("quantity-energy-{part}"), "J")
1760        }));
1761        for contact in self.friction_contacts() {
1762            for part in FRICTION_SIGNALS {
1763                let unit = match part {
1764                    "speed" => "m/s",
1765                    "load_scale" => "",
1766                    _ => "N",
1767                };
1768                out.push(SignalInfo::new(
1769                    format!("{}.friction_{part}", contact.id),
1770                    contact.owner_key,
1771                    &format!("quantity-friction-{}", part.replace('_', "-")),
1772                    unit,
1773                ));
1774            }
1775        }
1776        out.extend(
1777            self.belt_sections()
1778                .iter()
1779                .map(|b| SignalInfo::new(format!("{}.stretch", b.id), b.owner_key, "quantity-section-stretch", "m")),
1780        );
1781    }
1782}
1783
1784impl Machine for TGantry {
1785    /// In the tool's frame (x along the beam, z up, the carriage at the height z_com_drop): the carriage with the
1786    /// chain's moving run at x + q, the Z axis's centre of mass at x + q + u and z, the portal's own frame mass with
1787    /// effects.frame_compliance at its sway q, and the pulleys and rotors turning about y, positive as x grows.
1788    /// The idlers' spin (`idler_angular`) and the belt's runs' angular momentum (`belt_angular`) are in the angular
1789    /// momentum; the frame's own mass stands still but for its sway q, so its first moment is `frame` q (its place at rest
1790    /// is constant, which the base's load against the start pose cancels).
1791    fn frame_momentum(&self, s: &[f64]) -> Option<sim_core::FrameMomentum> {
1792        let cross = |r: [f64; 3], p: [f64; 3]| {
1793            [r[1] * p[2] - r[2] * p[1], r[2] * p[0] - r[0] * p[2], r[0] * p[1] - r[1] * p[0]]
1794        };
1795        let (r, ratio) = (self.r, self.gearbox.ratio);
1796        let (x, z, vx, vz, q, vq, u, vu, spin) = if self.elastic {
1797            let spin =
1798                (self.j_pulley - self.j_lump) * (s[V + A] + s[V + A + 1]) + self.j_rotor * (s[V + PA] + s[V + PA + 1]);
1799            (s[X], s[Z], s[V + X], s[V + Z], s[Q], s[V + Q], s[U], s[V + U], spin)
1800        } else {
1801            let pulleys = 2.0 * s[2] / r;
1802            (s[0], s[1], s[2], s[3], 0.0, 0.0, 0.0, 0.0, (self.j_pulley - self.j_lump + ratio * self.j_rotor) * pulleys)
1803        };
1804        // With effects.beam_vertical_mode the carriage hangs w lower and the Z axis with it (z is relative to the
1805        // carriage).
1806        let (w, vw) = if self.vertical().is_some() { (s[W], s[V + W]) } else { (0.0, 0.0) };
1807        // The beam's own mass moves with its mode too: its point s from the left post, at s - start + q along the beam
1808        // and at the carriage's height, by -phi(s; x) w, at -(phi w' + phi_x x' w) (`Beam::shape_moments`, the x-rates by
1809        // central differences): vertical momentum -(p0 w' + p0' x' w), about y (p1 + (q - start) p0) w' and the same
1810        // of the x-rates times x' w; first moment -p0 w.
1811        let (beam_vertical, beam_angular, beam_moment) = match self.vertical() {
1812            Some((beam, mode)) => {
1813                let moments = |x: f64| beam.shape_moments(mode.mass_per_m, x);
1814                let ([p0, p1], arm) = (moments(x), q - beam.start);
1815                let (dp0, dp1) = (slope(|x| moments(x)[0], x), slope(|x| moments(x)[1], x));
1816                (-(p0 * vw + dp0 * vx * w), (p1 + arm * p0) * vw + (dp1 + arm * dp0) * vx * w, -p0 * w)
1817            }
1818            None => (0.0, 0.0, 0.0),
1819        };
1820        let chain = self.chain.mass(x).0;
1821        let chain_moment = self.chain.mass_per_m * (self.chain.length0 * x + 0.25 * x * x);
1822        let (m_carriage, m_z) = (self.m_carriage + chain, self.m_z());
1823        let frame = self.frame.as_ref().map_or(0.0, |f| f.mass);
1824        // The chain lies on the beam and does not ride on the beam's mode (it is not on w in `elastic_mass`).
1825        let carriage = ([x + q, 0.0, self.z_com_drop - w], [m_carriage * (vx + vq), 0.0, -self.m_carriage * vw]);
1826        let z_axis = ([x + q + u, 0.0, z - w], [m_z * (vx + vq + vu), 0.0, m_z * (vz - vw)]);
1827        let (lc, lz) = (cross(carriage.0, carriage.1), cross(z_axis.0, z_axis.1));
1828        let process = self.process_force();
1829        let mut tool = [0.0; 2];
1830        self.tool_state(s, &mut tool, &mut [0.0; 2]);
1831        // The belt (`belt_mass`'s runs): its horizontal runs' momenta cancel, its vertical ones, (4 s + 2 sz) long, move at
1832        // (vx, vz) with the carriage and the Z axis, and all of it sways with the frame (`belt_sway`); its first moment
1833        // moves with x and z alike, mu (4 s + 2 sz) (x, z), and with the frame.
1834        let (belt_cross, belt) = self.belt_sway();
1835        // With the beam's mode the belt rides on w (`belt_on_beam`): the vertical runs at the carriage's x, down by w,
1836        // their momentum -cross w'; the horizontal ones tilt, a point at the share xi of the way from its post's pulley
1837        // (motor A at q - s, motor B at q + s + sx) to the carriage's idler (at xc -/+ d, `idler_side`) going down by xi w:
1838        // momentum -flat w' / 2, about y mu w' (len_A (x_A / 6 + (xc - d) / 3) + len_B (x_B / 6 + (xc + d) / 3)). Lowered, the runs' momenta along X (the vertical
1839        // runs' cross (vx + vq), the horizontal ones' sway flat vq) are w lower (the horizontal ones w / 2 on average).
1840        let (_, riding) = self.belt_on_beam();
1841        let belt_beam_angular = if self.vertical().is_some() {
1842            let (mu, s, sx, xc, d) = (self.belt.mass_per_m, self.span_min, self.axes[0].max, x + q, self.idler_side());
1843            let flat = mu * (4.0 * s + 2.0 * sx);
1844            let tilting = mu
1845                * vw
1846                * (2.0 * (s + x) * ((q - s) / 6.0 + (xc - d) / 3.0)
1847                    + 2.0 * (s + sx - x) * ((q + s + sx) / 6.0 + (xc + d) / 3.0));
1848            belt_cross * xc * vw + tilting - w * belt_cross * (vx + vq) - 0.5 * w * flat * vq
1849        } else {
1850            0.0
1851        };
1852        Some(sim_core::FrameMomentum {
1853            linear: [
1854                carriage.1[0] + z_axis.1[0] + frame * vq + belt_cross * vx + belt * vq,
1855                0.0,
1856                carriage.1[2] + z_axis.1[2] + belt_cross * vz + beam_vertical - riding * vw,
1857            ],
1858            angular: [
1859                0.0,
1860                lc[1]
1861                    + chain * (vx + vq) * w
1862                    + lz[1]
1863                    + spin
1864                    + self.idler_angular(vx)
1865                    + self.belt_angular(x + q, q, z, [vx, vz, vq])
1866                    + beam_angular
1867                    + belt_beam_angular,
1868                0.0,
1869            ],
1870            mass: m_carriage + m_z + belt,
1871            // The chain's moving run as on the one-axis machine: mu (L0 x + x^2 / 4), whose rate is its mass times vx.
1872            first_moment: [
1873                self.m_carriage * (x + q)
1874                    + chain * q
1875                    + chain_moment
1876                    + m_z * (x + q + u)
1877                    + frame * q
1878                    + belt_cross * x
1879                    + belt * q,
1880                0.0,
1881                m_carriage * self.z_com_drop - self.m_carriage * w + m_z * (z - w) + belt_cross * z + beam_moment
1882                    - riding * w,
1883            ],
1884            gravity: [0.0, 0.0, -self.g],
1885            // An obstacle's push is not in it: a compliant base takes it through the tool's shift (`base::Based`).
1886            external: [process[0], 0.0, process[1]],
1887            // The tool tip, z_tool_drop below the carriage where the Z axis's centre of mass (at z here) is z_com_drop below it.
1888            external_at: [tool[0], 0.0, tool[1] - (self.z_tool_drop - self.z_com_drop)],
1889        })
1890    }
1891    fn axes(&self) -> &[AxisInfo] {
1892        &self.axes
1893    }
1894    fn motors(&self) -> &[MotorInfo] {
1895        &self.motors
1896    }
1897
1898    fn inverse(&self, tool: &[f64], motors: &mut [f64]) {
1899        let k = self.gearbox.ratio / self.r;
1900        motors[0] = k * (tool[0] + tool[1]);
1901        motors[1] = k * (tool[0] - tool[1]);
1902    }
1903    fn forward(&self, motors: &[f64], tool: &mut [f64]) {
1904        let k = self.r / (2.0 * self.gearbox.ratio);
1905        tool[0] = k * (motors[0] + motors[1]);
1906        tool[1] = k * (motors[0] - motors[1]);
1907    }
1908
1909    fn state_len(&self) -> usize {
1910        if !self.elastic {
1911            N_RIGID
1912        } else if self.jump.is_some() {
1913            N_ELASTIC + 2 * JUMP_STATES
1914        } else {
1915            N_ELASTIC
1916        }
1917    }
1918
1919    fn equilibrium(&self, tool: &[f64], state: &mut Vec<f64>, torque: &mut [f64]) {
1920        let (x, z, r, ratio) = (tool[0], tool[1], self.r, self.gearbox.ratio);
1921        if !self.elastic {
1922            *state = vec![x, z, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0];
1923            let mut angle = [0.0; 2];
1924            self.inverse(tool, &mut angle);
1925            let lift = self.z_weight() * r / 2.0;
1926            for (k, at_pulley) in [lift, -lift].into_iter().enumerate() {
1927                let shaft = (at_pulley - r * self.mesh.force(r * angle[k] / ratio)) / ratio;
1928                torque[k] = self.ripple.invert(shaft, angle[k]);
1929            }
1930            return;
1931        }
1932        // X balance: T1 = T3. Z balance: 2 T2 - T1 - T3 = W_z (`z_weight`). The belt total fixes the level.
1933        // The beam's sag lowers the tool under the Z axis's place on its belt: the belt holds the state's Z, not z.
1934        let geo = self.geo(x, z + self.sag(x).0);
1935        let mat = self.belt.static_material(&geo, &[0.0, self.z_weight() / 2.0, 0.0], self.mat0.iter().sum());
1936        let (a, b) = ((mat[0] - self.mat0[0]) / self.r_mat, (self.mat0[2] - mat[2]) / self.r_mat);
1937        let m: [f64; 3] = std::array::from_fn(|i| self.belt.section(geo[i], mat[i], 0.0, 0.0).material);
1938        *state = vec![0.0; self.state_len()];
1939        state[X] = x;
1940        state[Z] = z + self.sag(x).0;
1941        if self.vertical().is_some() {
1942            // The beam rests at its quasi-static sag: k w = (m_c + m_z) g.
1943            state[W] = self.sag(x).0;
1944        }
1945        for (k, (theta, belt_torque)) in
1946            [(a, self.r_mat * (m[0] - m[1])), (b, self.r_mat * (m[1] - m[2]))].into_iter().enumerate()
1947        {
1948            let gear = -belt_torque - r * self.mesh.force(r * theta);
1949            let phi = ratio * (theta + self.gearbox.static_twist(gear));
1950            state[A + k] = theta;
1951            state[PA + k] = phi;
1952            torque[k] = self.ripple.invert(gear / ratio, phi);
1953        }
1954    }
1955
1956    fn derivatives(&self, state: &[f64], torque: &[f64], out: &mut [f64]) {
1957        if self.elastic {
1958            self.elastic_derivatives(state, torque, out)
1959        } else {
1960            self.rigid_derivatives(state, torque, out)
1961        }
1962    }
1963
1964    fn tool_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
1965        let v = if self.elastic { V } else { 2 };
1966        pos.copy_from_slice(&s[0..2]);
1967        vel.copy_from_slice(&s[v..v + 2]);
1968        if self.elastic {
1969            // The tool is at the tip of the leaning Z axis, not at the carriage, and the carriage rides on the
1970            // frame: the workpiece stands on the floor, so the frame's sway is the tool's too.
1971            let tip = self.flex_at(s[Z]).2;
1972            pos[0] += tip * s[U] + s[Q];
1973            vel[0] += tip * s[V + U] + self.tip_slope(s[Z])[0] * s[U] * s[V + Z] + s[V + Q];
1974            // The leaning Z axis's tip rises by a u^2 (`rise_coefficients`).
1975            let [rise, d_rise, _] = self.rise_coefficients(s[Z]);
1976            pos[1] += rise * s[U] * s[U];
1977            vel[1] += 2.0 * rise * s[U] * s[V + U] + d_rise * s[U] * s[U] * s[V + Z];
1978            if self.vertical().is_some() {
1979                // The beam's deflection is a state: the carriage, and the tool with it, hangs w lower.
1980                pos[1] -= s[W];
1981                vel[1] -= s[V + W];
1982            } else {
1983                let (sag, slope) = self.sag(s[X]);
1984                pos[1] -= sag;
1985                vel[1] -= slope * s[V + X];
1986            }
1987        }
1988    }
1989    /// The carriage on the beam, against the frame: neither the frame's sway nor the Z axis's lean is in it.
1990    fn scale_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
1991        let v = if self.elastic { V } else { 2 };
1992        pos.copy_from_slice(&s[0..2]);
1993        vel.copy_from_slice(&s[v..v + 2]);
1994    }
1995    fn set_tool_velocity(&self, s: &mut [f64], vel: &[f64]) {
1996        if !self.elastic {
1997            return s[2..4].copy_from_slice(vel);
1998        }
1999        s[V + X..V + X + 2].copy_from_slice(vel);
2000        let mut rotors = [0.0; 2];
2001        self.inverse(vel, &mut rotors);
2002        for k in 0..2 {
2003            (s[V + A + k], s[V + PA + k]) = (rotors[k] / self.gearbox.ratio, rotors[k]);
2004        }
2005    }
2006    fn motor_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
2007        if self.elastic {
2008            pos.copy_from_slice(&s[PA..PA + 2]);
2009            vel.copy_from_slice(&s[V + PA..V + PA + 2]);
2010        } else {
2011            self.inverse(&s[0..2], pos);
2012            self.inverse(&s[2..4], vel);
2013        }
2014    }
2015
2016    fn feedforward_torque(&self, pos: &[f64], acc: &[f64], out: &mut [f64]) {
2017        self.feedforward_torque_moving(pos, &[0.0; 2], acc, out);
2018    }
2019    /// The loss-free rigid model's (`rigid_solve`) torques for the tool's acceleration at its speed: its mass matrix, the
2020    /// belt's speed terms (`belt_speed_terms`), the growing chain's m' vx^2 / 2 and the weight.
2021    fn feedforward_torque_moving(&self, pos: &[f64], vel: &[f64], acc: &[f64], out: &mut [f64]) {
2022        let (belt_xx, belt_xz) = self.belt_mass(pos[0], pos[1]);
2023        let (belt_x, belt_z) = self.belt_speed_terms(vel[0], vel[1]);
2024        let (chain_mass, chain_growth) = self.chain.mass(pos[0]);
2025        let fx = (self.m_x() + self.m_motors() + self.m_idlers[0] + chain_mass + belt_xx) * acc[0]
2026            + belt_xz * acc[1]
2027            + 0.5 * chain_growth * vel[0] * vel[0]
2028            - belt_x;
2029        let fz =
2030            (self.m_z() + self.m_motors() + self.m_idlers[1]) * acc[1] + belt_xz * acc[0] + self.z_weight() - belt_z;
2031        let k = self.r / (2.0 * self.gearbox.ratio);
2032        out[0] = k * (fx + fz);
2033        out[1] = k * (fx - fz);
2034    }
2035
2036    /// The rigid model at a steady speed: the guides at their steady level (loads at rest), the idlers and the cable
2037    /// chain give F_x and F_z against the motion; motor a's belt force carries (F_x + F_z) / 2 and b's (F_x - F_z) / 2,
2038    /// each through its gearbox, r / (i loss) (F + W) - r W / i with W = ±W_z / 2 the weight on Z (`z_weight`) on that
2039    /// belt force,
2040    /// plus the motor shaft's friction (with the gearbox's drag) at its speed. The loss factor is the one of what the
2041    /// gearbox passes, the weight with the friction, as in `rigid_solve`; the weight itself is the rigid feedforward's,
2042    /// its loss is here.
2043    fn steady_friction(&self, pos: &[f64], vel: &[f64], out: &mut [f64]) {
2044        let (r, ratio, (vx, vz)) = (self.r, self.gearbox.ratio, (vel[0], vel[1]));
2045        let (scale_x, scale_z) = self.load_scales(pos[1], 0.0);
2046        let (idler_x, idler_z) = self.idler_friction(vx, vz);
2047        let fx = self.friction_x.feedforward(vx, scale_x) + idler_x + self.chain_drag(vx);
2048        let fz = self.friction_z.feedforward(vz, scale_z) + idler_z;
2049        let lift = self.z_weight() / 2.0;
2050        let mut speed = [0.0; 2];
2051        self.inverse(vel, &mut speed);
2052        for (k, (force, weight)) in [((fx + fz) / 2.0, lift), ((fx - fz) / 2.0, -lift)].into_iter().enumerate() {
2053            let loss = self.gears[k].loss_factor((force + weight) * r, speed[k] / ratio);
2054            out[k] = self.shaft[k].torque(speed[k]) + r / ratio * ((force + weight) / loss - weight);
2055        }
2056    }
2057
2058    /// F_x = T3 - T1 on the carriage and F_z = 2 T2 - T1 - T3 on the Z axis carry the moved masses (without the pulleys
2059    /// and rotors of `feedforward_torque`), and the belt keeps its length: sum (T_i - P) L_i = 0 over the geometric
2060    /// section lengths L_i (the elastic law T = EA (L - l) / l to first order in T / EA). With d_i = T_i - P:
2061    /// d1 = -((F_x + F_z) L2 / 2 + F_x L3) / (L1 + L2 + L3), d3 = d1 + F_x, d2 = d1 + (F_x + F_z) / 2.
2062    fn rigid_tensions(&self, pos: &[f64], acc: &[f64], out: &mut Vec<f64>) {
2063        let fx = (self.m_x() + self.m_idlers[0] + self.chain.mass(pos[0]).0) * acc[0];
2064        let fz = (self.m_z() + self.m_idlers[1]) * acc[1] + self.z_weight();
2065        let l = self.geo(pos[0], pos[1]);
2066        let d1 = -((fx + fz) * l[1] / 2.0 + fx * l[2]) / (l[0] + l[1] + l[2]);
2067        let p = self.belt.pretension;
2068        out.extend([p + d1, p + d1 + (fx + fz) / 2.0, p + d1 + fx]);
2069    }
2070
2071    /// `guide_loads` at the X acceleration of the tool: the X guide m_x g + |tilt|, the Z guide |side| + |tilt|, with
2072    /// side = m_z a_x and tilt = side 2 (z_com_drop - z) / guide_spacing.
2073    fn rigid_guide_loads(&self, pos: &[f64], acc: &[f64], out: &mut Vec<[f64; 2]>) {
2074        let (side, arm) = (self.m_z() * acc[X], 2.0 * (self.z_com_drop - pos[Z]) / self.guide_spacing);
2075        out.extend([[self.m_x() * self.g, side * arm], [0.0, side * (1.0 + arm.abs())]]);
2076    }
2077
2078    fn energy(&self, s: &[f64]) -> f64 {
2079        self.energy_parts(s).iter().sum()
2080    }
2081
2082    /// Elastic: per motor its gearbox's spring in series with the two belt sections its pulley feeds and takes from (a:
2083    /// sections 1 and 2, b: 2 and 3), dT/dL = EA / l at the belt that carries the weight at rest at the pose (as `modal`),
2084    /// r r_mat sum EA / l at the pulley; the rotor (and gearbox input) on the motor's side, the pulley with the load (so
2085    /// the load's share and frequency err high and low: more is kept back). Referred to the motor over the ratio.
2086    fn trains(&self, tool_pose: &[f64]) -> Vec<Option<sim_core::Train>> {
2087        if !self.elastic {
2088            return Vec::new();
2089        }
2090        let (x, z) = (tool_pose[0], tool_pose[1] + self.sag(tool_pose[0]).0);
2091        let geo = self.geo(x, z);
2092        let rest = self.belt.static_material(&geo, &[0.0, self.z_weight() / 2.0, 0.0], self.mat0.iter().sum());
2093        let k = |i: usize| self.belt.ea / rest[i];
2094        let whole = sim_components::control::rigid_inertias(self, tool_pose);
2095        [k(0) + k(1), k(1) + k(2)]
2096            .iter()
2097            .enumerate()
2098            .map(|(m, belt)| {
2099                let (gear, i2) = (&self.gears[m], self.gearbox.ratio * self.gearbox.ratio);
2100                let spring = 1.0 / (1.0 / gear.stiffness + gear.band_compliance + 1.0 / (self.r * self.r_mat * belt));
2101                sim_core::Train::of(spring / i2, self.j_rotor, whole[m])
2102            })
2103            .collect()
2104    }
2105
2106    /// The lowest of `modes`: the lowest mode that moves the tool, which the input shaper aims at (with the default frame
2107    /// the frame swaying with the carriage on it, 18.7 Hz at (0.9, 0.05)).
2108    fn resonance_hz(&self, tool_pose: &[f64]) -> Option<f64> {
2109        self.modes(tool_pose).first().map(|mode| mode.hz)
2110    }
2111
2112    /// Every mode of `modal` (those that move the tool), lowest first, so that the second shaper's `modes()[1]` is the
2113    /// next one that does: with the default frame and the leaning Z axis four, the frame swaying with the carriage on it,
2114    /// the carriage swaying against the frame with the Z axis leaning, the Z axis on its belt, and the Z axis's lean
2115    /// against the carriage (18.75, 30.68, 76.05 and 116.30 Hz at (0.9, 0.05)).
2116    fn modes(&self, tool_pose: &[f64]) -> Vec<Mode> {
2117        self.modal(tool_pose).into_iter().map(|(mode, _)| mode).collect()
2118    }
2119
2120    /// With effects.belt_wrap: the wrap at each motor pulley, from where `scene` puts the wheels next to it, the carriage
2121    /// idlers (`idler.radius_m`) beside the carriage (0.03 m either side of its middle) at the heights r + ri and
2122    /// -(r + ri). The spans to them are inner tangents that leave level, atan2(r + ri, d) = asin((r + ri) / D), at every
2123    /// pose: half a turn on each pulley wherever the carriage is (`mech::wrap_angle`). Only a wheel at another height
2124    /// would make it change with x.
2125    fn belt_wraps(&self, tool_pose: &[f64]) -> Vec<f64> {
2126        let Some(ri) = self.wrap_idler else { return Vec::new() };
2127        let (r, end, cx) = (self.r, 2.0 * self.span_min + self.axes[0].max, self.span_min + tool_pose[0]);
2128        [cx - 0.03 - ri, end - cx - 0.03 - ri]
2129            .iter()
2130            .map(|&d| wrap_angle(r, [d, r + ri, ri], [d, r + ri, ri]))
2131            .collect()
2132    }
2133
2134    /// The mode of `resonance_hz`: the lowest eigenvector of `modal` in the layout of the state (x, z, q and u move, as far
2135    /// as the model has them), scaled so that the largest of the carriage's travel x, the Z axis's z and the tool's travel
2136    /// x + q + tip u (`tool_state`) is 1 m, and signed so that the larger of the first and the last is positive. Not to
2137    /// the tool's alone: high on the Z axis tip turns negative and the tool stands still in a mode at one height, where
2138    /// that scale would be infinite.
2139    fn mode_shape(&self, tool_pose: &[f64]) -> Option<(f64, Vec<f64>)> {
2140        let (mode, mut shape) = self.modal(tool_pose).into_iter().next()?;
2141        let tool = shape[X] + shape[Q] + self.flex_at(tool_pose[1]).2 * shape[U];
2142        let largest = shape[X].abs().max(shape[Z].abs()).max(shape[W].abs()).max(tool.abs());
2143        let sign = if shape[X].abs() >= tool.abs() { shape[X].signum() } else { tool.signum() };
2144        shape.iter_mut().for_each(|v| *v *= sign / largest);
2145        Some((mode.hz, shape))
2146    }
2147
2148    fn set_payload_attached(&mut self, attached: bool) {
2149        self.payload_attached = attached;
2150    }
2151    fn set_dwelling(&mut self, dwelling: bool) {
2152        self.dwelling = dwelling;
2153    }
2154    /// The push acts on the contact point (`contact_state`) in either model; its power is the budget's crash row, not
2155    /// the process's.
2156    fn set_tool_force(&mut self, force: &[f64]) -> bool {
2157        self.push = Stack::new();
2158        force.iter().for_each(|f| self.push.push(*f));
2159        true
2160    }
2161    /// The tool's two axes, or with the lean the elastic model's coordinates (`pushes_on_coordinates`).
2162    fn contact_axes(&self) -> usize {
2163        if self.pushes_on_coordinates() { self.coordinates().len() } else { 2 }
2164    }
2165    /// With the lean the elastic model's coordinates and their rates (`pushes_on_coordinates`); a payload pushed at
2166    /// its own point stood back by the lean from the Z axis's foot, which then went into the obstacle unheld (the
2167    /// T-gantry's move into a slab sprang back with 107 J out of the crash row). Else the tool's.
2168    fn contact_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
2169        if !self.pushes_on_coordinates() {
2170            return self.tool_state(s, pos, vel);
2171        }
2172        for (k, &c) in self.coordinates().iter().enumerate() {
2173            (pos[k], vel[k]) = (s[c], s[V + c]);
2174        }
2175    }
2176    /// With the lean the contact's spring holds the lean through its lever, a mode faster than the load's on the belt:
2177    /// the move into a slab left 6.3e-5 of its supply out of the budget at the simulation's own refinement (4 times
2178    /// `sim.substeps`), 3.3e-5 at 8 times and 2.3e-5 at 16, near the 1.9e-5 that finer steps still leave.
2179    fn push_substeps(&self) -> u32 {
2180        if self.pushes_on_coordinates() { 4 } else { 1 }
2181    }
2182    /// The state with the coordinates at `at`, the rest as it is; else the rest at the tool pose `at`.
2183    fn contact_placed(&self, s: &[f64], at: &[f64], out: &mut Vec<f64>) {
2184        if !self.pushes_on_coordinates() {
2185            let mut torque = vec![0.0; self.motors().len()];
2186            return self.equilibrium(at, out, &mut torque);
2187        }
2188        out.clear();
2189        out.extend_from_slice(s);
2190        for (&c, &a) in self.coordinates().iter().zip(at) {
2191            out[c] = a;
2192        }
2193    }
2194    fn set_brake_engaged(&mut self, engaged: bool) {
2195        self.brake_engaged = engaged;
2196    }
2197    /// A stop met within the step (`HardStop::substeps`, `RotaryJoint::stop_substeps`).
2198    fn substeps_wanted(&self, s: &[f64], _torque: &[f64], dt: f64, _substeps: u32) -> u32 {
2199        let v = if self.elastic { [s[V + X], s[V + Z]] } else { [s[2], s[3]] };
2200        (0..2).map(|k| self.stops.substeps(s[k], v[k], self.axes[k].max, dt)).max().unwrap_or(1)
2201    }
2202
2203    fn memory(&self) -> Vec<f64> {
2204        Gearbox::anchors(&self.gears)
2205    }
2206    fn set_memory(&mut self, memory: &[f64]) {
2207        Gearbox::set_anchors(&mut self.gears, memory)
2208    }
2209
2210    /// Belt tooth jump at each motor pulley (`ToothJump`): a positive slip of pulley A feeds section 1, of pulley B
2211    /// section 2.
2212    fn after_step(&mut self, s: &mut [f64], dt: f64) {
2213        self.jump_loss = 0.0;
2214        // The gearboxes' hysteresis states move on to where the step ended (`Gearbox::commit`).
2215        if self.elastic {
2216            for k in 0..2 {
2217                self.gears[k].commit(s[PA + k], s[A + k]);
2218            }
2219        }
2220        let Some(mut jump) = self.jump.clone() else { return };
2221        let wraps = self.belt_wraps(&[s[X], s[Z]]);
2222        for k in 0..2 {
2223            if let Some(&wrap) = wraps.get(k) {
2224                jump.set_wrap(wrap);
2225            }
2226            let (before, t) = (self.energy(s), self.sections(s).map(|f| f.tension));
2227            let at = JUMP + JUMP_STATES * k;
2228            let (rest, mut v) = ((self.j_pulley / (self.r * self.r)) - jump.mass, self.r * s[V + A + k]);
2229            if jump.update(&mut s[at..at + JUMP_STATES], t[k], t[k + 1], rest, &mut v) {
2230                s[V + A + k] = v / self.r;
2231                self.jump_loss += (before - self.energy(s)) / dt;
2232            }
2233        }
2234    }
2235
2236    /// The gearboxes (where there are some) and the X and Z guides, in the order of `thermal_parts`.
2237    fn set_part_temperatures(&mut self, rises: &[f64]) {
2238        let Some((law, viscous)) = &self.thermal else { return };
2239        let gearboxes = if self.gearbox.is_coupling() { 0 } else { 2 };
2240        // Each motor's seal and drag follow its own gearbox's oil, as a machine file's do.
2241        for k in 0..gearboxes {
2242            self.gears[k].efficiency = law.gearbox_efficiency(rises[k]);
2243            self.shaft[k].set_oil(law.viscosity_factor(rises[k]));
2244        }
2245        self.friction_x.viscous = viscous[0] * law.viscosity_factor(rises[gearboxes]);
2246        self.friction_z.viscous = viscous[1] * law.viscosity_factor(rises[gearboxes + 1]);
2247    }
2248
2249    fn signal_infos(&self) -> Vec<SignalInfo> {
2250        let mut out: Vec<SignalInfo> = (1..=3)
2251            .map(|i| {
2252                SignalInfo::new(format!("belt.{i}.tension"), &format!("belt-section-{i}"), "quantity-tension", "N")
2253            })
2254            .collect();
2255        for axis in &self.axes {
2256            out.push(SignalInfo::new(format!("axis.{}.belt_stretch", axis.id), axis.key, "quantity-belt-stretch", "m"));
2257            out.push(SignalInfo::new(format!("axis.{}.friction", axis.id), axis.key, "quantity-friction-force", "N"));
2258        }
2259        out.push(SignalInfo::new("frame.deflection", "frame", "quantity-deflection", "m"));
2260        out.push(SignalInfo::new("axis.x.tool_deflection", "axis-x", "quantity-tool-deflection", "m"));
2261        out.push(SignalInfo::new("belt.slack_time", "group-belt", "quantity-slack-time", "s"));
2262        for motor in &self.motors {
2263            out.push(SignalInfo::new(
2264                format!("pulley.{}.radial_load", motor.id),
2265                motor.key,
2266                "quantity-radial-load",
2267                "N",
2268            ));
2269        }
2270        for axis in &self.axes {
2271            out.push(SignalInfo::new(format!("axis.{}.guide_load", axis.id), axis.key, "quantity-guide-load", "N"));
2272        }
2273        for motor in &self.motors {
2274            out.push(SignalInfo::new(
2275                format!("gearbox.{}.output_torque", motor.id),
2276                motor.key,
2277                "quantity-gearbox-torque",
2278                "N m",
2279            ));
2280        }
2281        if self.jump.is_some() {
2282            for motor in &self.motors {
2283                out.push(SignalInfo::new(
2284                    format!("pulley.{}.tooth_jumps", motor.id),
2285                    motor.key,
2286                    "quantity-tooth-jumps",
2287                    "",
2288                ));
2289                out.push(SignalInfo::new(
2290                    format!("pulley.{}.tooth_slip", motor.id),
2291                    motor.key,
2292                    "quantity-tooth-slip",
2293                    "m",
2294                ));
2295            }
2296        }
2297        if self.span_mass.is_some() {
2298            out.extend((1..=8).map(|i| {
2299                SignalInfo::new(
2300                    format!("belt.span.{i}.frequency"),
2301                    &format!("belt-span-{i}"),
2302                    "quantity-span-frequency",
2303                    "Hz",
2304                )
2305            }));
2306            out.push(SignalInfo::new("belt.span_detuning", "group-belt", "quantity-span-detuning", ""));
2307        }
2308        if self.vertical().is_some() {
2309            out.push(SignalInfo::new("beam.deflection", "group-beam", "quantity-deflection", "m"));
2310        }
2311        self.effect_infos(&mut out);
2312        out
2313    }
2314
2315    /// The two guides. Their speeds are those of the carriage along the beam and of the Z axis.
2316    fn friction_contacts(&self) -> Vec<FrictionContact> {
2317        vec![
2318            FrictionContact { id: "axis.x", owner_key: "axis-x" },
2319            FrictionContact { id: "axis.z", owner_key: "axis-z" },
2320        ]
2321    }
2322    fn friction_curve(&self, i: usize, speed: f64, load_scale: f64) -> [f64; 3] {
2323        [&self.friction_x, &self.friction_z].get(i).map_or([0.0; 3], |f| f.steady(speed, load_scale))
2324    }
2325
2326    /// The three belt sections, in the order of the signals `belt.<i>.tension`.
2327    fn belt_sections(&self) -> Vec<BeltSection> {
2328        ["belt-section-1", "belt-section-2", "belt-section-3"]
2329            .iter()
2330            .zip(["belt.1", "belt.2", "belt.3"])
2331            .map(|(&owner_key, id)| BeltSection { id, owner_key, pretension: self.belt.pretension })
2332            .collect()
2333    }
2334
2335    /// Both gearboxes, where there are gearboxes (not on a direct drive, see `Gearbox::is_coupling`), and both guides.
2336    /// The X guide is shown by the carriage, the Z guide by the Z axis's column.
2337    fn thermal_parts(&self) -> Vec<ThermalPart> {
2338        let part =
2339            |id, kind, owner_key, scene_part, scene_index| ThermalPart { id, kind, owner_key, scene_part, scene_index };
2340        let gearboxes = [
2341            part("gearbox_a", "gearbox", "motor-a", "gearbox", 0),
2342            part("gearbox_b", "gearbox", "motor-b", "gearbox", 1),
2343        ];
2344        let mut parts = if self.gearbox.is_coupling() { Vec::new() } else { gearboxes.to_vec() };
2345        parts.extend([
2346            part("guide_x", "guide", "axis-x", "carriage", 0),
2347            part("guide_z", "guide", "axis-z", "z-axis", 0),
2348        ]);
2349        parts
2350    }
2351
2352    /// The rigid model has no belt stretch: it reports pretension, zero stretch, zero deflection and no slack.
2353    /// The belt wraps each motor pulley by half a turn, so the two sections that end there pull its shaft
2354    /// the same way: the radial load is the sum of their tensions. The gearbox torques are those at the
2355    /// outputs, positive where they turn the pulley forwards: in the elastic model what the gear's spring
2356    /// passes on to the pulley, in the rigid one what its solver works out.
2357    fn base_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
2358        let (load_x, load_z) = self.guide_loads(s[Z], self.commanded_ax(s[X], s[Z], torque));
2359        if !self.elastic {
2360            let [_, _, ffx, ffz, _, _, gear_a, gear_b, ..] = self.rigid_solve(s, torque);
2361            out.extend([self.belt.pretension; 3]);
2362            out.extend([0.0, ffx, 0.0, ffz, 0.0, 0.0, 0.0]);
2363            out.extend([2.0 * self.belt.pretension, 2.0 * self.belt.pretension, load_x, load_z, gear_a, gear_b]);
2364            if let Some(mass) = self.span_mass {
2365                self.span_signals(s, mass, out);
2366            }
2367            return;
2368        }
2369        let sec = self.sections(s);
2370        let (ffx, ffz, ..) = self.guide_friction(s[X], s[Z], [s[V + X], s[V + Z]], s[S], s[S + 1], torque);
2371        let (a, b) = (s[A], s[A + 1]);
2372        out.extend(sec.iter().map(|f| f.tension));
2373        out.extend([
2374            s[X] - self.r / 2.0 * (a + b),
2375            ffx,
2376            s[Z] - self.r / 2.0 * (a - b),
2377            ffz,
2378            s[Q],
2379            self.flex_at(s[Z]).2 * s[U],
2380            s[SLACK],
2381        ]);
2382        out.extend([sec[0].tension + sec[1].tension, sec[1].tension + sec[2].tension, load_x, load_z]);
2383        out.extend((0..2).map(|k| self.gears[k].torque(s[PA + k], s[V + PA + k], s[A + k], s[V + A + k]).output));
2384        if self.jump.is_some() {
2385            for k in 0..2 {
2386                out.extend([s[JUMP + JUMP_STATES * k + 4], s[JUMP + JUMP_STATES * k]]);
2387            }
2388        }
2389        if let Some(mass) = self.span_mass {
2390            self.span_signals(s, mass, out);
2391        }
2392        if self.vertical().is_some() {
2393            out.push(s[W]);
2394        }
2395    }
2396    fn effect_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
2397        self.view_signals(s, torque, out);
2398    }
2399    fn loss_powers(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
2400        out.extend(self.losses(s, torque).0);
2401        if self.jump.is_some() {
2402            out.push(self.jump_loss);
2403        }
2404        if self.vertical().is_some() {
2405            out.push(self.beam_loss(s));
2406        }
2407    }
2408
2409    fn scene(&self, s: &[f64], out: &mut Scene) {
2410        use sim_core::scene::{belt_along, drive_unit, idler, on_circle};
2411        use std::f64::consts::{FRAC_PI_2, FRAC_PI_4, FRAC_PI_8, TAU};
2412        let (x, z, r, ratio) = (s[0], s[1], self.r, self.gearbox.ratio);
2413        let (sx, sz, span) = (self.axes[0].max, self.axes[1].max, self.span_min);
2414        let (mut rotor, mut rotor_speed) = ([0.0; 2], [0.0; 2]);
2415        self.motor_state(s, &mut rotor, &mut rotor_speed);
2416        let pulley = if self.elastic { [s[A], s[A + 1]] } else { rotor.map(|p| p / ratio) };
2417        // Belt colour: tension relative to pretension, per section.
2418        let tension = if self.elastic { self.sections(s).map(|f| f.tension) } else { [self.belt.pretension; 3] };
2419        let shade =
2420            tension.map(|t| ((t - self.belt.pretension) / self.belt.pretension.max(1.0)).clamp(-1.0, 1.0) as f32);
2421
2422        // The belt runs in one plane in front of the beam; the motors sit behind it at both ends.
2423        // The carriage rides on the beam at height 0; the Z axis hangs through it and rises with z.
2424        let y = -0.05;
2425        let (end, cx, half) = (2.0 * span + sx, span + x, 0.03);
2426        let (left, right, top, bottom) = (cx - half, cx + half, span + z, z - sz - span);
2427        let floor = -(sz + 2.0 * span + 0.2);
2428        // The beam has the height of the EXCT's profile, 170 mm; the posts stand under the ends of the carriage's
2429        // travel, where the EXCT's mounting plates are.
2430        let beam_half = 0.085;
2431        let part = Part::new;
2432        out.labels.clear();
2433        out.parts.clear();
2434        out.arrows.clear();
2435        let post = Shape::Box { size: [0.06, 0.06, -beam_half - floor] };
2436        out.parts.extend([
2437            part(
2438                "beam",
2439                Shape::Box { size: [end - 0.14, 0.07, 2.0 * beam_half] },
2440                [end / 2.0, 0.045, 0.0],
2441                [0.62, 0.64, 0.68],
2442            ),
2443            part("post", post.clone(), [span, 0.045, (floor - beam_half) / 2.0], [0.45, 0.47, 0.5]),
2444            part("post", post, [end - span, 0.045, (floor - beam_half) / 2.0], [0.45, 0.47, 0.5]),
2445            part("carriage", Shape::Box { size: [0.16, 0.02, 0.16] }, [cx, -0.02, 0.0], [0.2, 0.22, 0.26]),
2446        ]);
2447        cable_chain(&mut out.parts, end, x, cx, beam_half, self.chain.length0);
2448        let (hanging, lean) = self.hanging(s, out.exaggeration);
2449        let q = if self.elastic { s[Q] } else { 0.0 };
2450        let turn = |p: [f64; 2]| {
2451            let (sin, cos) = lean.sin_cos();
2452            [cx + (p[0] - cx) * cos - p[1] * sin, (p[0] - cx) * sin + p[1] * cos]
2453        };
2454        out.parts.extend(hanging);
2455        // Positive pulley angles turn clockwise seen from the front (the top of the pulley moves right).
2456        drive_unit(&mut out.parts, [0.0, 0.0], y, r, -pulley[0], -rotor[0], [0.9, 0.45, 0.1]);
2457        drive_unit(&mut out.parts, [end, 0.0], y, r, -pulley[1], -rotor[1], [0.1, 0.45, 0.9]);
2458        // Carriage idlers turn the belt from the beam into the Z axis; the idler at the bottom of
2459        // the Z axis turns it around. Each rolls with the belt that passes it (see the module comment).
2460        let ri = 0.012;
2461        for (side, lower_travel) in [(-1.0, z + 2.0 * x), (1.0, z - 2.0 * x)] {
2462            let ix = cx + side * (half + ri);
2463            idler(&mut out.parts, [ix, r + ri], y, ri, side * z / ri);
2464            idler(&mut out.parts, [ix, -r - ri], y, ri, side * lower_travel / ri);
2465        }
2466
2467        // The belt path from the clamp on the left to the clamp on the right. Its length does not
2468        // depend on the pose, so teeth at fixed belt length travel around the pulleys by themselves.
2469        let (a, b, bend) = ([0.0, 0.0], [end, 0.0], [cx, bottom]);
2470        // Each point with the section of the strip that ends at it, and whether that strip is a free horizontal span
2471        // (between a motor pulley and a carriage idler), which sags. Strips up to the middle of each motor pulley
2472        // belong to the section before it. Points on the Z axis (its ends and the bend at its bottom) lean with it.
2473        // The wraps on the motor pulleys get 8 strips per half turn, so the teeth there sit close to the pitch circle
2474        // (a chord is 0.994 of its arc and lies r (1 - cos(pi / 16)) = 0.02 r inside it at the middle).
2475        let wrap = |centre: [f64; 2], from: f64, sections: [usize; 2]| {
2476            (1..=8).map(move |k| (on_circle(centre, r, from + k as f64 * FRAC_PI_8), sections[(k > 4) as usize], false))
2477        };
2478        let mut key = vec![(turn([left, top]), 0, false), ([left, r], 0, false), ([0.0, r], 0, true)];
2479        key.extend(wrap(a, FRAC_PI_2, [0, 1]));
2480        key.extend([([left, -r], 1, true), (turn([left, bottom]), 1, false)]);
2481        key.extend((5..=7).map(|k| (turn(on_circle(bend, half, k as f64 * FRAC_PI_4)), 1, false)));
2482        key.extend([(turn([right, bottom]), 1, false), ([right, -r], 1, false), ([end, -r], 1, true)]);
2483        key.extend(wrap(b, -FRAC_PI_2, [1, 2]));
2484        key.extend([([right, r], 2, true), (turn([right, top]), 2, false)]);
2485        // Sagging spans get points along their sag, drawn larger like the other deflections, but never deeper than a
2486        // quarter of the span. Each span has a pulley or idler under one end (the motor pulley under the upper spans,
2487        // the lower carriage idler under the lower ones) and one above or level at the other. It leaves the end with
2488        // the wheel under it level, as a belt does off a wrap, so the sag cannot cut into that wheel: the shape is
2489        // 27/4 t^2 (1 - t), deepest at a third of the span from the other end, at the depth of the parabola's middle.
2490        // The belt length of every point is that of the straight path, so the teeth keep their places on the belt
2491        // (`belt_along`).
2492        let weight = self.belt.mass_per_m * self.g;
2493        let (mut path, mut along, mut section) = (vec![key[0].0], vec![0.0], Vec::new());
2494        for pair in key.windows(2) {
2495            let ((p, _, _), (q, sec, sags)) = (pair[0], pair[1]);
2496            let length = (q[0] - p[0]).hypot(q[1] - p[1]);
2497            // The motor pulleys stand at the ends, x = 0 and x = end: an upper span has its pulley under the end at
2498            // a pulley, a lower span its idler under the end away from it.
2499            let at_pulley = |point: [f64; 2]| point[0].abs() < 1e-9 || (point[0] - end).abs() < 1e-9;
2500            let level_at_q = if p[1] > 0.0 { at_pulley(q) } else { !at_pulley(q) };
2501            let sag =
2502                if sags { (out.exaggeration * span_sag(weight, length, tension[sec])).min(length / 4.0) } else { 0.0 };
2503            let pieces = if sags { SAG_PIECES } else { 1 };
2504            let start = *along.last().unwrap();
2505            for k in 1..=pieces {
2506                let t = k as f64 / pieces as f64;
2507                let shape = if level_at_q { 6.75 * (1.0 - t) * (1.0 - t) * t } else { 6.75 * t * t * (1.0 - t) };
2508                path.push([p[0] + t * (q[0] - p[0]), p[1] + t * (q[1] - p[1]) - sag * shape]);
2509                along.push(start + t * length);
2510                section.push(sec);
2511            }
2512        }
2513        belt_along(&mut out.parts, &path, &along, y, 0.025, 0.04, |i| shade[section[i]]);
2514
2515        // The belt's pull: on the carriage along X, on the Z axis along Z, and on each motor pulley's shaft, where
2516        // both sections that leave it pull the same way.
2517        let [t1, t2, t3] = tension;
2518        out.arrows.extend([
2519            Arrow { pos: [cx, y, 0.0], force: [t3 - t1, 0.0, 0.0], owner_key: self.axes[0].key },
2520            Arrow { pos: [cx, y, bottom], force: [0.0, 0.0, 2.0 * t2 - t1 - t3], owner_key: self.axes[1].key },
2521            Arrow { pos: [0.0, y, 0.0], force: [t1 + t2, 0.0, 0.0], owner_key: self.motors[0].key },
2522            Arrow { pos: [end, y, 0.0], force: [-(t2 + t3), 0.0, 0.0], owner_key: self.motors[1].key },
2523        ]);
2524
2525        let rpm = |speed: f64| speed * 60.0 / TAU;
2526        out.labels.extend([
2527            Label {
2528                pos: [0.0, y, 0.11],
2529                owner_key: self.motors[0].key,
2530                value: rpm(rotor_speed[0]),
2531                unit_key: "unit-rpm",
2532                decimals: 0,
2533            },
2534            Label {
2535                pos: [end, y, 0.11],
2536                owner_key: self.motors[1].key,
2537                value: rpm(rotor_speed[1]),
2538                unit_key: "unit-rpm",
2539                decimals: 0,
2540            },
2541            Label { pos: [cx, y, top + 0.08], owner_key: self.axes[0].key, value: x, unit_key: "unit-m", decimals: 3 },
2542            Label {
2543                pos: [cx + 0.12, y, bottom],
2544                owner_key: self.axes[1].key,
2545                value: z,
2546                unit_key: "unit-m",
2547                decimals: 3,
2548            },
2549        ]);
2550
2551        // The frame sways by q (x is the carriage on the frame): all of it moves, and the posts lean from the floor.
2552        let sway = out.exaggeration * q;
2553        let post_tilt = -(sway / (-beam_half - floor)).atan();
2554        for p in &mut out.parts {
2555            if p.id == "post" {
2556                p.pos[0] += sway / 2.0;
2557                p.angle = post_tilt;
2558            } else {
2559                p.pos[0] += sway;
2560                if let Shape::Segment { to, .. } = &mut p.shape {
2561                    to[0] += sway;
2562                }
2563            }
2564        }
2565        out.labels.iter_mut().for_each(|l| l.pos[0] += sway);
2566        out.arrows.iter_mut().for_each(|a| a.pos[0] += sway);
2567    }
2568
2569    /// The flange under the idler at the bottom of the Z axis, in the belt plane.
2570    fn scene_point(&self, tool_pose: &[f64]) -> Option<[f64; 3]> {
2571        Some([self.span_min + tool_pose[0], -0.05, tool_pose[1] - self.axes[1].max - self.span_min - 0.042])
2572    }
2573
2574    /// What hangs from the carriage and moves through the work area: the Z axis, the flange and the payload, where
2575    /// `scene` draws them (unexaggerated), without drawing the rest: the live check asks for them every base step.
2576    fn collision_bodies(&self, s: &[f64]) -> Vec<sim_core::Aabb> {
2577        let sway = if self.elastic { s[Q] } else { 0.0 };
2578        let mut boxes = sim_core::scene::scene_boxes(&self.hanging(s, 1.0).0, &["z-axis", "flange", "payload"]);
2579        boxes.iter_mut().for_each(|b| b.centre[0] += sway);
2580        boxes
2581    }
2582}
2583
2584/// How deep a slack belt span is drawn (before `Scene::exaggeration`), and the most any span sags in the drawing.
2585const SLACK_SAG: f64 = 0.015;
2586/// Strips per sagging span: their lengthening over the chord is a little short of the smooth sag's.
2587const SAG_PIECES: usize = 6;
2588
2589/// The sag at the middle of a horizontal belt span of `span` metres under `tension`, its weight `weight` N/m: the
2590/// shallow catenary's w L^2 / (8 T). A span without tension is drawn at `SLACK_SAG`.
2591fn span_sag(weight: f64, span: f64, tension: f64) -> f64 {
2592    if tension <= 0.0 { SLACK_SAG } else { (weight * span * span / (8.0 * tension)).min(SLACK_SAG) }
2593}
2594
2595/// The cable chain on top of the beam, link by link, as on the EXCT: fixed near the right end, its lower run lies
2596/// on the beam, turns up in a loop and comes back on top to a bracket on the carriage. Its length stays, so the
2597/// loop moves half as far as the carriage (its upper run is length_at_zero + x / 2 long), and each link keeps its place
2598/// along the chain from the fixed end.
2599/// It is the model's chain (`effects.cable_chain`, `CableChain`): the run that moves with the carriage is
2600/// `length_at_zero + x / 2` long, so it is drawn with exactly that upper run; the chain's fixed end sits at the far end of
2601/// the beam (its loop is between that end and the bracket, half as far from it as the carriage), which is the same chain
2602/// as the model's (the moving run grows by half of every metre the carriage travels).
2603fn cable_chain(parts: &mut Vec<Part>, end: f64, x: f64, cx: f64, beam_half: f64, length0: f64) {
2604    use std::f64::consts::PI;
2605    // The EXCT-30's chain: 49 mm wide, 24 mm links, a loop of 90 mm radius just left of the bracket at x = 0.
2606    let (radius, height, width, pitch, depth) = (0.09, 0.024, 0.049, 0.03, 0.05);
2607    let (fixed, moving) = (end - 0.07, cx - 0.1);
2608    let upper = length0 + x / 2.0;
2609    let turn = moving - upper;
2610    let (low, high) = (beam_half + height / 2.0, beam_half + height / 2.0 + 2.0 * radius);
2611    let lower = fixed - turn;
2612    let colour = [0.16, 0.16, 0.17];
2613    // The links share the chain's length evenly, so the last one ends at the bracket.
2614    let length = lower + PI * radius + upper;
2615    let links = (length / pitch).round().max(1.0) as usize;
2616    let pitch = length / links as f64;
2617    parts.extend((0..links).map(|i| {
2618        let along = (i as f64 + 0.5) * pitch;
2619        let (pos, angle) = if along < lower {
2620            ([fixed - along, low], 0.0)
2621        } else if along < lower + PI * radius {
2622            let round = (along - lower) / radius;
2623            ([turn - radius * round.sin(), (low + high) / 2.0 - radius * round.cos()], -round)
2624        } else {
2625            ([turn + along - lower - PI * radius, high], 0.0)
2626        };
2627        Part::new("cable-chain", Shape::Box { size: [0.9 * pitch, width, height] }, [pos[0], depth, pos[1]], colour)
2628            .turned(angle)
2629    }));
2630    // The bracket that carries the chain's end on the carriage.
2631    let (base, lift) = (0.08, high - height / 2.0);
2632    parts.push(Part::new(
2633        "chain-bracket",
2634        Shape::Box { size: [0.02, width, lift - base] },
2635        [moving, depth, (base + lift) / 2.0],
2636        colour,
2637    ));
2638}
2639
2640#[cfg(test)]
2641mod scene_tests;
2642#[cfg(test)]
2643mod tests;
2644#[cfg(test)]
2645mod tests_beam;