Skip to main content

machine_single_axis/
lib.rs

1//! Single-axis test machine: a motor at the left end drives a carriage through a belt loop around an
2//! idler at the right end. x = r * pulley angle. Component checks run here once and then hold for
3//! every machine that uses the component.
4//!
5//! The motor pulley cuts the belt into two sections of uniform tension:
6//! section 1 runs from the pulley straight to the carriage (length const + x, belt fed in by + r a),
7//! section 2 from the pulley around the idler to the carriage (length const - x, fed by - r a).
8//! Belt force on the carriage: T2 - T1. Belt torque on the pulley: r (T1 - T2).
9
10use sim_components::mech::{
11    Belt, CableChain, Gearbox, HardStop, HoldingBrake, JUMP_STATES, Lugre, Ripple, SectionForce, ShaftFriction,
12    ThermalFeedback, ToothJump, ToothMesh, drive_excitations, span_detuning, span_frequency, wrap_angle,
13};
14use sim_core::{
15    AxisInfo, BeltSection, Config, ConfigError, ENERGY_PARTS, FRICTION_SIGNALS, FrictionContact, LOSS_PREFIX, Label,
16    Machine, MachineEntry, Mode, MotorInfo, Part, Scene, Shape, SignalInfo, TORQUE_PARTS, ThermalPart,
17};
18
19pub static ENTRY: MachineEntry = MachineEntry {
20    id: "single-axis",
21    key: "machine-single-axis",
22    default_config: include_str!("../default.toml"),
23    i18n: &[("en", include_str!("../i18n/en.ftl")), ("de", include_str!("../i18n/de.ftl"))],
24    build,
25    suite_configs,
26};
27
28const G: f64 = 9.80665;
29
30/// Effects that take energy out or put it in; the standard suite runs with them off.
31pub const LOSSY_EFFECTS: [&str; 12] = [
32    "belt_damping",
33    "guide_friction",
34    "load_dependent_friction",
35    "motor_friction",
36    "gearbox_drag",
37    "gearbox_lost_motion",
38    "gearbox_efficiency",
39    "torque_ripple",
40    "tooth_meshing",
41    "temperature",
42    "process_force",
43    "holding_brake",
44];
45
46fn build(cfg: &Config) -> Result<Box<dyn Machine>, ConfigError> {
47    sim_components::base::mount(cfg, Box::new(SingleAxis::new(cfg)?))
48}
49
50/// The default config with every loss switched off.
51pub fn lossless_config() -> Config {
52    let mut cfg = ENTRY.config();
53    for effect in LOSSY_EFFECTS {
54        cfg.set_text(&format!("effects.{effect} = false")).unwrap();
55    }
56    cfg.set_text("gearbox.damping_nm_s_rad = 0.0").unwrap();
57    cfg.set_text("hard_stop.damping_n_s_m = 0.0").unwrap();
58    cfg.set_text("cable_chain.drag_n = 0.0").unwrap();
59    cfg
60}
61
62/// Loss-free rigid and full models, level and inclined (so that gravity takes part).
63fn suite_configs() -> Vec<Config> {
64    let mut out = Vec::new();
65    for (elastic, incline) in [(false, 0.0), (false, 30.0), (true, 0.0), (true, 30.0)] {
66        let mut cfg = lossless_config();
67        // The inclined runs have the tooth stiffness and the cable chain in, so the energy check covers the
68        // belt with and without, and the chain where its weight counts.
69        cfg.set_text(&format!("effects.belt_tooth_stiffness = {}", incline > 0.0)).unwrap();
70        cfg.set_text(&format!("effects.cable_chain = {}", incline > 0.0)).unwrap();
71        cfg.set_text(&format!("effects.part_heating = {}", incline > 0.0)).unwrap();
72        // The effects of 13 November in the level elastic run: no loss is on, so the parts stay at ambient, and no tooth
73        // jumps; the slip states and the span signals are there all the same. Not in the inclined one: nothing damps it,
74        // its gearbox knocks through the backlash, and a tooth climbing out and falling back sends it another way.
75        for effect in ["thermal_feedback", "belt_tooth_jump", "belt_span_vibration", "belt_wrap"] {
76            cfg.set_text(&format!("effects.{effect} = {}", elastic && incline == 0.0)).unwrap();
77        }
78        cfg.set_text(&format!("effects.belt_stretch = {elastic}")).unwrap();
79        cfg.set_text(&format!("geometry.incline_deg = {incline:.1}")).unwrap();
80        out.push(cfg);
81    }
82    out
83}
84
85pub struct SingleAxis {
86    elastic: bool,
87    r: f64,
88    /// Unstretched belt fed per radian of pulley. The pulley radius holds at pretension, where the
89    /// belt is already stretched, so that the kinematics are exact for an evenly tensioned belt.
90    r_mat: f64,
91    span_min: f64,
92    m_carriage: f64,
93    m_payload: f64,
94    j_rotor: f64,
95    /// Pulley inertia including the belt mass.
96    j_pulley: f64,
97    /// Gravity along the axis (pulling towards -x) and into the guide.
98    g_along: f64,
99    g_normal: f64,
100    belt: Belt,
101    /// Unstretched belt per section at x = 0 with the pulley at angle 0.
102    mat0: [f64; 2],
103    friction: Lugre,
104    shaft: ShaftFriction,
105    ripple: Ripple,
106    mesh: ToothMesh,
107    gearbox: Gearbox,
108    stops: HardStop,
109    chain: CableChain,
110    /// Force on the carriage towards +x while the cycle dwells.
111    process: f64,
112    dwelling: bool,
113    /// An obstacle's push on the carriage towards +x (`Machine::set_tool_force`), held until changed.
114    push: f64,
115    brake: HoldingBrake,
116    brake_engaged: bool,
117    payload_attached: bool,
118    /// With effects.thermal_feedback: the law, and the guide's viscous coefficient at the reference temperature.
119    thermal: Option<(ThermalFeedback, f64)>,
120    /// With effects.belt_tooth_jump (elastic model only): the law, and the energy the last step's jump took, J/s.
121    jump: Option<ToothJump>,
122    jump_loss: f64,
123    /// With effects.belt_span_vibration: the belt's mass per metre, for the spans' string frequencies.
124    span_mass: Option<f64>,
125    /// effects.belt_wrap: the teeth in mesh at the motor pulley from the belt's wrap there (`belt_wraps`).
126    wrap: bool,
127    axes: [AxisInfo; 1],
128    motors: [MotorInfo; 1],
129}
130
131// Elastic state: [x, a, p, vx, va, wp, s, slack, brake]. a: pulley angle, p: motor shaft angle, s: friction
132// state, slack: seconds a belt section has spent without tension, brake: deflection of the holding brake.
133const N_ELASTIC: usize = 9;
134// Rigid state: [x, v, s, brake].
135const N_RIGID: usize = 4;
136// With effects.belt_tooth_jump the elastic state goes on with the motor pulley's slip states (`JUMP_STATES`).
137const JUMP: usize = N_ELASTIC;
138
139impl SingleAxis {
140    /// The carriage at `x`, the belt's clamp on it and the payload, as `scene` draws them.
141    fn on_carriage(&self, x: f64) -> Vec<Part> {
142        let (cx, part) = (self.span_min + x, Part::new);
143        let mut parts = vec![
144            // The tool: drawn where `scene_point` says.
145            part(
146                "carriage",
147                Shape::Box { size: [0.16, 0.05, 0.03] },
148                self.scene_point(&[x]).unwrap_or_default(),
149                [0.2, 0.22, 0.26],
150            ),
151            part("clamp", Shape::Box { size: [0.06, 0.035, 0.03] }, [cx, -0.05, self.r + 0.017], [0.85, 0.3, 0.2]),
152        ];
153        if self.payload_attached && self.m_payload > 0.0 {
154            parts.push(part("payload", Shape::Box { size: [0.1, 0.1, 0.1] }, [cx, -0.03, 0.125], [0.2, 0.7, 0.3]));
155        }
156        parts
157    }
158
159    pub fn new(cfg: &Config) -> Result<Self, ConfigError> {
160        let g = if cfg.bool("effects.gravity")? { G } else { 0.0 };
161        let incline = cfg.f64("geometry.incline_deg")?.to_radians();
162        let r = cfg.positive("geometry.pulley_radius_m")?;
163        let belt = Belt::from_config(cfg)?;
164        // The gearbox's own inertia turns with the rotor.
165        let j_rotor = cfg.positive("motor.rotor_inertia_kgm2")? + cfg.non_negative("gearbox.inertia_at_input_kgm2")?;
166        let process = cfg.f64("process.force_x_n")?;
167        let mut m = Self {
168            elastic: cfg.bool("effects.belt_stretch")?,
169            r,
170            r_mat: belt.rest_length(r),
171            span_min: cfg.positive("geometry.span_min_m")?,
172            m_carriage: cfg.positive("mass.carriage_kg")?,
173            m_payload: if cfg.bool("effects.payload")? { cfg.non_negative("mass.payload_kg")? } else { 0.0 },
174            j_rotor,
175            j_pulley: cfg.positive("pulley.inertia_kgm2")?,
176            g_along: g * incline.sin(),
177            g_normal: g * incline.cos(),
178            belt,
179            mat0: [0.0; 2],
180            friction: Lugre::from_config(cfg, "friction_x")?,
181            shaft: ShaftFriction::from_config(cfg)?,
182            ripple: Ripple::from_config(cfg)?,
183            mesh: ToothMesh::from_config(cfg)?,
184            gearbox: Gearbox::from_config(cfg)?,
185            stops: HardStop::from_config(cfg)?,
186            chain: CableChain::from_config(cfg)?,
187            process: if cfg.bool("effects.process_force")? { process } else { 0.0 },
188            dwelling: false,
189            push: 0.0,
190            brake: HoldingBrake::from_config(cfg, j_rotor)?,
191            brake_engaged: false,
192            payload_attached: true,
193            thermal: match ThermalFeedback::from_config(cfg)? {
194                Some(law) => Some((law, cfg.non_negative("friction_x.viscous_n_s_m")?)),
195                None => None,
196            },
197            jump: None,
198            jump_loss: 0.0,
199            span_mass: if cfg.bool("effects.belt_span_vibration")? {
200                Some(cfg.positive("belt.mass_kg_m")?)
201            } else {
202                None
203            },
204            wrap: cfg.bool("effects.belt_wrap")?,
205            axes: [AxisInfo {
206                id: "x",
207                key: "axis-x",
208                unit: "m",
209                min: 0.0,
210                max: cfg.positive("geometry.stroke_m")?,
211                max_vel: cfg.positive("axis.x.max_velocity_m_s")?,
212                max_acc: cfg.positive("axis.x.max_acceleration_m_s2")?,
213                max_jerk: cfg.positive("axis.x.max_jerk_m_s3")?,
214            }],
215            motors: [MotorInfo { id: "m", key: "motor-m" }],
216        };
217        let geo = m.geo(0.0);
218        m.mat0 = geo.map(|g| m.belt.rest_length(g));
219        if m.elastic {
220            // The whole belt's mass is lumped on the motor pulley (below).
221            m.jump = ToothJump::from_config(cfg, r, m.belt.mass_per_m * (geo[0] + geo[1] - 2.0 * m.belt.tooth_length))?;
222        }
223        // The whole belt runs at carriage speed, so all of its mass sits on the pulley.
224        m.j_pulley += m.belt.mass_per_m * (geo[0] + geo[1] - 2.0 * m.belt.tooth_length) * r * r;
225        Ok(m)
226    }
227
228    fn m(&self) -> f64 {
229        self.m_carriage + if self.payload_attached { self.m_payload } else { 0.0 }
230    }
231    /// Inertia at the pulley: pulley plus rotor seen through the gearbox.
232    fn j(&self) -> f64 {
233        self.j_pulley + self.gearbox.ratio * self.gearbox.ratio * self.j_rotor
234    }
235    fn m_total(&self) -> f64 {
236        self.m() + self.j() / (self.r * self.r)
237    }
238
239    /// Geometric length of the two belt sections. Each ends at the motor pulley once, where the teeth
240    /// in mesh count as more belt (see `Belt::tooth_length`).
241    fn geo(&self, x: f64) -> [f64; 2] {
242        let (stroke, s, teeth) = (self.axes[0].max, self.span_min, self.belt.tooth_length);
243        [s + x + teeth, 3.0 * s + 2.0 * stroke - x + teeth]
244    }
245    /// Unstretched belt per section at rest at x: the carriage's balance T2 - T1 = its weight along the axis less what
246    /// pushes it at rest (the process force while dwelling); the belt total fixes the level.
247    fn rest_material(&self, x: f64) -> Vec<f64> {
248        let weight = (self.m() + self.chain.mass(x).0) * self.g_along - self.extra_force(x, 0.0);
249        self.belt.static_material(&self.geo(x), &[0.0, weight], self.mat0.iter().sum())
250    }
251    /// Unstretched belt per section of the elastic state `s`: the pulley at angle s[1] has fed in r_mat a, and with
252    /// effects.belt_tooth_jump the belt has slipped over it by u, which is r_mat / r u of material.
253    fn mat(&self, s: &[f64]) -> [f64; 2] {
254        let fed = self.r_mat * (s[1] + self.slip(s).0 / self.r);
255        [self.mat0[0] + fed, self.mat0[1] - fed]
256    }
257    /// The belt's slip over the motor pulley and its rate (m, m/s); 0 without effects.belt_tooth_jump.
258    fn slip(&self, s: &[f64]) -> (f64, f64) {
259        if self.jump.is_some() { (s[JUMP], s[JUMP + 1]) } else { (0.0, 0.0) }
260    }
261    fn sections(&self, s: &[f64]) -> [SectionForce; 2] {
262        let (geo, mat, r) = (self.geo(s[0]), self.mat(s), self.r_mat);
263        let fed = r * (s[4] + self.slip(s).1 / self.r);
264        [self.belt.section(geo[0], mat[0], s[3], fed), self.belt.section(geo[1], mat[1], -s[3], -fed)]
265    }
266
267    /// The guide carries the weight; the friction levels are given for the carriage without payload.
268    fn load_scale(&self) -> f64 {
269        self.friction.load_scale(self.m() * self.g_normal, self.m_carriage * self.g_normal)
270    }
271
272    /// Force of the end stops on the carriage.
273    fn stop_force(&self, x: f64, v: f64) -> f64 {
274        self.stops.force(x, v, self.axes[0].max)
275    }
276
277    /// What the cable chain and the process put on the carriage at x and v, beside the chain's inertia and
278    /// weight: the chain's drag (it fades out at rest like the guide friction's Stribeck speed), what picking
279    /// up chain costs (see `CableChain::mass`), and the process force while the cycle dwells.
280    fn extra_force(&self, x: f64, v: f64) -> f64 {
281        let process = if self.dwelling { self.process } else { 0.0 };
282        process - self.chain.drag(v, self.friction.stribeck_v) - 0.5 * self.chain.mass(x).1 * v * v
283    }
284
285    fn elastic_derivatives(&self, s: &[f64], torque: &[f64], out: &mut [f64]) {
286        let r = self.r;
287        let sec = self.sections(s);
288        let (ff, ds) = self.friction.eval(s[3], s[6], self.load_scale());
289        let gear = self.gearbox.torque(s[2], s[5], s[1], s[4]);
290        out[..3].copy_from_slice(&s[3..6]);
291        // The chain's moving run has inertia and, on an incline, weight like the carriage; it does not load the guide.
292        let m = self.m() + self.chain.mass(s[0]).0;
293        out[3] = (sec[1].tension - sec[0].tension - ff
294            + self.stop_force(s[0], s[3])
295            + self.extra_force(s[0], s[3])
296            + self.push)
297            / m
298            - self.g_along;
299        let belt_torque = self.r_mat * (sec[0].material - sec[1].material);
300        // While its teeth are out of mesh the pulley feels only the ridge it holds the sliding belt back with.
301        let on_pulley = self.jump.as_ref().map_or(belt_torque, |j| j.pulley_torque(&s[JUMP..], belt_torque, r));
302        let j_pulley = self.jump.as_ref().map_or(self.j_pulley, |j| j.pulley_inertia(&s[JUMP..], self.j_pulley, r));
303        out[4] = (gear.output + on_pulley + r * self.mesh.force(r * s[1])) / j_pulley;
304        if let Some(jump) = &self.jump {
305            jump.rates(&s[JUMP..], belt_torque / r, r * out[4], &mut out[JUMP..]);
306        }
307        let (brake, brake_rate) = self.brake.torque(self.brake_engaged, s[5], s[8]);
308        out[5] = (self.ripple.apply(torque[0], s[2]) - gear.rotor - self.shaft.torque(s[5]) - brake) / self.j_rotor;
309        out[8] = brake_rate;
310        out[6] = ds;
311        out[7] = if sec.iter().any(|f| f.tension <= 0.0) { 1.0 } else { 0.0 };
312    }
313
314    /// Rigid model: acceleration, guide friction force, friction state rate, the torque at the gearbox output and
315    /// the torque that goes into it before its loss.
316    ///
317    /// The gearbox loses torque only on what it transmits, which is the motor torque minus what
318    /// accelerates the rotor itself; the second pass uses the acceleration from the first for that.
319    fn rigid_solve(&self, s: &[f64], torque: &[f64]) -> (f64, f64, f64, f64, f64) {
320        let (r, ratio) = (self.r, self.gearbox.ratio);
321        let (angle, speed) = (ratio * s[0] / r, ratio * s[1] / r);
322        // Belt force the motor would give with a loss-free gearbox and a massless rotor; a brake holds the rotor.
323        let brake = self.brake.torque(self.brake_engaged, speed, s[3]).0;
324        let drive = ratio * (self.ripple.apply(torque[0], angle) - self.shaft.torque(speed) - brake) / r;
325        let (ff, ds) = self.friction.eval(s[1], s[2], self.load_scale());
326        let m = self.m() + self.chain.mass(s[0]).0;
327        let load = self.mesh.force(s[0]) - ff - m * self.g_along
328            + self.stop_force(s[0], s[1])
329            + self.extra_force(s[0], s[1])
330            + self.push;
331        let rotor = ratio * ratio * self.j_rotor / (r * r);
332        let solve = |loss: f64| (loss * drive + load) / (m + self.j_pulley / (r * r) + loss * rotor);
333        // The loss factor of the force through the gearbox, at its fixed point (`mech::settled_loss`).
334        let [loss] = sim_components::mech::settled_loss([1.0], |&[loss]| {
335            [self.gearbox.loss_factor((drive - rotor * solve(loss)) * r, s[1] / r)]
336        });
337        let a = solve(loss);
338        // The gearbox output carries what the rotor's own acceleration and the losses leave of the motor's torque.
339        (a, ff, ds, loss * (drive - rotor * a) * r, (drive - rotor * a) * r)
340    }
341
342    /// Kinetic, potential and elastic energy (see `ENERGY_PARTS`).
343    fn energy_parts(&self, s: &[f64]) -> [f64; 3] {
344        // The chain's moving run weighs mass_per_m (length0 + x / 2): lifted from 0 to x, that integrates to this.
345        let chain_height = self.chain.mass_per_m * (self.chain.length0 * s[0] + 0.25 * s[0] * s[0]);
346        let potential = (self.m() * s[0] + chain_height) * self.g_along;
347        let (chain, stops) = (self.chain.mass(s[0]).0, self.stops.energy(s[0], self.axes[0].max));
348        if !self.elastic {
349            return [0.5 * (self.m_total() + chain) * s[1] * s[1], potential, stops];
350        }
351        let (geo, mat) = (self.geo(s[0]), self.mat(s));
352        let slip = self.jump.as_ref().map_or(0.0, |j| j.slip_energy(&s[JUMP..], self.r * s[4]));
353        let kinetic = 0.5 * (self.m() + chain) * s[3] * s[3]
354            + 0.5 * self.j_pulley * s[4] * s[4]
355            + 0.5 * self.j_rotor * s[5] * s[5]
356            + slip;
357        [
358            kinetic,
359            potential,
360            stops
361                + self.belt.energy(geo[0], mat[0])
362                + self.belt.energy(geo[1], mat[1])
363                + self.gearbox.energy(s[2], s[1]),
364        ]
365    }
366
367    /// The loss powers in the order of `effect_infos`, the gearbox loss as a torque at the rotor and the brake torque,
368    /// which the torque breakdown takes too. No derivatives: cheap enough for every step.
369    fn losses(&self, s: &[f64], torque: &[f64]) -> ([f64; 7], f64, f64) {
370        let (r, ratio) = (self.r, self.gearbox.ratio);
371        let (x, v, state) = if self.elastic { (s[0], s[3], s[6]) } else { (s[0], s[1], s[2]) };
372        let ff = self.friction.eval(v, state, self.load_scale()).0;
373        let drag = self.chain.drag(v, self.friction.stribeck_v);
374        let (mut angle, mut speed) = ([0.0], [0.0]);
375        self.motor_state(s, &mut angle, &mut speed);
376        let (angle, speed) = (angle[0], speed[0]);
377        // Gearbox loss at the rotor and as power, brake, power of the tooth meshing put in, belt damping.
378        let (gear_loss, gear_power, brake, mesh_in, belt) = if self.elastic {
379            let gear = self.gearbox.torque(s[2], s[5], s[1], s[4]);
380            let (geo, mat, fed) = (self.geo(x), self.mat(s), self.r_mat * (s[4] + self.slip(s).1 / r));
381            let belt = self.belt.loss_power(geo[0], mat[0], v, fed) + self.belt.loss_power(geo[1], mat[1], -v, -fed);
382            let brake = self.brake.torque(self.brake_engaged, s[5], s[8]).0;
383            (
384                gear.rotor - gear.output / ratio,
385                self.gearbox.loss_power(s[2], s[5], s[1], s[4]),
386                brake,
387                r * self.mesh.force(r * s[1]) * s[4],
388                belt,
389            )
390        } else {
391            let (_, _, _, out, into) = self.rigid_solve(s, torque);
392            let loss = (into - out) / ratio;
393            (loss, loss * speed, self.brake.torque(self.brake_engaged, speed, s[3]).0, self.mesh.force(x) * v, 0.0)
394        };
395        let process_in = if self.dwelling { self.process * v } else { 0.0 };
396        let other = (torque[0] - self.ripple.apply(torque[0], angle)) * speed - mesh_in - process_in;
397        let stops = self.stops.loss_power(x, v, self.axes[0].max);
398        // The gearbox's drag acts on the rotor but is the gearbox's loss.
399        let gear_drag = self.shaft.drag_power(speed);
400        (
401            [
402                ff * v,
403                drag * v,
404                (self.shaft.torque(speed) + brake) * speed - gear_drag,
405                gear_power + gear_drag,
406                belt,
407                stops,
408                other,
409            ],
410            gear_loss,
411            brake,
412        )
413    }
414
415    /// The signals of the effect views, in the order of `effect_infos`, with the transpose r / i:
416    /// inertia = r / i ((m + J / r^2) a + m' v^2 / 2), a the carriage's acceleration and J pulley and rotor seen at the
417    /// pulley, as a rigid machine would turn them; gravity = r / i * m g sin(incline); friction = shaft friction +
418    /// brake + gearbox loss at the rotor + r / i (guide friction + chain drag); rest = motor torque less these.
419    fn view_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
420        let (r, ratio) = (self.r, self.gearbox.ratio);
421        let (x, v, state) = if self.elastic { (s[0], s[3], s[6]) } else { (s[0], s[1], s[2]) };
422        let scale = self.load_scale();
423        let ff = self.friction.eval(v, state, scale).0;
424        let drag = self.chain.drag(v, self.friction.stribeck_v);
425        let (chain_mass, chain_growth) = self.chain.mass(x);
426        let (mut angle, mut speed) = ([0.0], [0.0]);
427        self.motor_state(s, &mut angle, &mut speed);
428        let speed = speed[0];
429        let (powers, gear_loss, brake) = self.losses(s, torque);
430        // Carriage acceleration.
431        let acc = if self.elastic {
432            let mut d = [0.0; N_ELASTIC + JUMP_STATES];
433            self.elastic_derivatives(s, torque, &mut d[..self.state_len()]);
434            d[3]
435        } else {
436            self.rigid_solve(s, torque).0
437        };
438        let m = self.m() + chain_mass;
439        let parts = [
440            r / ratio * ((m + self.j() / (r * r)) * acc + 0.5 * chain_growth * v * v),
441            r / ratio * m * self.g_along,
442            self.shaft.torque(speed) + brake + gear_loss + r / ratio * (ff + drag),
443        ];
444        out.extend(parts);
445        out.push(torque[0] - parts.iter().sum::<f64>());
446        out.extend(powers);
447        if self.jump.is_some() {
448            out.push(self.jump_loss);
449        }
450        out.extend(self.energy_parts(s));
451        out.push(v);
452        out.extend(self.friction.split(v, state, scale));
453        out.push(scale);
454        // Stretch per belt section: its length less its unstretched belt; in the rigid model that of pretension.
455        let geo = self.geo(x);
456        let mat = if self.elastic { self.mat(s) } else { geo.map(|g| self.belt.rest_length(g)) };
457        out.extend([geo[0] - mat[0], geo[1] - mat[1]]);
458    }
459
460    /// The first-mode frequency of each free belt span (`span_frequency`) and how far the nearest of them is from what
461    /// the drive excites (`span_detuning`). Spans: 1 motor pulley to carriage (section 1), 2 motor pulley to idler and
462    /// 3 idler to carriage (section 2); their lengths are those of `geo` without the teeth in mesh.
463    fn span_signals(&self, s: &[f64], mass: f64, out: &mut Vec<f64>) {
464        let (x, stroke, span) = (s[0], self.axes[0].max, self.span_min);
465        let tension = if self.elastic { self.sections(s).map(|f| f.tension) } else { [self.belt.pretension; 2] };
466        let spans = [(span + x, tension[0]), (2.0 * span + stroke, tension[1]), (span + stroke - x, tension[1])];
467        let (mut angle, mut speed) = ([0.0], [0.0]);
468        self.motor_state(s, &mut angle, &mut speed);
469        let pulley = if self.elastic { s[4] } else { speed[0] / self.gearbox.ratio };
470        let mut excitations = Vec::with_capacity(3);
471        drive_excitations(self.mesh.pitch, self.r * pulley, &self.ripple, speed[0], &mut excitations);
472        let frequencies = spans.map(|(length, t)| span_frequency(length, t, mass));
473        out.extend(frequencies);
474        out.push(frequencies.iter().map(|f| span_detuning(*f, &excitations)).fold(1.0, f64::min));
475    }
476
477    /// The signal list of `effect_signals`.
478    fn effect_infos(&self, out: &mut Vec<SignalInfo>) {
479        let (motor, axis) = (&self.motors[0], self.axes[0].key);
480        out.extend(TORQUE_PARTS.map(|part| {
481            SignalInfo::new(
482                format!("motor.{}.torque_{part}", motor.id),
483                motor.key,
484                &format!("quantity-torque-{part}"),
485                "N m",
486            )
487        }));
488        let powers = [
489            ("guide_x", axis, "quantity-friction-power"),
490            ("cable_chain", "group-cable_chain", "quantity-friction-power"),
491            ("shaft_m", motor.key, "quantity-shaft-friction-power"),
492            (
493                "gearbox_m",
494                motor.key,
495                if self.gearbox.is_coupling() { "quantity-coupling-loss-power" } else { "quantity-gearbox-loss-power" },
496            ),
497            ("belt", "group-belt", "quantity-damping-power"),
498            ("hard_stops", "group-hard_stop", "quantity-damping-power"),
499            ("other", "loss-other", "quantity-power-given-off"),
500        ];
501        out.extend(
502            powers.map(|(id, owner, quantity)| SignalInfo::new(format!("{LOSS_PREFIX}{id}"), owner, quantity, "W")),
503        );
504        if self.jump.is_some() {
505            out.push(SignalInfo::new(
506                format!("{LOSS_PREFIX}tooth_jump"),
507                "group-belt",
508                "quantity-tooth-jump-power",
509                "W",
510            ));
511        }
512        out.extend(ENERGY_PARTS.map(|part| {
513            SignalInfo::new(format!("energy.{part}"), "group-energy", &format!("quantity-energy-{part}"), "J")
514        }));
515        for part in FRICTION_SIGNALS {
516            let unit = match part {
517                "speed" => "m/s",
518                "load_scale" => "",
519                _ => "N",
520            };
521            out.push(SignalInfo::new(
522                format!("axis.x.friction_{part}"),
523                axis,
524                &format!("quantity-friction-{}", part.replace('_', "-")),
525                unit,
526            ));
527        }
528        out.extend(
529            self.belt_sections()
530                .iter()
531                .map(|b| SignalInfo::new(format!("{}.stretch", b.id), b.owner_key, "quantity-section-stretch", "m")),
532        );
533    }
534}
535
536impl Machine for SingleAxis {
537    /// In the axis's frame: x along it, z across it (gravity has g sin(incline) along -x and g cos(incline) along -z).
538    /// The carriage, its payload and the chain's moving run along x, the pulley and the rotor turning about y,
539    /// positive as x grows.
540    fn frame_momentum(&self, s: &[f64]) -> Option<sim_core::FrameMomentum> {
541        let (x, v, pulley, rotor) = if self.elastic {
542            (s[0], s[3], s[4], s[5])
543        } else {
544            (s[0], s[1], s[1] / self.r, s[1] * self.gearbox.ratio / self.r)
545        };
546        let chain = self.chain.mass(x).0;
547        let chain_moment = self.chain.mass_per_m * (self.chain.length0 * x + 0.25 * x * x);
548        Some(sim_core::FrameMomentum {
549            linear: [(self.m() + chain) * v, 0.0, 0.0],
550            angular: [0.0, self.j_pulley * pulley + self.j_rotor * rotor, 0.0],
551            mass: self.m() + chain,
552            first_moment: [self.m() * x + chain_moment, 0.0, 0.0],
553            gravity: [-self.g_along, 0.0, -self.g_normal],
554            // An obstacle's push is not in it: a compliant base takes it through the tool's shift (`base::Based`).
555            external: [if self.dwelling { self.process } else { 0.0 }, 0.0, 0.0],
556            external_at: [x, 0.0, 0.0],
557        })
558    }
559    fn axes(&self) -> &[AxisInfo] {
560        &self.axes
561    }
562    fn motors(&self) -> &[MotorInfo] {
563        &self.motors
564    }
565
566    fn inverse(&self, tool: &[f64], motors: &mut [f64]) {
567        motors[0] = self.gearbox.ratio * tool[0] / self.r;
568    }
569    fn forward(&self, motors: &[f64], tool: &mut [f64]) {
570        tool[0] = motors[0] * self.r / self.gearbox.ratio;
571    }
572
573    fn state_len(&self) -> usize {
574        if !self.elastic {
575            N_RIGID
576        } else if self.jump.is_some() {
577            N_ELASTIC + JUMP_STATES
578        } else {
579            N_ELASTIC
580        }
581    }
582
583    fn equilibrium(&self, tool: &[f64], state: &mut Vec<f64>, torque: &mut [f64]) {
584        let (x, r, ratio) = (tool[0], self.r, self.gearbox.ratio);
585        // The weight along the axis less what pushes the carriage at rest (the process force while dwelling).
586        let weight = (self.m() + self.chain.mass(x).0) * self.g_along - self.extra_force(x, 0.0);
587        if !self.elastic {
588            *state = vec![x, 0.0, 0.0, 0.0];
589            let shaft = (weight - self.mesh.force(x)) * r / ratio;
590            torque[0] = self.ripple.invert(shaft, ratio * x / r);
591            return;
592        }
593        let (geo, mat) = (self.geo(x), self.rest_material(x));
594        let a = (mat[0] - self.mat0[0]) / self.r_mat;
595        let m: [f64; 2] = std::array::from_fn(|i| self.belt.section(geo[i], mat[i], 0.0, 0.0).material);
596        let gear = -self.r_mat * (m[0] - m[1]) - r * self.mesh.force(r * a);
597        let p = ratio * (a + self.gearbox.static_twist(gear));
598        *state = vec![x, a, p, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0];
599        state.resize(self.state_len(), 0.0);
600        torque[0] = self.ripple.invert(gear / ratio, p);
601    }
602
603    fn derivatives(&self, s: &[f64], torque: &[f64], out: &mut [f64]) {
604        if self.elastic {
605            return self.elastic_derivatives(s, torque, out);
606        }
607        let (a, _, ds, ..) = self.rigid_solve(s, torque);
608        let brake_rate = self.brake.torque(self.brake_engaged, self.gearbox.ratio * s[1] / self.r, s[3]).1;
609        out.copy_from_slice(&[s[1], a, ds, brake_rate]);
610    }
611
612    fn tool_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
613        pos[0] = s[0];
614        vel[0] = if self.elastic { s[3] } else { s[1] };
615    }
616    fn set_tool_velocity(&self, s: &mut [f64], vel: &[f64]) {
617        if self.elastic {
618            (s[3], s[4], s[5]) = (vel[0], vel[0] / self.r, self.gearbox.ratio * vel[0] / self.r);
619        } else {
620            s[1] = vel[0];
621        }
622    }
623    fn motor_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
624        if self.elastic {
625            pos[0] = s[2];
626            vel[0] = s[5];
627        } else {
628            self.inverse(&s[0..1], pos);
629            self.inverse(&s[1..2], vel);
630        }
631    }
632
633    fn feedforward_torque(&self, pos: &[f64], acc: &[f64], out: &mut [f64]) {
634        let chain = self.chain.mass(pos[0]).0;
635        out[0] = ((self.m_total() + chain) * acc[0] + (self.m() + chain) * self.g_along) * self.r / self.gearbox.ratio;
636    }
637
638    /// T2 - T1 = F, the force on the carriage and what it carries (without pulley and rotor), and the belt keeps its
639    /// length: (T1 - P) L1 + (T2 - P) L2 = 0. So T1 = P - F L2 / (L1 + L2), T2 = P + F L1 / (L1 + L2).
640    fn rigid_tensions(&self, pos: &[f64], acc: &[f64], out: &mut Vec<f64>) {
641        let force = (self.m() + self.chain.mass(pos[0]).0) * (acc[0] + self.g_along);
642        let [l1, l2] = self.geo(pos[0]);
643        let p = self.belt.pretension;
644        out.extend([p - force * l2 / (l1 + l2), p + force * l1 / (l1 + l2)]);
645    }
646
647    /// The guide carries the weight of the carriage and what it carries (as `axis.x.guide_load`), whatever the
648    /// acceleration.
649    fn rigid_guide_loads(&self, _pos: &[f64], _acc: &[f64], out: &mut Vec<[f64; 2]>) {
650        out.push([self.m() * self.g_normal, 0.0]);
651    }
652
653    /// The rigid model at a = 0: shaft friction (with the gearbox's drag) at the rotor's speed i v / r, and the guide's
654    /// steady sliding force and the cable chain's drag at v, through the pulley and the gearbox as `rigid_solve` takes
655    /// them: r / (i loss) (F + W) - r W / i, F the guide and chain force and W the weight along the guide (the rigid
656    /// feedforward carries r W / i itself). The loss factor is the one of the whole torque the gearbox passes, as in
657    /// `rigid_solve`, so the weight's own loss is in it too.
658    fn steady_friction(&self, pos: &[f64], vel: &[f64], out: &mut [f64]) {
659        let (r, ratio, v) = (self.r, self.gearbox.ratio, vel[0]);
660        let force = self.friction.feedforward(v, self.load_scale()) + self.chain.drag(v, self.friction.stribeck_v);
661        let weight = (self.m() + self.chain.mass(pos[0]).0) * self.g_along;
662        let loss = self.gearbox.loss_factor((force + weight) * r, v / r);
663        out[0] = self.shaft.torque(ratio * v / r) + r / ratio * ((force + weight) / loss - weight);
664    }
665
666    fn energy(&self, s: &[f64]) -> f64 {
667        self.energy_parts(s).iter().sum()
668    }
669
670    fn set_payload_attached(&mut self, attached: bool) {
671        self.payload_attached = attached;
672    }
673    fn set_dwelling(&mut self, dwelling: bool) {
674        self.dwelling = dwelling;
675    }
676    /// The push acts on the carriage, the tool, in either model; its power is the budget's crash row, not the
677    /// process's.
678    fn set_tool_force(&mut self, force: &[f64]) -> bool {
679        self.push = force[0];
680        true
681    }
682    fn set_brake_engaged(&mut self, engaged: bool) {
683        self.brake_engaged = engaged;
684    }
685    /// A stop met within the step (`HardStop::substeps`, `RotaryJoint::stop_substeps`).
686    fn substeps_wanted(&self, s: &[f64], _torque: &[f64], dt: f64, _substeps: u32) -> u32 {
687        let v = if self.elastic { s[3] } else { s[1] };
688        self.stops.substeps(s[0], v, self.axes[0].max, dt)
689    }
690
691    /// The carriage on the belt with the pulley held, as the gantry's `modes` takes it: the carriage, its payload and
692    /// the cable chain's share (m) on the two sections, k = EA / l1 + EA / l2 (dT/dL of `Belt::section`, l the
693    /// section's unstretched belt at rest there, `rest_material`), f = sqrt(k / m) / (2 pi). Its damping
694    /// ratio c / (2 m w), c the two sections' damping (`belt.damping_n_s_m` each, or `belt.damping_time_s` k). The
695    /// gearbox's twist and the motor's inertia behind it are left out: the drive's velocity loop holds the pulley far
696    /// below this frequency, and stiffer than the belt above it. `None` in the rigid model.
697    fn resonance_hz(&self, tool_pose: &[f64]) -> Option<f64> {
698        self.modes(tool_pose).first().map(|mode| mode.hz)
699    }
700    /// Elastic: the gearbox's spring in series with the two sections, r r_mat (EA / l1 + EA / l2) at the pulley as in
701    /// `modes`; the rotor (and gearbox input) on the motor's side, the pulley with the load. Over the ratio squared.
702    fn trains(&self, tool_pose: &[f64]) -> Vec<Option<sim_core::Train>> {
703        if !self.elastic {
704            return Vec::new();
705        }
706        let mat = self.rest_material(tool_pose[0]);
707        let belt = self.r * self.r_mat * (self.belt.ea / mat[0] + self.belt.ea / mat[1]);
708        let spring = 1.0 / (1.0 / self.gearbox.stiffness + self.gearbox.band_compliance + 1.0 / belt);
709        let whole = sim_components::control::rigid_inertias(self, tool_pose);
710        vec![sim_core::Train::of(spring / (self.gearbox.ratio * self.gearbox.ratio), self.j_rotor, whole[0])]
711    }
712    fn modes(&self, tool_pose: &[f64]) -> Vec<Mode> {
713        if !self.elastic {
714            return Vec::new();
715        }
716        let mat = self.rest_material(tool_pose[0]);
717        let (k, m) = (self.belt.ea / mat[0] + self.belt.ea / mat[1], self.m() + self.chain.mass(tool_pose[0]).0);
718        let (w, c) = ((k / m).sqrt(), 2.0 * self.belt.damping + self.belt.damping_time * k);
719        vec![Mode { hz: w / std::f64::consts::TAU, damping: c / (2.0 * m * w) }]
720    }
721
722    /// With effects.belt_wrap: the wrap at the motor pulley. The section to the carriage leaves its top for the clamp,
723    /// which holds the belt at the pulley's height r (`scene`), the other its bottom for the idler at the far end, as
724    /// large as the pulley: both spans leave level at every pose, half a turn (`mech::wrap_angle`).
725    fn belt_wraps(&self, tool_pose: &[f64]) -> Vec<f64> {
726        if !self.wrap {
727            return Vec::new();
728        }
729        let (r, end) = (self.r, 2.0 * self.span_min + self.axes[0].max);
730        vec![wrap_angle(r, [self.span_min + tool_pose[0], r, 0.0], [end, 0.0, -r])]
731    }
732
733    fn memory(&self) -> Vec<f64> {
734        self.gearbox.anchor.to_vec()
735    }
736    fn set_memory(&mut self, memory: &[f64]) {
737        Gearbox::set_anchors([&mut self.gearbox], memory)
738    }
739
740    /// Belt tooth jump at the motor pulley (`ToothJump`); section 1 is the one a positive slip feeds.
741    fn after_step(&mut self, s: &mut [f64], dt: f64) {
742        self.jump_loss = 0.0;
743        // The gearbox's hysteresis state moves on to where the step ended (`Gearbox::commit`).
744        if self.elastic {
745            self.gearbox.commit(s[2], s[1]);
746        }
747        let Some(mut jump) = self.jump.clone() else { return };
748        if let Some(&wrap) = self.belt_wraps(&s[..1]).first() {
749            jump.set_wrap(wrap);
750        }
751        let (before, sec) = (self.energy(s), self.sections(s));
752        let (rest, mut v) = ((self.j_pulley / (self.r * self.r)) - jump.mass, self.r * s[4]);
753        if jump.update(&mut s[JUMP..JUMP + JUMP_STATES], sec[0].tension, sec[1].tension, rest, &mut v) {
754            s[4] = v / self.r;
755            self.jump_loss = (before - self.energy(s)) / dt;
756        }
757    }
758
759    /// The gearbox (where there is one) and the guide, in the order of `thermal_parts`.
760    fn set_part_temperatures(&mut self, rises: &[f64]) {
761        let Some((law, viscous)) = &self.thermal else { return };
762        let (gearbox, guide) = if self.gearbox.is_coupling() { (None, rises[0]) } else { (Some(rises[0]), rises[1]) };
763        if let Some(rise) = gearbox {
764            self.gearbox.efficiency = law.gearbox_efficiency(rise);
765            self.shaft.set_oil(law.viscosity_factor(rise));
766        }
767        self.friction.viscous = viscous * law.viscosity_factor(guide);
768    }
769
770    fn signal_infos(&self) -> Vec<SignalInfo> {
771        let key = self.axes[0].key;
772        let mut out = vec![
773            SignalInfo::new("belt.1.tension", "belt-section-1", "quantity-tension", "N"),
774            SignalInfo::new("belt.2.tension", "belt-section-2", "quantity-tension", "N"),
775            SignalInfo::new("axis.x.belt_stretch", key, "quantity-belt-stretch", "m"),
776            SignalInfo::new("axis.x.friction", key, "quantity-friction-force", "N"),
777            SignalInfo::new("belt.slack_time", "group-belt", "quantity-slack-time", "s"),
778            SignalInfo::new("pulley.m.radial_load", self.motors[0].key, "quantity-radial-load", "N"),
779            SignalInfo::new("axis.x.guide_load", key, "quantity-guide-load", "N"),
780            SignalInfo::new("gearbox.m.output_torque", self.motors[0].key, "quantity-gearbox-torque", "N m"),
781        ];
782        if self.jump.is_some() {
783            out.push(SignalInfo::new("pulley.m.tooth_jumps", self.motors[0].key, "quantity-tooth-jumps", ""));
784            out.push(SignalInfo::new("pulley.m.tooth_slip", self.motors[0].key, "quantity-tooth-slip", "m"));
785        }
786        if self.span_mass.is_some() {
787            out.extend((1..=3).map(|i| {
788                SignalInfo::new(
789                    format!("belt.span.{i}.frequency"),
790                    &format!("belt-span-{i}"),
791                    "quantity-span-frequency",
792                    "Hz",
793                )
794            }));
795            out.push(SignalInfo::new("belt.span_detuning", "group-belt", "quantity-span-detuning", ""));
796        }
797        self.effect_infos(&mut out);
798        out
799    }
800
801    fn friction_contacts(&self) -> Vec<FrictionContact> {
802        vec![FrictionContact { id: "axis.x", owner_key: self.axes[0].key }]
803    }
804    fn friction_curve(&self, i: usize, speed: f64, load_scale: f64) -> [f64; 3] {
805        if i == 0 { self.friction.steady(speed, load_scale) } else { [0.0; 3] }
806    }
807
808    /// The two belt sections, in the order of the signals `belt.<i>.tension`.
809    fn belt_sections(&self) -> Vec<BeltSection> {
810        let pretension = self.belt.pretension;
811        vec![
812            BeltSection { id: "belt.1", owner_key: "belt-section-1", pretension },
813            BeltSection { id: "belt.2", owner_key: "belt-section-2", pretension },
814        ]
815    }
816
817    /// The gearbox, where there is one (not on a direct drive, see `Gearbox::is_coupling`), and the guide, shown by
818    /// the carriage.
819    fn thermal_parts(&self) -> Vec<ThermalPart> {
820        let gearbox = ThermalPart {
821            id: "gearbox_m",
822            kind: "gearbox",
823            owner_key: self.motors[0].key,
824            scene_part: "gearbox",
825            scene_index: 0,
826        };
827        let guide = ThermalPart {
828            id: "guide_x",
829            kind: "guide",
830            owner_key: self.axes[0].key,
831            scene_part: "carriage",
832            scene_index: 0,
833        };
834        if self.gearbox.is_coupling() { vec![guide] } else { vec![gearbox, guide] }
835    }
836
837    /// The rigid model has no belt stretch: it reports pretension and zero stretch. The belt wraps the motor
838    /// pulley by half a turn, so both sections pull its shaft the same way: the radial load is the sum of
839    /// their tensions. The guide carries the weight of what it moves. The gearbox torque is the one at its
840    /// output, positive where it drives the carriage towards +x: in the elastic model what the gear's spring
841    /// passes on to the pulley, in the rigid one what its solver works out.
842    fn base_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
843        if self.elastic {
844            let sec = self.sections(s);
845            let (ff, _) = self.friction.eval(s[3], s[6], self.load_scale());
846            out.extend([
847                sec[0].tension,
848                sec[1].tension,
849                s[0] - self.r * s[1],
850                ff,
851                s[7],
852                sec[0].tension + sec[1].tension,
853            ]);
854        } else {
855            let (ff, _) = self.friction.eval(s[1], s[2], self.load_scale());
856            out.extend([self.belt.pretension, self.belt.pretension, 0.0, ff, 0.0, 2.0 * self.belt.pretension]);
857        }
858        out.push(self.m() * self.g_normal);
859        out.push(if self.elastic {
860            self.gearbox.torque(s[2], s[5], s[1], s[4]).output
861        } else {
862            self.rigid_solve(s, torque).3
863        });
864        if self.jump.is_some() {
865            out.extend([s[JUMP + 4], s[JUMP]]);
866        }
867        if let Some(mass) = self.span_mass {
868            self.span_signals(s, mass, out);
869        }
870    }
871    fn effect_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
872        self.view_signals(s, torque, out);
873    }
874    fn loss_powers(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
875        out.extend(self.losses(s, torque).0);
876        if self.jump.is_some() {
877            out.push(self.jump_loss);
878        }
879    }
880
881    fn scene(&self, s: &[f64], out: &mut Scene) {
882        use sim_core::scene::{belt, drive_unit, idler, on_circle};
883        use std::f64::consts::{FRAC_PI_4, TAU};
884        let (x, r, ratio, span) = (s[0], self.r, self.gearbox.ratio, self.span_min);
885        let (mut rotor, mut rotor_speed) = ([0.0], [0.0]);
886        self.motor_state(s, &mut rotor, &mut rotor_speed);
887        let pulley = if self.elastic { s[1] } else { rotor[0] / ratio };
888        let tension = if self.elastic { self.sections(s).map(|f| f.tension) } else { [self.belt.pretension; 2] };
889        let shade =
890            tension.map(|t| ((t - self.belt.pretension) / self.belt.pretension.max(1.0)).clamp(-1.0, 1.0) as f32);
891
892        // The belt loop runs in one plane in front of the beam, the motor sits behind it at the left end.
893        let y = -0.05;
894        let (end, cx, floor) = (2.0 * span + self.axes[0].max, span + x, -0.4);
895        let part = Part::new;
896        out.labels.clear();
897        out.parts.clear();
898        out.parts.extend([
899            part("beam", Shape::Box { size: [end - 0.14, 0.07, 0.09] }, [end / 2.0, 0.045, 0.0], [0.62, 0.64, 0.68]),
900            part(
901                "post",
902                Shape::Box { size: [0.06, 0.06, -0.045 - floor] },
903                [0.13, 0.045, (floor - 0.045) / 2.0],
904                [0.45, 0.47, 0.5],
905            ),
906            part(
907                "post",
908                Shape::Box { size: [0.06, 0.06, -0.045 - floor] },
909                [end - 0.13, 0.045, (floor - 0.045) / 2.0],
910                [0.45, 0.47, 0.5],
911            ),
912        ]);
913        out.parts.extend(self.on_carriage(x));
914        // A positive pulley angle moves the carriage to the right: the top of the pulley moves
915        // right, which is clockwise seen from the front.
916        drive_unit(&mut out.parts, [0.0, 0.0], y, r, -pulley, -rotor[0], [0.9, 0.45, 0.1]);
917        idler(&mut out.parts, [end, 0.0], y, r, -x / r);
918
919        // The belt loop, starting and ending at the clamp on the carriage.
920        let (a, b) = ([0.0, 0.0], [end, 0.0]);
921        let path = [
922            [cx, r],
923            [0.0, r],
924            on_circle(a, r, 3.0 * FRAC_PI_4),
925            on_circle(a, r, 4.0 * FRAC_PI_4),
926            on_circle(a, r, 5.0 * FRAC_PI_4),
927            [0.0, -r],
928            [end, -r],
929            on_circle(b, r, -FRAC_PI_4),
930            on_circle(b, r, 0.0),
931            on_circle(b, r, FRAC_PI_4),
932            [end, r],
933            [cx, r],
934        ];
935        // Strips up to the middle of the motor pulley belong to the section straight to the carriage.
936        belt(&mut out.parts, &path, y, 0.025, 0.04, |i| shade[if i < 3 { 0 } else { 1 }]);
937
938        out.labels.extend([
939            Label {
940                pos: [0.0, y, 0.11],
941                owner_key: self.motors[0].key,
942                value: rotor_speed[0] * 60.0 / TAU,
943                unit_key: "unit-rpm",
944                decimals: 0,
945            },
946            Label { pos: [cx, y, 0.22], owner_key: self.axes[0].key, value: x, unit_key: "unit-m", decimals: 3 },
947        ]);
948    }
949
950    /// The carriage on the beam.
951    fn scene_point(&self, tool_pose: &[f64]) -> Option<[f64; 3]> {
952        Some([self.span_min + tool_pose[0], -0.03, 0.06])
953    }
954
955    /// The carriage and the payload on it, where `scene` draws them, without drawing the rest: the live check asks for
956    /// them every base step.
957    fn collision_bodies(&self, s: &[f64]) -> Vec<sim_core::Aabb> {
958        sim_core::scene::scene_boxes(&self.on_carriage(s[0]), &["carriage", "payload"])
959    }
960}
961
962#[cfg(test)]
963mod tests;