Skip to main content

sim_netlist/
machine.rs

1//! `ConfigMachine`: a belt-driven machine of any routing, built from a netlist (`Netlist`).
2//!
3//! The machine has n axes (tool coordinates q) and as many motors (one more per drive of a gantry beyond the first),
4//! and with a yawing gantry one more coordinate, its yaw, after the axes. Each motor turns one pulley through its gearbox.
5//! Belt section s has the geometric length L_s = L0_s + sum_i c_si q_i (plus the teeth in mesh at each pulley it ends
6//! at, see `Belt::tooth_length`), and pulley k feeds f_sk r_k of belt into it per radian (f = +1 or -1). So:
7//!
8//! * the belt pulls axis i with -sum_s c_si T_s, and turns pulley k with r_mat,k sum_s f_sk M_s (M the force on the belt
9//!   material, `SectionForce::material`);
10//! * in the rigid model the belt keeps its length: C q = F diag(r) a, so the pulley angles are a = K q with
11//!   K = (F diag(r))^+ C, which must reproduce C exactly (else the routing is refused) and be invertible;
12//! * bodies move with their axes, so the mass on axis i is the sum of the bodies that move with it; the axes are
13//!   taken square to each other, so the bodies' mass matrix is diagonal. Gravity pulls axis i with m_i g sin(incline_i).
14//!   A body that rides on rotary axes (or across a yawing gantry's bridge) is placed by `body_point` instead, and adds
15//!   m J^T J, -m g J_z and -m J^T (dJ/dt v) (its place's Jacobian J by differences): Lagrange's equations.
16//! * a gantry's yaw (`machine.gantry`, effects.gantry_yaw): the coordinate psi with its own inertia, spring and damper;
17//!   the sections that pull the bridge's ends get longer by their yaw coefficient per rad, a drive at its side has the
18//!   row e_axis + side e_psi in K. Where fewer motors than coordinates set it, the motors set the axes (`k_inv` from
19//!   their columns) and the spring the yaw; where the belts cannot keep their length with it, the rigid model has none.
20//! * a tool centre point (`machine.tcp`): the tool pose is the tip's, the axes stand at the tip less the tool turned by
21//!   the rotaries (`joints`, `tool_of`).
22//!
23//! The effects of the shipped crates, written for any routing:
24//!
25//! * idlers (`machine.idler`): idler d passes belt at the speed s_d . v (s_d its `speed` per axis), so its inertia
26//!   J_d / r_d^2 adds m_d s_d s_d^T to the axes' mass matrix (which is then no longer diagonal), and its bearing
27//!   friction torque F_d r_d pulls the axes back with F_d tanh(s_d . v / (w_s r_d)) s_d (w_s the motors' friction
28//!   smoothing speed, as for the gantry's idlers). They carry no weight.
29//! * a cable chain on an axis (`cable_chain = true`): mass m(q) = mu (L0 + q / 2) that moves with the axis, which
30//!   takes m dv/dt + m' v^2 / 2, and a drag that fades out below the axis guide's Stribeck speed (`mech::CableChain`).
31//! * a process force per axis, `process.force_<axis>_n`, on the tool while the cycle dwells.
32//! * the frame (`machine.frame`, elastic model only): it sways by u along a horizontal axis f on its spring. The axes
33//!   are measured on the frame, so the bodies move at v + e_f du/dt over ground: M (a + e_f u'') = F, and the frame
34//!   takes the forces its belt, guides, idlers, chain and stops put on them back, m_frame u'' = -k u - c u' - F_f
35//!   (less the process force, which the workpiece takes, and plus the chain's -m' w^2 / 2, w the chain's speed over
36//!   ground). Bodies that do not move along f ride on the frame: their mass sways with it.
37//! * thermal feedback: the gearboxes' efficiency and the guides' viscous friction follow their temperature
38//!   (`mech::ThermalFeedback`), the belt's stiffness the ambient one (in `Belt`).
39//! * belt tooth jump (elastic model only): at each driven pulley between a section it feeds (+1) and one it takes from
40//!   (-1), `mech::ToothJump`; the slip u of the belt over pulley k feeds u of belt into its +1 section.
41//! * span vibration (`machine.span`): each free span's first sideways mode at its section's tension, against what the
42//!   drives excite (`mech::span_frequency`, `drive_excitations`).
43//!
44//! Each motor's drive train (rotor, gearbox, motor friction, ripple, brake) is read from its own config
45//! (`catalog::motor_config`): the shared `[motor]` and `[gearbox]` with its `[motor.<id>]`, `[gearbox.<id>]` over them.
46//!
47//! Two of the registered belt machines are this with C = [[1], [-1]] and F = [[1], [-1]], and with
48//! C = [[1, 1], [0, -2], [-1, 1]] and F = [[1, 0], [-1, 1], [0, -1]]; `machines/*.toml` hold them, and
49//! crates/sim-machines/tests/machine_files.rs checks them against their crates. The equations are those crates',
50//! written for any C and F: their module comments derive them.
51//!
52//! A motor may drive an axis without a belt (`Direct`): a ball screw or a rack behind its gearbox, a linear motor, or a
53//! rotary table (an axis in rad). Its drive train is the registered one-axis machines' (`RotaryJoint` with the screw's or rack's
54//! `transmission::Converter` behind the gearbox): the gearbox is then one in the axis's unit, of ratio i / lever, its
55//! stiffness the gearbox's and the converter's in series, its efficiency both, the screw's or pinion's inertia on the
56//! rotor. Its "pulley" is the axis itself: K has a row e_i for it, the axis takes the gearbox's output as its force,
57//! and in the elastic model the pulley's states follow the axis. So the registered screw, rack, linear motor and table axes are this with no
58//! belt (crates/sim-machines/tests/machine_files.rs checks the screw axis against its crate). A rotary axis has no
59//! body: its rotary's inertia (and payload's) is its mass, no gravity along it.
60
61use crate::geometry::{
62    Wheel, arc, contacts, flex_at, lean_reach, lean_rise, lean_weight, rise_coefficients, tip_slope, wrap,
63};
64use crate::netlist::{LeanNode, Netlist, SpanNode, TcpNode, Transmission, Waypoint, WormNode};
65use sim_components::catalog::motor_config;
66use sim_components::joint::RotaryJoint;
67use sim_components::mech::{
68    Belt, CableChain, GearTorque, Gearbox, HardStop, HoldingBrake, JUMP_STATES, Lugre, Ripple, SectionForce,
69    ShaftFriction, ThermalFeedback, ToothJump, ToothMesh, drive_excitations, span_detuning, span_frequency,
70};
71use sim_components::transmission::{BallScrew, LinearMotor, RackPinion, StrainWave};
72use sim_core::scene::{MOTOR_PART, drive_unit, idler};
73use sim_core::{
74    AxisInfo, BeltSection, Config, ConfigError, ENERGY_PARTS, FRICTION_SIGNALS, FrictionContact, LOSS_PREFIX, Label,
75    Machine, Mode, MotorInfo, Part, RatingCheck, Scene, Shape, SignalInfo, TORQUE_PARTS, ThermalPart,
76};
77
78const G: f64 = 9.80665;
79/// Straight pieces the 3D view draws a belt's arc round a wheel with.
80const ARC_PIECES: usize = 8;
81
82/// Where the 3D view puts a body with every axis at 0 (the bodies' places, `body_point`, start at the origin).
83fn scene_origin() -> [f64; 3] {
84    [0.0, -0.03, 0.06]
85}
86
87/// A `&'static str` for an id or key read from a file, which `AxisInfo` and the other machine descriptions take.
88/// Each distinct text is leaked once, so rebuilding a machine on every config change does not grow memory.
89pub fn intern(text: &str) -> &'static str {
90    use std::collections::HashSet;
91    use std::sync::{Mutex, OnceLock};
92    static TEXTS: OnceLock<Mutex<HashSet<&'static str>>> = OnceLock::new();
93    let mut texts = TEXTS.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());
94    if let Some(known) = texts.get(text) {
95        return known;
96    }
97    let leaked: &'static str = Box::leak(text.to_string().into_boxed_str());
98    texts.insert(leaked);
99    leaked
100}
101
102struct Section {
103    id: &'static str,
104    key: &'static str,
105    /// Length at q = 0 with the teeth in mesh, and that without them; per axis and per motor.
106    length: f64,
107    bare: f64,
108    c: Vec<f64>,
109    f: Vec<f64>,
110    /// Unstretched belt at q = 0 with the pulleys at angle 0.
111    mat0: f64,
112    route: Vec<Waypoint>,
113    /// The plane its belt runs in, [along, up, depth] of the scene (`machine.section.plane`); `None` for the default
114    /// (`belt_plane`).
115    plane: Option<[usize; 3]>,
116}
117
118struct Body {
119    mass: f64,
120    payload: f64,
121    axes: Vec<bool>,
122    /// The rotary axes it rides on, outermost first, and its centre of mass from where their axes meet at angle 0.
123    rotaries: Vec<usize>,
124    offset: [f64; 3],
125    /// Its place is not a sum of the axes' travels (it rides on a rotary, or across a yawing bridge): its share of the
126    /// mass matrix, gravity and the forces of its speed come from its place's Jacobian (`body_point`).
127    general: bool,
128}
129
130/// A gantry's bridge that yaws (`machine.gantry`, effects.gantry_yaw): its yaw is the coordinate `coord`, after the
131/// axes. A body that moves with `axis` and along `across` sits `q_across + shift` from the bridge's centre, so the yaw
132/// moves it along `axis` by that times the yaw angle (small angles).
133struct Gantry {
134    id: &'static str,
135    coord: usize,
136    axis: usize,
137    across: Option<usize>,
138    shift: f64,
139    width: f64,
140    stiffness: f64,
141    damping: f64,
142    tolerance: Option<f64>,
143}
144
145struct Guide {
146    /// Its id, for its loss (`power.<id>`) and its warmth, `axis.<axis id>` for its friction signals.
147    loss_id: &'static str,
148    contact: &'static str,
149    axis: usize,
150    friction: Lugre,
151    carries: Vec<usize>,
152    overhang: Option<crate::netlist::Overhang>,
153}
154
155struct Idler {
156    /// J / r^2 and the belt force its bearing takes, both 0 with effects.idlers off; the belt speed below which that
157    /// fades out.
158    mass: f64,
159    drag: f64,
160    smoothing: f64,
161    radius: f64,
162    speed: Vec<f64>,
163    body: Option<usize>,
164    at: Option<[f64; 3]>,
165}
166
167struct FrameMode {
168    axis: usize,
169    mass: f64,
170    stiffness: f64,
171    damping: f64,
172}
173
174/// The beam under the carriage's axis (effects.beam_vertical_mode, `machine.lean` names the axes): a simple span of `span`
175/// m and bending stiffness `ei`, the carriage `start` m from the left post at 0, whose first vertical mode with the carriage
176/// on it is one more coordinate w, the beam's deflection under the carriage, down. Shape: the span's static deflection
177/// under a point load at the carriage, taken to 1 under it: stiffness k = 1 / `span_compliance` (so that m g / k is the
178/// quasi-static sag, exactly), modal mass M = mu integral of the shape squared (`BeamMode::modal_mass`, 17 mu L / 35 in
179/// the middle), damping c = 2 zeta sqrt(k (m + M)) with m the bodies it carries, so that zeta is the mode's damping ratio. The bodies that move along the beam's axis hang w lower with it (mass
180/// sum m + M), and those that also move along the vertical axis have their speed over ground there as z' - w' (the axis's
181/// own coordinate is relative to the carriage), so a push on the vertical axis drives the beam through -m_z between z and
182/// w. V = 1/2 k(x) w^2 - m g w; T keeps 1/2 M(x) w'^2 and drops what the shape's change with x adds (second order in the
183/// deflection, as in the crate of the T-shaped belt gantry), so on x: 1/2 M' w'^2 - 1/2 k' w^2, on w: -M' x' w'. The belt's
184/// runs ride on w too (`belt`, as the crate's `belt_on_beam`): a run that moves along the vertical axis goes down with
185/// the carriage whole (its speed there z' - w', as the bodies on the vertical axis), a run whose length changes with the
186/// beam's axis alone (from a post's pulley to the carriage) tilts with it, its point at the share xi of the way to the
187/// carriage going down by xi w: a third of its mass in the kinetic energy, half in the weight and the first moment. The
188/// tool hangs w lower: pos_vertical -= w.
189struct BeamMode {
190    /// The coordinate along the beam, and the vertical one.
191    axis: usize,
192    vertical: usize,
193    span: f64,
194    start: f64,
195    ei: f64,
196    mass_per_m: f64,
197    damping_ratio: f64,
198    /// The belt's runs riding on w (kg): [in the kinetic energy, in the weight and first moment, of them moving along
199    /// the vertical axis whole]. Constant: the riding runs keep their length together (checked when built).
200    belt: [f64; 3],
201}
202
203/// How far a belt run rides down with the beam's mode w (`BeamMode::belt`): whole (1) where it moves along the vertical
204/// axis `up`, half on average (its weight's and first moment's share) where its length changes with the beam's axis
205/// alone (tilting from a post's pulley to the carriage), not at all (`None`) otherwise or without its speeds.
206fn riding_share(span: &Span, up: [f64; 3], b: &BeamMode) -> Option<f64> {
207    let rows = span.velocity.as_ref()?;
208    if rows.iter().zip(up).any(|(row, e)| e != 0.0 && row.iter().any(|v| *v != 0.0)) {
209        Some(1.0)
210    } else if span.c[b.axis] != 0.0 && span.c.iter().enumerate().all(|(i, c)| i == b.axis || *c == 0.0) {
211        Some(0.5)
212    } else {
213        None
214    }
215}
216
217/// The belt's runs riding on the beam's mode (`BeamMode::belt`), mu the belt's mass per metre (0 without the runs' mass):
218/// the spans with a speed along the vertical axis whole, those whose length changes with the beam's axis alone tilting
219/// (a third in the kinetic energy, half in the weight). Refused where the riding runs' lengths together change with the
220/// coordinates (their mass on w would then change with the pose).
221fn belt_on_beam(spans: &[Span], dirs: &[[f64; 3]], b: &BeamMode, mu: f64) -> Result<[f64; 3], ConfigError> {
222    let (mut whole, mut tilting) = (vec![0.0; dirs.len() + 1], vec![0.0; dirs.len() + 1]);
223    for span in spans {
224        let Some(share) = riding_share(span, dirs[b.vertical], b) else { continue };
225        let into = if share == 1.0 { &mut whole } else { &mut tilting };
226        into[0] += span.length;
227        span.c.iter().enumerate().for_each(|(i, c)| into[i + 1] += c);
228    }
229    if whole[1..].iter().chain(&tilting[1..]).any(|c| c.abs() > 1e-12) {
230        return Err(ConfigError::Invalid(
231            "machine.span (the belt's runs riding on the beam's mode keep their length together, effects.beam_vertical_mode)"
232                .into(),
233        ));
234    }
235    let (whole, tilting) = (mu * whole[0], mu * tilting[0]);
236    Ok([whole + tilting / 3.0, whole + tilting / 2.0, whole])
237}
238
239impl BeamMode {
240    /// The carriage's distance from the left post at x, kept off the posts where the span's stiffness is infinite.
241    fn at(&self, x: f64) -> f64 {
242        (self.start + x).clamp(1e-3 * self.span, (1.0 - 1e-3) * self.span)
243    }
244    fn stiffness(&self, x: f64) -> f64 {
245        1.0 / sim_components::beam::span_compliance(self.ei, self.span, self.at(x))
246    }
247    /// The modal mass at x: with the load at a (b = L - a) the shape is phi = s (L^2 - b^2 - s^2) / (2 a^2 b) left of it,
248    /// mirrored right of it; with 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:
249    /// 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.
250    fn modal_mass(&self, x: f64) -> f64 {
251        let (a, l) = (self.at(x), self.span);
252        let b = l - a;
253        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;
254        self.mass_per_m
255            * (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)))
256    }
257    /// The beam's own moments of its shape at x, [mu integral of phi, mu integral of s phi] (s from the left post; the
258    /// crate's `Beam::shape_moments`): left of the load int_0^a s (c - s^2) and int_0^a s^2 (c - s^2) over 2 a^2 b
259    /// (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.
260    fn shape_moments(&self, x: f64) -> [f64; 2] {
261        let (a, l, mu) = (self.at(x), self.span, self.mass_per_m);
262        let b = l - a;
263        let (c_left, c_right) = (l * l - b * b, l * l - a * a);
264        let one = |a: f64, c: f64| c * a * a / 2.0 - a.powi(4) / 4.0;
265        let two = |a: f64, c: f64| c * a.powi(3) / 3.0 - a.powi(5) / 5.0;
266        let (left, right) = (2.0 * a * a * b, 2.0 * a * b * b);
267        [
268            mu * (one(a, c_left) / left + one(b, c_right) / right),
269            mu * (two(a, c_left) / left + (l * one(b, c_right) - two(b, c_right)) / right),
270        ]
271    }
272    /// (stiffness k, modal mass M, damping c, dk/dx, dM/dx) at x with the bodies of the mass `carried` on the beam; the
273    /// slopes by central differences over 1e-6 m.
274    fn at_x(&self, x: f64, carried: f64) -> [f64; 5] {
275        let (k, mass) = (self.stiffness(x), self.modal_mass(x));
276        let slope = |f: &dyn Fn(f64) -> f64| (f(x + 1e-6) - f(x - 1e-6)) / 2e-6;
277        [
278            k,
279            mass,
280            2.0 * self.damping_ratio * (k * (mass + carried)).sqrt(),
281            slope(&|x| self.stiffness(x)),
282            slope(&|x| self.modal_mass(x)),
283        ]
284    }
285}
286
287struct Span {
288    key: &'static str,
289    section: usize,
290    length: f64,
291    c: Vec<f64>,
292    /// Its belt's speed over ground along x, y, z per unit speed of each coordinate.
293    velocity: Option<[Vec<f64>; 3]>,
294    /// With a yawing gantry: where it lies across the bridge, l = l0 + b . q (`machine.span` yaw_lever_m, _axes): the
295    /// yaw rate adds l along the bridge's axis to its speed over ground (`span_rows`).
296    lever: Option<(f64, Vec<f64>)>,
297}
298
299/// What a motor drives without a belt: an axis, through its gearbox in the axis's unit (see the module comment).
300struct Direct {
301    axis: usize,
302    /// Where it acts across a yawing gantry's bridge, from its centre (0 elsewhere): its output travels with the yaw too.
303    side: f64,
304    kind: DirectKind,
305    /// Travel per radian of the gearbox's own output (screw, rack): the torque there is the force times it.
306    lever: Option<f64>,
307    /// `ratings.required_life_h` of its motor, where set.
308    required_life: Option<f64>,
309    /// `ratings.shaft_max_radial_load_n` of its motor, where set: what a rack's pinion may load the gearbox's output
310    /// shaft with sideways (`RackPinion::radial_load`).
311    radial_limit: Option<f64>,
312}
313
314enum DirectKind {
315    Screw(BallScrew),
316    Rack(RackPinion),
317    /// The attraction between forcer and magnets and the forcer's mass, which press on the axis's guide.
318    Linear {
319        attraction: f64,
320        forcer: f64,
321    },
322    Rotary(Option<StrainWave>),
323}
324
325/// The motor's config with its `[<layout>]` (`screw`, `rack`, ...) replaced by the file's table at `table`: what the
326/// transmissions' `from_config` reads.
327fn values_config(own: &Config, cfg: &Config, layout: &str, table: &str) -> Result<Config, ConfigError> {
328    let mut all: toml::Table = own.to_text()?.parse().map_err(|_| ConfigError::Parse(table.into()))?;
329    all.insert(layout.into(), cfg.get(table)?.clone());
330    Config::parse(&toml::to_string(&all).map_err(|e| ConfigError::Parse(e.to_string()))?)
331}
332
333/// Per motor its worm stage while effects.gearbox_efficiency counts it. Its gearbox then keeps only what a screw or rack
334/// behind it loses (`extra_efficiency`, 1 for none): `worm::factors` gives the worm's share. With
335/// effects.thermal_feedback its efficiencies follow its temperature (`set_part_temperatures`, `worm::warmed`).
336fn worm_stages(
337    cfg: &Config,
338    net: &Netlist,
339    gears: &mut [Gearbox],
340    extra: &[f64],
341) -> Result<Vec<Option<WormNode>>, ConfigError> {
342    let counts = cfg.bool("effects.gearbox_efficiency")?;
343    Ok(net
344        .motors
345        .iter()
346        .zip(gears.iter_mut().zip(extra))
347        .map(|(d, (gear, extra))| {
348            let worm = d.worm.filter(|_| counts)?;
349            gear.efficiency = *extra;
350            Some(worm)
351        })
352        .collect())
353}
354
355/// With effects.belt_wrap: per motor that drives a pulley the wheels next to it along the belt, the one before it in the
356/// route of the section that ends at it and the one after it in the route of the section that starts at it
357/// (`belt_wraps`); a motor with a screw, rack, linear motor or rotary has no wrap. Refused where a pulley does not end
358/// one route and start another, or it or a wheel next to it has no place (`at_m`).
359fn wrap_neighbours(net: &Netlist, direct: &[Option<Direct>]) -> Result<Vec<(usize, Waypoint, Waypoint)>, ConfigError> {
360    let refuse = |why: String| ConfigError::Invalid(format!("effects.belt_wrap ({why})"));
361    let (placed, name) = (
362        |w: Waypoint| match w {
363            Waypoint::Pulley(kk) => net.motors[kk].at.is_some(),
364            Waypoint::Idler(d) => net.idlers[d].at.is_some(),
365            Waypoint::Body(_) => true,
366        },
367        |w: Waypoint| match w {
368            Waypoint::Pulley(kk) => net.motors[kk].pulley.clone(),
369            Waypoint::Idler(d) => net.idlers[d].id.clone(),
370            Waypoint::Body(b) => net.bodies[b].id.clone(),
371        },
372    );
373    let mut out = Vec::new();
374    for (kk, d) in net.motors.iter().enumerate().filter(|(kk, _)| direct[*kk].is_none()) {
375        let me = Waypoint::Pulley(kk);
376        let ends: Vec<&Vec<Waypoint>> =
377            net.sections.iter().map(|s| &s.route).filter(|r| r.last() == Some(&me)).collect();
378        let starts: Vec<&Vec<Waypoint>> =
379            net.sections.iter().map(|s| &s.route).filter(|r| r.first() == Some(&me)).collect();
380        let before = match ends[..] {
381            [route] => route.iter().rev().nth(1),
382            _ => None,
383        };
384        let after = match starts[..] {
385            [route] => route.get(1),
386            _ => None,
387        };
388        let (Some(&before), Some(&after)) = (before, after) else {
389            return Err(refuse(format!(
390                "pulley {} has to end the route of one section and start the route of another",
391                d.pulley
392            )));
393        };
394        if let Some(w) = [me, before, after].into_iter().find(|w| !placed(*w)) {
395            return Err(refuse(format!("{} has no at_m", name(w))));
396        }
397        out.push((kk, before, after));
398    }
399    Ok(out)
400}
401
402/// An error about `<layout>.<key>` as one about the file's `<table>.<key>`.
403fn renamed(e: ConfigError, layout: &str, table: &str) -> ConfigError {
404    let fix = |d: String| match d.strip_prefix(&format!("{layout}.")) {
405        Some(rest) => format!("{table}.{rest}"),
406        None => d,
407    };
408    match e {
409        ConfigError::Missing(d) => ConfigError::Missing(fix(d)),
410        ConfigError::Type(d) => ConfigError::Type(fix(d)),
411        ConfigError::Invalid(d) => ConfigError::Invalid(fix(d)),
412        ConfigError::Bounded(b, d) => ConfigError::Bounded(b, fix(d)),
413        other => other,
414    }
415}
416
417pub struct ConfigMachine {
418    elastic: bool,
419    axes: Vec<AxisInfo>,
420    motors: Vec<MotorInfo>,
421    /// Per coordinate: gravity along it (pulling towards -) and across it; and gravity itself (0 with effects.gravity off).
422    g_along: Vec<f64>,
423    g: f64,
424    g_across: Vec<f64>,
425    /// The closed belts: each the sections of one belt whose every pulley feeds it on one side and takes it out on
426    /// another, so that the belt's material in them stays what it is. A belt that ends on a pulley (a drum) has
427    /// its material wound on and off, and no such sum.
428    loops: Vec<Vec<usize>>,
429    sections: Vec<Section>,
430    bodies: Vec<Body>,
431    guides: Vec<Guide>,
432    idlers: Vec<Idler>,
433    /// Elastic model: a rotary axis's bearing friction at the output, per axis [Coulomb N m, viscous N m s/rad, smoothing
434    /// rad/s]: it acts behind the gearbox's spring and efficiency (the rigid model puts it at the rotor, c / i + v w / i^2).
435    bearing: Vec<[f64; 3]>,
436    /// Pulley angle per metre of each axis (motors x axes), and its inverse.
437    k: Vec<Vec<f64>>,
438    k_inv: Vec<Vec<f64>>,
439    /// Per motor: pulley radius, unstretched belt fed per radian, pulley inertia with its share of the belt, where the
440    /// 3D view draws the pulley.
441    r: Vec<f64>,
442    r_mat: Vec<f64>,
443    j_pulley: Vec<f64>,
444    pulley_at: Vec<Option<[f64; 3]>>,
445    /// Per motor: the body its pulley rides on, which `pulley_at` is from.
446    pulley_body: Vec<Option<usize>>,
447    /// Per motor: rotor and gearbox input inertia, the gearbox ratio, its gearbox, shaft friction, ripple and brake.
448    j_rotor: Vec<f64>,
449    ratio: Vec<f64>,
450    gears: Vec<Gearbox>,
451    shafts: Vec<ShaftFriction>,
452    ripples: Vec<Ripple>,
453    brakes: Vec<HoldingBrake>,
454    mesh: ToothMesh,
455    belt: Belt,
456    stops: HardStop,
457    /// The cable chain, the axes that drag one, and per axis the speed below which its drag fades out.
458    chain: CableChain,
459    chain_axes: Vec<bool>,
460    chain_fade: Vec<f64>,
461    /// Force on the tool along each axis while the cycle dwells; zero with effects.process_force off.
462    process: Vec<f64>,
463    /// An obstacle's push on the tool (`Machine::set_tool_force`), per axis, held until changed; it acts like the process
464    /// force, whether or not the cycle dwells. Its power is not in the machine's rows: the simulation books it as the
465    /// crash's.
466    tool_push: Vec<f64>,
467    dwelling: bool,
468    /// The netlist has a frame, and with effects.frame_compliance in the elastic model it sways.
469    frame_node: bool,
470    frame: Option<FrameMode>,
471    /// With effects.thermal_feedback: the law per motor (its gearbox's efficiency), and each guide's viscous
472    /// coefficient at the reference temperature.
473    thermal: Option<(Vec<ThermalFeedback>, Vec<f64>)>,
474    /// With effects.belt_tooth_jump (elastic model only): per motor the law and the sections its pulley feeds (+1) and
475    /// takes from (-1); the energy the last step's jumps took, J/s.
476    /// Only the belt motors have one: `jump_motor` is the motor of each jump, `jump_of` the jump of each motor.
477    jumps: Vec<(ToothJump, usize, usize)>,
478    jump_motor: Vec<usize>,
479    jump_of: Vec<Option<usize>>,
480    jump_loss: f64,
481    /// With effects.belt_span_vibration: the belt's mass per metre, and the spans.
482    span_mass: Option<f64>,
483    spans: Vec<Span>,
484    /// The belt's mass per metre where the spans give their speeds over ground (`runs_mass`), else 0; the belt's mass
485    /// lumped on each belt pulley (at its radius).
486    run_mass: f64,
487    lump: f64,
488    payload_attached: bool,
489    brake_engaged: bool,
490    /// Per motor: the axis it drives without a belt, `None` for a belt motor.
491    direct: Vec<Option<Direct>>,
492    /// Per motor: its configured gearbox has ratio 1 (a coupling; a screw or rack behind it changes the ratio), and
493    /// what a screw or rack puts on its efficiency (1 for none), which thermal feedback keeps.
494    coupled: Vec<bool>,
495    extra_efficiency: Vec<f64>,
496    /// Per axis: the inertia a rotary turns with it and its payload's (0 on a straight axis), kg m^2.
497    turned: Vec<(f64, f64)>,
498    /// With effects.belt_wrap: per belt motor the wheels before and after its pulley along the belt (`belt_wraps`).
499    wraps: Vec<(usize, Waypoint, Waypoint)>,
500    /// Per motor and idler: the belt runs round it clockwise (`machine.pulley.clockwise`, `machine.idler.clockwise`).
501    clockwise: (Vec<bool>, Vec<bool>),
502    /// The netlist has a leaning body, and with effects.tool_flex in the elastic model it leans (`machine.lean`).
503    lean_node: Option<LeanNode>,
504    lean: Option<LeanNode>,
505    /// With effects.beam_vertical_mode (elastic model, with a `machine.lean` node naming the axes): the beam's mode.
506    beam: Option<BeamMode>,
507    /// Per motor: its worm stage while effects.gearbox_efficiency counts it (`worm::factors`), at its temperature; and
508    /// as configured, at the reference temperature.
509    worms: Vec<Option<WormNode>>,
510    worms_configured: Vec<Option<WormNode>>,
511    /// Per coordinate (the axes, then a yawing gantry's yaw): the direction a straight axis moves the bodies in the 3D
512    /// view (zero for the others), and the axis a rotary turns them about (zero for the others).
513    dirs: Vec<[f64; 3]>,
514    turn: Vec<[f64; 3]>,
515    /// Per axis the stroke of its joint, where its hard stops are (with a tcp the tool's range is wider).
516    stroke: Vec<f64>,
517    gantry: Option<Gantry>,
518    tcp: Option<TcpNode>,
519    /// A dual-drive gantry's two motors, the first the master (`Machine::gantry_motors`), whether or not its bridge yaws.
520    gantry_motors: Option<[usize; 2]>,
521}
522
523// ----------------------------------------------------------------------------------------------------------------
524// Small dense linear algebra: the systems have as many unknowns as the machine has axes or belt sections.
525
526/// Solves a x = b by Gaussian elimination with partial pivoting; `None` for a singular a.
527fn solve(mut a: Vec<Vec<f64>>, mut b: Vec<f64>) -> Option<Vec<f64>> {
528    let n = b.len();
529    for col in 0..n {
530        let pivot = (col..n).max_by(|&i, &j| a[i][col].abs().total_cmp(&a[j][col].abs()))?;
531        if a[pivot][col].abs() < 1e-300 {
532            return None;
533        }
534        a.swap(col, pivot);
535        b.swap(col, pivot);
536        for row in col + 1..n {
537            let factor = a[row][col] / a[col][col];
538            if factor != 0.0 {
539                for k in col..n {
540                    a[row][k] -= factor * a[col][k];
541                }
542                b[row] -= factor * b[col];
543            }
544        }
545    }
546    let mut x = vec![0.0; n];
547    for row in (0..n).rev() {
548        let sum: f64 = (row + 1..n).map(|k| a[row][k] * x[k]).sum();
549        x[row] = (b[row] - sum) / a[row][row];
550    }
551    Some(x)
552}
553
554/// The least-squares solution of a x = b (a: rows x cols), the one of least norm where it is not unique.
555fn lstsq(a: &[Vec<f64>], b: &[f64]) -> Option<Vec<f64>> {
556    let (rows, cols) = (a.len(), a.first().map_or(0, Vec::len));
557    if rows >= cols {
558        let ata = (0..cols).map(|i| (0..cols).map(|j| (0..rows).map(|r| a[r][i] * a[r][j]).sum()).collect()).collect();
559        let atb = (0..cols).map(|i| (0..rows).map(|r| a[r][i] * b[r]).sum()).collect();
560        solve(ata, atb)
561    } else {
562        let aat = (0..rows).map(|i| (0..rows).map(|j| (0..cols).map(|c| a[i][c] * a[j][c]).sum()).collect()).collect();
563        let y = solve(aat, b.to_vec())?;
564        Some((0..cols).map(|c| (0..rows).map(|r| a[r][c] * y[r]).sum()).collect())
565    }
566}
567
568fn dot(a: &[f64], b: &[f64]) -> f64 {
569    a.iter().zip(b).map(|(x, y)| x * y).sum()
570}
571
572/// `v` turned by `angle` about the unit axis `u` (Rodrigues): v cos + (u x v) sin + u (u . v) (1 - cos).
573fn rotate(u: [f64; 3], angle: f64, v: [f64; 3]) -> [f64; 3] {
574    let (s, c) = angle.sin_cos();
575    let cross = cross(u, v);
576    let along = dot(&u, &v) * (1.0 - c);
577    [0, 1, 2].map(|k| v[k] * c + cross[k] * s + u[k] * along)
578}
579
580fn cross(u: [f64; 3], v: [f64; 3]) -> [f64; 3] {
581    [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]]
582}
583
584/// The eigenvalues and eigenvectors (columns) of a symmetric matrix, by cyclic Jacobi rotations.
585fn symmetric_eigen(mut a: Vec<Vec<f64>>) -> (Vec<f64>, Vec<Vec<f64>>) {
586    let d = a.len();
587    let mut v: Vec<Vec<f64>> = (0..d).map(|i| (0..d).map(|j| if i == j { 1.0 } else { 0.0 }).collect()).collect();
588    let scale: f64 = a.iter().flatten().map(|x| x * x).sum();
589    for _ in 0..100 {
590        let off: f64 = (0..d)
591            .flat_map(|i| (0..d).filter(move |&j| j != i).map(move |j| (i, j)))
592            .map(|(i, j)| a[i][j] * a[i][j])
593            .sum();
594        if off <= 1e-30 * scale {
595            break;
596        }
597        for p in 0..d {
598            for q in p + 1..d {
599                if a[p][q] == 0.0 {
600                    continue;
601                }
602                let theta = (a[q][q] - a[p][p]) / (2.0 * a[p][q]);
603                let t = theta.signum() / (theta.abs() + (theta * theta + 1.0).sqrt());
604                let c = 1.0 / (t * t + 1.0).sqrt();
605                let s = t * c;
606                for k in 0..d {
607                    let (kp, kq) = (a[k][p], a[k][q]);
608                    (a[k][p], a[k][q]) = (c * kp - s * kq, s * kp + c * kq);
609                }
610                for k in 0..d {
611                    let (pk, qk) = (a[p][k], a[q][k]);
612                    (a[p][k], a[q][k]) = (c * pk - s * qk, s * pk + c * qk);
613                }
614                for row in v.iter_mut() {
615                    let (kp, kq) = (row[p], row[q]);
616                    (row[p], row[q]) = (c * kp - s * kq, s * kp + c * kq);
617                }
618            }
619        }
620    }
621    ((0..d).map(|i| a[i][i]).collect(), v)
622}
623
624/// The lowest mode of K x = w^2 M x (M symmetric positive definite, K symmetric) whose w^2 is above zero: (w^2, x).
625fn lowest_mode(m: &[Vec<f64>], k: &[Vec<f64>]) -> Option<(f64, Vec<f64>)> {
626    every_mode(m, k).into_iter().next()
627}
628
629/// Every mode of K x = w^2 M x whose w^2 is above zero (1e-9 of the largest), lowest first: (w^2, x), x normalised to
630/// x^T M x = 1. Through the Cholesky factor M = L L^T: L^-1 K L^-T y = w^2 y, x = L^-T y. Empty where M is not
631/// positive definite.
632fn every_mode(m: &[Vec<f64>], k: &[Vec<f64>]) -> Vec<(f64, Vec<f64>)> {
633    let d = m.len();
634    let mut l = vec![vec![0.0; d]; d];
635    for i in 0..d {
636        for j in 0..=i {
637            let sum = m[i][j] - (0..j).map(|p| l[i][p] * l[j][p]).sum::<f64>();
638            if i == j {
639                l[i][i] = if sum > 0.0 { sum.sqrt() } else { return Vec::new() };
640            } else {
641                l[i][j] = sum / l[j][j];
642            }
643        }
644    }
645    let lower = |b: &[f64]| {
646        let mut x = vec![0.0; d];
647        for i in 0..d {
648            x[i] = (b[i] - (0..i).map(|p| l[i][p] * x[p]).sum::<f64>()) / l[i][i];
649        }
650        x
651    };
652    // X = L^-1 K, column by column; A = L^-1 X^T.
653    let x: Vec<Vec<f64>> = (0..d).map(|c| lower(&(0..d).map(|r| k[r][c]).collect::<Vec<_>>())).collect();
654    // Column c of L^-1 X^T is L^-1 times row c of X (x[r][c] over r), not its column c.
655    let a: Vec<Vec<f64>> = (0..d).map(|c| lower(&(0..d).map(|r| x[r][c]).collect::<Vec<_>>())).collect();
656    let a: Vec<Vec<f64>> = (0..d).map(|i| (0..d).map(|j| 0.5 * (a[i][j] + a[j][i])).collect()).collect();
657    let (values, vectors) = symmetric_eigen(a);
658    let largest = values.iter().fold(0.0f64, |m, v| m.max(*v));
659    let mut found: Vec<(usize, f64)> =
660        values.iter().copied().enumerate().filter(|(_, v)| *v > 1e-9 * largest).collect();
661    found.sort_by(|a, b| a.1.total_cmp(&b.1));
662    found
663        .into_iter()
664        .map(|(index, w2)| {
665            // x = L^-T y.
666            let mut out = vec![0.0; d];
667            for i in (0..d).rev() {
668                out[i] = (vectors[i][index] - (i + 1..d).map(|p| l[p][i] * out[p]).sum::<f64>()) / l[i][i];
669            }
670            (w2, out)
671        })
672        .collect()
673}
674
675/// Generalised velocity of a rigid solve: accelerations, guide forces and states' rates, per motor the torque at the
676/// gearbox output and the torque that goes into it before its loss.
677#[derive(Clone)]
678struct Rigid {
679    acc: Vec<f64>,
680    rates: Vec<f64>,
681    out: Vec<f64>,
682    into: Vec<f64>,
683}
684
685/// The closed belts among the sections (see `ConfigMachine::loops`): sections that share a pulley are one belt.
686fn closed_belts(sections: &[Section], motors: usize) -> Vec<Vec<usize>> {
687    let mut belt: Vec<usize> = (0..sections.len()).collect();
688    let root = |belt: &[usize], mut s: usize| {
689        while belt[s] != s {
690            s = belt[s];
691        }
692        s
693    };
694    for k in 0..motors {
695        let at: Vec<usize> = (0..sections.len()).filter(|&s| sections[s].f[k] != 0.0).collect();
696        for pair in at.windows(2) {
697            let (a, b) = (root(&belt, pair[0]), root(&belt, pair[1]));
698            belt[a] = b;
699        }
700    }
701    let mut out: Vec<Vec<usize>> = Vec::new();
702    for s in 0..sections.len() {
703        let r = root(&belt, s);
704        match out.iter_mut().find(|l| root(&belt, l[0]) == r) {
705            Some(l) => l.push(s),
706            None => out.push(vec![s]),
707        }
708    }
709    out.retain(|l| (0..motors).all(|k| l.iter().map(|&s| sections[s].f[k]).sum::<f64>() == 0.0));
710    out
711}
712
713impl ConfigMachine {
714    pub fn new(cfg: &Config, net: &Netlist) -> Result<Self, ConfigError> {
715        let (n, m) = (net.axes.len(), net.motors.len());
716        let elastic = cfg.bool("effects.belt_stretch")?;
717        let gravity = if cfg.bool("effects.gravity")? { G } else { 0.0 };
718        let belt = Belt::from_config(cfg)?;
719        // Each motor's drive train from its own config; a worm stage's ratio is its gearbox's.
720        let mut own: Vec<Config> = net.motors.iter().map(|d| motor_config(cfg, &d.id)).collect::<Result<_, _>>()?;
721        for (own, d) in own.iter_mut().zip(&net.motors) {
722            if let Some(worm) = d.worm {
723                own.set("gearbox.ratio", toml::Value::Float(worm.ratio))?;
724            }
725        }
726        let own = own;
727        let mut gears = own.iter().map(Gearbox::from_config).collect::<Result<Vec<_>, _>>()?;
728        let mut j_rotor = own
729            .iter()
730            .map(|c| Ok(c.positive("motor.rotor_inertia_kgm2")? + c.non_negative("gearbox.inertia_at_input_kgm2")?))
731            .collect::<Result<Vec<f64>, ConfigError>>()?;
732        let mut shafts = own.iter().map(ShaftFriction::from_config).collect::<Result<Vec<_>, _>>()?;
733        let mut ripples = own.iter().map(Ripple::from_config).collect::<Result<Vec<_>, _>>()?;
734        let mut brakes =
735            own.iter().zip(&j_rotor).map(|(c, j)| HoldingBrake::from_config(c, *j)).collect::<Result<Vec<_>, _>>()?;
736        let mut coupled: Vec<bool> = gears.iter().map(Gearbox::is_coupling).collect();
737        let mut extra_efficiency = vec![1.0; m];
738        // A screw, rack, linear motor or rotary: the drive train as the registered one-axis machines build it, the converter behind the
739        // gearbox, which is then one in the axis's unit (see the module comment).
740        let guide_friction = cfg.bool("effects.guide_friction")?;
741        let mut direct = Vec::with_capacity(m);
742        let mut bearing = vec![[0.0; 3]; n];
743        for (kk, d) in net.motors.iter().enumerate() {
744            let Some(axis) = d.axis else {
745                direct.push(None);
746                continue;
747            };
748            let own = &own[kk];
749            let stroke = net.axes[axis].stroke;
750            let free = ShaftFriction::NONE;
751            let mut joint = RotaryJoint::with(own, free, HardStop { stiffness: 0.0, damping: 0.0 }, (0.0, stroke))?;
752            let ratio = joint.ratio();
753            // What the screw or rack moves at least: the bodies on its axis without their payload, shared with the
754            // other drives of that axis (a gantry's). The mesh friction's bristle is capped by the lighter of it and the
755            // rotor (`Converter::apply_to`); with no body on it, the rotor's alone.
756            let on_axis: f64 = net.bodies.iter().filter(|b| b.axes.get(axis) == Some(&true)).map(|b| b.mass).sum();
757            let output = match on_axis / net.motors.iter().filter(|o| o.axis == Some(axis)).count() as f64 {
758                x if x > 0.0 => x,
759                _ => f64::INFINITY,
760            };
761            let (kind, lever) = match &d.transmission {
762                Transmission::Screw { values } => {
763                    let screw = BallScrew::from_config(&values_config(own, cfg, "screw", values)?)
764                        .map_err(|e| renamed(e, "screw", values))?;
765                    if screw.length < stroke {
766                        return Err(ConfigError::Invalid(format!(
767                            "{values}.length_m (shorter than the stroke of axis {})",
768                            net.axes[axis].id
769                        )));
770                    }
771                    screw.converter(screw.softest_position()).apply_to(own, &mut joint, output)?;
772                    // The nut's preload drags as friction at the screw, at the rotor through the gearbox.
773                    if guide_friction {
774                        joint.shaft.coulomb += screw.preload_torque() / ratio;
775                    }
776                    let lever = 1.0 / screw.ratio();
777                    (DirectKind::Screw(screw), Some(lever))
778                }
779                Transmission::Rack { values } => {
780                    let rack = RackPinion::from_config(&values_config(own, cfg, "rack", values)?)
781                        .map_err(|e| renamed(e, "rack", values))?;
782                    rack.converter().apply_to(own, &mut joint, output)?;
783                    let lever = rack.radius();
784                    (DirectKind::Rack(rack), Some(lever))
785                }
786                Transmission::LinearMotor { values } => {
787                    let view = values_config(own, cfg, "linear_motor", values)?;
788                    let motor = LinearMotor::from_config(&view).map_err(|e| renamed(e, "linear_motor", values))?;
789                    if ratio != 1.0 {
790                        let own_ratio = format!("gearbox.{}.ratio", d.id);
791                        let at = if cfg.get(&own_ratio).is_ok() { own_ratio } else { "gearbox.ratio".into() };
792                        return Err(ConfigError::Invalid(format!(
793                            "{at} (motor {} is a linear motor: its gearbox is the forcer's mounting, ratio 1)",
794                            d.id
795                        )));
796                    }
797                    joint.ripple.cogging_order = motor.cogging_order();
798                    // The attraction presses the guides: its friction, as the registered one-axis machines add it.
799                    if guide_friction {
800                        joint.shaft.coulomb += view
801                            .non_negative("linear_motor.guide_friction_coefficient")
802                            .map_err(|e| renamed(e, "linear_motor", values))?
803                            * motor.attraction;
804                    }
805                    (DirectKind::Linear { attraction: motor.attraction, forcer: joint.rotor_inertia }, None)
806                }
807                Transmission::Rotary { strain_wave, bearing: [coulomb, viscous], .. } => {
808                    // The table's bearing drags at the axis. The rigid model has it at the rotor, i times as fast, as
809                    // c / i + v w / i^2; the elastic one at the output, behind the gearbox's spring and efficiency
810                    // (the smoothing speed of the rotor's friction over i).
811                    if guide_friction && elastic {
812                        let smoothing = ShaftFriction::from_config(own)?.smoothing / ratio.abs();
813                        for (b, x) in bearing[axis].iter_mut().zip([*coulomb, *viscous, smoothing]) {
814                            *b += x;
815                        }
816                    } else if guide_friction {
817                        joint.shaft.coulomb += coulomb / ratio;
818                        joint.shaft.viscous += viscous / (ratio * ratio);
819                    }
820                    let read = |t: &String| {
821                        StrainWave::from_config(&values_config(own, cfg, "strain_wave", t)?)
822                            .map_err(|e| renamed(e, "strain_wave", t))
823                    };
824                    (DirectKind::Rotary(strain_wave.as_ref().map(read).transpose()?), None)
825                }
826                Transmission::Belt => return Err(ConfigError::Invalid(format!("machine.motor[{}]", d.id))),
827            };
828            let RotaryJoint {
829                gearbox,
830                rotor_inertia,
831                shaft,
832                ripple,
833                brake,
834                extra_efficiency: extra,
835                coupled: coupling,
836                ..
837            } = joint;
838            (gears[kk], j_rotor[kk], shafts[kk], ripples[kk], brakes[kk]) =
839                (gearbox, rotor_inertia, shaft, ripple, brake);
840            (coupled[kk], extra_efficiency[kk]) = (coupling, extra);
841            let side = net.gantry.as_ref().and_then(|g| g.drives[kk]).unwrap_or(0.0);
842            direct.push(Some(Direct {
843                axis,
844                side,
845                kind,
846                lever,
847                required_life: own.f64("ratings.required_life_h").ok(),
848                radial_limit: own.f64("ratings.shaft_max_radial_load_n").ok(),
849            }));
850        }
851        let worms = worm_stages(cfg, net, &mut gears, &extra_efficiency)?;
852        // With a tcp the tool's range is where its tip can be whatever the head's angles: the strokes shifted by the tool
853        // turned by the head, per direction by the most and the least of it over the rotaries' strokes (sampled, 13
854        // angles each). Beyond that a pose may still be reachable at some angles (`unreachable` judges it).
855        let span = net.tcp.as_ref().map(|t| {
856            let mut span = [[f64::INFINITY, f64::NEG_INFINITY]; 3];
857            let samples = 13usize;
858            for k in 0..samples.pow(t.rotaries.len() as u32) {
859                let mut v = t.tool;
860                for (j, &r) in t.rotaries.iter().enumerate().rev() {
861                    let (a, step) = (&net.axes[r], (k / samples.pow(j as u32)) % samples);
862                    let turn = [a.incline_deg.to_radians().sin(), 0.0, a.incline_deg.to_radians().cos()];
863                    v = rotate(turn, a.stroke * step as f64 / (samples - 1) as f64, v);
864                }
865                for (s, x) in span.iter_mut().zip(v) {
866                    *s = [s[0].min(x), s[1].max(x)];
867                }
868            }
869            span
870        });
871        let axes = net
872            .axes
873            .iter()
874            .enumerate()
875            .map(|(i, a)| -> Result<AxisInfo, ConfigError> {
876                // A rotary axis's limits are in rad: max_velocity_rad_s.
877                let unit = if a.rotary { "rad" } else { "m" };
878                let limit = |what: &str, rate: &str| cfg.positive(&format!("axis.{}.max_{what}_{unit}_{rate}", a.id));
879                let (min, max) = match net.tcp.as_ref().and_then(|t| Some((t, t.axes.iter().position(|&x| x == i)?))) {
880                    None => (0.0, a.stroke),
881                    Some((t, k)) if t.table.is_empty() => {
882                        let [low, high] = span.map_or([0.0; 2], |s| s[k]);
883                        (high, a.stroke + low)
884                    }
885                    // On a turning table: the workpiece within the round the table can turn under the tool, the box
886                    // about its pivot as wide as the pivot's least distance from an end of X's and Y's strokes, which the
887                    // head's tool offset shifts as in the case above: the tip always reaches [high, stroke + low] of the span.
888                    Some((t, k)) => {
889                        let reach = |j: usize| {
890                            let [low, high] = span.map_or([0.0; 2], |s| s[j]);
891                            (high, net.axes[t.axes[j]].stroke + low)
892                        };
893                        // A direction every table rotary turns about (Z under a C table alone) is not turned: its own reach.
894                        let about = |r: usize| net.axes[r].incline_deg.to_radians().sin_cos();
895                        let unturned = t.table.iter().all(|&r| {
896                            let (s, c) = about(r);
897                            [s, 0.0, c][k].abs() > 1.0 - 1e-12
898                        });
899                        let half = (0..2)
900                            .map(|j| (t.pivot[j] - reach(j).0).min(reach(j).1 - t.pivot[j]))
901                            .fold(f64::INFINITY, f64::min)
902                            .max(0.0);
903                        if unturned { reach(k) } else { (t.pivot[k] - half, t.pivot[k] + half) }
904                    }
905                };
906                Ok(AxisInfo {
907                    id: intern(&a.id),
908                    key: intern(&a.key),
909                    unit,
910                    min,
911                    max,
912                    max_vel: limit("velocity", "s")?,
913                    max_acc: limit("acceleration", "s2")?,
914                    max_jerk: limit("jerk", "s3")?,
915                })
916            })
917            .collect::<Result<Vec<_>, _>>()?;
918        let incline: Vec<f64> = net.axes.iter().map(|a| a.incline_deg.to_radians()).collect();
919        let teeth = belt.tooth_length;
920        let mut sections: Vec<Section> = net
921            .sections
922            .iter()
923            .map(|s| {
924                let length = s.length + teeth * s.pulleys.iter().filter(|f| **f != 0.0).count() as f64;
925                Section {
926                    id: intern(&format!("belt.{}", s.id)),
927                    key: intern(&s.key),
928                    length,
929                    bare: s.length,
930                    c: s.axes.clone(),
931                    f: s.pulleys.clone(),
932                    mat0: belt.rest_length(length),
933                    route: s.route.clone(),
934                    plane: s.plane,
935                }
936            })
937            .collect();
938        let r: Vec<f64> = net.motors.iter().map(|d| d.radius).collect();
939        // The rigid kinematics: F diag(r) K = C, over the motors that drive belts (the columns of F).
940        let belted: Vec<usize> = (0..m).filter(|&kk| direct[kk].is_none()).collect();
941        let fr: Vec<Vec<f64>> = sections.iter().map(|s| belted.iter().map(|&k| s.f[k] * r[k]).collect()).collect();
942        // A gantry's yaw is a coordinate after the axes (effects.gantry_yaw); the sections that pull the bridge's ends get
943        // longer with it.
944        let yaw_on = match cfg.bool("effects.gantry_yaw") {
945            Err(ConfigError::Missing(_)) => false,
946            other => other?,
947        };
948        let gantry_node = net.gantry.as_ref().filter(|_| yaw_on);
949        let mut columns: Vec<Vec<f64>> = (0..n).map(|i| sections.iter().map(|s| s.c[i]).collect()).collect();
950        columns.extend(gantry_node.map(|g| g.sections.clone()));
951        let mut yaw = gantry_node.is_some();
952        let mut k = vec![vec![0.0; columns.len()]; m];
953        // Without belt sections (every motor drives its axis without a belt) there is nothing to solve.
954        for (i, column) in columns.iter().enumerate().filter(|_| !sections.is_empty()) {
955            let solved = lstsq(&fr, column)
956                .ok_or_else(|| ConfigError::Invalid("machine.section (the pulleys do not set every section)".into()))?;
957            let wrong = (0..sections.len()).find(|&s| {
958                let follows: f64 = fr[s].iter().zip(&solved).map(|(a, b)| a * b).sum();
959                (follows - column[s]).abs() > 1e-9 * (1.0 + column[s].abs())
960            });
961            match wrong {
962                Some(s) if i < n => {
963                    return Err(ConfigError::Invalid(format!(
964                        "machine.section[{}].axes (the belt cannot keep its length)",
965                        &sections[s].id["belt.".len()..]
966                    )));
967                }
968                // The belts hold the yaw where they cannot keep their length with it (a CoreXY's): the rigid model has
969                // none, the elastic one takes their stretch.
970                Some(_) if !elastic => yaw = false,
971                _ => {}
972            }
973            for (j, &kk) in belted.iter().enumerate() {
974                k[kk][i] = solved[j];
975            }
976        }
977        if !yaw {
978            k.iter_mut().for_each(|row| row.truncate(n));
979        }
980        let d = n + usize::from(yaw);
981        // The yaw coordinate has no bearing of its own; the per-coordinate tables are indexed up to d.
982        bearing.resize(d, [0.0; 3]);
983        if let Some(g) = gantry_node.filter(|_| yaw) {
984            sections.iter_mut().zip(&g.sections).for_each(|(s, c)| s.c.push(*c));
985        }
986        // A motor that drives an axis without a belt turns its "pulley" (the gearbox output, in the axis's unit) with it,
987        // and at a yawing gantry's side with the yaw too.
988        for (row, x) in k.iter_mut().zip(&direct) {
989            if let Some(x) = x {
990                *row = (0..d)
991                    .map(|i| {
992                        if i == x.axis {
993                            1.0
994                        } else if i == n {
995                            x.side
996                        } else {
997                            0.0
998                        }
999                    })
1000                    .collect();
1001            }
1002        }
1003        // The coordinates the motors set: all of them, or the axes where a gantry's yaw is left to its spring. Two
1004        // drives on a gantry whose yaw is off share its axis: the least-squares inverse halves its force between them.
1005        let set: Vec<usize> = if m >= d { (0..d).collect() } else { (0..n).collect() };
1006        if set.len() > m {
1007            return Err(ConfigError::Invalid("machine.motor (the motors do not set every axis)".into()));
1008        }
1009        let k_set: Vec<Vec<f64>> = k.iter().map(|row| set.iter().map(|&i| row[i]).collect()).collect();
1010        let mut k_inv = vec![vec![0.0; m]; d];
1011        for kk in 0..m {
1012            let unit: Vec<f64> = (0..m).map(|j| if j == kk { 1.0 } else { 0.0 }).collect();
1013            let column = if m == set.len() { solve(k_set.clone(), unit) } else { lstsq(&k_set, &unit) }
1014                .ok_or_else(|| ConfigError::Invalid("machine.motor (the motors do not set every axis)".into()))?;
1015            for (j, &i) in set.iter().enumerate() {
1016                k_inv[i][kk] = column[j];
1017            }
1018        }
1019        // The belt runs at pulley surface speed: its mass is shared out on the driven pulleys.
1020        let belt_motors = direct.iter().filter(|d| d.is_none()).count().max(1);
1021        let belt_mass = belt.mass_per_m * sections.iter().map(|s| s.bare).sum::<f64>() / belt_motors as f64;
1022        let payload_on = cfg.bool("effects.payload")?;
1023        let mut turned = vec![(0.0, 0.0); d];
1024        // The bridge's own yaw inertia is the yaw's "mass".
1025        if let Some(g) = gantry_node.filter(|_| yaw) {
1026            turned[n] = (g.inertia, 0.0);
1027        }
1028        for d in &net.motors {
1029            if let (Transmission::Rotary { inertia, payload, .. }, Some(axis)) = (&d.transmission, d.axis) {
1030                turned[axis] = (*inertia, if payload_on { *payload } else { 0.0 });
1031            }
1032        }
1033        let guides = net
1034            .guides
1035            .iter()
1036            .map(|g| -> Result<Guide, ConfigError> {
1037                Ok(Guide {
1038                    loss_id: intern(&g.id),
1039                    contact: intern(&format!("axis.{}", net.axes[g.axis].id)),
1040                    axis: g.axis,
1041                    friction: Lugre::from_config(cfg, &g.friction)?,
1042                    carries: g.carries.clone(),
1043                    overhang: g.overhang.as_ref().map(|o| crate::netlist::Overhang { ..*o }),
1044                })
1045            })
1046            .collect::<Result<Vec<_>, _>>()?;
1047        // A file written before machine files had these effects may leave their switches out: off.
1048        let on = |effect: &str| match cfg.bool(&format!("effects.{effect}")) {
1049            Err(ConfigError::Missing(_)) => Ok(false),
1050            other => other,
1051        };
1052        let idlers_on = on("idlers")?;
1053        // A vector per axis with zeros for the yaw.
1054        let pad = |v: &[f64]| -> Vec<f64> { (0..d).map(|i| v.get(i).copied().unwrap_or(0.0)).collect() };
1055        let smoothing = ShaftFriction::from_config(cfg)?.smoothing;
1056        let idlers = net
1057            .idlers
1058            .iter()
1059            .map(|d| Idler {
1060                mass: if idlers_on { d.inertia / (d.radius * d.radius) } else { 0.0 },
1061                drag: if idlers_on { d.friction / d.radius } else { 0.0 },
1062                smoothing: smoothing * d.radius,
1063                radius: d.radius,
1064                speed: pad(&d.speed),
1065                body: d.body,
1066                at: d.at,
1067            })
1068            .collect();
1069        let mut chain_axes: Vec<bool> = net.axes.iter().map(|a| a.cable_chain).collect();
1070        chain_axes.resize(d, false);
1071        let chain = if chain_axes.contains(&true) {
1072            CableChain::from_config(cfg)?
1073        } else {
1074            CableChain { mass_per_m: 0.0, length0: 0.0, drag: 0.0 }
1075        };
1076        // shortcut: an axis without a guide fades its chain's drag out below 1 cm/s; give it a guide to set it.
1077        let chain_fade =
1078            (0..d).map(|i| guides.iter().find(|g| g.axis == i).map_or(0.01, |g| g.friction.stribeck_v)).collect();
1079        let process = if on("process_force")? {
1080            pad(&net
1081                .axes
1082                .iter()
1083                .map(|a| cfg.f64(&format!("process.force_{}_n", a.id)))
1084                .collect::<Result<Vec<_>, _>>()?)
1085        } else {
1086            vec![0.0; d]
1087        };
1088        let frame = match (&net.frame, on("frame_compliance")? && elastic) {
1089            (Some(f), true) => {
1090                Some(FrameMode { axis: f.axis, mass: f.mass, stiffness: f.stiffness, damping: f.damping })
1091            }
1092            (None, true) => return Err(ConfigError::Missing("machine.frame (effects.frame_compliance)".into())),
1093            (_, false) => None,
1094        };
1095        let thermal = own
1096            .iter()
1097            .map(ThermalFeedback::from_config)
1098            .collect::<Result<Option<Vec<_>>, _>>()?
1099            .map(|laws| (laws, guides.iter().map(|g| g.friction.viscous).collect()));
1100        // The jump states are laid out for the belt motors only (a screw, rack, linear motor or rotary has no tooth to jump).
1101        let mut jumps = Vec::new();
1102        let mut jump_motor = Vec::new();
1103        let mut jump_of = vec![None; m];
1104        if elastic && on("belt_tooth_jump")? {
1105            for (kk, d) in net.motors.iter().enumerate().filter(|(kk, _)| direct[*kk].is_none()) {
1106                let side = |f: f64| -> Result<usize, ConfigError> {
1107                    let found: Vec<usize> = (0..sections.len()).filter(|&s| sections[s].f[kk] == f).collect();
1108                    match found[..] {
1109                        [s] => Ok(s),
1110                        _ => Err(ConfigError::Invalid(format!(
1111                            "effects.belt_tooth_jump (pulley {} has no section on each side)",
1112                            d.pulley
1113                        ))),
1114                    }
1115                };
1116                let law = ToothJump::from_config(&own[kk], d.radius, belt_mass)?
1117                    .ok_or_else(|| ConfigError::Invalid("effects.belt_tooth_jump".into()))?;
1118                jump_of[kk] = Some(jumps.len());
1119                jump_motor.push(kk);
1120                jumps.push((law, side(1.0)?, side(-1.0)?));
1121            }
1122        }
1123        let span_mass = if on("belt_span_vibration")? {
1124            if net.spans.is_empty() {
1125                return Err(ConfigError::Missing("machine.span (effects.belt_span_vibration)".into()));
1126            }
1127            Some(cfg.positive("belt.mass_kg_m")?)
1128        } else {
1129            None
1130        };
1131        let spans: Vec<Span> = net
1132            .spans
1133            .iter()
1134            .map(|s| Span {
1135                key: intern(&format!("belt-span-{}", s.id)),
1136                section: s.section,
1137                length: s.length,
1138                c: pad(&s.axes),
1139                velocity: s.velocity.as_ref().map(|v| [pad(&v[0]), pad(&v[1]), pad(&v[2])]),
1140                lever: s.yaw_lever.as_ref().map(|(l, b)| (*l, pad(b))),
1141            })
1142            .collect();
1143        // The belt run by run (`runs_mass`): every span with its speed over ground, and the spans the whole belt.
1144        let runs = spans.iter().any(|s| s.velocity.is_some());
1145        if runs {
1146            let total =
1147                |length: f64, c: &[f64]| -> Vec<f64> { std::iter::once(length).chain(c.iter().copied()).collect() };
1148            let sum = |rows: Vec<Vec<f64>>| -> Vec<f64> {
1149                rows.iter().fold(vec![0.0; d + 1], |a, r| a.iter().zip(r).map(|(a, b)| a + b).collect())
1150            };
1151            let of_spans = sum(spans.iter().map(|s| total(s.length, &s.c)).collect());
1152            let of_sections = sum(sections.iter().map(|s| total(s.bare, &s.c)).collect());
1153            let whole = of_spans.iter().zip(&of_sections).all(|(a, b)| (a - b).abs() <= 1e-9 * of_sections[0]);
1154            if spans.iter().any(|s| s.velocity.is_none()) || !whole {
1155                return Err(ConfigError::Invalid(
1156                    "machine.span (with velocity_x, _y or _z every span needs one, and the spans together are the whole belt)"
1157                        .into(),
1158                ));
1159            }
1160        }
1161        let wraps = if on("belt_wrap")? { wrap_neighbours(net, &direct)? } else { Vec::new() };
1162        let lean = match (net.lean, on("tool_flex")?) {
1163            (None, true) => return Err(ConfigError::Missing("machine.lean (effects.tool_flex)".into())),
1164            // As in the machine crate with a leaning axis: the lean is a mode of the elastic model.
1165            (lean, flex) => lean.filter(|_| flex && elastic),
1166        };
1167        // A belt that moves the lean's lever axis holds the lean back by its vertical runs (`lean_runs`), which the spans
1168        // give: without one the geometric stiffness would silently be missing.
1169        if let Some(z) = lean.as_ref().and_then(|l| l.lever_axis) {
1170            let belted = sections.iter().any(|s| s.c.get(z).is_some_and(|c| *c != 0.0));
1171            let vertical = |s: &SpanNode| {
1172                s.axes.get(z).is_some_and(|c| c.abs() == 1.0)
1173                    && s.axes.iter().enumerate().all(|(i, c)| i == z || *c == 0.0)
1174            };
1175            if belted && !net.spans.iter().any(vertical) {
1176                return Err(ConfigError::Missing(format!(
1177                    "machine.span (the belt's runs along {} that hold the leaning body back, effects.tool_flex)",
1178                    net.axes[z].id
1179                )));
1180            }
1181        }
1182        let mut beam = if elastic && on("beam_vertical_mode")? {
1183            let lean =
1184                net.lean.ok_or_else(|| ConfigError::Missing("machine.lean (effects.beam_vertical_mode)".into()))?;
1185            let vertical = lean
1186                .lever_axis
1187                .ok_or_else(|| ConfigError::Missing("machine.lean.lever_axis (effects.beam_vertical_mode)".into()))?;
1188            Some(BeamMode {
1189                axis: lean.axis,
1190                vertical,
1191                span: cfg.positive("beam.span_m")?,
1192                start: cfg.non_negative("beam.carriage_at_zero_m")?,
1193                ei: cfg.positive("beam.bending_stiffness_nm2")?,
1194                mass_per_m: cfg.positive("beam.mass_kg_m")?,
1195                damping_ratio: cfg.non_negative("beam.damping_ratio")?,
1196                belt: [0.0; 3],
1197            })
1198        } else {
1199            None
1200        };
1201        let gantry = gantry_node.filter(|_| yaw).map(|g| Gantry {
1202            id: intern(&g.id),
1203            coord: n,
1204            axis: g.axis,
1205            across: g.across,
1206            shift: g.across_shift,
1207            width: g.width,
1208            stiffness: g.stiffness,
1209            damping: g.damping,
1210            tolerance: g.tolerance,
1211        });
1212        // Rotary axes have no weight along or across them: what rides on them weighs through its place (`body_point`).
1213        let straight = |i: usize, v: f64| if i < n && !net.axes[i].rotary { v } else { 0.0 };
1214        let dirs: Vec<[f64; 3]> = (0..d)
1215            .map(|i| {
1216                let (up, across) = incline.get(i).map_or((0.0, 0.0), |a| a.sin_cos());
1217                let (up, across) = (straight(i, up), straight(i, across));
1218                if i == 0 { [across, 0.0, up] } else { [0.0, across, up] }
1219            })
1220            .collect();
1221        if let Some(b) = beam.as_mut() {
1222            b.belt = belt_on_beam(&spans, &dirs, b, if runs { belt.mass_per_m } else { 0.0 })?;
1223        }
1224        let turn = (0..d)
1225            .map(|i| match net.axes.get(i) {
1226                Some(a) if a.rotary => [incline[i].sin(), 0.0, incline[i].cos()],
1227                _ => [0.0; 3],
1228            })
1229            .collect();
1230        let bodies = net
1231            .bodies
1232            .iter()
1233            .map(|b| {
1234                let mut axes = b.axes.clone();
1235                axes.resize(d, false);
1236                let across = gantry.as_ref().is_some_and(|g| axes[g.axis] && g.across.is_some_and(|a| axes[a]));
1237                Body {
1238                    mass: b.mass,
1239                    payload: if payload_on { b.payload } else { 0.0 },
1240                    general: across || !b.rotaries.is_empty(),
1241                    axes,
1242                    rotaries: b.rotaries.clone(),
1243                    offset: b.offset,
1244                }
1245            })
1246            .collect();
1247        Ok(Self {
1248            elastic,
1249            g: gravity,
1250            g_along: (0..d).map(|i| straight(i, gravity * incline[i.min(n - 1)].sin())).collect(),
1251            // cos(90 deg) is 6e-17, not 0: a vertical axis has no weight across it.
1252            g_across: (0..d)
1253                .map(|i| {
1254                    let a = incline[i.min(n - 1)];
1255                    straight(i, if (a.cos()).abs() < 1e-12 { 0.0 } else { gravity * a.cos() })
1256                })
1257                .collect(),
1258            loops: closed_belts(&sections, m),
1259            bodies,
1260            dirs,
1261            turn,
1262            stroke: net.axes.iter().map(|a| a.stroke).collect(),
1263            gantry,
1264            tcp: net.tcp.clone(),
1265            gantry_motors: net.gantry.as_ref().and_then(|g| {
1266                let mut drives = g.drives.iter().enumerate().filter(|(_, d)| d.is_some()).map(|(k, _)| k);
1267                Some([drives.next()?, drives.next()?])
1268            }),
1269            motors: net.motors.iter().map(|d| MotorInfo { id: intern(&d.id), key: intern(&d.key) }).collect(),
1270            r_mat: r.iter().map(|r| belt.rest_length(*r)).collect(),
1271            j_pulley: net
1272                .motors
1273                .iter()
1274                .zip(&direct)
1275                .map(|(d, x)| if x.is_some() { 0.0 } else { d.inertia + belt_mass * d.radius * d.radius })
1276                .collect(),
1277            pulley_at: net.motors.iter().map(|d| d.at).collect(),
1278            pulley_body: net.motors.iter().map(|d| d.body).collect(),
1279            r,
1280            k,
1281            k_inv,
1282            ratio: gears.iter().map(|g| g.ratio).collect(),
1283            shafts,
1284            ripples,
1285            brakes,
1286            j_rotor,
1287            gears,
1288            mesh: ToothMesh::from_config(cfg)?,
1289            stops: HardStop::from_config(cfg)?,
1290            chain,
1291            chain_axes,
1292            chain_fade,
1293            process,
1294            tool_push: Vec::new(),
1295            dwelling: false,
1296            frame_node: net.frame.is_some(),
1297            frame,
1298            thermal,
1299            jumps,
1300            jump_motor,
1301            jump_of,
1302            jump_loss: 0.0,
1303            span_mass,
1304            spans,
1305            run_mass: if runs { belt.mass_per_m } else { 0.0 },
1306            lump: belt_mass,
1307            belt,
1308            sections,
1309            guides,
1310            idlers,
1311            bearing,
1312            axes,
1313            payload_attached: true,
1314            brake_engaged: false,
1315            direct,
1316            coupled,
1317            extra_efficiency,
1318            turned,
1319            wraps,
1320            clockwise: (
1321                net.motors.iter().map(|d| d.clockwise).collect(),
1322                net.idlers.iter().map(|d| d.clockwise).collect(),
1323            ),
1324            lean_node: net.lean,
1325            lean,
1326            beam,
1327            worms_configured: worms.clone(),
1328            worms,
1329        })
1330    }
1331
1332    /// The angle and speed of motor kk's gearbox output in the elastic model: its pulley's, or the axis's that its
1333    /// screw, rack, linear motor or rotary drives.
1334    fn output(&self, s: &[f64], kk: usize) -> (f64, f64) {
1335        let (n, v) = (self.n(), self.vel());
1336        match &self.direct[kk] {
1337            Some(_) => (dot(&self.k[kk], &s[..n]), dot(&self.k[kk], &s[v..v + n])),
1338            None => (s[n + kk], s[v + n + kk]),
1339        }
1340    }
1341    /// The belt's tooth mesh force at motor kk's pulley; none where it drives no pulley.
1342    fn mesh_force(&self, kk: usize, x: f64) -> f64 {
1343        if self.direct[kk].is_some() { 0.0 } else { self.mesh.force(x) }
1344    }
1345    /// A screw, rack, linear motor or rotary drives coordinate i (a gantry's yaw where one stands at its side).
1346    fn driven(&self, i: usize) -> bool {
1347        self.direct.iter().zip(&self.k).any(|(d, k)| d.is_some() && k[i] != 0.0)
1348    }
1349    /// What presses on axis i's guide beside the weights: a linear motor's attraction and its forcer's weight.
1350    fn pressed(&self, i: usize) -> f64 {
1351        let on = |d: &&Direct| d.axis == i;
1352        self.direct
1353            .iter()
1354            .flatten()
1355            .filter(on)
1356            .map(|d| {
1357                if let DirectKind::Linear { attraction, forcer } = d.kind {
1358                    attraction + forcer * self.g_across[i]
1359                } else {
1360                    0.0
1361                }
1362            })
1363            .sum()
1364    }
1365
1366    /// The coordinates: the axes, then a yawing gantry's yaw.
1367    fn n(&self) -> usize {
1368        self.dirs.len()
1369    }
1370    /// The axes, the tool's coordinates.
1371    fn nt(&self) -> usize {
1372        self.axes.len()
1373    }
1374    fn m(&self) -> usize {
1375        self.motors.len()
1376    }
1377    // Elastic state: [q, a (pulleys), p (rotors), u (the frame, with one), w (the leaning body, with effects.tool_flex)],
1378    // their rates, a friction state per axis, the slack time, a brake state per motor, and with effects.belt_tooth_jump
1379    // `JUMP_STATES` per belt motor.
1380    // Rigid state: [q, v, friction states, brakes].
1381    fn vel(&self) -> usize {
1382        if self.elastic { self.beam_at() + usize::from(self.beam.is_some()) } else { self.n() }
1383    }
1384    fn frame_at(&self) -> usize {
1385        self.n() + 2 * self.m()
1386    }
1387    fn lean_at(&self) -> usize {
1388        self.frame_at() + usize::from(self.frame.is_some())
1389    }
1390    fn beam_at(&self) -> usize {
1391        self.lean_at() + usize::from(self.lean.is_some())
1392    }
1393    /// The rows of the lean and the beam's deflection in the elastic mass matrix: after the axes and the frame's sway.
1394    fn lean_row(&self) -> usize {
1395        self.n() + usize::from(self.frame.is_some())
1396    }
1397    fn beam_row(&self) -> usize {
1398        self.lean_row() + usize::from(self.lean.is_some())
1399    }
1400    /// The beam's deflection under the carriage and its rate; zero without the beam mode.
1401    fn deflection(&self, s: &[f64]) -> (f64, f64) {
1402        if self.beam.is_some() { (s[self.beam_at()], s[self.vel() + self.beam_at()]) } else { (0.0, 0.0) }
1403    }
1404    /// The beam mode at the carriage's place: (k, M, c, dk/dx, dM/dx), zeros without it.
1405    fn beam_mode(&self, q: &[f64]) -> [f64; 5] {
1406        self.beam.as_ref().map_or([0.0; 5], |b| b.at_x(q[b.axis], self.beam_load().0 + b.belt[0]))
1407    }
1408    /// The mass of the bodies that move along the beam's axis (the carriage and what rides on it, with the payload while
1409    /// attached), and of those of them that also move along the vertical axis: what hangs on w.
1410    fn beam_load(&self) -> (f64, f64) {
1411        let Some(b) = &self.beam else { return (0.0, 0.0) };
1412        let on = self.bodies.iter().filter(|body| body.axes[b.axis]);
1413        let riding = on.clone().filter(|body| body.axes[b.vertical]);
1414        (on.map(|body| self.body_mass(body)).sum(), riding.map(|body| self.body_mass(body)).sum())
1415    }
1416    /// The weight on the beam's mode, N: the bodies on its axis and the belt's runs riding on it (`BeamMode::belt`).
1417    fn beam_weight(&self) -> f64 {
1418        self.beam.as_ref().map_or(0.0, |b| (self.beam_load().0 + b.belt[1]) * self.g)
1419    }
1420    /// With the beam mode, shifts `q` to where the Z axis stands on its belt above the beam's quasi-static sag
1421    /// w0 = (carried weight) / k (its own coordinate is relative to the carriage) and returns w0; 0 and no change without it.
1422    fn sag_at_rest(&self, q: &mut [f64]) -> f64 {
1423        let Some(b) = &self.beam else { return 0.0 };
1424        let w0 = self.beam_weight() / b.stiffness(q[b.axis]);
1425        q[b.vertical] += w0;
1426        w0
1427    }
1428    /// The leaning body's sideways travel against its carriage and its rate; zero without it.
1429    fn leaning(&self, s: &[f64]) -> (f64, f64) {
1430        if self.lean.is_some() { (s[self.lean_at()], s[self.vel() + self.lean_at()]) } else { (0.0, 0.0) }
1431    }
1432    /// The tool tip's travel along the leaning body's axis per metre it leans (`geometry::flex_at`); 0 without it.
1433    fn tip(&self, q: &[f64]) -> f64 {
1434        self.lean.as_ref().map_or(0.0, |lean| flex_at(lean, q).2)
1435    }
1436    /// The belt runs' geometric stiffness, per section: how much longer the leaning body's runs get as it leans, to second
1437    /// order (the crate's `lean_runs`). The runs are the spans that change length with the lean's lever axis alone, one
1438    /// metre per metre (the belt's vertical runs: the clamp's, whose far end is on the leaning body at d = -length below
1439    /// the carriage's idlers, and the idler at the body's bottom, d = length below them). Under the spring's force k u the
1440    /// end is out sideways by delta = k u `lean_reach`(d) and has risen along the body by (k u)^2 `lean_rise`(d), so the
1441    /// run is longer by delta^2 / (2 |d|) - sign(d) rise (a guide that only tilts turns the end about the run's other end
1442    /// and leaves its length; the guide's sideways give is what is left), each section by 1/2 c u^2; its tension,
1443    /// its force on the lean (sum T c u), on the lever axis (-1/2 u^2 sum T c') and its damping follow from the lengths. Zero
1444    /// without the lean or a span to give the runs (the crate has them as s + z, 2 times s + sz - z, s + z).
1445    fn lean_runs(&self, q: &[f64]) -> Vec<f64> {
1446        let mut c = vec![0.0; self.sections.len()];
1447        let Some((lean, z)) = self.lean.as_ref().and_then(|l| Some((l, l.lever_axis?))) else { return c };
1448        let (k, h) = (flex_at(lean, q).0, lean.com_drop - q[z]);
1449        for span in &self.spans {
1450            let up = span.c[z];
1451            if up.abs() != 1.0 || span.c.iter().enumerate().any(|(i, c)| i != z && *c != 0.0) {
1452                continue;
1453            }
1454            let (length, d) = (span.length + up * q[z], -up * span.length - q[z]);
1455            let end = k * lean_reach(lean, d, h);
1456            c[span.section] += end * end / length - 2.0 * d.signum() * k * k * lean_rise(lean, d, h);
1457        }
1458        c
1459    }
1460    /// With effects.belt_run_offset: per section how much longer it gets per metre of lean, first order (the crate's
1461    /// `lean_offset`). The runs that reach the leaning body from above (`lean_runs`' clamp runs, d < 0) meet it the lean's
1462    /// `belt_offset` to the side their other wheel is on along the lean's axis; the guide's tilt theta = k u h / tilt
1463    /// (h = com_drop - z) lifts the end on the + side by e theta and lowers the other: that run's section is longer by
1464    /// +- e k h / tilt per u. Zeros without the offset.
1465    fn lean_offset(&self, q: &[f64]) -> Vec<f64> {
1466        let mut out = vec![0.0; self.sections.len()];
1467        let Some((lean, z)) = self.lean.as_ref().and_then(|l| Some((l, l.lever_axis?))) else { return out };
1468        if lean.belt_offset == 0.0 {
1469            return out;
1470        }
1471        let per_u = lean.belt_offset * flex_at(lean, q).0 * (lean.com_drop - q[z]) / lean.tilt;
1472        let along = self.dirs[lean.axis];
1473        let mut next = vec![0usize; self.sections.len()];
1474        for span in &self.spans {
1475            let at = next[span.section];
1476            next[span.section] += 1;
1477            if span.c[z] != 1.0 || span.c.iter().enumerate().any(|(i, c)| i != z && *c != 0.0) {
1478                continue;
1479            }
1480            let route = self.route_waypoints(span.section);
1481            let (Some(&a), Some(&b)) = (route.get(at), route.get(at + 1)) else { continue };
1482            let body = Waypoint::Body(lean.body);
1483            let other = if a == body { b } else { a };
1484            let plane = self.plane(span.section);
1485            let side = dot(&self.wheel(other, q, plane).1, &along) - dot(&self.wheel(body, q, plane).1, &along);
1486            out[span.section] += side.signum() * per_u;
1487        }
1488        out
1489    }
1490    /// How much longer `lean_runs` and `lean_offset` make the sections at the state's lean u and height z, and the rate of
1491    /// that: 1/2 c u^2 + e u and c u u' + 1/2 c' z' u^2 + e u' + e' z' u (c' and e' by central differences over 2e-6 m, as
1492    /// the crate takes them).
1493    fn lean_lengths(&self, s: &[f64]) -> (Vec<f64>, Vec<f64>) {
1494        let zero = vec![0.0; self.sections.len()];
1495        let Some(z) = self.lean.as_ref().and_then(|l| l.lever_axis) else { return (zero.clone(), zero) };
1496        let (n, v) = (self.n(), self.vel());
1497        let ((u, du), q) = (self.leaning(s), &s[..n]);
1498        let (c, mut ahead, mut behind) = (self.lean_runs(q), q.to_vec(), q.to_vec());
1499        (ahead[z], behind[z]) = (q[z] + 1e-6, q[z] - 1e-6);
1500        let (e, e_ahead, e_behind) = (self.lean_offset(q), self.lean_offset(&ahead), self.lean_offset(&behind));
1501        let (ahead, behind) = (self.lean_runs(&ahead), self.lean_runs(&behind));
1502        let longer = (0..c.len()).map(|i| 0.5 * c[i] * u * u + e[i] * u).collect();
1503        let rate = (0..c.len())
1504            .map(|i| {
1505                c[i] * u * du
1506                    + 0.5 * (ahead[i] - behind[i]) / 2e-6 * s[v + z] * u * u
1507                    + e[i] * du
1508                    + (e_ahead[i] - e_behind[i]) / 2e-6 * s[v + z] * u
1509            })
1510            .collect();
1511        (longer, rate)
1512    }
1513
1514    /// Motor kk's gearbox (`Gearbox::torque_with`, its Maxwell arm at `u`, `arm`), with its worm stage's share where it
1515    /// has one that turns back (`worm::factors`, at the power its spring's torque puts through the output). A
1516    /// self-locking worm passes the gearbox's torques on as they are; its mesh's friction is `worm_drag`, at the rotor.
1517    fn gear_torque(&self, kk: usize, phi: f64, w_phi: f64, theta: f64, w_theta: f64, u: f64) -> GearTorque {
1518        let gear = self.gears[kk].torque_with(phi, w_phi, theta, w_theta, u);
1519        let Some(worm) = self.worms[kk].filter(|w| w.back_efficiency > 0.0) else { return gear };
1520        let (output, rotor) = crate::worm::factors(&worm, gear.rotor * self.ratio[kk] * w_theta);
1521        GearTorque { output: gear.output * output, rotor: gear.rotor * rotor }
1522    }
1523    /// The friction torque a self-locking worm's mesh puts on motor kk's rotor in the elastic model, against its speed
1524    /// `w_phi`, N m (0 without one): what would take the rotor's speed out over `worm::STICK_TIME_S` given its other
1525    /// torques `drive` (motor less shaft and brake), held to Coulomb's level of the flank the gear's torque at the rotor
1526    /// `rotor` loads (`worm::levels`) and never along the motion, so that the mesh only ever takes power
1527    /// (`F w_phi >= 0`). At speed that is the level (sliding); where the level would stop the rotor within the time,
1528    /// it stops it over that time (sticking), and at rest it holds anything within the levels. No speed band: the
1529    /// rotor's own acceleration on the level (16000 rad/s2 for the table's jam) crosses any band of a step's width.
1530    fn worm_drag(&self, kk: usize, rotor: f64, w_phi: f64, drive: f64) -> f64 {
1531        let Some(worm) = self.worms[kk].filter(|w| w.back_efficiency <= 0.0) else { return 0.0 };
1532        let (up, down) = crate::worm::levels(&worm, rotor);
1533        let stuck = drive - rotor + self.j_rotor[kk] * w_phi / crate::worm::STICK_TIME_S;
1534        let (low, high) = match w_phi.partial_cmp(&0.0) {
1535            Some(std::cmp::Ordering::Greater) => (0.0, up),
1536            Some(std::cmp::Ordering::Less) => (-down, 0.0),
1537            _ => (-down, up),
1538        };
1539        stuck.clamp(low, high)
1540    }
1541    /// The share of the load motor kk holds at rest: none behind a self-locking worm, all of it otherwise.
1542    fn held(&self, kk: usize) -> f64 {
1543        if self.worms[kk].is_some_and(|w| w.back_efficiency <= 0.0) { 0.0 } else { 1.0 }
1544    }
1545    /// What motor kk's gearbox loses, W (`Gearbox::loss_power`), with its worm stage's share, `drag` the self-locking
1546    /// worm's (`worm_drag`).
1547    fn gear_loss_power(&self, kk: usize, angles: [f64; 4], u: f64, drag: f64) -> f64 {
1548        let [phi, w_phi, theta, w_theta] = angles;
1549        let (plain, worm) = (
1550            self.gears[kk].torque_with(phi, w_phi, theta, w_theta, u),
1551            self.gear_torque(kk, phi, w_phi, theta, w_theta, u),
1552        );
1553        self.gears[kk].loss_power_with(phi, w_phi, theta, w_theta, u) + (worm.rotor - plain.rotor + drag) * w_phi
1554            - (worm.output - plain.output) * w_theta
1555    }
1556    /// The factors on motor kk's torque at its gearbox's output and at its rotor, in the rigid model, at the torque `into`
1557    /// that goes in (on the output's scale) and the output's speed: (`Gearbox::loss_factor`, 1), times the worm's share.
1558    fn rigid_factors(&self, kk: usize, into: f64, speed: f64) -> (f64, f64) {
1559        let loss = self.gears[kk].loss_factor(into, speed);
1560        match &self.worms[kk] {
1561            Some(worm) => {
1562                let (output, rotor) = crate::worm::factors(worm, into * speed);
1563                (loss * output, rotor)
1564            }
1565            None => (loss, 1.0),
1566        }
1567    }
1568    fn friction_at(&self) -> usize {
1569        2 * self.vel()
1570    }
1571    fn slack_at(&self) -> usize {
1572        self.friction_at() + self.n()
1573    }
1574    fn brake_at(&self) -> usize {
1575        self.slack_at() + usize::from(self.elastic)
1576    }
1577    fn jump_at(&self, j: usize) -> usize {
1578        self.brake_at() + self.m() + JUMP_STATES * j
1579    }
1580    /// Where the gears' Maxwell arms' states start (`Gearbox::arm`), after the belt jumps': one each for the elastic
1581    /// drives whose gear has an arm (a screw or rack behind a damped gear or coupling).
1582    fn arm_at(&self) -> usize {
1583        self.jump_at(self.jumps.len())
1584    }
1585    /// Motor kk's arm's place in the state, if its gear has one.
1586    fn arm_slot(&self, kk: usize) -> Option<usize> {
1587        let has = |i: usize| self.elastic && self.gears[i].relax_stiffness > 0.0;
1588        has(kk).then(|| self.arm_at() + (0..kk).filter(|&i| has(i)).count())
1589    }
1590    /// Motor kk's arm's state, 0 where its gear has none.
1591    fn arm(&self, s: &[f64], kk: usize) -> f64 {
1592        self.arm_slot(kk).map_or(0.0, |i| s[i])
1593    }
1594
1595    fn body_mass(&self, b: &Body) -> f64 {
1596        b.mass + if self.payload_attached { b.payload } else { 0.0 }
1597    }
1598    /// The bodies' mass on each axis; on a rotary axis its rotary's inertia (with the payload's while attached), on a
1599    /// gantry's yaw the bridge's own. Bodies whose place is not a sum of the axes' travels are not in it (`general_mass`).
1600    fn mass(&self) -> Vec<f64> {
1601        let turned = |i: usize| self.turned[i].0 + if self.payload_attached { self.turned[i].1 } else { 0.0 };
1602        (0..self.n())
1603            .map(|i| {
1604                self.bodies.iter().filter(|b| b.axes[i] && !b.general).map(|b| self.body_mass(b)).sum::<f64>()
1605                    + turned(i)
1606            })
1607            .collect()
1608    }
1609
1610    /// Where a body's centre of mass is at q, from where it is with every coordinate at 0: the straight axes' travels
1611    /// along their directions, on a yawing gantry's bridge its lever times the yaw along the bridge's axis, and its
1612    /// offset turned by the rotaries it rides on, the innermost first.
1613    fn body_point(&self, b: &Body, q: &[f64]) -> [f64; 3] {
1614        let mut p = [0.0; 3];
1615        let mut add = |dir: [f64; 3], t: f64| (0..3).for_each(|k| p[k] += dir[k] * t);
1616        for i in (0..self.n()).filter(|&i| b.axes[i]) {
1617            add(self.dirs[i], q[i]);
1618        }
1619        if let Some(g) = self.gantry.as_ref().filter(|g| b.axes[g.axis]) {
1620            let lever = g.across.filter(|&a| b.axes[a]).map_or(0.0, |a| q[a] + g.shift);
1621            add(self.dirs[g.axis], lever * q[g.coord]);
1622        }
1623        add(self.turned_by(&b.rotaries, q, b.offset), 1.0);
1624        p
1625    }
1626    /// `v` turned by the rotaries (outermost first) at their angles in q.
1627    fn turned_by(&self, rotaries: &[usize], q: &[f64], mut v: [f64; 3]) -> [f64; 3] {
1628        for &r in rotaries.iter().rev() {
1629            v = rotate(self.turn[r], q[r], v);
1630        }
1631        v
1632    }
1633    /// d body_point / d q_i, per coordinate, exactly: an axis's direction, the yaw's lever and the yaw on the lever's
1634    /// axis, and for rotary r the outer rotaries turning turn_r x (r and the inner ones turning the offset).
1635    fn body_jacobian(&self, b: &Body, q: &[f64]) -> Vec<[f64; 3]> {
1636        let mut out: Vec<[f64; 3]> = (0..self.n()).map(|i| if b.axes[i] { self.dirs[i] } else { [0.0; 3] }).collect();
1637        let mut add = |i: usize, dir: [f64; 3], t: f64| (0..3).for_each(|k| out[i][k] += dir[k] * t);
1638        if let Some(g) = self.gantry.as_ref().filter(|g| b.axes[g.axis]) {
1639            let across = g.across.filter(|&a| b.axes[a]);
1640            add(g.coord, self.dirs[g.axis], across.map_or(0.0, |a| q[a] + g.shift));
1641            if let Some(a) = across {
1642                add(a, self.dirs[g.axis], q[g.coord]);
1643            }
1644        }
1645        for (p, &r) in b.rotaries.iter().enumerate() {
1646            let inner = self.turned_by(&b.rotaries[p..], q, b.offset);
1647            add(r, self.turned_by(&b.rotaries[..p], q, cross(self.turn[r], inner)), 1.0);
1648        }
1649        out
1650    }
1651    /// The second derivative of body_point along the speeds v (dJ/dt v), exactly: 2 v_across v_yaw along the bridge's
1652    /// axis, and through each rotary R (speed w about u) of what it turns, x'' -> R x'' + 2 w u x (R x') + w^2 u x (u x R x).
1653    fn body_curve(&self, b: &Body, q: &[f64], v: &[f64]) -> [f64; 3] {
1654        let (mut x, mut d1, mut d2) = (b.offset, [0.0; 3], [0.0; 3]);
1655        for &r in b.rotaries.iter().rev() {
1656            let (u, w) = (self.turn[r], v[r]);
1657            let (y, y1) = (rotate(u, q[r], x), rotate(u, q[r], d1));
1658            let (uy, uy1, uuy) = (cross(u, y), cross(u, y1), cross(u, cross(u, y)));
1659            d2 = rotate(u, q[r], d2);
1660            (0..3).for_each(|k| d2[k] += 2.0 * w * uy1[k] + w * w * uuy[k]);
1661            d1 = [0, 1, 2].map(|k| y1[k] + w * uy[k]);
1662            x = y;
1663        }
1664        if let Some(g) = self.gantry.as_ref().filter(|g| b.axes[g.axis])
1665            && let Some(a) = g.across.filter(|&a| b.axes[a])
1666        {
1667            (0..3).for_each(|k| d2[k] += 2.0 * v[a] * v[g.coord] * self.dirs[g.axis][k]);
1668        }
1669        d2
1670    }
1671    /// The bodies whose place is not a sum of the axes' travels, as m J^T J at q (J = `body_jacobian`).
1672    fn general_mass(&self, q: &[f64], out: &mut [Vec<f64>]) {
1673        for b in self.bodies.iter().filter(|b| b.general) {
1674            let (j, m) = (self.body_jacobian(b, q), self.body_mass(b));
1675            for (i, row) in out.iter_mut().enumerate() {
1676                for (l, x) in row.iter_mut().enumerate() {
1677                    *x += m * (0..3).map(|k| j[i][k] * j[l][k]).sum::<f64>();
1678                }
1679            }
1680        }
1681    }
1682    /// What the speeds v ask of those bodies beside their mass matrix, as forces on the coordinates:
1683    /// -m J^T (dJ/dt v), the centripetal and Coriolis forces (`body_curve`). With the mass matrix m J^T J these are
1684    /// Lagrange's equations, so the energy keeps.
1685    fn inertial(&self, q: &[f64], v: &[f64]) -> Vec<f64> {
1686        let mut out = vec![0.0; self.n()];
1687        for b in self.bodies.iter().filter(|b| b.general) {
1688            let curve = self.body_curve(b, q, v);
1689            let (j, m) = (self.body_jacobian(b, q), self.body_mass(b));
1690            for (i, f) in out.iter_mut().enumerate() {
1691                *f -= m * (0..3).map(|k| j[i][k] * curve[k]).sum::<f64>();
1692            }
1693        }
1694        out
1695    }
1696    /// The yaw spring's and damper's force on the coordinates: -k psi - c psi' on a yawing gantry's yaw, none elsewhere.
1697    fn yaw_force(&self, q: &[f64], v: &[f64]) -> Vec<f64> {
1698        let mut out = vec![0.0; self.n()];
1699        if let Some(g) = &self.gantry {
1700            out[g.coord] = -g.stiffness * q[g.coord] - g.damping * v[g.coord];
1701        }
1702        out
1703    }
1704    /// The joint coordinates (the yaw 0) of a tool pose: with a tcp the straight axes stand off the tool's tip by the
1705    /// tool turned by the rotaries.
1706    fn joints(&self, tool: &[f64]) -> Vec<f64> {
1707        let mut q = tool.to_vec();
1708        q.resize(self.n(), 0.0);
1709        if let Some(t) = &self.tcp {
1710            // The tip on the workpiece where the table has turned it, less the tool turned by the head.
1711            let on = [0, 1, 2].map(|k| q[t.axes[k]] - t.pivot[k]);
1712            let at = self.turned_by(&t.table, &q, on);
1713            let r = self.turned_by(&t.rotaries, &q, t.tool);
1714            (0..3).for_each(|k| q[t.axes[k]] = t.pivot[k] + at[k] - r[k]);
1715        }
1716        q
1717    }
1718    /// `v` turned back by the rotaries (outermost first) at their angles in q: `turned_by` undone.
1719    fn unturned_by(&self, rotaries: &[usize], q: &[f64], mut v: [f64; 3]) -> [f64; 3] {
1720        for &r in rotaries {
1721            v = rotate(self.turn[r], -q[r], v);
1722        }
1723        v
1724    }
1725    /// The tool pose of the joint coordinates q.
1726    fn tool_of(&self, q: &[f64]) -> Vec<f64> {
1727        let mut tool = q[..self.nt()].to_vec();
1728        // The tool rides on the carriage across a yawing bridge: the yaw moves it along the bridge's axis.
1729        if let Some(g) = &self.gantry {
1730            tool[g.axis] += g.across.map_or(0.0, |a| q[a] + g.shift) * q[g.coord];
1731        }
1732        if let Some(t) = &self.tcp {
1733            let r = self.turned_by(&t.rotaries, q, t.tool);
1734            let tip = [0, 1, 2].map(|k| tool[t.axes[k]] + r[k] - t.pivot[k]);
1735            let on = self.unturned_by(&t.table, q, tip);
1736            (0..3).for_each(|k| tool[t.axes[k]] = t.pivot[k] + on[k]);
1737        }
1738        tool
1739    }
1740    /// The joints' speeds and accelerations for a tool pose, speed and acceleration (`joints` differentiated).
1741    fn joint_motion(&self, tool: &[f64], vel: &[f64], acc: &[f64]) -> (Vec<f64>, Vec<f64>, Vec<f64>) {
1742        let q = self.joints(tool);
1743        let pad = |v: &[f64]| -> Vec<f64> { (0..self.n()).map(|i| v.get(i).copied().unwrap_or(0.0)).collect() };
1744        if self.tcp.is_none() {
1745            return (q, pad(vel), pad(acc));
1746        }
1747        let along = |dir: &[f64], h: f64| -> Vec<f64> {
1748            self.joints(&tool.iter().zip(dir).map(|(t, d)| t + h * d).collect::<Vec<_>>())
1749        };
1750        let size = |v: &[f64]| v.iter().map(|x| x * x).sum::<f64>().sqrt();
1751        // The first derivative along a direction over 1 um, the second over 0.1 mm.
1752        let first = |dir: &[f64]| -> Vec<f64> {
1753            if size(dir) == 0.0 {
1754                return vec![0.0; self.n()];
1755            }
1756            let h = 1e-6 / size(dir);
1757            along(dir, h).iter().zip(along(dir, -h)).map(|(a, b)| (a - b) / (2.0 * h)).collect()
1758        };
1759        let (dq, mut ddq) = (first(vel), first(acc));
1760        if size(vel) > 0.0 {
1761            let h = 1e-4 / size(vel);
1762            let (a, b) = (along(vel, h), along(vel, -h));
1763            ddq.iter_mut().enumerate().for_each(|(i, x)| *x += (a[i] - 2.0 * q[i] + b[i]) / (h * h));
1764        }
1765        (q, dq, ddq)
1766    }
1767    /// The mass matrix of the axes at q: the bodies, the cable chains and the idlers.
1768    fn axis_mass(&self, q: &[f64]) -> Vec<Vec<f64>> {
1769        let n = self.n();
1770        let mut out = vec![vec![0.0; n]; n];
1771        for (i, m) in self.mass().into_iter().enumerate() {
1772            out[i][i] = m + if self.chain_axes[i] { self.chain.mass(q[i]).0 } else { 0.0 };
1773        }
1774        self.general_mass(q, &mut out);
1775        for (row, idle) in out.iter_mut().zip(self.idler_mass()) {
1776            row.iter_mut().zip(idle).for_each(|(a, b)| *a += b);
1777        }
1778        out
1779    }
1780    /// The idlers' share of the axes' mass matrix: each spins with the belt's speed past its carriage, s_d . v with v the
1781    /// axes' speeds on the frame, J / r^2 (s_d s_d').
1782    fn idler_mass(&self) -> Vec<Vec<f64>> {
1783        let n = self.n();
1784        let mut out = vec![vec![0.0; n]; n];
1785        for d in &self.idlers {
1786            for i in 0..n {
1787                for l in 0..n {
1788                    out[i][l] += d.mass * d.speed[i] * d.speed[l];
1789                }
1790            }
1791        }
1792        out
1793    }
1794    /// The frame's mass in its sway, with the bodies that do not move along its axis and so ride on it.
1795    fn frame_mass(&self, f: &FrameMode) -> f64 {
1796        f.mass + self.bodies.iter().filter(|b| !b.axes[f.axis]).map(|b| self.body_mass(b)).sum::<f64>()
1797    }
1798    /// Gravity's force on each coordinate at q: -m g along the straight axes, and through their places' Jacobian for
1799    /// the bodies `body_point` places.
1800    fn gravity(&self, q: &[f64]) -> Vec<f64> {
1801        let mut out: Vec<f64> = self.mass().iter().zip(&self.g_along).map(|(m, g)| -m * g).collect();
1802        for b in self.bodies.iter().filter(|b| b.general) {
1803            let (j, m) = (self.body_jacobian(b, q), self.body_mass(b));
1804            out.iter_mut().zip(&j).for_each(|(f, j)| *f -= m * self.g * j[2]);
1805        }
1806        let (_, rise) = self.runs_height(q);
1807        out.iter_mut().zip(rise).for_each(|(f, r)| *f -= self.g * r);
1808        out
1809    }
1810    /// The belt's runs' weight where the frame momentum has their mass: the height of their first moment (`runs_mass`'s
1811    /// mu), mu sum_s (L0_s + c_s . q / 2) V_s,z . q, and its gradient by q, mu sum_s ((c_s / 2) V_s,z . q + (L0_s +
1812    /// c_s . q / 2) V_s,z). Runs that hang from a clamp and down to an idler on a rising axis give mu (4 s + 2 s_z) z:
1813    /// their weight on that axis.
1814    fn runs_height(&self, q: &[f64]) -> (f64, Vec<f64>) {
1815        let (mut height, mut rise) = (0.0, vec![0.0; q.len()]);
1816        if self.run_mass == 0.0 {
1817            return (height, rise);
1818        }
1819        for s in &self.spans {
1820            let Some(rows) = &s.velocity else { continue };
1821            let (moment, up) = (self.run_mass * (s.length + 0.5 * dot(&s.c, q)), dot(&rows[2], q));
1822            height += moment * up;
1823            for (i, r) in rise.iter_mut().enumerate() {
1824                *r += self.run_mass * (0.5 * s.c.get(i).copied().unwrap_or(0.0) * up)
1825                    + moment * rows[2].get(i).copied().unwrap_or(0.0);
1826            }
1827        }
1828        (height, rise)
1829    }
1830    /// The potential energy of gravity at q, from where it is with every coordinate at 0.
1831    fn potential(&self, q: &[f64]) -> f64 {
1832        let straight: f64 = self.mass().iter().zip(&self.g_along).zip(q).map(|((m, g), q)| m * g * q).sum();
1833        let general: f64 = self
1834            .bodies
1835            .iter()
1836            .filter(|b| b.general)
1837            .map(|b| self.body_mass(b) * self.g * self.body_point(b, q)[2])
1838            .sum();
1839        straight + general + self.g * self.runs_height(q).0
1840    }
1841    /// Pulleys and rotors seen on the axes, J_pulley + i^2 J_rotor per motor, through K.
1842    fn drive_mass(&self) -> Vec<Vec<f64>> {
1843        let n = self.n();
1844        let mut out = vec![vec![0.0; n]; n];
1845        for (kk, row) in self.k.iter().enumerate() {
1846            let j = self.j_pulley[kk] + self.ratio[kk] * self.ratio[kk] * self.j_rotor[kk];
1847            for i in 0..n {
1848                for l in 0..n {
1849                    out[i][l] += j * row[i] * row[l];
1850                }
1851            }
1852        }
1853        out
1854    }
1855    /// The rigid model's mass matrix at q: bodies, chains, idlers, pulleys and rotors, and the belt's runs beyond its lumps.
1856    fn rigid_mass(&self, q: &[f64]) -> Vec<Vec<f64>> {
1857        let mut out = self.drive_mass();
1858        for ((row, axis), runs) in out.iter_mut().zip(self.axis_mass(q)).zip(self.runs_mass(q, [0.0; 3]).0) {
1859            row.iter_mut().zip(axis).zip(runs).for_each(|((a, b), c)| *a += b + c);
1860        }
1861        out
1862    }
1863    /// Torques at the motors for forces on the axes: (J^T)^-1 with J = diag(i) K.
1864    fn to_motors(&self, forces: &[f64]) -> Vec<f64> {
1865        (0..self.m())
1866            .map(|kk| (0..self.n()).map(|i| self.k_inv[i][kk] * forces[i]).sum::<f64>() / self.ratio[kk])
1867            .collect()
1868    }
1869
1870    fn positions<'s>(&self, s: &'s [f64]) -> (&'s [f64], &'s [f64]) {
1871        let (n, v) = (self.n(), self.vel());
1872        (&s[..n], &s[v..v + n])
1873    }
1874    fn pulley_angle(&self, kk: usize, q: &[f64]) -> f64 {
1875        dot(&self.k[kk], q)
1876    }
1877    /// The motor angles at the coordinates q.
1878    fn motor_angles(&self, q: &[f64], out: &mut [f64]) {
1879        for (kk, out) in out.iter_mut().enumerate() {
1880            *out = self.ratio[kk] * self.pulley_angle(kk, q);
1881        }
1882    }
1883    /// The tool's speed at the coordinates q moving at v.
1884    fn tool_speed(&self, q: &[f64], v: &[f64]) -> Vec<f64> {
1885        if self.tcp.is_none() && self.gantry.is_none() {
1886            return v[..self.nt()].to_vec();
1887        }
1888        let size = v.iter().map(|x| x * x).sum::<f64>().sqrt();
1889        if size == 0.0 {
1890            return vec![0.0; self.nt()];
1891        }
1892        let h = 1e-6 / size;
1893        let at = |t: f64| self.tool_of(&q.iter().zip(v).map(|(q, v)| q + t * v).collect::<Vec<_>>());
1894        at(h).iter().zip(at(-h)).map(|(a, b)| (a - b) / (2.0 * h)).collect()
1895    }
1896    /// Where the 3D view draws a body at q.
1897    fn body_scene_at(&self, b: &Body, q: &[f64]) -> [f64; 3] {
1898        if !b.general {
1899            return self.scene_at(q, &b.axes);
1900        }
1901        let p = self.body_point(b, q);
1902        [p[0], p[1] - 0.03, p[2] + 0.06]
1903    }
1904    /// The frame's sway and its rate; zero without it.
1905    fn sway(&self, s: &[f64]) -> (f64, f64) {
1906        if self.frame.is_some() { (s[self.frame_at()], s[self.vel() + self.frame_at()]) } else { (0.0, 0.0) }
1907    }
1908
1909    /// The pulley angles as far as the belt sections see them: each pulley's angle plus the belt's slip over it
1910    /// (effects.belt_tooth_jump) over the radius, and their rates. Elastic model only.
1911    fn fed(&self, s: &[f64]) -> (Vec<f64>, Vec<f64>) {
1912        let (n, m, v) = (self.n(), self.m(), self.vel());
1913        let (mut angle, mut rate) = (s[n..n + m].to_vec(), s[v + n..v + n + m].to_vec());
1914        if !self.jumps.is_empty() {
1915            for (j, &kk) in self.jump_motor.iter().enumerate() {
1916                angle[kk] += s[self.jump_at(j)] / self.r[kk];
1917                rate[kk] += s[self.jump_at(j) + 1] / self.r[kk];
1918            }
1919        }
1920        (angle, rate)
1921    }
1922    fn sections(&self, s: &[f64]) -> Vec<SectionForce> {
1923        let (n, v) = (self.n(), self.vel());
1924        let (angle, rate) = self.fed(s);
1925        let (longer, longer_rate) = self.lean_lengths(s);
1926        self.sections
1927            .iter()
1928            .enumerate()
1929            .map(|(i, sec)| {
1930                let geo = sec.length + dot(&sec.c, &s[..n]) + longer[i];
1931                let mat = sec.mat0 + (0..self.m()).map(|kk| sec.f[kk] * self.r_mat[kk] * angle[kk]).sum::<f64>();
1932                let mat_rate: f64 = (0..self.m()).map(|kk| sec.f[kk] * self.r_mat[kk] * rate[kk]).sum();
1933                self.belt.section(geo, mat, dot(&sec.c, &s[v..v + n]) + longer_rate[i], mat_rate)
1934            })
1935            .collect()
1936    }
1937    fn geo(&self, q: &[f64]) -> Vec<f64> {
1938        self.sections.iter().map(|s| s.length + dot(&s.c, q)).collect()
1939    }
1940    fn mat(&self, s: &[f64]) -> Vec<f64> {
1941        let (angle, _) = self.fed(s);
1942        self.sections
1943            .iter()
1944            .map(|sec| sec.mat0 + (0..self.m()).map(|kk| sec.f[kk] * self.r_mat[kk] * angle[kk]).sum::<f64>())
1945            .collect()
1946    }
1947    /// The tension of each section: the belt's in the elastic model, pretension in the rigid one.
1948    fn tensions(&self, s: &[f64]) -> Vec<f64> {
1949        if self.elastic {
1950            self.sections(s).iter().map(|f| f.tension).collect()
1951        } else {
1952            vec![self.belt.pretension; self.sections.len()]
1953        }
1954    }
1955
1956    /// The acceleration of each axis that the motor torques would give a loss-free rigid machine: what an overhang's
1957    /// tilt on a guide is worked out with. The true acceleration would make friction depend on itself, and its absolute
1958    /// value would turn every belt vibration into extra friction. Over the rigid model's whole mass matrix
1959    /// (`rigid_mass`: bodies, chains, idlers, pulleys, rotors and the belt's runs), with gravity: M a = F + gravity, so
1960    /// that a torque that holds an axis against its weight accelerates nothing, neither that axis nor, through the belt
1961    /// runs' coupling, another.
1962    fn commanded_acc(&self, q: &[f64], torque: &[f64]) -> Vec<f64> {
1963        let forces: Vec<f64> = (0..self.n())
1964            .zip(self.gravity(q))
1965            .map(|(i, g)| g + (0..self.m()).map(|kk| self.ratio[kk] * self.k[kk][i] * torque[kk]).sum::<f64>())
1966            .collect();
1967        solve(self.rigid_mass(q), forces).unwrap_or_else(|| vec![0.0; self.n()])
1968    }
1969
1970    /// The load on a guide: the weight across its axis of what it carries, and with an overhang the tilt
1971    /// 2 m a lever / spacing (and with side_load the overhang's inertia force m a).
1972    fn guide_load(&self, g: &Guide, q: &[f64], acc: &[f64]) -> f64 {
1973        let weight: f64 = g.carries.iter().map(|&b| self.body_mass(&self.bodies[b]) * self.g_across[g.axis]).sum();
1974        let Some(o) = &g.overhang else { return weight };
1975        let side = self.body_mass(&self.bodies[o.body]) * acc[o.axis];
1976        let lever = o.lever - o.lever_axis.map_or(0.0, |a| q[a]);
1977        let tilt = 2.0 * side * lever / o.spacing;
1978        weight + tilt.abs() + if o.side_load { side.abs() } else { 0.0 }
1979    }
1980    /// Friction level factor per guide at the motor torques `torque` (their commanded acceleration, `commanded_acc`).
1981    fn load_scales(&self, q: &[f64], torque: &[f64]) -> Vec<f64> {
1982        let acc = if self.guides.iter().any(|g| g.overhang.is_some()) {
1983            self.commanded_acc(q, torque)
1984        } else {
1985            vec![0.0; self.n()]
1986        };
1987        self.load_scales_at(q, &acc)
1988    }
1989    /// Friction level factor per guide at the axes' acceleration `acc` (zeros: at rest): its load against that of what
1990    /// it carries without the payload.
1991    fn load_scales_at(&self, q: &[f64], acc: &[f64]) -> Vec<f64> {
1992        self.guides
1993            .iter()
1994            .map(|g| {
1995                let nominal: f64 = g.carries.iter().map(|&b| self.bodies[b].mass * self.g_across[g.axis]).sum();
1996                g.friction.load_scale(self.guide_load(g, q, acc), nominal)
1997            })
1998            .collect()
1999    }
2000    /// Guide friction force and friction state rate per axis (zero where an axis has no guide).
2001    fn friction(&self, q: &[f64], v: &[f64], states: &[f64], torque: &[f64]) -> (Vec<f64>, Vec<f64>) {
2002        let (mut force, mut rate) = (vec![0.0; self.n()], vec![0.0; self.n()]);
2003        for (g, scale) in self.guides.iter().zip(self.load_scales(q, torque)) {
2004            (force[g.axis], rate[g.axis]) = g.friction.eval(v[g.axis], states[g.axis], scale);
2005        }
2006        (force, rate)
2007    }
2008    /// The idlers' bearing friction as forces on the axes, and the power it takes.
2009    fn idler_friction(&self, v: &[f64]) -> (Vec<f64>, f64) {
2010        let (mut force, mut power) = (vec![0.0; self.n()], 0.0);
2011        for d in &self.idlers {
2012            let speed = dot(&d.speed, v);
2013            let drag = d.drag * (speed / d.smoothing).tanh();
2014            power += drag * speed;
2015            force.iter_mut().zip(&d.speed).for_each(|(f, s)| *f -= drag * s);
2016        }
2017        (force, power)
2018    }
2019    /// The rotary axes' bearing friction at the output (elastic model), the force against each axis's motion; the
2020    /// smoothing is the one of the shaft friction at the output, and the powers it takes per axis.
2021    fn bearing_force(&self, v: &[f64]) -> Vec<f64> {
2022        (0..self.n())
2023            .map(|i| {
2024                let [coulomb, viscous, smoothing] = self.bearing[i];
2025                if coulomb == 0.0 && viscous == 0.0 {
2026                    0.0
2027                } else {
2028                    coulomb * (v[i] / smoothing).tanh() + viscous * v[i]
2029                }
2030            })
2031            .collect()
2032    }
2033    /// The cable chains' drag on each axis (opposing it).
2034    fn chain_drag(&self, v: &[f64]) -> Vec<f64> {
2035        (0..self.n())
2036            .map(|i| if self.chain_axes[i] { self.chain.drag(v[i], self.chain_fade[i]) } else { 0.0 })
2037            .collect()
2038    }
2039    /// What a growing chain takes, m' w (w / 2 - v) on each axis with one (w its speed over ground, v along the axis), and
2040    /// on the frame -m' w^2 / 2 (see the module comment); m' v^2 / 2 against the motion without a frame.
2041    fn chain_inertia(&self, v: &[f64], sway_rate: f64) -> (Vec<f64>, f64) {
2042        let (mut force, mut on_frame) = (vec![0.0; self.n()], 0.0);
2043        for i in (0..self.n()).filter(|&i| self.chain_axes[i]) {
2044            let growth = self.chain.mass(0.0).1;
2045            let w = v[i] + if self.frame.as_ref().is_some_and(|f| f.axis == i) { sway_rate } else { 0.0 };
2046            force[i] = growth * w * (0.5 * w - v[i]);
2047            if self.frame.as_ref().is_some_and(|f| f.axis == i) {
2048                on_frame = -0.5 * growth * w * w;
2049            }
2050        }
2051        (force, on_frame)
2052    }
2053    /// The force on the tool along each axis: the process force while the cycle dwells, and an obstacle's push.
2054    fn process_force(&self) -> Vec<f64> {
2055        let mut force = self.dwelling_force();
2056        force.iter_mut().zip(&self.tool_push).for_each(|(f, p)| *f += p);
2057        force
2058    }
2059    /// The process force alone (its power is the budget's process row; a push's is the crash row, `sim::Sim::pushed`).
2060    fn dwelling_force(&self) -> Vec<f64> {
2061        if self.dwelling { self.process.clone() } else { vec![0.0; self.n()] }
2062    }
2063    /// The generalised force on the coordinates q of a force on the tool along its axes (`process_force`): its virtual
2064    /// work per unit of each coordinate, sum_i F_i d tool_i / d q_j. The tool's axes are the first coordinates, so
2065    /// that is F itself unless a tcp or a yawing bridge moves the tool with other coordinates too (by central
2066    /// differences of `tool_of` then).
2067    fn on_coordinates(&self, q: &[f64], tool: &[f64]) -> Vec<f64> {
2068        let (n, nt) = (self.n(), self.nt());
2069        let mut out: Vec<f64> = (0..n).map(|j| tool.get(j).copied().unwrap_or(0.0)).collect();
2070        if (self.tcp.is_none() && self.gantry.is_none()) || tool.iter().all(|f| *f == 0.0) {
2071            return out;
2072        }
2073        const STEP: f64 = 1e-7;
2074        for (j, out) in out.iter_mut().enumerate() {
2075            let (mut ahead, mut behind) = (q.to_vec(), q.to_vec());
2076            (ahead[j], behind[j]) = (q[j] + STEP, q[j] - STEP);
2077            let (a, b) = (self.tool_of(&ahead), self.tool_of(&behind));
2078            *out = (0..nt).map(|i| tool.get(i).copied().unwrap_or(0.0) * (a[i] - b[i]) / (2.0 * STEP)).sum();
2079        }
2080        out
2081    }
2082    /// The hard stops at the ends of axis i's joint; none on the yaw.
2083    fn stop_force(&self, i: usize, pos: f64, vel: f64) -> f64 {
2084        if i < self.nt() { self.stops.force(pos, vel, self.stroke[i]) } else { 0.0 }
2085    }
2086
2087    /// The direction of the 3D view the frame sways in (`dirs` of its axis), zero without a swaying frame.
2088    fn sway_direction(&self) -> [f64; 3] {
2089        self.frame.as_ref().map_or([0.0; 3], |f| self.dirs[f.axis])
2090    }
2091
2092    /// The belt run by run, where the spans give their speeds over ground (`machine.span` velocity_x, _y, _z; mu =
2093    /// `run_mass` per metre). Run s, L_s = L0_s + c_s . q long, moves at y_s = V_s v over ground (V_s its velocity rows),
2094    /// and where the frame sways at du along e all of the belt sways with it: y_s = V_s v + e du. Half the belt is lumped
2095    /// on each belt pulley already (`j_pulley`), 1/2 J_l (K_k v)^2 with J_l = lump r_k^2, so the runs add
2096    ///   T = 1/2 mu sum_s L_s |V_s v + e du|^2 - 1/2 sum_k J_l (K_k v)^2:
2097    /// over the coordinates mu sum L_s V_s' V_s - sum J_l K_k K_k', between them and the sway mu sum L_s V_s' e, and on the
2098    /// sway mu sum L_s (the belt's mass): (block, column, mass). All zero without runs.
2099    fn runs_mass(&self, q: &[f64], e: [f64; 3]) -> (Vec<Vec<f64>>, Vec<f64>, f64) {
2100        let n = self.n();
2101        let (mut block, mut column, mut total) = (vec![vec![0.0; n]; n], vec![0.0; n], 0.0);
2102        if self.run_mass == 0.0 {
2103            return (block, column, total);
2104        }
2105        for s in &self.spans {
2106            let Some(v) = self.span_rows(s, q) else { continue };
2107            let weight = self.run_mass * (s.length + dot(&s.c, q));
2108            total += weight;
2109            for i in 0..n {
2110                column[i] += weight * (0..3).map(|k| v[k][i] * e[k]).sum::<f64>();
2111                for l in 0..n {
2112                    block[i][l] += weight * (0..3).map(|k| v[k][i] * v[k][l]).sum::<f64>();
2113                }
2114            }
2115        }
2116        for (kk, row) in self.k.iter().enumerate().filter(|(kk, _)| self.direct[*kk].is_none()) {
2117            let lumped = self.lump * self.r[kk] * self.r[kk];
2118            for i in 0..n {
2119                for l in 0..n {
2120                    block[i][l] -= lumped * row[i] * row[l];
2121                }
2122            }
2123        }
2124        (block, column, total)
2125    }
2126
2127    /// The forces the runs' speeds ask for in Lagrange's equations of `runs_mass` (whose lengths change, dL_s/dt = c_s . v):
2128    /// on the coordinates -mu sum_s [(c_s . v) V_s' y_s - 1/2 c_s |y_s|^2], on the sway -mu sum_s (c_s . v) e . y_s.
2129    fn runs_speed(&self, q: &[f64], v: &[f64], e: [f64; 3], du: f64) -> (Vec<f64>, f64) {
2130        let n = self.n();
2131        let (mut force, mut on_frame) = (vec![0.0; n], 0.0);
2132        if self.run_mass == 0.0 {
2133            return (force, on_frame);
2134        }
2135        let mu = self.run_mass;
2136        for s in &self.spans {
2137            let Some(rows) = self.span_rows(s, q) else { continue };
2138            let y: [f64; 3] = std::array::from_fn(|k| dot(&rows[k], v) + e[k] * du);
2139            let (grows, squared) = (dot(&s.c, v), y.iter().map(|y| y * y).sum::<f64>());
2140            for (i, f) in force.iter_mut().enumerate() {
2141                *f -= mu * (grows * (0..3).map(|k| rows[k][i] * y[k]).sum::<f64>() - 0.5 * s.c[i] * squared);
2142            }
2143            on_frame -= mu * grows * (0..3).map(|k| e[k] * y[k]).sum::<f64>();
2144            // The lever's own change with the coordinates (b), the rows' d/dt and d/dq in Lagrange's equations: with
2145            // V = V0 + l d e_yaw^T, dV/dt = (b . v) d e_yaw^T, so on the yaw's row -mu L (b . v) d . y and on every
2146            // row -mu L [(V_i . d) (b . v) v_yaw - (d . y) b_i v_yaw], on the sway -mu L (b . v) (e . d) v_yaw.
2147            if let (Some(g), Some((_, b))) = (&self.gantry, &s.lever) {
2148                let (d, weight, rate) = (self.dirs[g.axis], s.length + dot(&s.c, q), dot(b, v));
2149                let along: f64 = (0..3).map(|k| d[k] * y[k]).sum();
2150                let with_e: f64 = (0..3).map(|k| d[k] * e[k]).sum();
2151                for (i, f) in force.iter_mut().enumerate() {
2152                    let column: f64 = (0..3).map(|k| rows[k][i] * d[k]).sum();
2153                    let yaw_row = if i == g.coord { rate * along } else { 0.0 };
2154                    *f -= mu * weight * (yaw_row + column * rate * v[g.coord] - along * b[i] * v[g.coord]);
2155                }
2156                on_frame -= mu * weight * rate * with_e * v[g.coord];
2157            }
2158        }
2159        (force, on_frame)
2160    }
2161
2162    /// A span's belt speed over ground per unit speed of each coordinate at q, its rows (`Span::velocity`) with the yaw's
2163    /// column where the span lies across a yawing bridge: its lever l (`Span::lever`) along the bridge's axis. `None`
2164    /// where the file gives the span no speeds.
2165    fn span_rows<'a>(&self, s: &'a Span, q: &[f64]) -> Option<std::borrow::Cow<'a, [Vec<f64>; 3]>> {
2166        let rows = s.velocity.as_ref()?;
2167        let (Some(g), Some((l0, b))) = (&self.gantry, &s.lever) else { return Some(std::borrow::Cow::Borrowed(rows)) };
2168        let (lever, d) = (l0 + dot(b, q), self.dirs[g.axis]);
2169        let mut own = rows.clone();
2170        (0..3).for_each(|k| own[k][g.coord] += lever * d[k]);
2171        Some(std::borrow::Cow::Owned(own))
2172    }
2173
2174    /// The elastic model's mass matrix over its coordinates that carry mass: the axes (on the frame), then the frame's
2175    /// sway and the lean, where they are; T = 1/2 y' M y of all but the pulleys and rotors (on their own states). The
2176    /// bodies, chains and idlers move at their axes' speed plus the sway along its axis (`axis_mass` on the speeds over
2177    /// ground), the bodies that do not move along it and the frame with the sway (`frame_mass`), the leaning body at its
2178    /// axis's speed plus the lean's, and the belt's runs as `runs_mass` has them. The idlers' inertia rides on their axes'
2179    /// speeds alone: the belt's speed past a carriage is the difference of two speeds over ground, in which the frame's
2180    /// sway cancels, so the idlers are in the axes' block and not in the sway's row and column.
2181    fn elastic_mass(&self, q: &[f64]) -> Vec<Vec<f64>> {
2182        let n = self.n();
2183        let d =
2184            n + usize::from(self.frame.is_some()) + usize::from(self.lean.is_some()) + usize::from(self.beam.is_some());
2185        let mut mass = vec![vec![0.0; d]; d];
2186        let axis_mass = self.axis_mass(q);
2187        let (runs, column, belt) = self.runs_mass(q, self.sway_direction());
2188        for i in 0..n {
2189            for l in 0..n {
2190                mass[i][l] = axis_mass[i][l] + runs[i][l];
2191            }
2192        }
2193        if let Some(f) = &self.frame {
2194            let idle = self.idler_mass();
2195            for i in 0..n {
2196                (mass[i][n], mass[n][i]) = (
2197                    axis_mass[i][f.axis] - idle[i][f.axis] + column[i],
2198                    axis_mass[f.axis][i] - idle[f.axis][i] + column[i],
2199                );
2200            }
2201            mass[n][n] = axis_mass[f.axis][f.axis] - idle[f.axis][f.axis] + self.frame_mass(f) + belt;
2202        }
2203        if let Some(lean) = &self.lean {
2204            let (at, body) = (self.lean_row(), self.body_mass(&self.bodies[lean.body]));
2205            (mass[lean.axis][at], mass[at][lean.axis], mass[at][at]) = (body, body, body);
2206            if self.frame.as_ref().is_some_and(|f| f.axis == lean.axis) {
2207                (mass[n][at], mass[at][n]) = (body, body);
2208            }
2209        }
2210        // The beam's deflection carries the bodies that move along the beam and its own modal mass; the vertical axis's
2211        // coordinate is relative to the carriage, so the bodies that move along both have z' - w' over ground (`BeamMode`).
2212        if let Some(b) = &self.beam {
2213            let (at, (carried, riding)) = (self.beam_row(), self.beam_load());
2214            mass[at][at] = carried + self.beam_mode(q)[1] + b.belt[0];
2215            let riding = riding + b.belt[2];
2216            (mass[b.vertical][at], mass[at][b.vertical]) = (-riding, -riding);
2217        }
2218        mass
2219    }
2220
2221    /// The axes' accelerations, the frame's and the friction states' rates of the elastic model, with the axes' own
2222    /// forces (all but the inertia) that go with them.
2223    fn elastic_derivatives(&self, s: &[f64], torque: &[f64], out: &mut [f64]) {
2224        let (n, m, v) = (self.n(), self.m(), self.vel());
2225        let sec = self.sections(s);
2226        let (fa, ba) = (self.friction_at(), self.brake_at());
2227        let (q, vq) = (&s[..n], &s[v..v + n]);
2228        let (friction, rates) = self.friction(q, vq, &s[fa..fa + n], torque);
2229        out[..v].copy_from_slice(&s[v..2 * v]);
2230        let (gravity, (idlers, _), drag) = (self.gravity(q), self.idler_friction(vq), self.chain_drag(vq));
2231        let bearing = self.bearing_force(vq);
2232        let (inertial, yaw) = (self.inertial(q, vq), self.yaw_force(q, vq));
2233        let (u, du) = self.sway(s);
2234        // What the screws, racks, linear motors and rotaries pass to their axes (and a gantry's yaw): their gearbox's
2235        // output.
2236        let mut driven = vec![0.0; n];
2237        for (kk, d) in self.direct.iter().enumerate() {
2238            if d.is_some() {
2239                let (theta, w_theta) = self.output(s, kk);
2240                let out =
2241                    self.gear_torque(kk, s[n + m + kk], s[v + n + m + kk], theta, w_theta, self.arm(s, kk)).output;
2242                driven.iter_mut().zip(&self.k[kk]).for_each(|(f, k)| *f += k * out);
2243            }
2244        }
2245        // What the frame and the things on it put on the axes: it takes all of it back.
2246        let mut force: Vec<f64> = (0..n)
2247            .map(|i| {
2248                let belt: f64 = self.sections.iter().zip(&sec).map(|(x, f)| -x.c[i] * f.tension).sum();
2249                belt - friction[i] + idlers[i] - drag[i] - bearing[i]
2250                    + self.stop_force(i, q[i], vq[i])
2251                    + gravity[i]
2252                    + driven[i]
2253                    + inertial[i]
2254                    + yaw[i]
2255            })
2256            .collect();
2257        let (chain, chain_on_frame) = self.chain_inertia(vq, du);
2258        let process = self.process_force();
2259        let on_q = self.on_coordinates(q, &process);
2260        let (runs, runs_on_frame) = self.runs_speed(q, vq, self.sway_direction(), du);
2261        for i in 0..n {
2262            force[i] += chain[i] + on_q[i] + runs[i];
2263        }
2264        out[fa..fa + n].copy_from_slice(&rates[..n]);
2265        // Lagrange's equations over the axes (on the frame), the frame's sway and the lean, M a = F (`elastic_mass`). The
2266        // frame takes its spring and damper and what the chain's and the belt's runs' speeds ask of it; the forces between
2267        // it and the axes act inside. The process force acts on the tool, which the sway and the lean move too (`tip` per
2268        // unit of lean). The lean's spring acts between the carriage and the body, and stiffens as the lever axis
2269        // travels: -w^2 / 2 dk/dz there; and the body's weight rises as it leans, a pendulum's stiffness c on top of k
2270        // (`lean_weight`), whose rate with the lever axis acts there too.
2271        if let Some(f) = &self.frame {
2272            force.push(
2273                -f.stiffness * u - f.damping * du + chain_on_frame + chain[f.axis] + process[f.axis] + runs_on_frame,
2274            );
2275        }
2276        //
2277        // The belt runs' geometric stiffness (`lean_runs`) is in the section tensions through the lengths: it holds the lean
2278        // back with sum T_i c_i u and pushes on the lever axis with -1/2 u^2 sum T_i c_i'. The process force's vertical part
2279        // works on the tip's rise rho = a u^2 (`rise_coefficients`): 2 a u on the lean, a' u^2 on the lever axis.
2280        if let Some(lean) = &self.lean {
2281            let (w, dw) = self.leaning(s);
2282            let (k, dk, tip) = flex_at(lean, q);
2283            let (c, dc) = lean_weight(lean, q, self.body_mass(&self.bodies[lean.body]), self.g);
2284            let mut on_lean = 0.0;
2285            let mut rise = 0.0;
2286            if let Some(z) = lean.lever_axis {
2287                let (runs, mut ahead, mut behind) = (self.lean_runs(q), q.to_vec(), q.to_vec());
2288                (ahead[z], behind[z]) = (q[z] + 1e-6, q[z] - 1e-6);
2289                // The runs' offset (`lean_offset`): sum T e on the lean, its change with z on Z.
2290                let (e, e_ahead, e_behind) = (self.lean_offset(q), self.lean_offset(&ahead), self.lean_offset(&behind));
2291                let (ahead, behind) = (self.lean_runs(&ahead), self.lean_runs(&behind));
2292                on_lean = (0..runs.len()).map(|i| sec[i].tension * (runs[i] * w + e[i])).sum::<f64>();
2293                let on_z: f64 = (0..runs.len())
2294                    .map(|i| {
2295                        sec[i].tension
2296                            * ((ahead[i] - behind[i]) / 2e-6 * 0.5 * w * w + (e_ahead[i] - e_behind[i]) / 2e-6 * w)
2297                    })
2298                    .sum();
2299                let [a, da, _] = rise_coefficients(lean, q);
2300                force[z] += -0.5 * w * w * (dk + dc) - on_z
2301                    + process[z] * da * w * w
2302                    + process[lean.axis] * tip_slope(lean, q)[0] * w;
2303                rise = 2.0 * process[z] * a * w;
2304            }
2305            force.push(tip * process[lean.axis] + rise - on_lean - (k + c) * w - lean.damping * dw);
2306        }
2307        // The beam mode (`BeamMode`): M(x) w'' + M' x' w' + c w' + k w = (carried weight) - F_vertical on w, and on the beam's
2308        // axis the speed term 1/2 M' w'^2 less the stiffness's change with it, 1/2 k' w^2.
2309        if let Some(b) = &self.beam {
2310            let ((w, dw), [k, _, c, dk, dm]) = (self.deflection(s), self.beam_mode(q));
2311            force[b.axis] += 0.5 * dm * dw * dw - 0.5 * dk * w * w;
2312            force.push(self.beam_weight() - process[b.vertical] - k * w - c * dw - dm * vq[b.axis] * dw);
2313        }
2314        let size = force.len();
2315        let acc = solve(self.elastic_mass(q), force).unwrap_or_else(|| vec![0.0; size]);
2316        out[v..v + n].copy_from_slice(&acc[..n]);
2317        if self.frame.is_some() {
2318            out[v + self.frame_at()] = acc[n];
2319        }
2320        if self.lean.is_some() {
2321            out[v + self.lean_at()] = acc[self.lean_row()];
2322        }
2323        if self.beam.is_some() {
2324            out[v + self.beam_at()] = acc[self.beam_row()];
2325        }
2326        for kk in 0..m {
2327            let (phi, w_phi) = (s[n + m + kk], s[v + n + m + kk]);
2328            let (theta, w_theta) = self.output(s, kk);
2329            let gear = self.gear_torque(kk, phi, w_phi, theta, w_theta, self.arm(s, kk));
2330            if let Some(i) = self.arm_slot(kk) {
2331                out[i] = self.gears[kk].arm(phi, theta, s[i]).1;
2332            }
2333            if self.direct[kk].is_some() {
2334                // Its pulley is the axis: the pulley's states follow it.
2335                out[v + n + kk] = dot(&self.k[kk], &acc);
2336            } else {
2337                let belt: f64 =
2338                    self.r_mat[kk] * self.sections.iter().zip(&sec).map(|(x, f)| x.f[kk] * f.material).sum::<f64>();
2339                let r = self.r[kk];
2340                // While its teeth are out of mesh the pulley feels only the ridge it holds the sliding belt back with.
2341                let (on_pulley, j_pulley) = match self.jump_of[kk].map(|j| (j, &self.jumps[j])) {
2342                    Some((j, (jump, ..))) => {
2343                        let slip = &s[self.jump_at(j)..];
2344                        (jump.pulley_torque(slip, belt, r), jump.pulley_inertia(slip, self.j_pulley[kk], r))
2345                    }
2346                    None => (belt, self.j_pulley[kk]),
2347                };
2348                out[v + n + kk] = (gear.output + on_pulley + r * self.mesh.force(r * theta)) / j_pulley;
2349                if let Some((j, (jump, ..))) = self.jump_of[kk].map(|j| (j, &self.jumps[j])) {
2350                    let at = self.jump_at(j);
2351                    jump.rates(&s[at..], belt / r, r * out[v + n + kk], &mut out[at..]);
2352                }
2353            }
2354            let (brake, brake_rate) = self.brakes[kk].torque(self.brake_engaged, w_phi, s[ba + kk]);
2355            let drive = self.ripples[kk].apply(torque[kk], phi) - self.shafts[kk].torque(w_phi) - brake;
2356            out[v + n + m + kk] =
2357                (drive - gear.rotor - self.worm_drag(kk, gear.rotor, w_phi, drive)) / self.j_rotor[kk];
2358            out[ba + kk] = brake_rate;
2359        }
2360        out[self.slack_at()] = if sec.iter().any(|f| f.tension <= 0.0) { 1.0 } else { 0.0 };
2361    }
2362
2363    /// Rigid model. The gearbox loses torque only on what it transmits, which is the motor torque less what
2364    /// accelerates the rotor itself; that depends on the acceleration solved for, and three passes settle it.
2365    fn rigid_solve(&self, s: &[f64], torque: &[f64]) -> Rigid {
2366        let (n, m) = (self.n(), self.m());
2367        let (q, v) = (&s[..n], &s[n..2 * n]);
2368        let (fa, ba) = (self.friction_at(), self.brake_at());
2369        let (friction, rates) = self.friction(q, v, &s[fa..fa + n], torque);
2370        let (angle, speed): (Vec<f64>, Vec<f64>) = (0..m)
2371            .map(|kk| (self.ratio[kk] * self.pulley_angle(kk, q), self.ratio[kk] * self.pulley_angle(kk, v)))
2372            .unzip();
2373        // The torque each rotor passes on, before its own inertia and the gearbox; a brake holds the rotor.
2374        let drive: Vec<f64> = (0..m)
2375            .map(|kk| {
2376                self.ripples[kk].apply(torque[kk], angle[kk])
2377                    - self.shafts[kk].torque(speed[kk])
2378                    - self.brakes[kk].torque(self.brake_engaged, speed[kk], s[ba + kk]).0
2379            })
2380            .collect();
2381        let (gravity, (idlers, _), drag, (chain, _), process) = (
2382            self.gravity(q),
2383            self.idler_friction(v),
2384            self.chain_drag(v),
2385            self.chain_inertia(v, 0.0),
2386            self.on_coordinates(q, &self.process_force()),
2387        );
2388        let (inertial, yaw, runs) = (self.inertial(q, v), self.yaw_force(q, v), self.runs_speed(q, v, [0.0; 3], 0.0).0);
2389        let base: Vec<f64> = (0..n)
2390            .map(|i| {
2391                let mesh: f64 = (0..m)
2392                    .map(|kk| self.r[kk] * self.mesh_force(kk, self.r[kk] * angle[kk] / self.ratio[kk]) * self.k[kk][i])
2393                    .sum();
2394                mesh - friction[i] + self.stop_force(i, q[i], v[i]) + gravity[i] + idlers[i] - drag[i]
2395                    + chain[i]
2396                    + process[i]
2397                    + inertial[i]
2398                    + yaw[i]
2399                    + runs[i]
2400            })
2401            .collect();
2402        let mut fixed = self.rigid_mass(q);
2403        for kk in 0..m {
2404            let rotor = self.ratio[kk] * self.ratio[kk] * self.j_rotor[kk];
2405            for i in 0..n {
2406                for l in 0..n {
2407                    fixed[i][l] -= rotor * self.k[kk][i] * self.k[kk][l];
2408                }
2409            }
2410        }
2411        let solved = Rigid { acc: vec![0.0; n], rates, out: vec![0.0; m], into: vec![0.0; m] };
2412        if self.worms.iter().flatten().any(|w| w.back_efficiency <= 0.0) {
2413            return self.rigid_locking(&fixed, &base, &drive, v, solved);
2414        }
2415        // One pass with the factors (output, rotor) of each motor's gear, flat: the solution, and the factors of the torques
2416        // it puts into the gears.
2417        let pass = |flat: &Vec<f64>| -> (Rigid, Vec<f64>) {
2418            let mut solved = solved.clone();
2419            let loss: Vec<f64> = flat.chunks(2).map(|f| f[0] / f[1]).collect();
2420            let mut a = fixed.clone();
2421            let mut b = base.clone();
2422            for kk in 0..m {
2423                let rotor = self.ratio[kk] * self.ratio[kk] * self.j_rotor[kk];
2424                for i in 0..n {
2425                    b[i] += loss[kk] * self.ratio[kk] * drive[kk] * self.k[kk][i];
2426                    for l in 0..n {
2427                        a[i][l] += loss[kk] * rotor * self.k[kk][i] * self.k[kk][l];
2428                    }
2429                }
2430            }
2431            let acc = solve(a, b).unwrap_or_else(|| vec![0.0; n]);
2432            for kk in 0..m {
2433                // What the gearbox output carries: what the rotor's own acceleration and the losses of this pass leave.
2434                let into =
2435                    self.ratio[kk] * (drive[kk] - self.j_rotor[kk] * self.ratio[kk] * self.pulley_angle(kk, &acc));
2436                (solved.out[kk], solved.into[kk]) = (loss[kk] * into, into);
2437            }
2438            solved.acc = acc;
2439            let next = (0..m)
2440                .flat_map(|kk| {
2441                    let (output, rotor) = self.rigid_factors(kk, solved.into[kk], self.pulley_angle(kk, v));
2442                    [output, rotor]
2443                })
2444                .collect();
2445            (solved, next)
2446        };
2447        // The factors at their fixed point (`mech::settled_loss`): a gear's loss fades in smoothly over its power, and so
2448        // does a worm's that turns back (`worm::factors`), so they settle as the other machines' do.
2449        // Three passes left up to 1.6e-2 of the acceleration on the shipped files' rigid models and 1.2e-2 on a worm that
2450        // turns back.
2451        pass(&sim_components::mech::settled_loss(vec![1.0; 2 * m], |flat| pass(flat).1)).0
2452    }
2453
2454    /// `rigid_solve` with a self-locking worm (`worm::factors`), whose rotor takes no share of the load at rest and
2455    /// pushes against it while it is driven back: the outputs o are solved for beside the accelerations, so that a
2456    /// rotor factor of 0 stays solvable. With `fixed` the mass matrix less the rotors and `base` the axes' forces, the
2457    /// axes take fixed acc - K^T o = base, and each rotor puts into its gearbox what its motor's torque (`drive`) leaves
2458    /// after its own acceleration, into = i (drive - J i K acc), of which the output gets o = into * output factor /
2459    /// rotor factor: rotor factor o + i^2 J K acc = output factor i drive.
2460    ///
2461    /// A locking worm moving (`worm`, the module comment) drags D = into - o = s max((1 / e - 1) s o,
2462    /// (1 - eta_back) max(-s o_rest, 0)) at the wheel, s the sign of its speed, e its forward efficiency times its
2463    /// gearbox's, o_rest the torque its output holds at rest against the axes' forces (K^T o_rest = -base): its row is
2464    /// the driving flank's, o + e i^2 J K acc = e i drive, or the drag's, o + i^2 J K acc = i drive - s C with
2465    /// C = `worm::overhauling_drag`, whichever holds at the solution. That drag rises with o, so exactly one choice holds
2466    /// (both at the seam, where they agree): every choice is solved and the one that holds is taken, no starting guess.
2467    /// Its output at rest, or slower than `worm::STICK_SPEED`, sticks (K acc = -K v / `worm::STICK_TIME_S`, 0 at rest)
2468    /// while the drag that takes, o - i drive, lies between what the worm gives raising the load, -(1 / eta - 1) o_rest,
2469    /// and lowering it, (1 - eta_back) o_rest; beyond, it breaks loose with the drag at that bound.
2470    fn rigid_locking(&self, fixed: &[Vec<f64>], base: &[f64], drive: &[f64], v: &[f64], mut solved: Rigid) -> Rigid {
2471        let (n, m) = (self.n(), self.m());
2472        let kt: Vec<Vec<f64>> = (0..n).map(|i| (0..m).map(|kk| self.k[kk][i]).collect()).collect();
2473        let holds = lstsq(&kt, &base.iter().map(|f| -f).collect::<Vec<_>>()).unwrap_or_else(|| vec![0.0; m]);
2474        let locking: Vec<Option<WormNode>> =
2475            self.worms.iter().map(|w| w.filter(|w| w.back_efficiency <= 0.0)).collect();
2476        // Per motor: (output factor, rotor factor), the drag a locking worm broken loose from rest takes, (Stuck) it
2477        // sticks, or (Moving) a locking worm moving with its forward efficiency e and its overhauling flank's drag C.
2478        #[derive(Clone, Copy, PartialEq)]
2479        enum Row {
2480            Factors(f64, f64),
2481            Drag(f64),
2482            Stuck,
2483            Moving(f64, f64),
2484        }
2485        let speed = |kk: usize| self.pulley_angle(kk, v);
2486        let sticks = |kk: usize| speed(kk).abs() < crate::worm::STICK_SPEED;
2487        let moving_row = |kk: usize, w: &WormNode, out: f64| {
2488            let e = w.efficiency * self.gears[kk].loss_factor(out.abs(), speed(kk).abs());
2489            Row::Moving(e, crate::worm::overhauling_drag(w, holds[kk], speed(kk)))
2490        };
2491        let mut rows: Vec<Row> = (0..m)
2492            .map(|kk| match locking[kk] {
2493                Some(_) if sticks(kk) => Row::Stuck,
2494                Some(w) => moving_row(kk, &w, 0.0),
2495                None => Row::Factors(1.0, 1.0),
2496            })
2497            .collect();
2498        let moving: Vec<usize> = (0..m).filter(|&kk| matches!(rows[kk], Row::Moving(..))).collect();
2499        // The solution with each moving worm on its driving flank (bit set in `flanks`) or dragging.
2500        let solve_rows = |rows: &[Row], flanks: usize| -> Vec<f64> {
2501            let mut a = vec![vec![0.0; n + m]; n + m];
2502            let mut b = base.to_vec();
2503            for i in 0..n {
2504                a[i][..n].copy_from_slice(&fixed[i]);
2505                for kk in 0..m {
2506                    a[i][n + kk] = -self.k[kk][i];
2507                }
2508            }
2509            for (kk, row) in rows.iter().enumerate() {
2510                let inertia = self.ratio[kk] * self.ratio[kk] * self.j_rotor[kk];
2511                let into = self.ratio[kk] * drive[kk];
2512                let driving = moving.iter().position(|&j| j == kk).is_some_and(|bit| flanks >> bit & 1 == 1);
2513                let (at_acc, at_o, rhs) = match *row {
2514                    Row::Factors(output, rotor) => (output * inertia, rotor, output * into),
2515                    Row::Drag(drag) => (inertia, 1.0, into + drag),
2516                    Row::Stuck => (1.0, 0.0, -speed(kk) / crate::worm::STICK_TIME_S),
2517                    Row::Moving(e, _) if driving => (e * inertia, 1.0, e * into),
2518                    Row::Moving(_, c) => (inertia, 1.0, into - speed(kk).signum() * c),
2519                };
2520                for l in 0..n {
2521                    a[n + kk][l] = at_acc * self.k[kk][l];
2522                }
2523                a[n + kk][n + kk] = at_o;
2524                b.push(rhs);
2525            }
2526            solve(a, b).unwrap_or_else(|| vec![0.0; n + m])
2527        };
2528        // How far the moving worms' flanks miss the drag law at a solution: the driving flank's drag (1 / e - 1) s o
2529        // has to reach C, the dragging one's must not exceed it.
2530        let missed = |rows: &[Row], flanks: usize, x: &[f64]| -> f64 {
2531            moving
2532                .iter()
2533                .enumerate()
2534                .map(|(bit, &kk)| {
2535                    let Row::Moving(e, c) = rows[kk] else { return 0.0 };
2536                    let flank = (1.0 / e - 1.0) * speed(kk).signum() * x[n + kk];
2537                    if flanks >> bit & 1 == 1 { (c - flank).max(0.0) } else { (flank - c).max(0.0) }
2538                })
2539                .sum()
2540        };
2541        // Rounds until the rows settle: a gearbox's loss factor fades over its power (`mech::settled_loss`), and a
2542        // locking worm at rest that breaks loose takes its drag from the round that found it stuck.
2543        for _ in 0..12 {
2544            let x = (0..1usize << moving.len())
2545                .map(|flanks| {
2546                    let x = solve_rows(&rows, flanks);
2547                    (missed(&rows, flanks, &x), x)
2548                })
2549                .min_by(|a, b| a.0.total_cmp(&b.0))
2550                .map(|(_, x)| x)
2551                .unwrap_or_default();
2552            solved.acc = x[..n].to_vec();
2553            for kk in 0..m {
2554                solved.into[kk] = self.ratio[kk]
2555                    * (drive[kk] - self.j_rotor[kk] * self.ratio[kk] * self.pulley_angle(kk, &solved.acc));
2556                solved.out[kk] = x[n + kk];
2557            }
2558            let before = rows.clone();
2559            for kk in 0..m {
2560                rows[kk] = match (rows[kk], locking[kk]) {
2561                    (Row::Stuck | Row::Drag(_), Some(worm)) if sticks(kk) => {
2562                        // Stuck, or broken loose this step: the bounds of the drag at rest.
2563                        let ends =
2564                            [-(1.0 / worm.efficiency - 1.0) * holds[kk], (1.0 - worm.back_efficiency) * holds[kk]];
2565                        let (low, high) = (ends[0].min(ends[1]), ends[0].max(ends[1]));
2566                        let drag = solved.out[kk] - solved.into[kk];
2567                        match rows[kk] {
2568                            Row::Stuck if (low..=high).contains(&drag) => Row::Stuck,
2569                            Row::Stuck => Row::Drag(drag.clamp(low, high)),
2570                            kept => kept,
2571                        }
2572                    }
2573                    (_, Some(w)) => moving_row(kk, &w, solved.out[kk]),
2574                    (_, None) => {
2575                        let (output, rotor) = self.rigid_factors(kk, solved.into[kk], speed(kk));
2576                        Row::Factors(output, rotor)
2577                    }
2578                };
2579            }
2580            if rows == before {
2581                break;
2582            }
2583        }
2584        solved
2585    }
2586
2587    /// Kinetic, potential and elastic energy (see `ENERGY_PARTS`).
2588    fn energy_parts(&self, s: &[f64]) -> [f64; 3] {
2589        let (n, m, v) = (self.n(), self.m(), self.vel());
2590        let q = &s[..n];
2591        let potential = self.potential(q);
2592        let mut stops: f64 = (0..self.nt()).map(|i| self.stops.energy(q[i], self.stroke[i])).sum();
2593        // The gantry's yaw spring.
2594        stops += self.gantry.as_ref().map_or(0.0, |g| 0.5 * g.stiffness * q[g.coord] * q[g.coord]);
2595        let vq = &s[v..v + n];
2596        let quadratic = |mass: &[Vec<f64>], w: &[f64]| 0.5 * (0..n).map(|i| w[i] * dot(&mass[i], w)).sum::<f64>();
2597        if !self.elastic {
2598            return [quadratic(&self.rigid_mass(q), vq), potential, stops];
2599        }
2600        // Over the axes, the sway and the lean (`elastic_mass`).
2601        let (u, du) = self.sway(s);
2602        let frame = self.frame.as_ref().map_or(0.0, |f| 0.5 * f.stiffness * u * u);
2603        let mut speeds = vq.to_vec();
2604        speeds.extend(self.frame.as_ref().map(|_| du));
2605        speeds.extend(self.lean.as_ref().map(|_| self.leaning(s).1));
2606        speeds.extend(self.beam.as_ref().map(|_| self.deflection(s).1));
2607        let elastic_mass = self.elastic_mass(q);
2608        let kinetic = 0.5 * speeds.iter().zip(&elastic_mass).map(|(a, row)| a * dot(row, &speeds)).sum::<f64>();
2609        let mut turning: f64 = (0..m)
2610            .map(|kk| {
2611                0.5 * self.j_pulley[kk] * s[v + n + kk].powi(2) + 0.5 * self.j_rotor[kk] * s[v + n + m + kk].powi(2)
2612            })
2613            .sum();
2614        for (j, (jump, ..)) in self.jumps.iter().enumerate() {
2615            let kk = self.jump_motor[j];
2616            turning += jump.slip_energy(&s[self.jump_at(j)..], self.r[kk] * s[v + n + kk]);
2617        }
2618        let lean = self.lean.as_ref().map_or(0.0, |lean| 0.5 * flex_at(lean, q).0 * self.leaning(s).0.powi(2));
2619        // The leaning body's weight rises as it leans: its potential 1/2 c w^2 (`lean_weight`).
2620        let potential = potential
2621            + self.lean.as_ref().map_or(0.0, |lean| {
2622                let c = lean_weight(lean, q, self.body_mass(&self.bodies[lean.body]), self.g).0;
2623                0.5 * c * self.leaning(s).0.powi(2)
2624            });
2625        let (geo, mat, longer) = (self.geo(q), self.mat(s), self.lean_lengths(s).0);
2626        let belt: f64 = (0..geo.len()).map(|i| self.belt.energy(geo[i] + longer[i], mat[i])).sum();
2627        let gears: f64 =
2628            (0..m).map(|kk| self.gears[kk].energy_with(s[n + m + kk], self.output(s, kk).0, self.arm(s, kk))).sum();
2629        // The beam: the carried weight at w lower, the beam's own at -phi w (its first moment, -p0 w), and its spring,
2630        // which holds the stress of the beam's own sag: its cross term with the mode is +g p0 w by virtual work
2631        // (EI u'''' = mu g), so the beam's weight does no work on w in all.
2632        let (w, k) = (self.deflection(s).0, self.beam_mode(q)[0]);
2633        // As the frame momentum has the beam's own mass: with a body on the beam's axis that does not ride the vertical.
2634        let own = self
2635            .beam
2636            .as_ref()
2637            .filter(|b| self.bodies.iter().any(|body| body.axes[b.axis] && !body.axes[b.vertical]))
2638            .map_or(0.0, |b| self.g * b.shape_moments(q[b.axis])[0] * w);
2639        let potential = potential - self.beam_weight() * w - own;
2640        let beam = 0.5 * k * w * w + own;
2641        [kinetic + turning, potential, stops + belt + gears + frame + lean + beam]
2642    }
2643
2644    /// The loss powers in the order of `effect_infos`, and per motor the gearbox loss as a torque at the rotor and the
2645    /// brake torque, which the torque breakdown takes too.
2646    fn losses(&self, s: &[f64], torque: &[f64]) -> (Vec<f64>, Vec<f64>, Vec<f64>) {
2647        let (n, m, v) = (self.n(), self.m(), self.vel());
2648        let (q, vq) = self.positions(s);
2649        let fa = self.friction_at();
2650        let (friction, _) = self.friction(q, vq, &s[fa..fa + n], torque);
2651        let (mut angle, mut speed) = (vec![0.0; m], vec![0.0; m]);
2652        self.motor_state(s, &mut angle, &mut speed);
2653        let (mut gear_loss, mut gear_power, mut brake, mut mesh_in) = (vec![0.0; m], vec![0.0; m], vec![0.0; m], 0.0);
2654        let (mut belt, mut tool_v) = (0.0, vq.to_vec());
2655        if self.elastic {
2656            for kk in 0..m {
2657                let (phi, w_phi) = (s[n + m + kk], s[v + n + m + kk]);
2658                let (theta, w_theta) = self.output(s, kk);
2659                let gear = self.gear_torque(kk, phi, w_phi, theta, w_theta, self.arm(s, kk));
2660                brake[kk] = self.brakes[kk].torque(self.brake_engaged, w_phi, s[self.brake_at() + kk]).0;
2661                let drive = self.ripples[kk].apply(torque[kk], phi) - self.shafts[kk].torque(w_phi) - brake[kk];
2662                let drag = self.worm_drag(kk, gear.rotor, w_phi, drive);
2663                gear_loss[kk] = gear.rotor + drag - gear.output / self.ratio[kk];
2664                gear_power[kk] = self.gear_loss_power(kk, [phi, w_phi, theta, w_theta], self.arm(s, kk), drag);
2665                mesh_in += self.r[kk] * self.mesh_force(kk, self.r[kk] * theta) * w_theta;
2666            }
2667            let (geo, mat, (_, rate)) = (self.geo(q), self.mat(s), self.fed(s));
2668            let (longer, longer_rate) = self.lean_lengths(s);
2669            for (i, sec) in self.sections.iter().enumerate() {
2670                let mat_rate: f64 = (0..m).map(|kk| sec.f[kk] * self.r_mat[kk] * rate[kk]).sum();
2671                belt += self.belt.loss_power(geo[i] + longer[i], mat[i], dot(&sec.c, vq) + longer_rate[i], mat_rate);
2672            }
2673            if let Some(f) = &self.frame {
2674                tool_v[f.axis] += self.sway(s).1;
2675            }
2676            // The tool's velocity (`tool_state`): with the lean's tip, its rise and the beam's deflection.
2677            if let Some(lean) = &self.lean {
2678                let ((u, du), [a, da, _]) = (self.leaning(s), rise_coefficients(lean, q));
2679                tool_v[lean.axis] += self.tip(q) * du;
2680                if let Some(z) = lean.lever_axis {
2681                    tool_v[lean.axis] += tip_slope(lean, q)[0] * u * vq[z];
2682                    tool_v[z] += 2.0 * a * u * du + da * u * u * vq[z];
2683                }
2684            }
2685            if let Some(b) = &self.beam {
2686                tool_v[b.vertical] -= self.deflection(s).1;
2687            }
2688        } else {
2689            let solved = self.rigid_solve(s, torque);
2690            for kk in 0..m {
2691                brake[kk] = self.brakes[kk].torque(self.brake_engaged, speed[kk], s[self.brake_at() + kk]).0;
2692                gear_loss[kk] = (solved.into[kk] - solved.out[kk]) / self.ratio[kk];
2693                gear_power[kk] = gear_loss[kk] * speed[kk];
2694                mesh_in += self.mesh_force(kk, self.r[kk] * angle[kk] / self.ratio[kk])
2695                    * self.r[kk]
2696                    * self.pulley_angle(kk, vq);
2697            }
2698        }
2699        let mut powers: Vec<f64> = self.guides.iter().map(|g| friction[g.axis] * vq[g.axis]).collect();
2700        // The gearboxes' drag acts on the rotors but is the gearboxes' loss.
2701        let drag: Vec<f64> = (0..m).map(|kk| self.shafts[kk].drag_power(speed[kk])).collect();
2702        // The rotaries' bearing friction at the output is booked with the shaft friction of the motor that turns the axis.
2703        let bearing = self.bearing_force(vq);
2704        let at_output = |kk: usize| match self.direct[kk].as_ref() {
2705            Some(d) => {
2706                bearing[d.axis] * vq[d.axis] / self.direct.iter().flatten().filter(|o| o.axis == d.axis).count() as f64
2707            }
2708            None => 0.0,
2709        };
2710        powers.extend(
2711            (0..m).map(|kk| (self.shafts[kk].torque(speed[kk]) + brake[kk]) * speed[kk] - drag[kk] + at_output(kk)),
2712        );
2713        powers.extend((0..m).map(|kk| gear_power[kk] + drag[kk]));
2714        if !self.idlers.is_empty() {
2715            powers.push(self.idler_friction(vq).1);
2716        }
2717        if self.chain_axes.contains(&true) {
2718            powers.push(dot(&self.chain_drag(vq), vq));
2719        }
2720        powers.push(belt);
2721        if self.frame_node {
2722            powers.push(self.frame.as_ref().map_or(0.0, |f| f.damping * self.sway(s).1.powi(2)));
2723        }
2724        if self.lean_node.is_some() {
2725            powers.push(self.lean.as_ref().map_or(0.0, |lean| lean.damping * self.leaning(s).1.powi(2)));
2726        }
2727        if let Some(g) = &self.gantry {
2728            powers.push(g.damping * vq[g.coord] * vq[g.coord]);
2729        }
2730        let ripple: f64 =
2731            (0..m).map(|kk| (torque[kk] - self.ripples[kk].apply(torque[kk], angle[kk])) * speed[kk]).sum();
2732        let stops: f64 = (0..self.nt()).map(|i| self.stops.loss_power(q[i], vq[i], self.stroke[i])).sum();
2733        powers.extend([stops, ripple - mesh_in - dot(&self.dwelling_force(), &tool_v)]);
2734        if !self.jumps.is_empty() {
2735            powers.push(self.jump_loss);
2736        }
2737        if self.beam.is_some() {
2738            powers.push(self.beam_mode(q)[2] * self.deflection(s).1.powi(2));
2739        }
2740        (powers, gear_loss, brake)
2741    }
2742
2743    /// The signals of the effect views, in the order of `effect_infos`. Torque parts per motor, through (J^T)^-1:
2744    /// inertia from the mass matrices times the axes' accelerations (bodies, chains and idlers at their speed over
2745    /// ground, pulleys and rotors as a rigid machine would turn them, and what picking up chain costs), gravity, and
2746    /// friction (guides, idlers, chains, and at the motor its shaft friction, brake and gearbox loss); the rest is the
2747    /// motor torque less these, so belt and gearbox ringing are in it.
2748    fn view_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
2749        let (n, m) = (self.n(), self.m());
2750        let (q, vq) = self.positions(s);
2751        let fa = self.friction_at();
2752        let states = &s[fa..fa + n];
2753        let (friction, _) = self.friction(q, vq, states, torque);
2754        let (mut angle, mut speed) = (vec![0.0; m], vec![0.0; m]);
2755        self.motor_state(s, &mut angle, &mut speed);
2756        let (powers, gear_loss, brake) = self.losses(s, torque);
2757        // The axes' rows of the mass matrix (`elastic_mass`, with the sway and the lean) times the accelerations, and the
2758        // pulleys and rotors at the axes' (`drive_mass`).
2759        let (acc, moved) = if self.elastic {
2760            let mut d = vec![0.0; self.state_len()];
2761            self.elastic_derivatives(s, torque, &mut d);
2762            let mut all = d[self.vel()..self.vel() + n].to_vec();
2763            all.extend(self.frame.as_ref().map(|_| d[self.vel() + self.frame_at()]));
2764            all.extend(self.lean.as_ref().map(|_| d[self.vel() + self.lean_at()]));
2765            all.extend(self.beam.as_ref().map(|_| d[self.vel() + self.beam_at()]));
2766            let mass = self.elastic_mass(q);
2767            (all[..n].to_vec(), (0..n).map(|i| dot(&mass[i], &all)).collect::<Vec<f64>>())
2768        } else {
2769            let acc = self.rigid_solve(s, torque).acc;
2770            let (axis_mass, runs) = (self.axis_mass(q), self.runs_mass(q, [0.0; 3]).0);
2771            let moved = (0..n).map(|i| dot(&axis_mass[i], &acc) + dot(&runs[i], &acc)).collect();
2772            (acc, moved)
2773        };
2774        let (drive_mass, (chain, _)) = (self.drive_mass(), self.chain_inertia(vq, self.sway(s).1));
2775        let (inertial, runs) = (self.inertial(q, vq), self.runs_speed(q, vq, self.sway_direction(), self.sway(s).1).0);
2776        let inertia: Vec<f64> =
2777            (0..n).map(|i| moved[i] + dot(&drive_mass[i], &acc) - chain[i] - inertial[i] - runs[i]).collect();
2778        let gravity: Vec<f64> = self.gravity(q).iter().map(|g| -g).collect();
2779        let (idlers, drag) = (self.idler_friction(vq).0, self.chain_drag(vq));
2780        let bearing = self.bearing_force(vq);
2781        let resisting: Vec<f64> = (0..n).map(|i| friction[i] - idlers[i] + drag[i] + bearing[i]).collect();
2782        let [inertia, gravity, friction_at] = [inertia, gravity, resisting].map(|f| self.to_motors(&f));
2783        for kk in 0..m {
2784            let parts = [
2785                inertia[kk],
2786                gravity[kk],
2787                self.shafts[kk].torque(speed[kk]) + brake[kk] + gear_loss[kk] + friction_at[kk],
2788            ];
2789            out.extend(parts);
2790            out.push(torque[kk] - parts.iter().sum::<f64>());
2791        }
2792        out.extend(powers);
2793        out.extend(self.energy_parts(s));
2794        for (g, scale) in self.guides.iter().zip(self.load_scales(q, torque)) {
2795            out.push(vq[g.axis]);
2796            out.extend(g.friction.split(vq[g.axis], states[g.axis], scale));
2797            out.push(scale);
2798        }
2799        let geo = self.geo(q);
2800        let mat = if self.elastic { self.mat(s) } else { geo.iter().map(|g| self.belt.rest_length(*g)).collect() };
2801        out.extend(geo.iter().zip(&mat).map(|(g, l)| g - l));
2802    }
2803
2804    fn effect_infos(&self, out: &mut Vec<SignalInfo>) {
2805        for motor in &self.motors {
2806            out.extend(TORQUE_PARTS.map(|part| {
2807                SignalInfo::new(
2808                    format!("motor.{}.torque_{part}", motor.id),
2809                    motor.key,
2810                    &format!("quantity-torque-{part}"),
2811                    "N m",
2812                )
2813            }));
2814        }
2815        for g in &self.guides {
2816            out.push(SignalInfo::new(
2817                format!("{LOSS_PREFIX}{}", g.loss_id),
2818                self.axes[g.axis].key,
2819                "quantity-friction-power",
2820                "W",
2821            ));
2822        }
2823        for motor in &self.motors {
2824            out.push(SignalInfo::new(
2825                format!("{LOSS_PREFIX}shaft_{}", motor.id),
2826                motor.key,
2827                "quantity-shaft-friction-power",
2828                "W",
2829            ));
2830        }
2831        for (motor, coupled) in self.motors.iter().zip(&self.coupled) {
2832            let quantity = if *coupled { "quantity-coupling-loss-power" } else { "quantity-gearbox-loss-power" };
2833            out.push(SignalInfo::new(format!("{LOSS_PREFIX}gearbox_{}", motor.id), motor.key, quantity, "W"));
2834        }
2835        if !self.idlers.is_empty() {
2836            out.push(SignalInfo::new(format!("{LOSS_PREFIX}idlers"), "group-idler", "quantity-friction-power", "W"));
2837        }
2838        if self.chain_axes.contains(&true) {
2839            out.push(SignalInfo::new(
2840                format!("{LOSS_PREFIX}cable_chain"),
2841                "group-cable_chain",
2842                "quantity-friction-power",
2843                "W",
2844            ));
2845        }
2846        out.push(SignalInfo::new(format!("{LOSS_PREFIX}belt"), "group-belt", "quantity-damping-power", "W"));
2847        if self.frame_node {
2848            out.push(SignalInfo::new(format!("{LOSS_PREFIX}frame"), "frame", "quantity-damping-power", "W"));
2849        }
2850        if self.lean_node.is_some() {
2851            out.push(SignalInfo::new(
2852                format!("{LOSS_PREFIX}tool_flex"),
2853                "group-tool_flex",
2854                "quantity-damping-power",
2855                "W",
2856            ));
2857        }
2858        if let Some(g) = &self.gantry {
2859            out.push(SignalInfo::new(
2860                format!("{LOSS_PREFIX}gantry_{}", g.id),
2861                "group-gantry_yaw",
2862                "quantity-damping-power",
2863                "W",
2864            ));
2865        }
2866        out.push(SignalInfo::new(format!("{LOSS_PREFIX}hard_stops"), "group-hard_stop", "quantity-damping-power", "W"));
2867        out.push(SignalInfo::new(format!("{LOSS_PREFIX}other"), "loss-other", "quantity-power-given-off", "W"));
2868        if !self.jumps.is_empty() {
2869            out.push(SignalInfo::new(
2870                format!("{LOSS_PREFIX}tooth_jump"),
2871                "group-belt",
2872                "quantity-tooth-jump-power",
2873                "W",
2874            ));
2875        }
2876        if self.beam.is_some() {
2877            out.push(SignalInfo::new(format!("{LOSS_PREFIX}beam"), "group-beam", "quantity-damping-power", "W"));
2878        }
2879        out.extend(ENERGY_PARTS.map(|part| {
2880            SignalInfo::new(format!("energy.{part}"), "group-energy", &format!("quantity-energy-{part}"), "J")
2881        }));
2882        for g in &self.guides {
2883            for part in FRICTION_SIGNALS {
2884                let unit = match part {
2885                    "speed" => "m/s",
2886                    "load_scale" => "",
2887                    _ => "N",
2888                };
2889                out.push(SignalInfo::new(
2890                    format!("{}.friction_{part}", g.contact),
2891                    self.axes[g.axis].key,
2892                    &format!("quantity-friction-{}", part.replace('_', "-")),
2893                    unit,
2894                ));
2895            }
2896        }
2897        out.extend(
2898            self.sections
2899                .iter()
2900                .map(|s| SignalInfo::new(format!("{}.stretch", s.id), s.key, "quantity-section-stretch", "m")),
2901        );
2902    }
2903
2904    /// The first-mode frequency of each span (`span_frequency`) at its section's tension, and how far the nearest of
2905    /// them is from what the drives excite (`span_detuning`).
2906    fn span_signals(&self, s: &[f64], mass: f64, out: &mut Vec<f64>) {
2907        let (n, m) = (self.n(), self.m());
2908        let (q, tension) = (&s[..n], self.tensions(s));
2909        let (mut angle, mut speed) = (vec![0.0; m], vec![0.0; m]);
2910        self.motor_state(s, &mut angle, &mut speed);
2911        let mut excitations = Vec::with_capacity(3 * m);
2912        for kk in (0..m).filter(|&kk| self.direct[kk].is_none()) {
2913            let pulley = if self.elastic { s[self.vel() + n + kk] } else { speed[kk] / self.ratio[kk] };
2914            drive_excitations(self.mesh.pitch, self.r[kk] * pulley, &self.ripples[kk], speed[kk], &mut excitations);
2915        }
2916        let frequencies: Vec<f64> =
2917            self.spans.iter().map(|p| span_frequency(p.length + dot(&p.c, q), tension[p.section], mass)).collect();
2918        out.extend(&frequencies);
2919        out.push(frequencies.iter().map(|f| span_detuning(*f, &excitations)).fold(1.0, f64::min));
2920    }
2921
2922    /// The sections' tensions at rest at q and their unstretched belt, L_s / (1 + T_s / EA): the tensions hold every axis
2923    /// against gravity, sum_s c_si T_s = gravity_i, and each closed belt keeps its material, sum over its sections of
2924    /// L_s / (1 + T_s / EA) = what it had at q = 0. Newton from the pretension; the first equations are linear, the
2925    /// others nearly so. The frame stands at 0: nothing pulls along its horizontal axis. An axis a screw, rack, linear
2926    /// motor or rotary drives is held by that, not by the belt. A yaw left to its spring is not among the equations: its
2927    /// balance sets the yaw (`settled_yaw`), which q brings.
2928    fn rest_tensions(&self, q: &[f64]) -> (Vec<f64>, Vec<f64>) {
2929        let (n, geo, gravity) = (self.n(), self.geo(q), self.gravity(q));
2930        let (ea, slack) = (self.belt.ea, self.belt.slack);
2931        let taut = |t: f64| if slack { t.max(0.0) } else { t };
2932        let mut tension = vec![self.belt.pretension; self.sections.len()];
2933        let sprung = self.gantry.as_ref().filter(|_| self.yaw_sprung()).map(|g| g.coord);
2934        let belt_held: Vec<usize> = (0..n).filter(|&i| !self.driven(i) && Some(i) != sprung).collect();
2935        for _ in 0..50 {
2936            let mut jac: Vec<Vec<f64>> =
2937                belt_held.iter().map(|&i| self.sections.iter().map(|s| s.c[i]).collect()).collect();
2938            let mut res: Vec<f64> =
2939                belt_held.iter().zip(&jac).map(|(&i, row)| gravity[i] - dot(row, &tension)).collect();
2940            for belt in &self.loops {
2941                let mut row = vec![0.0; self.sections.len()];
2942                let mut held = 0.0;
2943                for &s in belt {
2944                    let stretch = 1.0 + taut(tension[s]) / ea;
2945                    held += geo[s] / stretch - self.sections[s].mat0;
2946                    row[s] = if slack && tension[s] < 0.0 { 0.0 } else { -geo[s] / (ea * stretch * stretch) };
2947                }
2948                jac.push(row);
2949                res.push(-held);
2950            }
2951            let step = lstsq(&jac, &res).unwrap_or_else(|| vec![0.0; self.sections.len()]);
2952            tension.iter_mut().zip(&step).for_each(|(t, d)| *t += d);
2953            if step.iter().all(|d| d.abs() < 1e-12 * (1.0 + self.belt.pretension)) {
2954                break;
2955            }
2956        }
2957        let mat = geo.iter().zip(&tension).map(|(g, t)| g / (1.0 + taut(*t) / ea)).collect();
2958        (tension, mat)
2959    }
2960
2961    /// The force each screw, rack, linear motor or rotary passes to its axis at rest at q with the belts at `tension`
2962    /// (zero for the belt motors): the balance of the driven coordinates, the gearboxes' outputs against the belt's pull
2963    /// and gravity, in least squares where two drives share an axis. A gantry's yaw left to its spring is not among
2964    /// them: the spring holds it (`settled_yaw`).
2965    fn held_forces(&self, q: &[f64], tension: &[f64]) -> Vec<f64> {
2966        let taut = |t: f64| if self.belt.slack { t.max(0.0) } else { t };
2967        let gravity = self.gravity(q);
2968        let drives: Vec<usize> = (0..self.m()).filter(|&kk| self.direct[kk].is_some()).collect();
2969        let sprung = self.yaw_sprung();
2970        let rows: Vec<usize> = (0..self.n()).filter(|&i| self.driven(i) && !(sprung && i >= self.nt())).collect();
2971        let a: Vec<Vec<f64>> = rows.iter().map(|&i| drives.iter().map(|&kk| self.k[kk][i]).collect()).collect();
2972        let b: Vec<f64> = rows
2973            .iter()
2974            .map(|&i| self.sections.iter().zip(tension).map(|(s, t)| s.c[i] * taut(*t)).sum::<f64>() - gravity[i])
2975            .collect();
2976        let mut held = vec![0.0; self.m()];
2977        if !drives.is_empty() {
2978            let solved = lstsq(&a, &b).unwrap_or_else(|| vec![0.0; drives.len()]);
2979            drives.iter().zip(solved).for_each(|(&kk, o)| held[kk] = o);
2980        }
2981        held
2982    }
2983
2984    /// A yawing gantry whose yaw the motors do not set (fewer motors than coordinates): its spring holds it.
2985    fn yaw_sprung(&self) -> bool {
2986        self.gantry.is_some() && self.m() < self.n()
2987    }
2988
2989    /// The yaw's resting deflection, which a yaw left to its spring takes: the sum of the forces on the coordinate
2990    /// vanishes, sum_drives side F_d - k psi = sum_s c_s,psi T_s - G_psi (the drives' moment, the spring's, the belts'
2991    /// pull and gravity's), the tensions at that yaw (`rest_tensions`: the belts keep their length with it) and the
2992    /// drives' forces from the axes' balance. Solved for psi by the secant method from psi = f(0) / k, 0 if it does not
2993    /// converge.
2994    fn settled_yaw(&self, q: &[f64]) -> f64 {
2995        let Some(g) = &self.gantry else { return 0.0 };
2996        let residual = |psi: f64| -> f64 {
2997            let mut at = q.to_vec();
2998            at[g.coord] = psi;
2999            if !self.elastic {
3000                // The rigid model: the motors' torques at the pulleys carry the other coordinates against gravity, K^T P =
3001                // -gravity there (least squares, the yaw's row left out), and what P then puts on the yaw less the spring's
3002                // and gravity's leaves the residual, as the belts' pull does above.
3003                let gravity = self.gravity(&at);
3004                let rows: Vec<usize> = (0..self.n()).filter(|&i| i != g.coord).collect();
3005                let kt: Vec<Vec<f64>> = rows.iter().map(|&i| (0..self.m()).map(|kk| self.k[kk][i]).collect()).collect();
3006                let pulley = lstsq(&kt, &rows.iter().map(|&i| -gravity[i]).collect::<Vec<_>>())
3007                    .unwrap_or_else(|| vec![0.0; self.m()]);
3008                let moment: f64 = (0..self.m()).map(|kk| self.k[kk][g.coord] * pulley[kk]).sum();
3009                return moment - g.stiffness * psi + gravity[g.coord];
3010            }
3011            let (tension, _) = self.rest_tensions(&at);
3012            let held = self.held_forces(&at, &tension);
3013            let taut = |t: f64| if self.belt.slack { t.max(0.0) } else { t };
3014            let moment: f64 =
3015                (0..self.m()).filter(|&kk| self.direct[kk].is_some()).map(|kk| self.k[kk][g.coord] * held[kk]).sum();
3016            let pull: f64 = self.sections.iter().zip(&tension).map(|(s, t)| s.c[g.coord] * taut(*t)).sum();
3017            moment - g.stiffness * psi - (pull - self.gravity(&at)[g.coord])
3018        };
3019        let (mut x0, mut f0) = (0.0, residual(0.0));
3020        if f0 == 0.0 || g.stiffness <= 0.0 {
3021            return 0.0;
3022        }
3023        let mut x1 = f0 / g.stiffness;
3024        for _ in 0..40 {
3025            let f1 = residual(x1);
3026            if !f1.is_finite() || f1 == f0 {
3027                return if f1.is_finite() { x1 } else { 0.0 };
3028            }
3029            let x2 = x1 - f1 * (x1 - x0) / (f1 - f0);
3030            if (x2 - x1).abs() <= 1e-14 + 1e-12 * x1.abs() {
3031                return x2;
3032            }
3033            (x0, f0, x1) = (x1, f1, x2);
3034        }
3035        0.0
3036    }
3037
3038    /// The lowest belt mode at a pose (elastic model): the axes (and the frame, where it sways, and the leaning body,
3039    /// where it leans) on the belt's stiffness with the pulleys held, K = sum_s EA / l_s c_s c_s^T (l_s the section's
3040    /// unstretched belt at rest; plus the frame's and
3041    /// the lean's springs), against their mass matrix (see `energy_parts`): (w^2, the axes', frame's and lean's motion).
3042    fn belt_mode(&self, pose: &[f64]) -> Option<(f64, Vec<f64>)> {
3043        let (mass, stiffness) = self.mode_matrices(pose)?;
3044        lowest_mode(&mass, &stiffness)
3045    }
3046
3047    /// The mass and stiffness matrices of the modes at a pose (`belt_mode`), over the axes, the yaw, the frame, the lean
3048    /// and the beam; `None` in the rigid model.
3049    fn mode_matrices(&self, pose: &[f64]) -> Option<(Vec<Vec<f64>>, Vec<Vec<f64>>)> {
3050        if !self.elastic {
3051            return None;
3052        }
3053        // dT/dL = EA / l of `Belt::section`, l the section's unstretched belt at rest at the pose (`rest_tensions`), as
3054        // the crates take it.
3055        let (n, rest) = (self.n(), self.rest_tensions(pose).1);
3056        let mass = self.elastic_mass(pose);
3057        let d = mass.len();
3058        let mut stiffness = vec![vec![0.0; d]; d];
3059        for i in 0..n {
3060            for (sec, length) in self.sections.iter().zip(&rest) {
3061                for l in 0..n {
3062                    stiffness[i][l] += self.belt.ea / length * sec.c[i] * sec.c[l];
3063                }
3064            }
3065        }
3066        // The runs' offset beside the leaning body (`lean_offset`): its sections change with the lean too.
3067        self.add_lean_offset(pose, &rest, &mut stiffness, |length| self.belt.ea / length);
3068        // A screw's, rack's, linear motor's or rotary's gearbox (with its converter) holds its axis on the rotor.
3069        for (kk, d) in self.direct.iter().enumerate() {
3070            if d.is_some() {
3071                let (k, gear) = (&self.k[kk], self.gears[kk].at(self.pulley_angle(kk, pose)));
3072                for i in 0..n {
3073                    for l in 0..n {
3074                        stiffness[i][l] += gear.stiffness * k[i] * k[l];
3075                    }
3076                }
3077            }
3078        }
3079        if let Some(g) = &self.gantry {
3080            stiffness[g.coord][g.coord] += g.stiffness;
3081        }
3082        if let Some(f) = &self.frame {
3083            stiffness[n][n] = f.stiffness;
3084        }
3085        if let Some(lean) = &self.lean {
3086            let mass = self.body_mass(&self.bodies[lean.body]);
3087            let lr = self.lean_row();
3088            let process = self.process_force();
3089            // The lean's own stiffness at the pose moved along the lever axis by `step`: its spring, the weight's
3090            // pendulum stiffness, the belt runs' geometric stiffness (at the tensions at rest, `lean_runs`) and the
3091            // process force's vertical part on the tip's rise (`rise_coefficients`), V = 1/2 k_u(z) u^2 - F tip(z) u. At
3092            // the lean u0 = tip F / k_u that the pose's sideways process force F holds: K_uu = k_u, K_uz = k_u' u0 -
3093            // F tip', K_zz = 1/2 k_u'' u0^2 - F tip'' u0 (central differences over 1e-4 m; the crate's `modal`).
3094            let tension = self.rest_tensions(pose).0;
3095            let k_u = |step: f64| {
3096                let mut at = pose.to_vec();
3097                if let Some(z) = lean.lever_axis {
3098                    at[z] += step;
3099                }
3100                let (runs, rise) = (self.lean_runs(&at), rise_coefficients(lean, &at)[0]);
3101                let process_z = lean.lever_axis.map_or(0.0, |z| process[z]);
3102                flex_at(lean, &at).0
3103                    + lean_weight(lean, &at, mass, self.g).0
3104                    + tension.iter().zip(&runs).map(|(t, c)| t * c).sum::<f64>()
3105                    - 2.0 * process_z * rise
3106            };
3107            let here = k_u(0.0);
3108            stiffness[lr][lr] += here;
3109            if let Some(z) = lean.lever_axis {
3110                let (ahead, behind, step) = (k_u(1e-4), k_u(-1e-4), 1e-4);
3111                let (u0, [dtip, ddtip]) = (flex_at(lean, pose).2 * process[lean.axis] / here, tip_slope(lean, pose));
3112                let uz = (ahead - behind) / (2.0 * step) * u0 - process[lean.axis] * dtip;
3113                stiffness[lr][z] += uz;
3114                stiffness[z][lr] += uz;
3115                stiffness[z][z] +=
3116                    0.5 * (ahead - 2.0 * here + behind) / (step * step) * u0 * u0 - process[lean.axis] * ddtip * u0;
3117            }
3118        }
3119        // The beam's deflection w: 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 and
3120        // K_xx += k'' w0^2 / 2 (k'' by a central difference over 1e-4 m, as the crate takes it).
3121        if let Some(b) = &self.beam {
3122            let (at, x) = (self.beam_row(), b.axis);
3123            let [k, _, _, dk, _] = self.beam_mode(pose);
3124            let w0 = self.beam_weight() / k;
3125            let slope = |h: f64| {
3126                let mut moved = pose.to_vec();
3127                moved[x] += h;
3128                self.beam_mode(&moved)[3]
3129            };
3130            let ddk = (slope(1e-4) - slope(-1e-4)) / 2e-4;
3131            stiffness[at][at] += k;
3132            stiffness[at][x] += dk * w0;
3133            stiffness[x][at] += dk * w0;
3134            stiffness[x][x] += 0.5 * ddk * w0 * w0;
3135        }
3136        Some((mass, stiffness))
3137    }
3138
3139    /// With the runs' offset beside the leaning body (`lean_offset`, e per section): each section's row over the
3140    /// coordinates gains e at the lean's, so `matrix` (stiffness or damping, `per(l)` per section of unstretched belt l)
3141    /// gains per(l) (g g^T - c c^T) for g = c + e at the lean's row: the lean's diagonal and its couplings.
3142    fn add_lean_offset(&self, pose: &[f64], rest: &[f64], matrix: &mut [Vec<f64>], per: impl Fn(f64) -> f64) {
3143        if self.lean.is_none() {
3144            return;
3145        }
3146        let (n, lr, e) = (self.n(), self.lean_row(), self.lean_offset(pose));
3147        for ((sec, length), e) in self.sections.iter().zip(rest).zip(e).filter(|(_, e)| *e != 0.0) {
3148            let k = per(*length);
3149            for i in 0..n {
3150                matrix[i][lr] += k * sec.c[i] * e;
3151                matrix[lr][i] += k * sec.c[i] * e;
3152            }
3153            matrix[lr][lr] += k * e * e;
3154        }
3155    }
3156
3157    /// The damping matrix over the coordinates of `mode_matrices` at a pose, for a mode at w (rad/s): each belt section's
3158    /// c + c_t EA / l on its length's rate (`Belt::section`, the pulleys held), the gearbox's damper behind a screw,
3159    /// rack, linear motor or rotary at w (`Gearbox::damping_at`, a Zener arm damping by frequency) on its output's
3160    /// travel, the yaw's, the frame's, the lean's and the beam's dampers.
3161    fn mode_damping(&self, pose: &[f64], w: f64, dim: usize) -> Vec<Vec<f64>> {
3162        let (n, rest) = (self.n(), self.rest_tensions(pose).1);
3163        let mut c = vec![vec![0.0; dim]; dim];
3164        for (sec, length) in self.sections.iter().zip(&rest) {
3165            let damper = self.belt.damping + self.belt.damping_time * self.belt.ea / length;
3166            for i in 0..n {
3167                for l in 0..n {
3168                    c[i][l] += damper * sec.c[i] * sec.c[l];
3169                }
3170            }
3171        }
3172        self.add_lean_offset(pose, &rest, &mut c, |length| {
3173            self.belt.damping + self.belt.damping_time * self.belt.ea / length
3174        });
3175        for (kk, d) in self.direct.iter().enumerate() {
3176            if d.is_some() {
3177                let (k, damper) = (&self.k[kk], self.gears[kk].at(self.pulley_angle(kk, pose)).damping_at(w));
3178                for i in 0..n {
3179                    for l in 0..n {
3180                        c[i][l] += damper * k[i] * k[l];
3181                    }
3182                }
3183            }
3184        }
3185        if let Some(g) = &self.gantry {
3186            c[g.coord][g.coord] += g.damping;
3187        }
3188        if let Some(f) = &self.frame {
3189            c[n][n] += f.damping;
3190        }
3191        if let Some(lean) = &self.lean {
3192            c[self.lean_row()][self.lean_row()] += lean.damping;
3193        }
3194        if self.beam.is_some() {
3195            c[self.beam_row()][self.beam_row()] += self.beam_mode(pose)[2];
3196        }
3197        c
3198    }
3199
3200    /// Where the scene draws a pose: each axis runs from the origin along its incline in the x-z plane.
3201    fn scene_at(&self, q: &[f64], moves: &[bool]) -> [f64; 3] {
3202        let mut p = scene_origin();
3203        // Up by the incline, and across: the first axis along x, the others along y (`dirs`). A rotary axis turns
3204        // its table in place.
3205        for i in (0..self.n()).filter(|i| moves[*i]) {
3206            (0..3).for_each(|k| p[k] += self.dirs[i][k] * q[i]);
3207        }
3208        p
3209    }
3210    /// Where the scene draws the pulley of motor `kk` at the pose `q`: its `at_m` (from its body where it rides on one),
3211    /// else at the ends of the first axis, two by two further down.
3212    fn pulley_scene_at(&self, kk: usize, q: &[f64]) -> [f64; 3] {
3213        let end = self.stroke[0];
3214        let at = self.pulley_at[kk].unwrap_or([
3215            if kk.is_multiple_of(2) { -0.1 } else { end + 0.1 },
3216            -0.05,
3217            -0.15 * (kk / 2) as f64,
3218        ]);
3219        match self.pulley_body[kk] {
3220            Some(b) => {
3221                let body = self.scene_at(q, &self.bodies[b].axes);
3222                [body[0] + at[0], body[1] + at[1], body[2] + at[2]]
3223            }
3224            None => at,
3225        }
3226    }
3227    /// A screw, rack or magnet track along its axis from 0 to its stroke, carried by what carries the axis (the first
3228    /// body it moves, without its own travel), with the motor at the 0 end; a rotary as a disc where the motor's pulley
3229    /// would be, its mark turned with the axis. Where the motor's label goes.
3230    fn direct_scene(&self, kk: usize, d: &Direct, q: &[f64], out: &mut Scene) -> [f64; 3] {
3231        let motor = [0.9, 0.45, 0.1];
3232        let id = match d.kind {
3233            DirectKind::Screw(_) => "screw",
3234            DirectKind::Rack(_) => "rack",
3235            DirectKind::Linear { .. } => "magnet-track",
3236            DirectKind::Rotary(_) => {
3237                // At the bodies that ride on it, where there are some.
3238                let at = self.bodies.iter().find(|b| b.rotaries.contains(&d.axis)).map_or_else(
3239                    || self.pulley_scene_at(kk, q),
3240                    |b| {
3241                        let carried: Vec<bool> = (0..self.n()).map(|i| b.axes[i] && i != d.axis).collect();
3242                        self.scene_at(q, &carried)
3243                    },
3244                );
3245                out.parts.push(Part::new(
3246                    "table",
3247                    Shape::Cylinder { radius: 0.15, length: 0.04 },
3248                    at,
3249                    [0.55, 0.55, 0.6],
3250                ));
3251                out.parts.push(
3252                    Part::new(
3253                        "index-mark",
3254                        Shape::Box { size: [0.27, 0.004, 0.02] },
3255                        [at[0], at[1] - 0.025, at[2]],
3256                        [0.1, 0.1, 0.1],
3257                    )
3258                    .turned(q[d.axis]),
3259                );
3260                out.parts.push(Part::new(
3261                    MOTOR_PART,
3262                    Shape::Cylinder { radius: 0.04, length: 0.1 },
3263                    [at[0], at[1], at[2] - 0.1],
3264                    motor,
3265                ));
3266                return at;
3267            }
3268        };
3269        let moves =
3270            self.bodies.iter().find(|b| b.axes[d.axis]).map_or_else(|| vec![false; self.n()], |b| b.axes.clone());
3271        let mut pose = q.to_vec();
3272        pose[d.axis] = 0.0;
3273        // At a yawing gantry's side: across the bridge from where its across axis puts the carriage at 0.
3274        let side = |p: [f64; 3]| match self.gantry.as_ref().and_then(|g| g.across.map(|a| (a, d.side - g.shift))) {
3275            Some((a, across)) if d.side != 0.0 => [0, 1, 2].map(|k| p[k] + self.dirs[a][k] * across),
3276            _ => p,
3277        };
3278        let start = side(self.scene_at(&pose, &moves));
3279        pose[d.axis] = self.stroke[d.axis];
3280        let end = side(self.scene_at(&pose, &moves));
3281        out.parts.push(Part::new(id, Shape::Segment { to: end, width: 0.02 }, start, [0.75, 0.75, 0.78]));
3282        // A linear motor's forcer rides on the carriage.
3283        let motor_at = if matches!(d.kind, DirectKind::Linear { .. }) { side(self.scene_at(q, &moves)) } else { start };
3284        out.parts.push(Part::new(MOTOR_PART, Shape::Cylinder { radius: 0.04, length: 0.1 }, motor_at, motor));
3285        motor_at
3286    }
3287    fn idler_scene_at(&self, d: &Idler, q: &[f64]) -> [f64; 3] {
3288        let at = d.at.unwrap_or_default();
3289        match d.body {
3290            Some(b) => {
3291                let body = self.scene_at(q, &self.bodies[b].axes);
3292                [body[0] + at[0], body[1] + at[1], body[2] + at[2]]
3293            }
3294            None => at,
3295        }
3296    }
3297    /// The default plane of the belts in the 3D view (a section without `plane`), as the scene's coordinates [along, up,
3298    /// depth]: x-z seen from the front, or x-y seen from above where the belt lies flat, a section's length changing with
3299    /// axes along x and along y and none along z (an H-bot's, a CoreXY's).
3300    fn belt_plane(&self) -> [usize; 3] {
3301        let flat = self.sections.iter().any(|s| {
3302            let along = |k: usize| (0..self.n()).any(|i| s.c[i] != 0.0 && self.dirs[i][k].abs() > 1e-9);
3303            along(0) && along(1) && !along(2)
3304        });
3305        if flat { [0, 1, 2] } else { [0, 2, 1] }
3306    }
3307    /// The plane section `s`'s belt runs in: its `plane`, else the default (`belt_plane`).
3308    fn plane(&self, s: usize) -> [usize; 3] {
3309        self.sections[s].plane.unwrap_or_else(|| self.belt_plane())
3310    }
3311    /// The plane a wheel turns in: that of the first section its pulley feeds or whose route runs past it (the
3312    /// sections that share a wheel share their plane); the default for a wheel on no section.
3313    fn wheel_plane(&self, w: Waypoint) -> [usize; 3] {
3314        let on = |s: usize| match w {
3315            Waypoint::Pulley(kk) => self.sections[s].f[kk] != 0.0 || self.sections[s].route.contains(&w),
3316            _ => self.route_waypoints(s).contains(&w),
3317        };
3318        (0..self.sections.len()).find(|&s| on(s)).map_or_else(|| self.belt_plane(), |s| self.plane(s))
3319    }
3320    /// A point of the plane `plane` at the depth `depth`, in the 3D view.
3321    fn in_view(p: [f64; 2], depth: f64, plane: [usize; 3]) -> [f64; 3] {
3322        let mut out = [0.0; 3];
3323        (out[plane[0]], out[plane[1]], out[plane[2]]) = (p[0], p[1], depth);
3324        out
3325    }
3326    /// A waypoint of a belt as a wheel in the plane `plane`, its radius signed by the sense the belt runs round it, and
3327    /// where the 3D view puts it at the pose `q`.
3328    fn wheel(&self, w: Waypoint, q: &[f64], plane: [usize; 3]) -> (Wheel, [f64; 3]) {
3329        let sense = |clockwise: bool| if clockwise { -1.0 } else { 1.0 };
3330        let (at, radius) = match w {
3331            Waypoint::Pulley(kk) => (self.pulley_scene_at(kk, q), self.r[kk] * sense(self.clockwise.0[kk])),
3332            Waypoint::Idler(d) => {
3333                let idler = &self.idlers[d];
3334                (self.idler_scene_at(idler, q), idler.radius * sense(self.clockwise.1[d]))
3335            }
3336            Waypoint::Body(b) => (self.scene_at(q, &self.bodies[b].axes), 0.0),
3337        };
3338        (Wheel { centre: [at[plane[0]], at[plane[1]]], radius }, at)
3339    }
3340
3341    /// Where each span (a straight run of the belt) lies at the pose `q`: the tangent points on the two wheels of its
3342    /// section's route (`contacts`) it runs between, each with its waypoint, in the frame of the bodies' places (the 3D
3343    /// view's, less where `scene_at` starts). The section's spans are taken in order as the route's consecutive pairs of
3344    /// waypoints; `None` for a section whose span count is not the route's pairs, and for a pair with no straight piece.
3345    fn run_ends(&self, q: &[f64]) -> Vec<Option<[(Waypoint, [f64; 3]); 2]>> {
3346        let mut next = vec![0usize; self.sections.len()];
3347        let routes: Vec<Vec<Waypoint>> = (0..self.sections.len()).map(|s| self.route_waypoints(s)).collect();
3348        let mut count = vec![0usize; self.sections.len()];
3349        self.spans.iter().for_each(|span| count[span.section] += 1);
3350        self.spans
3351            .iter()
3352            .map(|span| {
3353                let (route, at) = (&routes[span.section], next[span.section]);
3354                next[span.section] += 1;
3355                if count[span.section] + 1 != route.len() {
3356                    return None;
3357                }
3358                let plane = self.plane(span.section);
3359                let ((a, pa), (b, pb)) = (self.wheel(route[at], q, plane), self.wheel(route[at + 1], q, plane));
3360                let [from, to] = contacts(a, b);
3361                let (deep, origin) = (plane[2], scene_origin());
3362                let place = |p: [f64; 2], depth: f64| -> [f64; 3] {
3363                    let at = Self::in_view(p, depth, plane);
3364                    std::array::from_fn(|k| at[k] - origin[k])
3365                };
3366                let ends = [(route[at], place(from, pa[deep])), (route[at + 1], place(to, pb[deep]))];
3367                ends.iter().all(|(_, p)| p.iter().all(|x| x.is_finite())).then_some(ends)
3368            })
3369            .collect()
3370    }
3371
3372    /// The belt of section `s` as the 3D view draws it, a polyline in scene coordinates: its straight runs from tangent
3373    /// to tangent between the wheels of its route (`geometry::contacts`), round each wheel inside the route in the
3374    /// wheel's sense (`geometry::arc`). Each point keeps the depth of its wheel off the belt's plane.
3375    fn belt_line(&self, s: usize, q: &[f64]) -> Vec<[f64; 3]> {
3376        let route = self.route_waypoints(s);
3377        let plane = self.plane(s);
3378        let wheels: Vec<(Wheel, [f64; 3])> = route.iter().map(|&w| self.wheel(w, q, plane)).collect();
3379        let (deep, view) = (plane[2], |p, depth| Self::in_view(p, depth, plane));
3380        let mut line = Vec::new();
3381        for (i, pair) in wheels.windows(2).enumerate() {
3382            let [(a, pa), (b, pb)] = [pair[0], pair[1]];
3383            let [leave, meet] = contacts(a, b);
3384            if i > 0 {
3385                // Round wheel a from where the run before met it.
3386                let came = contacts(wheels[i - 1].0, a)[1];
3387                line.extend(arc(a, came, leave, ARC_PIECES).into_iter().skip(1).map(|p| view(p, pa[deep])));
3388            } else {
3389                line.push(view(leave, pa[deep]));
3390            }
3391            line.push(view(meet, pb[deep]));
3392        }
3393        line
3394    }
3395
3396    /// The wraps round the belt motors' pulleys between the section that ends at each and the one that starts there
3397    /// (`wrap_neighbours`' rule), as polylines with the section that ends there; none where a pulley does not end one
3398    /// route and start another.
3399    fn pulley_wraps(&self, q: &[f64]) -> Vec<(usize, Vec<[f64; 3]>)> {
3400        let routes: Vec<Vec<Waypoint>> = (0..self.sections.len()).map(|s| self.route_waypoints(s)).collect();
3401        (0..self.m())
3402            .filter(|&kk| self.direct[kk].is_none())
3403            .filter_map(|kk| {
3404                let me = Waypoint::Pulley(kk);
3405                let ends: Vec<usize> = (0..routes.len()).filter(|&i| routes[i].last() == Some(&me)).collect();
3406                let starts: Vec<usize> = (0..routes.len()).filter(|&i| routes[i].first() == Some(&me)).collect();
3407                let (&[section], &[next]) = (&ends[..], &starts[..]) else { return None };
3408                let (before, after) = (*routes[section].iter().rev().nth(1)?, *routes[next].get(1)?);
3409                let plane = self.plane(section);
3410                let ((wheel, at), from, to) =
3411                    (self.wheel(me, q, plane), self.wheel(before, q, plane).0, self.wheel(after, q, plane).0);
3412                let points = arc(wheel, contacts(from, wheel)[1], contacts(wheel, to)[0], ARC_PIECES);
3413                Some((section, points.into_iter().map(|p| Self::in_view(p, at[plane[2]], plane)).collect()))
3414            })
3415            .collect()
3416    }
3417
3418    /// The axis a wheel spins about per rad/s of the belt running along its section's route: the normal of its plane
3419    /// (`wheel_plane`, [along, up, depth]), pointing as a clockwise turn seen in the plane (along to the right, up up)
3420    /// does, -(along x up): +y in x-z (seen from the front, the viewer at -y), -z in x-y (from above), -x in y-z (from +x);
3421    /// reversed for a wheel the belt runs round counter-clockwise.
3422    fn wheel_axis(plane: [usize; 3], clockwise: bool) -> [f64; 3] {
3423        let unit = |k: usize| std::array::from_fn::<f64, 3, _>(|i| if i == k { 1.0 } else { 0.0 });
3424        let cw = cross(unit(plane[0]), unit(plane[1])).map(|c| -c);
3425        cw.map(|c| if clockwise { c } else { -c })
3426    }
3427    /// +1 where a positive turn of pulley kk, or a positive speed past an idler of section `sec` (fed by that pulley),
3428    /// moves the belt along the section's route, -1 against it: the belt goes from the pulley into a section it feeds
3429    /// (`f` = +1), so along the route where the route starts at the pulley and against it where it ends there; reversed
3430    /// for a section it takes from (`f` = -1).
3431    fn route_sense(&self, sec: usize, kk: usize) -> f64 {
3432        let f = self.sections[sec].f[kk];
3433        if self.route_waypoints(sec).last() == Some(&Waypoint::Pulley(kk)) { -f } else { f }
3434    }
3435
3436    /// The waypoints a section's belt runs through: its `route`, else its pulleys and the body it is clamped to (the
3437    /// one that moves with most of the axes its length changes with, and the fewest others).
3438    fn route_waypoints(&self, s: usize) -> Vec<Waypoint> {
3439        let sec = &self.sections[s];
3440        let mut route = sec.route.clone();
3441        if route.is_empty() {
3442            route.extend((0..self.m()).filter(|&kk| sec.f[kk] != 0.0).map(Waypoint::Pulley));
3443            let fits = |b: &Body| {
3444                let shared = (0..self.n()).filter(|&i| sec.c[i] != 0.0 && b.axes[i]).count() as i64;
3445                (shared, -((0..self.n()).filter(|&i| sec.c[i] == 0.0 && b.axes[i]).count() as i64))
3446            };
3447            if let Some(b) =
3448                (0..self.bodies.len()).filter(|&b| fits(&self.bodies[b]).0 > 0).max_by_key(|&b| fits(&self.bodies[b]))
3449            {
3450                route.insert(
3451                    if sec.f.iter().position(|f| *f != 0.0).is_some_and(|kk| sec.f[kk] < 0.0) {
3452                        0
3453                    } else {
3454                        route.len()
3455                    },
3456                    Waypoint::Body(b),
3457                );
3458            }
3459        }
3460        route
3461    }
3462}
3463
3464impl ConfigMachine {
3465    /// The racking moment of a yawing gantry (effects.gantry_yaw) at a tool pose and acceleration, N m: what the belts'
3466    /// pull on the bridge's ends (`rigid_tensions`), its drives at its sides and gravity put on its yaw beyond what
3467    /// turns the bodies on it with the bridge held square, in the loss-free rigid model. The yaw's spring takes it while
3468    /// the acceleration lasts (signal gantry.<id>.moment). Zero where two drives set the yaw; `None` without a yawing
3469    /// gantry.
3470    pub fn racking_moment(&self, pos: &[f64], acc: &[f64]) -> Option<f64> {
3471        let g = self.gantry.as_ref()?;
3472        let (q, _, ddq) = self.joint_motion(pos, &vec![0.0; pos.len()], acc);
3473        let mut tensions = Vec::new();
3474        self.rigid_tensions(pos, acc, &mut tensions);
3475        let (mass, gravity) = (self.axis_mass(&q), self.gravity(&q));
3476        let wanted: Vec<f64> = (0..self.n())
3477            .map(|i| {
3478                let belt: f64 = self.sections.iter().zip(&tensions).map(|(s, t)| s.c[i] * t).sum();
3479                dot(&mass[i], &ddq) - gravity[i] + belt
3480            })
3481            .collect();
3482        // The drives' forces: on the coordinates they set (the yaw too where two of them do).
3483        let drives: Vec<usize> = (0..self.m()).filter(|&kk| self.direct[kk].is_some()).collect();
3484        let rows: Vec<usize> =
3485            (0..self.n()).filter(|&i| self.driven(i) && (i < self.nt() || self.m() >= self.n())).collect();
3486        let a: Vec<Vec<f64>> = rows.iter().map(|&i| drives.iter().map(|&kk| self.k[kk][i]).collect()).collect();
3487        let b: Vec<f64> = rows.iter().map(|&i| wanted[i]).collect();
3488        let forces = if drives.is_empty() { Vec::new() } else { lstsq(&a, &b)? };
3489        let driving: f64 = drives.iter().zip(&forces).map(|(&kk, f)| self.k[kk][g.coord] * f).sum();
3490        Some(driving - wanted[g.coord])
3491    }
3492
3493    /// `belt_wraps` at the coordinates q.
3494    fn wraps_at(&self, q: &[f64]) -> Vec<f64> {
3495        let mut out = vec![f64::NAN; self.m()];
3496        for &(kk, before, after) in &self.wraps {
3497            let plane = self.wheel_plane(Waypoint::Pulley(kk));
3498            let wheel = |w: Waypoint| self.wheel(w, q, plane).0;
3499            out[kk] = wrap(wheel(before), wheel(Waypoint::Pulley(kk)), wheel(after));
3500        }
3501        out
3502    }
3503}
3504
3505impl Machine for ConfigMachine {
3506    /// Each body moving with its axes (an axis with the id x, y or z along that direction), over ground with the frame's
3507    /// sway and the lean; the frame's own mass in its sway; a rotary axis's inertia turning about its own axis; the process
3508    /// force on the tool, each along its axis's direction (`dirs`, whatever the axis's id). The belt drives' spin: a
3509    /// pulley, its rotor and the idlers turn about the normal of the belt's plane (`belt_plane`), a screw's rotor about
3510    /// its axis, I w each. The sense of a wheel: the belt along its section's route turns it as its `clockwise` says (seen
3511    /// from the front, from above for a flat belt), and a positive pulley turn and an idler's positive `speed` move the
3512    /// belt as the first pulley of the section feeds it (`route_sense`). A rack's pinion turns about up x e (e the rack's
3513    /// direction, the pinion riding with the axis above the rack fixed to the frame; a vertical rack's y x e), a rotary's motor about the rotary's own axis, positive
3514    /// as the axis grows. The belt's runs carry angular momentum m x (mu L y) too, each about the middle of its straight
3515    /// piece (`run_ends`); the arcs round the wheels are in the wheels' spin. What does not move is left out (see
3516    /// `FrameMomentum`).
3517    fn frame_momentum(&self, s: &[f64]) -> Option<sim_core::FrameMomentum> {
3518        // The axes, not the coordinates: a yawing gantry's yaw is one more, which no tool axis has.
3519        let n = self.axes.len();
3520        let g = self.g_along.first().zip(self.g_across.first()).map_or(0.0, |(a, b)| a.hypot(*b));
3521        let mut f = sim_core::FrameMomentum { gravity: [0.0, 0.0, -g], ..Default::default() };
3522        let (mut pos, mut vel) = (vec![0.0; n], vec![0.0; n]);
3523        self.tool_state(s, &mut pos, &mut vel);
3524        let (q, v) = self.positions(s);
3525        let (mut ground, mut place) = (v.to_vec(), q.to_vec());
3526        if let Some(fr) = &self.frame {
3527            let (u, du) = self.sway(s);
3528            ground[fr.axis] += du;
3529            place[fr.axis] += u;
3530            let e = self.sway_direction();
3531            for k in 0..3 {
3532                f.linear[k] += fr.mass * du * e[k];
3533                f.first_moment[k] += fr.mass * u * e[k];
3534            }
3535        }
3536        let mut beam_done = false;
3537        // The cable chains' moving runs, mass mu (L0 + q / 2) at their axis's speed over ground, as on the crates: where the
3538        // first body along that axis is (its first moment mu (L0 q + q^2 / 4) along the axis, whose rate that is, and the
3539        // sway's on top).
3540        for i in (0..self.n()).filter(|&i| self.chain_axes[i]) {
3541            let (m, e) = (self.chain.mass(q[i]).0, self.dirs[i]);
3542            let moment =
3543                self.chain.mass_per_m * (self.chain.length0 * q[i] + 0.25 * q[i] * q[i]) + m * (place[i] - q[i]);
3544            let at = self.bodies.iter().find(|b| b.axes[i]).map_or([0.0; 3], |b| self.body_point(b, &place));
3545            let l = cross(at, e.map(|e| m * ground[i] * e));
3546            for k in 0..3 {
3547                f.linear[k] += m * ground[i] * e[k];
3548                f.angular[k] += l[k];
3549                f.first_moment[k] += moment * e[k];
3550            }
3551            f.mass += m;
3552        }
3553        for (b, body) in self.bodies.iter().enumerate() {
3554            // Where the body is (straight axes, its offset turned by the rotaries it rides on) and how fast, by the
3555            // Jacobian of that place: a rotary's lever arm and omega x r come with it.
3556            let mut r = self.body_point(body, &place);
3557            let mut w = [0.0; 3];
3558            for (i, column) in self.body_jacobian(body, &place).iter().enumerate() {
3559                (0..3).for_each(|k| w[k] += column[k] * ground[i]);
3560            }
3561            // A body that does not move along the frame's axis rides on the frame.
3562            if self.frame.as_ref().is_some_and(|fr| !body.axes[fr.axis]) {
3563                let (e, (u, du)) = (self.sway_direction(), self.sway(s));
3564                (0..3).for_each(|k| (r[k], w[k]) = (r[k] + u * e[k], w[k] + du * e[k]));
3565            }
3566            if let Some(lean) = self.lean.as_ref().filter(|l| l.body == b) {
3567                let (e, (x, dx)) = (self.dirs[lean.axis], self.leaning(s));
3568                (0..3).for_each(|k| (r[k], w[k]) = (r[k] + x * e[k], w[k] + dx * e[k]));
3569            }
3570            // The bodies that move along the beam hang w lower with it.
3571            if let Some(beam) = self.beam.as_ref().filter(|beam| body.axes[beam.axis]) {
3572                let (e, (x, dx)) = (self.dirs[beam.vertical], self.deflection(s));
3573                (0..3).for_each(|k| (r[k], w[k]) = (r[k] - x * e[k], w[k] - dx * e[k]));
3574            }
3575            sim_components::base::add_point(&mut f, self.body_mass(body), r, w);
3576            // The beam's own mass moves with its mode: its point s from the left post, at r_c + (s - a) e along the beam
3577            // from the carriage's point r_c (a its place on the beam), by -phi(s; x) w along the vertical, at
3578            // -(phi w' + phi_x x' w) (`BeamMode::shape_moments`, the x-rates by central differences over 1e-6 m).
3579            if let Some(beam) = self.beam.as_ref().filter(|beam| body.axes[beam.axis] && !body.axes[beam.vertical])
3580                && !std::mem::replace(&mut beam_done, true)
3581            {
3582                let (x, (dev, rate)) = (q[beam.axis], self.deflection(s));
3583                let moments = |x: f64| beam.shape_moments(x);
3584                let [p0, p1] = moments(x);
3585                let dp: Vec<f64> = (0..2).map(|i| (moments(x + 1e-6)[i] - moments(x - 1e-6)[i]) / 2e-6).collect();
3586                let (along, up, a) = (self.dirs[beam.axis], self.dirs[beam.vertical], beam.at(x));
3587                let (m0, m1) = (
3588                    p0 * rate + dp[0] * v[beam.axis] * dev,
3589                    (p1 - a * p0) * rate + (dp[1] - a * dp[0]) * v[beam.axis] * dev,
3590                );
3591                let lever: [f64; 3] = std::array::from_fn(|k| m0 * r[k] + m1 * along[k]);
3592                let turn = cross(lever, up);
3593                for k in 0..3 {
3594                    f.linear[k] -= m0 * up[k];
3595                    f.angular[k] -= turn[k];
3596                    f.first_moment[k] -= p0 * dev * up[k];
3597                }
3598            }
3599        }
3600        // Each rotary's own spin, about its axis as the rotaries outside it have turned it.
3601        let rotary_axis = |i: usize| {
3602            let outer =
3603                self.bodies.iter().find_map(|b| b.rotaries.iter().position(|&r| r == i).map(|at| &b.rotaries[..at]));
3604            self.turned_by(outer.unwrap_or(&[]), q, self.turn[i])
3605        };
3606        for i in (0..n).filter(|&i| self.axes[i].unit == "rad") {
3607            let turned = self.turned[i].0 + if self.payload_attached { self.turned[i].1 } else { 0.0 };
3608            let axis = rotary_axis(i);
3609            (0..3).for_each(|k| f.angular[k] += turned * v[i] * axis[k]);
3610        }
3611        // The belt drives' spin (see above): pulleys, rotors and idlers.
3612        let (mut turn, mut rotor_speed) = (vec![0.0; self.m()], vec![0.0; self.m()]);
3613        self.motor_state(s, &mut turn, &mut rotor_speed);
3614        let (nn, vv) = (self.n(), self.vel());
3615        for kk in 0..self.m() {
3616            let mut ax =
3617                |axis: [f64; 3], w: f64, inertia: f64| (0..3).for_each(|k| f.angular[k] += inertia * w * axis[k]);
3618            match (&self.direct[kk], self.sections.iter().position(|sec| sec.f[kk] != 0.0)) {
3619                (None, Some(sec)) => {
3620                    let w_pulley = if self.elastic { s[vv + nn + kk] } else { self.pulley_angle(kk, v) };
3621                    let sense = self.route_sense(sec, kk);
3622                    let (cw, r) = (self.clockwise.0[kk], self.r[kk]);
3623                    let spin = Self::wheel_axis(self.plane(sec), cw);
3624                    ax(spin, sense * w_pulley, (self.j_pulley[kk] - self.lump * r * r).max(0.0));
3625                    ax(spin, sense * rotor_speed[kk], self.j_rotor[kk]);
3626                }
3627                (Some(Direct { kind: DirectKind::Screw(_), axis, .. }), _) => {
3628                    ax(self.dirs[*axis], rotor_speed[kk], self.j_rotor[kk]);
3629                }
3630                // A rack's pinion rides with the axis on the rack fixed to the frame, above it (a vertical rack's on its
3631                // +y side): rolling forward along the rack's direction e it turns about up x e (y x e). A rotary's rotor
3632                // turns about the rotary's own axis, as the rotaries outside it have turned it.
3633                (Some(Direct { kind: DirectKind::Rack(_), axis, .. }), _) => {
3634                    let e = self.dirs[*axis];
3635                    let across = if e[2].abs() > 0.999 { [0.0, 1.0, 0.0] } else { [0.0, 0.0, 1.0] };
3636                    let a = cross(across, e);
3637                    let size = dot(&a, &a).sqrt();
3638                    ax(a.map(|a| a / size), rotor_speed[kk], self.j_rotor[kk]);
3639                }
3640                (Some(Direct { kind: DirectKind::Rotary(_), axis, .. }), _) => {
3641                    ax(rotary_axis(*axis), rotor_speed[kk], self.j_rotor[kk]);
3642                }
3643                _ => {}
3644            }
3645        }
3646        for (d, idler) in self.idlers.iter().enumerate() {
3647            let Some(sec) =
3648                (0..self.sections.len()).find(|&sec| self.route_waypoints(sec).contains(&Waypoint::Idler(d)))
3649            else {
3650                continue;
3651            };
3652            let Some(first) = (0..self.m()).find(|&kk| self.sections[sec].f[kk] != 0.0) else { continue };
3653            let w = self.route_sense(sec, first) * dot(&idler.speed, v) / idler.radius;
3654            let spin = Self::wheel_axis(self.plane(sec), self.clockwise.1[d]);
3655            (0..3).for_each(|k| f.angular[k] += idler.mass * idler.radius * idler.radius * w * spin[k]);
3656        }
3657        // The belt's runs (`runs_mass`), each at V_s v over ground and the sway on top: momentum mu sum L_s y_s, and the
3658        // first moment mu sum (L0_s + c_s . q / 2) V_s q, whose rate that is (the belt's runs being one piece), with
3659        // mu L e u of the sway.
3660        // The runs' angular momentum, m_s x (mu L_s y_s) about the origin of the bodies' places, from where each run lies
3661        // (`run_ends`, the middle of its straight piece, the sway on top).
3662        if self.run_mass > 0.0 {
3663            let (e, (u, du)) = (self.sway_direction(), self.sway(s));
3664            let ends = self.run_ends(q);
3665            // With the beam's mode the runs riding on it (`riding_share`) go down by their share of w: the vertical ones
3666            // whole, the tilting ones by w / 2 on average. A tilting run's point at the share xi of the way from its
3667            // fixed end f to the end c on the carriage goes down by xi w: its first moment is w / 2 at the middle, its
3668            // angular momentum from w' the weighted point's, f + 2/3 (c - f), as the crate has it.
3669            let (up, (dev, rate)) =
3670                (self.beam.as_ref().map_or([0.0; 3], |b| self.dirs[b.vertical]), self.deflection(s));
3671            let rides = |w: Waypoint| {
3672                let Some(b) = &self.beam else { return false };
3673                let body = match w {
3674                    Waypoint::Body(body) => Some(body),
3675                    Waypoint::Idler(d) => self.idlers[d].body,
3676                    Waypoint::Pulley(kk) => self.pulley_body[kk],
3677                };
3678                body.is_some_and(|body| self.bodies[body].axes[b.axis])
3679            };
3680            for (span, ends) in self.spans.iter().zip(ends) {
3681                let middle = ends.map(|[(_, a), (_, b)]| std::array::from_fn::<f64, 3, _>(|k| 0.5 * (a[k] + b[k])));
3682                let Some(rows) = &span.velocity else { continue };
3683                let weight = self.run_mass * (span.length + dot(&span.c, q));
3684                let moment = self.run_mass * (span.length + 0.5 * dot(&span.c, q));
3685                let share = self.beam.as_ref().and_then(|b| riding_share(span, up, b)).unwrap_or(0.0);
3686                let y: [f64; 3] = std::array::from_fn(|k| dot(&rows[k], v) + e[k] * du - share * rate * up[k]);
3687                for k in 0..3 {
3688                    f.linear[k] += weight * y[k];
3689                    f.first_moment[k] += moment * dot(&rows[k], q) + weight * (e[k] * u - share * dev * up[k]);
3690                }
3691                f.mass += weight;
3692                if let (Some(m), Some([(wa, a), (wb, b)])) = (middle, ends) {
3693                    let at = std::array::from_fn(|k| m[k] + e[k] * u - share * dev * up[k]);
3694                    let mut turning = cross(at, y);
3695                    // A tilting run: its w' at the weighted point, a sixth of the run from the middle towards the carriage.
3696                    if share == 0.5 && rides(wa) != rides(wb) {
3697                        let (fixed, carried) = if rides(wb) { (a, b) } else { (b, a) };
3698                        let off: [f64; 3] = std::array::from_fn(|k| (carried[k] - fixed[k]) / 6.0);
3699                        let more = cross(off, up.map(|c| -share * rate * c));
3700                        (0..3).for_each(|k| turning[k] += more[k]);
3701                    }
3702                    (0..3).for_each(|k| f.angular[k] += weight * turning[k]);
3703                }
3704            }
3705        }
3706        // The process force acts on the tool along the axes' directions, at the tool's place over ground. An obstacle's
3707        // push is not in it: a compliant base takes it through the tool's shift (`base::Based`).
3708        for (i, force) in self.dwelling_force().iter().enumerate().take(n) {
3709            (0..3).for_each(|k| f.external[k] += *force * self.dirs[i][k]);
3710        }
3711        for i in (0..n).filter(|&i| self.axes[i].unit != "rad") {
3712            (0..3).for_each(|k| f.external_at[k] += pos[i] * self.dirs[i][k]);
3713        }
3714        Some(f)
3715    }
3716    fn axes(&self) -> &[AxisInfo] {
3717        &self.axes
3718    }
3719    fn motors(&self) -> &[MotorInfo] {
3720        &self.motors
3721    }
3722    fn motor_linear(&self, motor: usize) -> bool {
3723        matches!(self.direct.get(motor), Some(Some(Direct { kind: DirectKind::Linear { .. }, .. })))
3724    }
3725
3726    fn inverse(&self, tool: &[f64], motors: &mut [f64]) {
3727        self.motor_angles(&self.joints(tool), motors);
3728    }
3729    /// The motors set the coordinates they can (`k_inv`); a gantry's yaw they leave to its spring stands at 0.
3730    fn forward(&self, motors: &[f64], tool: &mut [f64]) {
3731        let q: Vec<f64> = (0..self.n())
3732            .map(|i| (0..self.m()).map(|kk| self.k_inv[i][kk] * motors[kk] / self.ratio[kk]).sum())
3733            .collect();
3734        tool.copy_from_slice(&self.tool_of(&q));
3735    }
3736
3737    fn state_len(&self) -> usize {
3738        self.arm_at() + (0..self.m()).filter(|&kk| self.arm_slot(kk).is_some()).count()
3739    }
3740
3741    fn equilibrium(&self, tool: &[f64], state: &mut Vec<f64>, torque: &mut [f64]) {
3742        let (n, m) = (self.n(), self.m());
3743        *state = vec![0.0; self.state_len()];
3744        let mut q = self.joints(tool);
3745        // Where the motors leave a gantry's yaw to its spring, the drives' moment about it deflects the spring.
3746        if self.yaw_sprung() {
3747            q[self.gantry.as_ref().map_or(0, |g| g.coord)] = self.settled_yaw(&q);
3748        }
3749        // With the beam mode the Z axis stands on its belt above the beam's sag, which the beam rests at.
3750        let sag = self.sag_at_rest(&mut q);
3751        let tool = &q[..];
3752        state[..n].copy_from_slice(tool);
3753        if self.beam.is_some() {
3754            state[self.beam_at()] = sag;
3755        }
3756        let gravity = self.gravity(tool);
3757        if !self.elastic {
3758            // K^T (pulley torque + r mesh force) = -gravity.
3759            let kt: Vec<Vec<f64>> = (0..n).map(|i| (0..m).map(|kk| self.k[kk][i]).collect()).collect();
3760            // With the yaw on its spring (`settled_yaw`) the spring's force -k psi is among the forces to hold.
3761            let spring = self.yaw_force(tool, &vec![0.0; n]);
3762            let at_pulley = lstsq(&kt, &gravity.iter().zip(&spring).map(|(g, y)| -g - y).collect::<Vec<_>>())
3763                .unwrap_or_else(|| vec![0.0; m]);
3764            for kk in 0..m {
3765                let angle = self.ratio[kk] * self.pulley_angle(kk, tool);
3766                let shaft = (at_pulley[kk] - self.r[kk] * self.mesh_force(kk, self.r[kk] * angle / self.ratio[kk]))
3767                    / self.ratio[kk];
3768                torque[kk] = self.ripples[kk].invert(shaft * self.held(kk), angle);
3769            }
3770            return;
3771        }
3772        let geo = self.geo(tool);
3773        let (tension, mat) = self.rest_tensions(tool);
3774        // The belt motors' pulley angles that feed that material (a motor without a pulley feeds none).
3775        let belted: Vec<usize> = (0..m).filter(|&kk| self.direct[kk].is_none()).collect();
3776        let fed: Vec<Vec<f64>> =
3777            self.sections.iter().map(|s| belted.iter().map(|&kk| s.f[kk] * self.r_mat[kk]).collect()).collect();
3778        let change: Vec<f64> = self.sections.iter().zip(&mat).map(|(s, l)| l - s.mat0).collect();
3779        let mut angles = vec![0.0; m];
3780        for (&kk, a) in belted.iter().zip(lstsq(&fed, &change).unwrap_or_else(|| vec![0.0; belted.len()])) {
3781            angles[kk] = a;
3782        }
3783        let material: Vec<f64> =
3784            geo.iter().zip(&mat).map(|(g, l)| self.belt.section(*g, *l, 0.0, 0.0).material).collect();
3785        // The force balance of the coordinates the screws, racks, linear motors and rotaries drive: their gearboxes'
3786        // outputs, the belt's pull and gravity (two drives at a gantry's sides share it by their places).
3787        let held = self.held_forces(tool, &tension);
3788        for kk in 0..m {
3789            let (theta, gear) = match &self.direct[kk] {
3790                Some(_) => (self.pulley_angle(kk, tool), held[kk]),
3791                None => {
3792                    let belt: f64 =
3793                        self.r_mat[kk] * self.sections.iter().zip(&material).map(|(s, f)| s.f[kk] * f).sum::<f64>();
3794                    (angles[kk], -belt - self.r[kk] * self.mesh.force(self.r[kk] * angles[kk]))
3795                }
3796            };
3797            let phi = self.ratio[kk] * (theta + self.gears[kk].static_twist_at(theta, gear));
3798            state[n + kk] = theta;
3799            state[n + m + kk] = phi;
3800            torque[kk] =
3801                self.ripples[kk].invert(self.gears[kk].held_at(theta, gear) * self.held(kk) / self.ratio[kk], phi);
3802            // The gear's arm at rest carries nothing.
3803            if let Some(i) = self.arm_slot(kk) {
3804                state[i] = self.gears[kk].arm_rest(phi, self.output(state, kk).0);
3805            }
3806        }
3807    }
3808
3809    fn derivatives(&self, s: &[f64], torque: &[f64], out: &mut [f64]) {
3810        if self.elastic {
3811            return self.elastic_derivatives(s, torque, out);
3812        }
3813        let (n, m) = (self.n(), self.m());
3814        let solved = self.rigid_solve(s, torque);
3815        out[..n].copy_from_slice(&s[n..2 * n]);
3816        out[n..2 * n].copy_from_slice(&solved.acc);
3817        out[2 * n..3 * n].copy_from_slice(&solved.rates);
3818        for kk in 0..m {
3819            let speed = self.ratio[kk] * self.pulley_angle(kk, &s[n..2 * n]);
3820            out[3 * n + kk] = self.brakes[kk].torque(self.brake_engaged, speed, s[3 * n + kk]).1;
3821        }
3822    }
3823
3824    /// The tool is where the axes put it on the frame, and the frame sways: the workpiece stands on the floor.
3825    fn tool_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
3826        let (q, v) = self.positions(s);
3827        pos.copy_from_slice(&self.tool_of(q));
3828        vel.copy_from_slice(&self.tool_speed(q, v));
3829        if let Some(f) = &self.frame {
3830            let (u, du) = self.sway(s);
3831            pos[f.axis] += u;
3832            vel[f.axis] += du;
3833        }
3834        // The tool sits at the tip of the leaning body.
3835        if let Some(lean) = &self.lean {
3836            let ((w, dw), tip) = (self.leaning(s), self.tip(q));
3837            pos[lean.axis] += tip * w;
3838            vel[lean.axis] += tip * dw;
3839            // The leaning body's tip rises by a u^2 along the lever axis (`rise_coefficients`).
3840            if let Some(z) = lean.lever_axis {
3841                let [rise, d_rise, _] = rise_coefficients(lean, q);
3842                vel[lean.axis] += tip_slope(lean, q)[0] * w * v[z];
3843                pos[z] += rise * w * w;
3844                vel[z] += 2.0 * rise * w * dw + d_rise * w * w * v[z];
3845            }
3846        }
3847        // The carriage hangs w lower on the beam, and the tool with it.
3848        if let Some(b) = &self.beam {
3849            let (w, dw) = self.deflection(s);
3850            pos[b.vertical] -= w;
3851            vel[b.vertical] -= dw;
3852        }
3853    }
3854    /// The carriage's position against the frame: the frame's sway and the lean are not in it.
3855    fn scale_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
3856        let (q, v) = self.positions(s);
3857        pos.copy_from_slice(&self.tool_of(q));
3858        vel.copy_from_slice(&self.tool_speed(q, v));
3859    }
3860    fn set_tool_velocity(&self, s: &mut [f64], vel: &[f64]) {
3861        let (n, m, v) = (self.n(), self.m(), self.vel());
3862        let tool = self.tool_of(&s[..n]);
3863        let (_, vel, _) = self.joint_motion(&tool, vel, &vec![0.0; tool.len()]);
3864        s[v..v + n].copy_from_slice(&vel);
3865        if self.elastic {
3866            for kk in 0..m {
3867                let w = self.pulley_angle(kk, &vel);
3868                (s[v + n + kk], s[v + n + m + kk]) = (w, self.ratio[kk] * w);
3869            }
3870        }
3871    }
3872    fn motor_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
3873        let (n, m, v) = (self.n(), self.m(), self.vel());
3874        if self.elastic {
3875            pos.copy_from_slice(&s[n + m..n + 2 * m]);
3876            vel.copy_from_slice(&s[v + n + m..v + n + 2 * m]);
3877        } else {
3878            self.motor_angles(&s[..n], pos);
3879            self.motor_angles(&s[n..2 * n], vel);
3880        }
3881    }
3882
3883    fn feedforward_torque(&self, pos: &[f64], acc: &[f64], out: &mut [f64]) {
3884        self.feedforward_torque_moving(pos, &vec![0.0; pos.len()], acc, out);
3885    }
3886    /// With the joints' motion of the tool's (`joint_motion`) and the forces its speed asks of the bodies on rotaries
3887    /// (`inertial`). Where a gantry's yaw is driven, its row asks the two drives for the moment that keeps the bridge
3888    /// square: they share the bridge's load by the lever rule.
3889    fn feedforward_torque_moving(&self, pos: &[f64], vel: &[f64], acc: &[f64], out: &mut [f64]) {
3890        let (q, dq, ddq) = self.joint_motion(pos, vel, acc);
3891        let mass = self.rigid_mass(&q);
3892        let (gravity, inertial) = (self.gravity(&q), self.inertial(&q, &dq));
3893        // The rigid model's speed terms as `rigid_solve` has them: the belt's runs and the growing chains.
3894        let (runs, chain) = (self.runs_speed(&q, &dq, [0.0; 3], 0.0).0, self.chain_inertia(&dq, 0.0).0);
3895        let forces: Vec<f64> =
3896            (0..self.n()).map(|i| dot(&mass[i], &ddq) - gravity[i] - inertial[i] - runs[i] - chain[i]).collect();
3897        out.copy_from_slice(&self.to_motors(&forces));
3898    }
3899
3900    /// The belt pulls the bodies (with chains and idlers) with the force F their masses take, without pulleys and
3901    /// rotors, -C^T T = F, and each closed belt keeps its length: sum_s (T_s - P) L_s = 0 over its geometric section
3902    /// lengths (the elastic law to first order in T / EA).
3903    fn rigid_tensions(&self, pos: &[f64], acc: &[f64], out: &mut Vec<f64>) {
3904        let (q, _, acc) = self.joint_motion(pos, &vec![0.0; pos.len()], acc);
3905        let (mass, gravity) = (self.axis_mass(&q), self.gravity(&q));
3906        let geo = self.geo(&q);
3907        // An axis a screw, rack, linear motor or rotary drives takes its force from that; a gantry's yaw spring takes
3908        // the moment the belt leaves.
3909        let belt_held: Vec<usize> = (0..self.nt()).filter(|&i| !self.driven(i)).collect();
3910        let mut a: Vec<Vec<f64>> = belt_held.iter().map(|&i| self.sections.iter().map(|s| s.c[i]).collect()).collect();
3911        let mut b: Vec<f64> = belt_held.iter().map(|&i| -(dot(&mass[i], &acc) - gravity[i])).collect();
3912        // Each closed belt keeps its length.
3913        for belt in &self.loops {
3914            a.push((0..self.sections.len()).map(|s| if belt.contains(&s) { geo[s] } else { 0.0 }).collect());
3915            b.push(0.0);
3916        }
3917        let d = lstsq(&a, &b).unwrap_or_else(|| vec![0.0; self.sections.len()]);
3918        out.extend(d.iter().map(|d| self.belt.pretension + d));
3919    }
3920
3921    /// Each guide's load (`guide_load`, with what a linear motor presses on it) at the axis positions `pos` and
3922    /// accelerations `acc`: at rest its weight across the axis and the press, moving the overhang's tilt (and side
3923    /// load), m a (2 |lever| / spacing (+ 1)), signed with the acceleration.
3924    /// Each guide's Coulomb and viscous friction (`Lugre::steady`) on its axis's coordinate, as torque at the motors by
3925    /// the map the rigid forces take (`to_motors`).
3926    /// Each guide's level takes its load at rest at the pose (the load scale `load_scales` has, 1 without
3927    /// effects.load_dependent_friction); a moving overhang's added load follows the acceleration, which this does not
3928    /// see (`rigid_guide_loads` gives it). The pair [c, b] of c + b v has no room for the Stribeck rise, which fades
3929    /// within a few v_s: `rigid_friction_rise` gives it.
3930    fn rigid_friction(&self, pos: &[f64], dir: &[f64], out: &mut Vec<[f64; 2]>) {
3931        let (q, rate, _) = self.joint_motion(pos, dir, &vec![0.0; pos.len()]);
3932        let (mut coulomb, mut viscous) = (vec![0.0; self.n()], vec![0.0; self.n()]);
3933        for (g, scale) in self.guides.iter().zip(self.load_scales_at(&q, &vec![0.0; self.n()])) {
3934            let [c, b, _] = g.friction.steady(rate[g.axis], scale);
3935            (coulomb[g.axis], viscous[g.axis]) = (coulomb[g.axis] + c, viscous[g.axis] + b);
3936        }
3937        out.extend(self.to_motors(&coulomb).into_iter().zip(self.to_motors(&viscous)).map(|(c, b)| [c, b]));
3938    }
3939
3940    /// The guides' Stribeck rise per motor, [level, speed]: the friction beyond c + b v is level exp(-(v / speed)^2) at
3941    /// the speed v along the path, level the guides' (stiction - Coulomb) at their load at rest taken to the motor as
3942    /// `rigid_friction` does, signed by the way each axis turns, and its Stribeck speed along the path (the guide's over
3943    /// its axis's rate): a pair per guide that reaches the motor.
3944    fn rigid_friction_rise(&self, pos: &[f64], dir: &[f64], out: &mut Vec<Vec<[f64; 2]>>) {
3945        let (q, rate, _) = self.joint_motion(pos, dir, &vec![0.0; pos.len()]);
3946        let (n, m) = (self.n(), self.m());
3947        let mut rises = vec![Vec::new(); m];
3948        for (g, scale) in self.guides.iter().zip(self.load_scales_at(&q, &vec![0.0; n])) {
3949            let (axis, turning) = (g.axis, rate[g.axis]);
3950            if !g.friction.on || turning == 0.0 {
3951                continue;
3952            }
3953            let mut rise = vec![0.0; n];
3954            rise[axis] = scale * (g.friction.stiction - g.friction.coulomb) * turning.signum();
3955            let speed = g.friction.stribeck_v / turning.abs();
3956            for (kk, torque) in self.to_motors(&rise).into_iter().enumerate().filter(|(_, t)| *t != 0.0) {
3957                rises[kk].push([torque, speed]);
3958            }
3959        }
3960        out.extend(rises);
3961    }
3962
3963    /// `rigid_solve` at a steady speed: the guides (`Lugre::feedforward`, at their load at rest), idlers and cable chains
3964    /// as forces on the axes, taken to the motors as the rigid forces are (`to_motors`), over each gearbox's loss factor
3965    /// for what it passes at rest (that friction less the weight; the loss on the weight counts as friction), plus each shaft's friction at its rotor's speed.
3966    fn steady_friction(&self, pos: &[f64], vel: &[f64], out: &mut [f64]) {
3967        let (q, v, _) = self.joint_motion(pos, vel, &vec![0.0; pos.len()]);
3968        let n = self.n();
3969        let mut force = vec![0.0; n];
3970        for (g, scale) in self.guides.iter().zip(self.load_scales_at(&q, &vec![0.0; self.n()])) {
3971            force[g.axis] += g.friction.feedforward(v[g.axis], scale);
3972        }
3973        let ((idlers, _), drag, gravity) = (self.idler_friction(&v), self.chain_drag(&v), self.gravity(&q));
3974        let friction: Vec<f64> = (0..n).map(|i| force[i] - idlers[i] + drag[i]).collect();
3975        let held: Vec<f64> = (0..n).map(|i| friction[i] - gravity[i]).collect();
3976        let (weight, passed) = (self.to_motors(&gravity), self.to_motors(&held));
3977        for (kk, out) in out.iter_mut().enumerate() {
3978            let pulley = self.pulley_angle(kk, &v);
3979            let (output, rotor) = self.rigid_factors(kk, self.ratio[kk] * passed[kk], pulley);
3980            // The loss factor acts on everything the gearbox passes, the weight included; the weight's own lossless torque
3981            // (-weight) is not friction, so it comes off again.
3982            *out = self.shafts[kk].torque(self.ratio[kk] * pulley) + passed[kk] * rotor / output + weight[kk];
3983        }
3984    }
3985
3986    fn rigid_guide_loads(&self, pos: &[f64], acc: &[f64], out: &mut Vec<[f64; 2]>) {
3987        let still = vec![0.0; self.n()];
3988        for g in &self.guides {
3989            let moving = g.overhang.as_ref().map_or(0.0, |o| {
3990                let lever = o.lever - o.lever_axis.map_or(0.0, |a| pos[a]);
3991                let side = self.body_mass(&self.bodies[o.body]) * acc[o.axis];
3992                side * (2.0 * lever.abs() / o.spacing + if o.side_load { 1.0 } else { 0.0 })
3993            });
3994            out.push([self.guide_load(g, pos, &still) + self.pressed(g.axis), moving]);
3995        }
3996    }
3997
3998    fn energy(&self, s: &[f64]) -> f64 {
3999        self.energy_parts(s).iter().sum()
4000    }
4001
4002    /// Elastic model: per motor its gearbox's spring (K1 holds a screw's or rack's own compliance) in series with
4003    /// the belt sections its pulley feeds or takes from, r r_mat sum f^2 EA / l at the pulley over the sections' lengths
4004    /// at the pose; the rotor (and gearbox input) on the motor's side, the pulley with the load (so more is kept back).
4005    /// Referred to the motor over the ratio. A drive with no spring (a linear motor) has none.
4006    fn trains(&self, tool_pose: &[f64]) -> Vec<Option<sim_core::Train>> {
4007        if !self.elastic {
4008            return Vec::new();
4009        }
4010        let geo = self.geo(&self.joints(tool_pose));
4011        let whole = sim_components::control::rigid_inertias(self, tool_pose);
4012        (0..self.m())
4013            .map(|kk| {
4014                let belt: f64 = self.sections.iter().zip(&geo).map(|(s, l)| s.f[kk] * s.f[kk] * self.belt.ea / l).sum();
4015                let belt = if belt > 0.0 { 1.0 / (self.r[kk] * self.r_mat[kk] * belt) } else { 0.0 };
4016                let gear = self.gears[kk].at(self.pulley_angle(kk, tool_pose));
4017                let spring = 1.0 / (1.0 / gear.stiffness + belt);
4018                sim_core::Train::of(spring / (self.ratio[kk] * self.ratio[kk]), self.j_rotor[kk], whole[kk])
4019            })
4020            .collect()
4021    }
4022
4023    /// The lowest belt mode (`belt_mode`), in the elastic model.
4024    fn resonance_hz(&self, tool_pose: &[f64]) -> Option<f64> {
4025        let mut q = self.joints(tool_pose);
4026        self.sag_at_rest(&mut q);
4027        self.belt_mode(&q).map(|(w2, _)| w2.sqrt() / std::f64::consts::TAU)
4028    }
4029
4030    /// Every mode of `mode_matrices`, lowest first (the first is `resonance_hz`'s): the belts', a yawing bridge's, the
4031    /// frame's, the lean's and the beam's, with the pulleys and rotors held. Each mode's damping ratio is x^T C(w) x /
4032    /// (2 w), x its shape with x^T M x = 1 and C at its w (`mode_damping`), as the crates' `chain::matrix_modes` takes it.
4033    fn modes(&self, tool_pose: &[f64]) -> Vec<Mode> {
4034        let mut q = self.joints(tool_pose);
4035        self.sag_at_rest(&mut q);
4036        let Some((mass, stiffness)) = self.mode_matrices(&q) else { return Vec::new() };
4037        every_mode(&mass, &stiffness)
4038            .into_iter()
4039            .map(|(w2, x)| {
4040                let w = w2.sqrt();
4041                let c = self.mode_damping(&q, w, x.len());
4042                let cx: f64 = (0..x.len()).map(|i| (0..x.len()).map(|l| x[i] * c[i][l] * x[l]).sum::<f64>()).sum();
4043                Mode { hz: w / std::f64::consts::TAU, damping: cx / (2.0 * w) }
4044            })
4045            .collect()
4046    }
4047
4048    /// The mode of `resonance_hz`: the axes and the frame move, pulleys and rotors stand. Scaled so that the tool's
4049    /// largest travel along an axis is 1 m, positive (with the frame the tool moves with it, see `tool_state`).
4050    fn mode_shape(&self, tool_pose: &[f64]) -> Option<(f64, Vec<f64>)> {
4051        let mut q = self.joints(tool_pose);
4052        self.sag_at_rest(&mut q);
4053        let (w2, x) = self.belt_mode(&q)?;
4054        let n = self.n();
4055        let mut tool = x[..self.nt()].to_vec();
4056        if let Some(f) = &self.frame {
4057            tool[f.axis] += x[n];
4058        }
4059        if let Some(lean) = &self.lean {
4060            tool[lean.axis] += self.tip(&q) * x[self.lean_row()];
4061        }
4062        if let Some(b) = &self.beam {
4063            tool[b.vertical] -= x[self.beam_row()];
4064        }
4065        let largest = tool.iter().copied().max_by(|a, b| a.abs().total_cmp(&b.abs())).filter(|t| t.abs() > 0.0)?;
4066        let mut shape = vec![0.0; self.state_len()];
4067        for i in 0..n {
4068            shape[i] = x[i] / largest;
4069        }
4070        if self.frame.is_some() {
4071            shape[self.frame_at()] = x[n] / largest;
4072        }
4073        if self.lean.is_some() {
4074            shape[self.lean_at()] = x[self.lean_row()] / largest;
4075        }
4076        if self.beam.is_some() {
4077            shape[self.beam_at()] = x[self.beam_row()] / largest;
4078        }
4079        Some((w2.sqrt() / std::f64::consts::TAU, shape))
4080    }
4081
4082    /// With effects.belt_wrap: per motor the wrap at its pulley (`geometry::wrap`), from where the 3D view puts it and
4083    /// the wheels before and after it along the belt (`wrap_neighbours`) at this pose, in the belt's plane (elt_plane); NaN
4084    /// for a motor that drives no belt (a screw, rack, linear motor or rotary).
4085    fn belt_wraps(&self, tool_pose: &[f64]) -> Vec<f64> {
4086        if self.wraps.is_empty() {
4087            return Vec::new();
4088        }
4089        self.wraps_at(&self.joints(tool_pose))
4090    }
4091
4092    fn set_payload_attached(&mut self, attached: bool) {
4093        self.payload_attached = attached;
4094    }
4095    fn set_dwelling(&mut self, dwelling: bool) {
4096        self.dwelling = dwelling;
4097    }
4098    fn set_tool_force(&mut self, force: &[f64]) -> bool {
4099        self.tool_push.clear();
4100        self.tool_push.extend_from_slice(force);
4101        true
4102    }
4103    fn set_brake_engaged(&mut self, engaged: bool) {
4104        self.brake_engaged = engaged;
4105    }
4106    /// A stop met within the step (`HardStop::substeps`, `RotaryJoint::stop_substeps`).
4107    fn substeps_wanted(&self, s: &[f64], _torque: &[f64], dt: f64, _substeps: u32) -> u32 {
4108        let at = if self.elastic { self.vel() } else { self.n() };
4109        (0..self.nt()).map(|i| self.stops.substeps(s[i], s[at + i], self.stroke[i], dt)).max().unwrap_or(1)
4110    }
4111
4112    fn memory(&self) -> Vec<f64> {
4113        Gearbox::anchors(&self.gears)
4114    }
4115    fn set_memory(&mut self, memory: &[f64]) {
4116        Gearbox::set_anchors(&mut self.gears, memory)
4117    }
4118
4119    /// Belt tooth jump at each motor pulley (`ToothJump`): a positive slip feeds the section the pulley feeds.
4120    fn after_step(&mut self, s: &mut [f64], dt: f64) {
4121        self.jump_loss = 0.0;
4122        // The gearboxes' hysteresis states move on to where the step ended (`Gearbox::commit`).
4123        if self.elastic {
4124            let (n, m) = (self.n(), self.m());
4125            for kk in 0..m {
4126                let (phi, theta) = (s[n + m + kk], self.output(s, kk).0);
4127                self.gears[kk].commit(phi, theta);
4128            }
4129        }
4130        let v = self.vel() + self.n();
4131        let wraps = self.wraps_at(&s[..self.n()]);
4132        for j in 0..self.jumps.len() {
4133            let kk = self.jump_motor[j];
4134            let (mut jump, feeds, takes) = self.jumps[j].clone();
4135            if let Some(&wrap) = wraps.get(kk).filter(|w| w.is_finite()) {
4136                jump.set_wrap(wrap);
4137            }
4138            let (before, t) = (self.energy(s), self.tensions(s));
4139            let (at, r) = (self.jump_at(j), self.r[kk]);
4140            let (rest, mut speed) = (self.j_pulley[kk] / (r * r) - jump.mass, r * s[v + kk]);
4141            if jump.update(&mut s[at..at + JUMP_STATES], t[feeds], t[takes], rest, &mut speed) {
4142                s[v + kk] = speed / r;
4143                self.jump_loss += (before - self.energy(s)) / dt;
4144            }
4145        }
4146    }
4147
4148    /// The gearboxes (where there are some) and the guides, in the order of `thermal_parts`.
4149    fn set_part_temperatures(&mut self, rises: &[f64]) {
4150        let Some((laws, viscous)) = &self.thermal else { return };
4151        let mut next = rises.iter();
4152        // A screw's or rack's share of the efficiency stays what it is.
4153        for (kk, (gear, law)) in self.gears.iter_mut().zip(laws).enumerate() {
4154            if !self.coupled[kk] {
4155                let rise = *next.next().unwrap_or(&0.0);
4156                self.shafts[kk].set_oil(law.viscosity_factor(rise));
4157                // A worm stage's efficiencies are its own (`worm_stages`), its loss following the oil as the gearbox's.
4158                match &self.worms_configured[kk] {
4159                    Some(worm) => {
4160                        let s = law.gearbox_viscous_share;
4161                        self.worms[kk] = Some(crate::worm::warmed(worm, 1.0 - s + s * law.viscosity_factor(rise)));
4162                    }
4163                    None => gear.efficiency = law.gearbox_efficiency(rise) * self.extra_efficiency[kk],
4164                }
4165            }
4166        }
4167        for (g, base) in self.guides.iter_mut().zip(viscous) {
4168            g.friction.viscous = base * laws[0].viscosity_factor(*next.next().unwrap_or(&0.0));
4169        }
4170    }
4171
4172    fn signal_infos(&self) -> Vec<SignalInfo> {
4173        let mut out: Vec<SignalInfo> = self
4174            .sections
4175            .iter()
4176            .map(|s| SignalInfo::new(format!("{}.tension", s.id), s.key, "quantity-tension", "N"))
4177            .collect();
4178        for axis in &self.axes {
4179            out.push(SignalInfo::new(format!("axis.{}.belt_stretch", axis.id), axis.key, "quantity-belt-stretch", "m"));
4180            out.push(SignalInfo::new(format!("axis.{}.friction", axis.id), axis.key, "quantity-friction-force", "N"));
4181        }
4182        if self.frame_node {
4183            out.push(SignalInfo::new("frame.deflection", "frame", "quantity-deflection", "m"));
4184        }
4185        if let Some(lean) = &self.lean_node {
4186            let axis = &self.axes[lean.axis];
4187            out.push(SignalInfo::new(
4188                format!("axis.{}.tool_deflection", axis.id),
4189                axis.key,
4190                "quantity-tool-deflection",
4191                "m",
4192            ));
4193        }
4194        if self.beam.is_some() {
4195            out.push(SignalInfo::new("beam.deflection", "group-beam", "quantity-deflection", "m"));
4196        }
4197        if let Some(g) = &self.gantry {
4198            for (name, quantity, unit) in [
4199                ("yaw", "quantity-yaw-angle", "rad"),
4200                ("sync_error", "quantity-sync-error", "m"),
4201                ("moment", "quantity-yaw-moment", "N m"),
4202            ] {
4203                out.push(SignalInfo::new(format!("gantry.{}.{name}", g.id), "group-gantry_yaw", quantity, unit));
4204            }
4205        }
4206        out.push(SignalInfo::new("belt.slack_time", "group-belt", "quantity-slack-time", "s"));
4207        // Only a motor that turns a pulley has one: the verdicts judge belt teeth and pulley bearings where it does.
4208        for (motor, _) in self.motors.iter().zip(&self.direct).filter(|(_, d)| d.is_none()) {
4209            out.push(SignalInfo::new(
4210                format!("pulley.{}.radial_load", motor.id),
4211                motor.key,
4212                "quantity-radial-load",
4213                "N",
4214            ));
4215        }
4216        for g in &self.guides {
4217            out.push(SignalInfo::new(
4218                format!("{}.guide_load", g.contact),
4219                self.axes[g.axis].key,
4220                "quantity-guide-load",
4221                "N",
4222            ));
4223        }
4224        for motor in &self.motors {
4225            out.push(SignalInfo::new(
4226                format!("gearbox.{}.output_torque", motor.id),
4227                motor.key,
4228                "quantity-gearbox-torque",
4229                "N m",
4230            ));
4231        }
4232        if !self.jumps.is_empty() {
4233            for motor in self.jump_motor.iter().map(|&kk| &self.motors[kk]) {
4234                out.push(SignalInfo::new(
4235                    format!("pulley.{}.tooth_jumps", motor.id),
4236                    motor.key,
4237                    "quantity-tooth-jumps",
4238                    "",
4239                ));
4240                out.push(SignalInfo::new(
4241                    format!("pulley.{}.tooth_slip", motor.id),
4242                    motor.key,
4243                    "quantity-tooth-slip",
4244                    "m",
4245                ));
4246            }
4247        }
4248        if self.span_mass.is_some() {
4249            // Numbered from 1 in the file's order, as the crates number theirs (`belt.span.<i>.frequency`); the label names the node.
4250            out.extend(self.spans.iter().enumerate().map(|(i, p)| {
4251                SignalInfo::new(format!("belt.span.{}.frequency", i + 1), p.key, "quantity-span-frequency", "Hz")
4252            }));
4253            out.push(SignalInfo::new("belt.span_detuning", "group-belt", "quantity-span-detuning", ""));
4254        }
4255        // Named by the motor, as the registered one-axis machines name them by their joint (`joint.1.force`, `screw.1.speed`).
4256        for (kk, d) in self.direct.iter().enumerate() {
4257            let Some(d) = d else { continue };
4258            let (motor, axis) = (&self.motors[kk], &self.axes[d.axis]);
4259            out.push(SignalInfo::new(
4260                format!("joint.{}.force", motor.id),
4261                axis.key,
4262                "quantity-joint-force",
4263                if axis.unit == "m" { "N" } else { "N m" },
4264            ));
4265            match &d.kind {
4266                DirectKind::Screw(screw) => out.extend(screw.signal_infos(motor.id, motor.key)),
4267                DirectKind::Rack(rack) => out.extend([
4268                    rack.signal_info(motor.id, motor.key),
4269                    SignalInfo::new(format!("rack.{}.radial_load", motor.id), motor.key, "quantity-radial-load", "N"),
4270                ]),
4271                DirectKind::Rotary(Some(gear)) => out.push(gear.signal_info(motor.id, motor.key)),
4272                _ => {}
4273            }
4274        }
4275        self.effect_infos(&mut out);
4276        out
4277    }
4278
4279    /// The checks of the screws (speed, d n, buckling, static load, life), racks (feed force) and strain wave gears
4280    /// (life, where the motor's ratings.required_life_h is set), as the registered one-axis machines judge them.
4281    fn gantry_motors(&self) -> Option<[usize; 2]> {
4282        self.gantry_motors
4283    }
4284
4285    fn rating_checks(&self) -> Vec<RatingCheck> {
4286        let mut out = Vec::new();
4287        // The yaw's synchronisation error (width times yaw) against the gantry's tolerance, where it has one.
4288        if let Some(g) = &self.gantry {
4289            out.extend(g.tolerance.map(|limit| RatingCheck {
4290                check: "gantry-sync",
4291                signal: format!("gantry.{}.sync_error", g.id),
4292                motor: None,
4293                limit,
4294                life: false,
4295            }));
4296        }
4297        for (kk, d) in self.direct.iter().enumerate() {
4298            let Some(d) = d else { continue };
4299            let id = self.motors[kk].id;
4300            match &d.kind {
4301                DirectKind::Screw(screw) => out.extend(screw.rating_checks(id, kk, d.required_life)),
4302                DirectKind::Rack(rack) => {
4303                    out.extend(rack.rating_checks(id, kk));
4304                    out.extend(d.radial_limit.map(|limit| RatingCheck {
4305                        check: "gearbox-radial-load",
4306                        signal: format!("rack.{id}.radial_load"),
4307                        motor: Some(kk),
4308                        limit,
4309                        life: false,
4310                    }));
4311                }
4312                DirectKind::Rotary(Some(gear)) => {
4313                    out.extend(d.required_life.map(|life| gear.rating_check(id, kk, life)))
4314                }
4315                _ => {}
4316            }
4317        }
4318        out
4319    }
4320
4321    fn friction_contacts(&self) -> Vec<FrictionContact> {
4322        self.guides.iter().map(|g| FrictionContact { id: g.contact, owner_key: self.axes[g.axis].key }).collect()
4323    }
4324    fn friction_curve(&self, i: usize, speed: f64, load_scale: f64) -> [f64; 3] {
4325        self.guides.get(i).map_or([0.0; 3], |g| g.friction.steady(speed, load_scale))
4326    }
4327
4328    fn belt_sections(&self) -> Vec<BeltSection> {
4329        self.sections
4330            .iter()
4331            .map(|s| BeltSection { id: s.id, owner_key: s.key, pretension: self.belt.pretension })
4332            .collect()
4333    }
4334
4335    /// The gearboxes (not on a direct drive, see `Gearbox::is_coupling`), then the guides, each shown by the first
4336    /// body it carries (or its overhang).
4337    fn thermal_parts(&self) -> Vec<ThermalPart> {
4338        let mut parts = Vec::new();
4339        for (kk, motor) in self.motors.iter().enumerate().filter(|(kk, _)| !self.coupled[*kk]) {
4340            parts.push(ThermalPart {
4341                id: intern(&format!("gearbox_{}", motor.id)),
4342                kind: "gearbox",
4343                owner_key: motor.key,
4344                scene_part: "gearbox",
4345                scene_index: kk,
4346            });
4347        }
4348        for g in &self.guides {
4349            let body = g.carries.first().copied().or(g.overhang.as_ref().map(|o| o.body)).unwrap_or(0);
4350            parts.push(ThermalPart {
4351                id: g.loss_id,
4352                kind: "guide",
4353                owner_key: self.axes[g.axis].key,
4354                scene_part: "carriage",
4355                scene_index: body,
4356            });
4357        }
4358        parts
4359    }
4360
4361    /// The rigid model has no belt stretch: it reports pretension, zero stretch and no slack. A section is taken to
4362    /// wrap the pulleys it ends at by half a turn, so the radial load on a pulley's shaft is the sum of the tensions
4363    /// of the sections that end there.
4364    fn base_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
4365        let (n, m) = (self.n(), self.m());
4366        let (q, vq) = self.positions(s);
4367        let fa = self.friction_at();
4368        let (friction, _) = self.friction(q, vq, &s[fa..fa + n], torque);
4369        let tensions = self.tensions(s);
4370        let (stretch, slack, outputs) = if self.elastic {
4371            let angles: Vec<f64> = (0..m).map(|kk| self.output(s, kk).0).collect();
4372            let stretch: Vec<f64> = (0..n).map(|i| q[i] - dot(&self.k_inv[i], &angles)).collect();
4373            let outputs: Vec<f64> = (0..m)
4374                .map(|kk| {
4375                    let (theta, w_theta) = self.output(s, kk);
4376                    let u = self.arm(s, kk);
4377                    self.gear_torque(kk, s[n + m + kk], s[self.vel() + n + m + kk], theta, w_theta, u).output
4378                })
4379                .collect();
4380            (stretch, s[self.slack_at()], outputs)
4381        } else {
4382            (vec![0.0; n], 0.0, self.rigid_solve(s, torque).out)
4383        };
4384        out.extend(&tensions);
4385        for i in 0..self.nt() {
4386            out.extend([stretch[i], friction[i]]);
4387        }
4388        if self.frame_node {
4389            out.push(self.sway(s).0);
4390        }
4391        if self.lean_node.is_some() {
4392            out.push(self.tip(q) * self.leaning(s).0);
4393        }
4394        if self.beam.is_some() {
4395            out.push(self.deflection(s).0);
4396        }
4397        if let Some(g) = &self.gantry {
4398            let (yaw, rate) = (q[g.coord], vq[g.coord]);
4399            out.extend([yaw, g.width * yaw, g.stiffness * yaw + g.damping * rate]);
4400        }
4401        out.push(slack);
4402        for kk in (0..m).filter(|&kk| self.direct[kk].is_none()) {
4403            out.push(self.sections.iter().zip(&tensions).filter(|(sec, _)| sec.f[kk] != 0.0).map(|(_, t)| t).sum());
4404        }
4405        let acc =
4406            if self.guides.iter().any(|g| g.overhang.is_some()) { self.commanded_acc(q, torque) } else { vec![0.0; n] };
4407        out.extend(self.guides.iter().map(|g| self.guide_load(g, q, &acc) + self.pressed(g.axis)));
4408        // Behind a screw or rack the gearbox's own output, ahead of the converter: more than the force times the lever
4409        // while it drives, less while the load drives it back (as the registered one-axis machines).
4410        out.extend((0..m).map(|kk| match &self.direct[kk] {
4411            Some(Direct { lever: Some(lever), .. }) => {
4412                let (force, e) = (outputs[kk], self.extra_efficiency[kk]);
4413                force * lever * if force * dot(&self.k[kk], vq) >= 0.0 { 1.0 / e } else { e }
4414            }
4415            _ => outputs[kk],
4416        }));
4417        for j in 0..self.jumps.len() {
4418            out.extend([s[self.jump_at(j) + 4], s[self.jump_at(j)]]);
4419        }
4420        if let Some(mass) = self.span_mass {
4421            self.span_signals(s, mass, out);
4422        }
4423        // The screws', racks' and strain wave gears' own signals, from the force each passes to its axis.
4424        for (kk, d) in self.direct.iter().enumerate() {
4425            let Some(d) = d else { continue };
4426            let (force, speed) = (outputs[kk], dot(&self.k[kk], vq));
4427            out.push(force);
4428            match &d.kind {
4429                DirectKind::Screw(screw) => screw.signals(speed, force, out),
4430                DirectKind::Rack(rack) => {
4431                    let teeth = RackPinion::feed_force(force, speed, self.extra_efficiency[kk]);
4432                    out.extend([teeth, rack.radial_load(teeth)]);
4433                }
4434                DirectKind::Rotary(Some(gear)) => out.push(gear.signal(force, speed * self.ratio[kk])),
4435                _ => {}
4436            }
4437        }
4438    }
4439    fn effect_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
4440        self.view_signals(s, torque, out);
4441    }
4442    fn loss_powers(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
4443        out.extend(self.losses(s, torque).0);
4444    }
4445
4446    /// A plain scene: a beam, a box per body, a drive unit per motor at its pulley's `at_m`, the idlers, and the belt
4447    /// round its pulleys and idlers: each section from tangent to tangent through its route (`belt_line`), shaded by its
4448    /// tension against the pretension, and the wraps round the motors' pulleys between sections (`pulley_wraps`).
4449    fn scene(&self, s: &[f64], out: &mut Scene) {
4450        use std::f64::consts::TAU;
4451        let (n, m) = (self.n(), self.m());
4452        let (q, _) = self.positions(s);
4453        let (mut rotor, mut rotor_speed) = (vec![0.0; m], vec![0.0; m]);
4454        self.motor_state(s, &mut rotor, &mut rotor_speed);
4455        out.parts.clear();
4456        out.labels.clear();
4457        let end = self.stroke[0];
4458        // The tool from where the rotaries' axes meet to its tip.
4459        if let Some(t) = &self.tcp {
4460            let pivot: Vec<bool> = (0..n).map(|i| t.axes.contains(&i)).collect();
4461            let from = self.scene_at(q, &pivot);
4462            let tip = self.turned_by(&t.rotaries, q, t.tool);
4463            let to = [0, 1, 2].map(|k| from[k] + tip[k]);
4464            out.parts.push(Part::new("tool", Shape::Segment { to, width: 0.015 }, from, [0.85, 0.2, 0.2]));
4465        }
4466        out.parts.push(Part::new(
4467            "beam",
4468            Shape::Box { size: [end + 0.2, 0.07, 0.09] },
4469            [end / 2.0, 0.045, 0.0],
4470            [0.62, 0.64, 0.68],
4471        ));
4472        for (b, body) in self.bodies.iter().enumerate() {
4473            let at = self.body_scene_at(body, q);
4474            let shade = 0.2 + 0.1 * b as f32;
4475            out.parts.push(Part::new(
4476                "carriage",
4477                Shape::Box { size: [0.16, 0.05, 0.03] },
4478                at,
4479                [shade, shade + 0.02, shade + 0.06],
4480            ));
4481        }
4482        // A wheel of a belt that lies flat is drawn upright at its place in the belt's plane and laid flat
4483        // (`Part::lay_flat`): it faces up, the motor below it. A wheel of a belt in the y-z plane is drawn facing the front
4484        // as one in x-z (the view has no part turned about z).
4485        let flat = |w: Waypoint| self.wheel_plane(w)[2] == 2;
4486        let upright = |at: [f64; 3], flat: bool| if flat { ([at[0], at[1]], -at[2]) } else { ([at[0], at[2]], at[1]) };
4487        let lay = |parts: &mut [Part], flat: bool| {
4488            if flat {
4489                parts.iter_mut().for_each(Part::lay_flat)
4490            }
4491        };
4492        for kk in 0..m {
4493            let at = match &self.direct[kk] {
4494                Some(d) => self.direct_scene(kk, d, q, out),
4495                None => {
4496                    let (at, flat) = (self.pulley_scene_at(kk, q), flat(Waypoint::Pulley(kk)));
4497                    let pulley = if self.elastic { s[n + kk] } else { rotor[kk] / self.ratio[kk] };
4498                    let (from, (centre, depth)) = (out.parts.len(), upright(at, flat));
4499                    drive_unit(&mut out.parts, centre, depth, self.r[kk], -pulley, -rotor[kk], [0.9, 0.45, 0.1]);
4500                    lay(&mut out.parts[from..], flat);
4501                    at
4502                }
4503            };
4504            out.labels.push(Label {
4505                pos: [at[0], at[1], at[2] + 0.11],
4506                owner_key: self.motors[kk].key,
4507                value: rotor_speed[kk] * 60.0 / TAU,
4508                unit_key: "unit-rpm",
4509                decimals: 0,
4510            });
4511        }
4512        for (i, d) in self.idlers.iter().enumerate() {
4513            let flat = flat(Waypoint::Idler(i));
4514            let (from, (centre, depth)) = (out.parts.len(), upright(self.idler_scene_at(d, q), flat));
4515            idler(&mut out.parts, centre, depth, d.radius, -dot(&d.speed, q) / d.radius);
4516            lay(&mut out.parts[from..], flat);
4517        }
4518        // A machine without idler nodes and one belt motor gets the idler at the far end the one-axis machine has.
4519        if m == 1 && self.idlers.is_empty() && self.direct[0].is_none() {
4520            idler(&mut out.parts, [end + 0.1, 0.0], -0.05, self.r[0], 0.0);
4521        }
4522        let tensions = self.tensions(s);
4523        let pretension = self.belt.pretension.max(1.0);
4524        let strip = |from: [f64; 3], to: [f64; 3]| {
4525            Part::new("belt", Shape::Segment { to, width: 0.02 }, from, [0.12, 0.12, 0.13])
4526        };
4527        let shade = |t: f64| ((t - self.belt.pretension) / pretension).clamp(-1.0, 1.0) as f32;
4528        for (i, t) in tensions.iter().enumerate() {
4529            for pair in self.belt_line(i, q).windows(2) {
4530                out.parts.push(strip(pair[0], pair[1]).highlighted(shade(*t)));
4531            }
4532        }
4533        // Shaded as the section that comes onto the pulley.
4534        for (section, wrap) in self.pulley_wraps(q) {
4535            out.parts.extend(wrap.windows(2).map(|pair| strip(pair[0], pair[1]).highlighted(shade(tensions[section]))));
4536        }
4537        for (i, axis) in self.axes.iter().enumerate() {
4538            let moves: Vec<bool> = (0..n).map(|l| l <= i).collect();
4539            let at = self.scene_at(q, &moves);
4540            let (value, unit_key, decimals) =
4541                if axis.unit == "m" { (q[i], "unit-m", 3) } else { (q[i].to_degrees(), "unit-deg", 1) };
4542            out.labels.push(Label {
4543                pos: [at[0], at[1], at[2] + 0.16 + 0.06 * i as f64],
4544                owner_key: axis.key,
4545                value,
4546                unit_key,
4547                decimals,
4548            });
4549        }
4550    }
4551
4552    /// The tool's tip: where the straight axes put the rotaries, plus the tool turned by them.
4553    fn scene_point(&self, tool_pose: &[f64]) -> Option<[f64; 3]> {
4554        let q = self.joints(tool_pose);
4555        let mut p = self.scene_at(&q, &vec![true; self.n()]);
4556        if let Some(t) = &self.tcp {
4557            let tip = self.turned_by(&t.rotaries, &q, t.tool);
4558            (0..3).for_each(|k| p[k] += tip[k]);
4559        }
4560        Some(p)
4561    }
4562
4563    /// With a tcp: the tool's tip where the straight axes would have to stand beyond their strokes.
4564    fn unreachable(&self, tool_pose: &[f64], slack: f64) -> Option<&'static str> {
4565        let t = self.tcp.as_ref()?;
4566        let q = self.joints(tool_pose);
4567        t.axes.iter().any(|&i| q[i] < -slack || q[i] > self.stroke[i] + slack).then_some("error-tcp-joint-range")
4568    }
4569}
4570
4571#[cfg(test)]
4572#[path = "wheel_sense_tests.rs"]
4573mod wheel_sense_tests;
4574
4575#[cfg(test)]
4576#[path = "yaw_run_tests.rs"]
4577mod yaw_run_tests;