Skip to main content

machine_delta_d4/
lib.rs

1//! Delta picker D4: the three-arm delta of `machine-delta-d3` with a fourth axis that turns the tool about the
2//! vertical, as in the four-axis pickers (ABB IRB 360 with its fourth axis, Autonox's four-axis deltas): a fourth motor
3//! with its gearbox on the base, in its centre, drives a telescopic shaft through a cardan (universal) joint, and the
4//! shaft drives the tool's shaft in a bearing of the platform through a second cardan joint. The tool is the
5//! platform's centre and the tool's turn, x, y, z, c.
6//!
7//! The arms are the D3's (`machine_delta_d3::Delta`, its kinematics, dynamics, rods, bending arms, modes, collision
8//! rods), built from this config with the shaft's share of mass at the platform added to it. What the fourth axis adds:
9//!
10//! ```text
11//! shaft     d = p + (0, 0, h) - (0, 0, z_u)      upper cardan on the base's axis at z_u, lower one h above the platform
12//!           L = |d|,  beta = angle(d, -z),  psi = atan2(d_y, d_x)    (length, cardan angle at both joints, bending plane)
13//! cardan    tan chi = tan phi / cos beta     one joint, phi and chi from the bending plane (the input yoke's pin in it
14//!           chi' / phi' = cos beta / (1 - sin^2 beta cos^2 phi)       at phi = 0): the shaft turns unevenly
15//! pair      tan phi_out = cos beta tan chi = tan phi                 the second joint in phase undoes the first
16//! ```
17//!
18//! The pair cancels exactly here: the motor's shaft and the tool's shaft are both vertical (the platform never tilts),
19//! so the two joints are bent by the same beta in one plane, the Z arrangement; with the intermediate shaft's yokes
20//! in phase the tool turns as the gearbox's output, c = theta_out, at any pose. Only the intermediate shaft turns
21//! unevenly, between cos beta and 1 / cos beta of the tool's speed (the signal shaft.speed).
22//!
23//! Dynamics. The tool's turn is a rotary joint (`RotaryJoint`: motor, gearbox, brake, the tool bearing's friction), its
24//! load the tool and gripper, the payload (with effects.payload) and the shaft's spin, J_c = J_tool + J_payload + J_s,
25//! with no stops (the turn is endless):
26//!
27//! ```text
28//! J_c c'' = tau_gear + tau_bearing
29//! ```
30//!
31//! Nothing turns the arms' parallelograms, so the turn and the arms are coupled only through the shaft: its weight at
32//! the platform (a share of its mass, effects.shaft_mass, added to the D3's platform mass) and the telescope's sliding
33//! friction along the shaft against its lengthening, F = -f(L') u (effects.telescope_friction, a `PlatformDrag` on
34//! the D3, J^T F at the arms). The torque the shaft passes and the cardans' bending moments on the platform do no work
35//! on the arms: the parallelograms hold the platform level.
36//!
37//! Each arm reads its own `[motor.<id>]`, `[gearbox.<id>]` and `[parts.<id>]` over the shared tables (ids 1 to 3, the
38//! tool's 4); without them the three share `[motor]` and `[gearbox]`. Each arm's modes take its own gearbox.
39//!
40//! With effects.joint_elasticity the tool's gearbox twists, and with effects.shaft_torsion the shaft twists in series
41//! with it: one spring 1 / (1/k_gear + 1/k_shaft) between the gearbox and the tool, with the shaft's damping (the
42//! shaft's spin inertia sits at the tool and the gearbox's output has none, so the two springs are one). The shaft is
43//! in series with the whole gear as a screw's or a rack's converter is (`transmission::Converter`, lever 1): with
44//! effects.gearbox_lost_motion it stretches over the band too (`Gearbox::band_compliance`) and the hysteresis and its
45//! reversal stiffness are those of the series spring.
46//!
47//! With effects.tool_gearbox_body (and both of those) the gearbox's output is a body of its own, `J_o`
48//! (`tool.gearbox_output_inertia_kgm2`: the planet carrier and output flange), between the two springs. The
49//! catalogue's inertia at the input holds it as J_o / i^2, so that much leaves the rotor: the chain's inertia is the
50//! same with the body as without it.
51//!
52//! ```text
53//! J_o th_o'' = T_gear(rotor, th_o) - T_s        T_s = k_s (th_o - c) + c_s (th_o' - c')   the shaft's torque
54//! J_c  c''   = T_s + tau_bearing                 the gearbox keeps its own stiffness and damping
55//! rotor held:  det(K - lambda M) = 0,  M = diag(J_o, J_c),  K = [[k_g + k_s, -k_s], [-k_s, k_s]]
56//!              J_o J_c lambda^2 - (J_c (k_g + k_s) + J_o k_s) lambda + k_g k_s = 0
57//! ```
58//!
59//! Two modes: the tool's (the lower, the series spring's when J_o -> 0: lambda -> k_g k_s / (J_c (k_g + k_s))) and
60//! the gearbox's against the shaft's spring (about (k_g + k_s) / J_o, above 1 kHz). Energy: the shaft's spring and
61//! J_o's kinetic energy are stored, the shaft's damping c_s (th_o' - c')^2 is booked with the gearbox's loss. The
62//! damping ratios are the undamped shapes' (phi^T C phi / (2 w phi^T M phi)): the tool's 0.02272 against 0.02267 of the
63//! damped system's roots (41.068 Hz against 41.083), and the gearbox's own 2.7 says it is overdamped (the roots are
64//! real, -1786 and -48963 1/s, with the gearbox's 5 N m s/rad on J_o = 1e-4). RK4 at the 15.6 us sub-step holds the
65//! fast root for h lambda < 2.785: 0.77 as shipped, 2.17 at the bounds' corner (10 N m s/rad on 7.2e-5 kg m^2).
66
67use machine_delta_d3::{Arms, Delta, PlatformDrag};
68use sim_components::catalog::motor_config;
69use sim_components::joint::RotaryJoint;
70use sim_components::mech::{HardStop, HoldingBrake, ShaftFriction, ThermalFeedback};
71use sim_components::transmission::Converter;
72use sim_core::{
73    AxisInfo, Config, ConfigError, LOSS_PREFIX, Label, Machine, MachineEntry, Mode, MotorInfo, Part, Scene, Shape,
74    SignalInfo, TORQUE_PARTS, ThermalPart,
75};
76
77pub static ENTRY: MachineEntry = MachineEntry {
78    id: "delta-d4",
79    key: "machine-delta-d4",
80    default_config: include_str!("../default.toml"),
81    // The arms are the D3's, and so are their labels; the D4's own come after them and win where both have a key.
82    i18n: &[
83        ("en", include_str!("../../machine-delta-d3/i18n/en.ftl")),
84        ("de", include_str!("../../machine-delta-d3/i18n/de.ftl")),
85        ("en", include_str!("../i18n/en.ftl")),
86        ("de", include_str!("../i18n/de.ftl")),
87    ],
88    build,
89    suite_configs,
90};
91
92/// Effects that take energy out or put it in; the standard suite runs with them off: the D3's and the telescope's
93/// sliding friction.
94pub const LOSSY_EFFECTS: [&str; 8] = [
95    "joint_friction",
96    "motor_friction",
97    "gearbox_drag",
98    "gearbox_lost_motion",
99    "gearbox_efficiency",
100    "torque_ripple",
101    "holding_brake",
102    "telescope_friction",
103];
104
105fn build(cfg: &Config) -> Result<Box<dyn Machine>, ConfigError> {
106    sim_components::base::mount(cfg, Box::new(Delta4::new(cfg)?))
107}
108
109/// The default config with every loss switched off.
110pub fn lossless_config() -> Config {
111    let mut cfg = ENTRY.config();
112    for effect in LOSSY_EFFECTS {
113        cfg.set_text(&format!("effects.{effect} = false")).unwrap();
114    }
115    for damping in [
116        "gearbox.damping_nm_s_rad",
117        "joint.stop_damping_nm_s_rad",
118        "upper_arm.bending_damping_nm_s_rad",
119        "upper_arm.lateral_damping_n_s_m",
120        "gearbox.4.damping_nm_s_rad",
121        "shaft.torsional_damping_nm_s_rad",
122    ] {
123        cfg.set_text(&format!("{damping} = 0.0")).unwrap();
124    }
125    cfg
126}
127
128/// The start pose and the cycle's targets moved by `dz` in z, the tool's turn kept.
129fn lowered(cfg: &mut Config, dz: f64) {
130    let s = cfg.f64s("start.pose").unwrap();
131    cfg.set_text(&format!("start.pose = [{:?}, {:?}, {:?}, {:?}]", s[0], s[1], s[2] + dz, s[3])).unwrap();
132    let segments: Vec<String> = cfg
133        .array("cycle.segment")
134        .unwrap()
135        .iter()
136        .map(|s| {
137            let t: Vec<f64> = s["target"].as_array().unwrap().iter().map(|v| v.as_float().unwrap()).collect();
138            format!(
139                "{{ target = [{:?}, {:?}, {:?}, {:?}], dwell_s = {:?}, payload = {} }}",
140                t[0],
141                t[1],
142                t[2] + dz,
143                t[3],
144                s["dwell_s"].as_float().unwrap(),
145                s["payload"].as_bool().unwrap()
146            )
147        })
148        .collect();
149    cfg.set_text(&format!("cycle.segment = [{}]", segments.join(", "))).unwrap();
150}
151
152/// As the D3's (see `machine_delta_d3`): loss-free rigid and elastic models, with and without the payload, the working
153/// range 175 mm lower, where the delta held by constant torques is stable in its vertical mode. The shaft's torsion
154/// is on in the elastic ones.
155fn suite_configs() -> Vec<Config> {
156    let mut out = Vec::new();
157    for (elastic, payload) in [(false, true), (false, false), (true, true), (true, false)] {
158        let mut cfg = lossless_config();
159        cfg.set_text("workspace.top_z_m = -0.85").unwrap();
160        lowered(&mut cfg, -0.175);
161        cfg.set_text(&format!("effects.joint_elasticity = {elastic}")).unwrap();
162        cfg.set_text(&format!("effects.payload = {payload}")).unwrap();
163        cfg.set_text(&format!("effects.part_heating = {}", elastic && payload)).unwrap();
164        cfg.set_text(&format!("effects.thermal_feedback = {}", elastic && payload)).unwrap();
165        out.push(cfg);
166    }
167    out
168}
169
170type V3 = [f64; 3];
171
172fn dot(a: V3, b: V3) -> f64 {
173    a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
174}
175
176/// `a` moved by whole turns to lie within half a turn of `near`.
177fn unwrap_near(a: f64, near: f64) -> f64 {
178    a + std::f64::consts::TAU * ((near - a) / std::f64::consts::TAU).round()
179}
180
181/// One cardan joint bent by `beta`: the output's angle for the input's `phi`, both from the bending plane (the plane of
182/// the two shafts), the input yoke's pin lying in that plane at phi = 0: tan chi = tan phi / cos beta.
183pub fn cardan(beta: f64, phi: f64) -> f64 {
184    unwrap_near(phi.sin().atan2(beta.cos() * phi.cos()), phi)
185}
186
187/// The second joint of a pair whose intermediate shaft has its yokes in phase, bent by the same `beta` in the same
188/// plane: the output's angle for the intermediate shaft's `chi`, tan phi_out = cos beta tan chi (the first joint
189/// backwards).
190pub fn cardan_back(beta: f64, chi: f64) -> f64 {
191    unwrap_near((beta.cos() * chi.sin()).atan2(chi.cos()), chi)
192}
193
194/// The speed of a cardan joint's output over its input's at the input's angle `phi` from the bending plane:
195/// cos beta / (1 - sin^2 beta cos^2 phi), between cos beta (phi = 90 degrees) and 1 / cos beta (phi = 0).
196pub fn cardan_speed_ratio(beta: f64, phi: f64) -> f64 {
197    beta.cos() / (1.0 - (beta.sin() * phi.cos()).powi(2))
198}
199
200/// The telescopic shaft between its two cardan joints.
201#[derive(Debug, Clone)]
202pub struct Shaft {
203    /// The upper joint's height on the base's axis, and the lower joint's above the platform's centre, m.
204    pub upper_z: f64,
205    pub lower_offset: f64,
206    /// Shortest and longest the telescope can be, m; the largest bend of a joint, rad.
207    pub min_length: f64,
208    pub max_length: f64,
209    pub max_angle: f64,
210}
211
212impl Shaft {
213    /// The upper and the lower joint with the platform's centre at p.
214    pub fn joints(&self, p: V3) -> (V3, V3) {
215        ([0.0, 0.0, self.upper_z], [p[0], p[1], p[2] + self.lower_offset])
216    }
217
218    /// Length, the cardan angle (both joints) and the bending plane's azimuth with the platform's centre at p.
219    pub fn geometry(&self, p: V3) -> (f64, f64, f64) {
220        let d = [p[0], p[1], p[2] + self.lower_offset - self.upper_z];
221        let across = d[0].hypot(d[1]);
222        (dot(d, d).sqrt(), across.atan2(-d[2]), d[1].atan2(d[0]))
223    }
224}
225
226pub struct Delta4 {
227    /// The three arms: the D3 with the shaft's share at its platform and the telescope's friction on it.
228    arms: Delta,
229    /// How many of the state's entries and of the base signals are the arms'.
230    n3: usize,
231    arm_base_signals: usize,
232    /// Where the arms' kinetic, potential and elastic energy stand among their effect signals.
233    arm_energy_at: usize,
234    /// The tool's turn: motor, gearbox (twisted together with the shaft), brake, the tool bearing's friction.
235    tool: RotaryJoint,
236    elastic: bool,
237    /// With effects.tool_gearbox_body: the gearbox output's inertia J_o, and the shaft's spring and damping between it
238    /// and the tool (two more states, th_o and its speed); `out_inertia` is 0 without it.
239    out_inertia: f64,
240    k_shaft: f64,
241    c_shaft: f64,
242    /// Tool and gripper with the shaft's spin (kg m^2), and the payload's about the tool's axis.
243    j_tool: f64,
244    j_payload: f64,
245    payload_attached: bool,
246    brake_engaged: bool,
247    /// An obstacle's torque on the tool about its turn (`Machine::set_tool_force`, its c component), N m.
248    turn_push: f64,
249    shaft: Shaft,
250    /// The telescope's friction as the D3 has it, for its loss power; `None` with effects.telescope_friction off.
251    drag: Option<PlatformDrag>,
252    thermal: Option<ThermalFeedback>,
253    axes: [AxisInfo; 4],
254    motors: [MotorInfo; 4],
255}
256
257/// The tool's losses of one moment: its bearing (and stops: none), its motor's friction with the brake, its gearbox,
258/// the telescope's sliding, the ripple's; and the gearbox's loss as a torque at the rotor.
259struct ToolLosses {
260    powers: [f64; 5],
261    gear_at_rotor: f64,
262}
263
264impl Delta4 {
265    pub fn new(cfg: &Config) -> Result<Self, ConfigError> {
266        let shaft = Shaft {
267            upper_z: cfg.f64("shaft.upper_joint_z_m")?,
268            lower_offset: cfg.non_negative("shaft.lower_joint_offset_m")?,
269            min_length: cfg.positive("shaft.min_length_m")?,
270            max_length: cfg.positive("shaft.max_length_m")?,
271            max_angle: cfg.positive("shaft.max_cardan_angle_deg")?.to_radians(),
272        };
273        if shaft.max_length <= shaft.min_length {
274            return Err(ConfigError::Invalid("shaft.max_length_m".into()));
275        }
276        let share = cfg.non_negative("shaft.platform_share")?;
277        if share > 1.0 {
278            return Err(ConfigError::Invalid("shaft.platform_share".into()));
279        }
280        let with_mass = cfg.bool("effects.shaft_mass")?;
281        // The arms: the D3 with the shaft's share of mass on its platform (the share of the inner shaft and the lower
282        // joint, which the platform carries; the outer tube hangs from the upper joint).
283        let mut inner = cfg.clone();
284        if with_mass {
285            let platform = cfg.positive("mass.platform_kg")? + share * cfg.non_negative("shaft.mass_kg")?;
286            inner.set_text(&format!("mass.platform_kg = {platform:?}"))?;
287        }
288        // The arms are the D3's (`Delta::build`) with, per arm, the joint of its own motor's config
289        // (`catalog::motor_config`: `[motor.<id>]`, `[gearbox.<id>]`, `[parts.<id>]` over the shared tables; absent =
290        // the shared ones, as before).
291        let mut drives = Arms::shared(&inner, [("x", "axis-x"), ("y", "axis-y"), ("z", "axis-z")])?;
292        for (k, id) in ["1", "2", "3"].into_iter().enumerate() {
293            drives.joints[k] = RotaryJoint::from_config(&motor_config(&inner, id)?)?;
294        }
295        let mut arms = Delta::build(&inner, &inner, drives)?;
296        let drag = if cfg.bool("effects.telescope_friction")? {
297            let friction = ShaftFriction {
298                coulomb: cfg.non_negative("shaft.slide_friction_n")?,
299                viscous: cfg.non_negative("shaft.slide_friction_viscous_n_s_m")?,
300                smoothing: cfg.positive("shaft.slide_friction_smoothing_m_s")?,
301                ..ShaftFriction::NONE
302            };
303            Some(PlatformDrag { pivot: [0.0, 0.0, shaft.upper_z], offset: [0.0, 0.0, shaft.lower_offset], friction })
304        } else {
305            None
306        };
307        arms.set_platform_drag(drag.clone());
308        // The tool's joint: motor 4's own motor and gearbox, `[motor.4]` and `[gearbox.4]` over the shared tables
309        // (`catalog::motor_config`), as its drive and its verdicts read them.
310        let tcfg = motor_config(cfg, "4")?;
311        let bearing = cfg.bool("effects.joint_friction")?;
312        let friction = ShaftFriction {
313            coulomb: if bearing { cfg.non_negative("tool.friction_coulomb_nm")? } else { 0.0 },
314            viscous: if bearing { cfg.non_negative("tool.friction_viscous_nm_s_rad")? } else { 0.0 },
315            smoothing: cfg.positive("tool.friction_smoothing_rad_s")?,
316            ..ShaftFriction::NONE
317        };
318        let (min, max) = (cfg.f64("axis.c.min_angle_deg")?.to_radians(), cfg.f64("axis.c.max_angle_deg")?.to_radians());
319        if min >= max {
320            return Err(ConfigError::Invalid("axis.c.max_angle_deg".into()));
321        }
322        // No stops: the turn is endless, the axis range is the controller's.
323        let mut tool = RotaryJoint::with(&tcfg, friction, HardStop { stiffness: 0.0, damping: 0.0 }, (min, max))?;
324        let (k_shaft, c_shaft) =
325            (cfg.positive("shaft.torsional_stiffness_nm_rad")?, cfg.non_negative("shaft.torsional_damping_nm_s_rad")?);
326        let elastic = cfg.bool("effects.joint_elasticity")?;
327        let torsion = cfg.bool("effects.shaft_torsion")?;
328        let body = cfg.bool("effects.tool_gearbox_body")? && elastic && torsion;
329        if torsion && !body {
330            // One spring in series, damped by the shaft (the softer by far): the gearbox's output has no inertia.
331            let shaft = Converter {
332                lever: 1.0,
333                stiffness: k_shaft,
334                backlash: 0.0,
335                efficiency: 1.0,
336                inertia: 0.0,
337                damping_ratio: 0.0,
338            };
339            shaft.apply_to(&tcfg, &mut tool, cfg.positive("tool.inertia_kgm2")?)?;
340            // The shaft's damper across the series spring in place of the gear's (no Maxwell arm, `Gearbox::arm`).
341            (tool.gearbox.damping, tool.gearbox.relax_stiffness) = (c_shaft, 0.0);
342        }
343        let out_inertia = if body { cfg.positive("tool.gearbox_output_inertia_kgm2")? } else { 0.0 };
344        if body {
345            // The body's share of the catalogue's inertia at the input leaves the rotor.
346            let share = out_inertia / (tool.ratio() * tool.ratio());
347            if share >= tcfg.non_negative("gearbox.inertia_at_input_kgm2")? {
348                return Err(ConfigError::Invalid("tool.gearbox_output_inertia_kgm2".into()));
349            }
350            tool.rotor_inertia -= share;
351            tool.brake = HoldingBrake::from_config(&tcfg, tool.rotor_inertia)?;
352        }
353        let j_shaft = if with_mass { cfg.non_negative("shaft.spin_inertia_kgm2")? } else { 0.0 };
354        let mut axes: Vec<AxisInfo> = arms.axes().to_vec();
355        axes.push(AxisInfo {
356            id: "c",
357            key: "axis-c",
358            unit: "rad",
359            min,
360            max,
361            max_vel: cfg.positive("axis.c.max_velocity_rad_s")?,
362            max_acc: cfg.positive("axis.c.max_acceleration_rad_s2")?,
363            max_jerk: cfg.positive("axis.c.max_jerk_rad_s3")?,
364        });
365        let motors = [
366            MotorInfo { id: "1", key: "motor-arm-1" },
367            MotorInfo { id: "2", key: "motor-arm-2" },
368            MotorInfo { id: "3", key: "motor-arm-3" },
369            MotorInfo { id: "4", key: "motor-tool" },
370        ];
371        // The arms' share of the base signals, counted at rest in the middle of the range.
372        let mid: Vec<f64> = arms.axes().iter().map(|a| 0.5 * (a.min + a.max)).collect();
373        let (mut state, mut torque, mut signals) = (Vec::new(), [0.0; 3], Vec::new());
374        arms.equilibrium(&[0.0, 0.0, mid[2]], &mut state, &mut torque);
375        arms.base_signals(&state, &torque, &mut signals);
376        let infos = arms.signal_infos();
377        let arm_energy_at =
378            infos.iter().position(|i| i.id == "energy.kinetic").expect("the arms report their energy") - signals.len();
379        Ok(Self {
380            n3: arms.state_len(),
381            arm_base_signals: signals.len(),
382            arm_energy_at,
383            arms,
384            elastic,
385            out_inertia,
386            k_shaft,
387            c_shaft,
388            j_tool: cfg.positive("tool.inertia_kgm2")? + j_shaft,
389            j_payload: if cfg.bool("effects.payload")? { cfg.non_negative("tool.payload_inertia_kgm2")? } else { 0.0 },
390            payload_attached: true,
391            brake_engaged: false,
392            turn_push: 0.0,
393            shaft,
394            drag,
395            thermal: ThermalFeedback::from_config(&tcfg)?,
396            tool,
397            axes: axes.try_into().map_err(|_| ConfigError::Invalid("axis".into()))?,
398            motors,
399        })
400    }
401
402    /// The arms, a D3.
403    pub fn arms(&self) -> &Delta {
404        &self.arms
405    }
406
407    pub fn shaft(&self) -> &Shaft {
408        &self.shaft
409    }
410
411    pub fn tool_joint(&self) -> &RotaryJoint {
412        &self.tool
413    }
414
415    /// What the tool's joint turns: tool, gripper, shaft spin and, while held, the payload.
416    pub fn tool_inertia(&self) -> f64 {
417        self.j_tool + if self.payload_attached { self.j_payload } else { 0.0 }
418    }
419
420    /// The tool's turn and its speed.
421    fn turn(&self, s: &[f64]) -> (f64, f64) {
422        (s[self.n3], s[self.n3 + 1])
423    }
424
425    /// The tool motor's rotor angle and speed.
426    fn rotor(&self, s: &[f64]) -> (f64, f64) {
427        if self.elastic {
428            (s[self.n3 + 2], s[self.n3 + 3])
429        } else {
430            let (c, w) = self.turn(s);
431            (self.tool.ratio() * c, self.tool.ratio() * w)
432        }
433    }
434
435    fn brake(&self, s: &[f64]) -> f64 {
436        s[self.n3 + if self.elastic { 4 } else { 2 }]
437    }
438
439    /// Whether the gearbox's output is a body of its own (effects.tool_gearbox_body).
440    fn has_body(&self) -> bool {
441        self.out_inertia > 0.0
442    }
443
444    /// The angle and speed the tool's gearbox turns its output at: the body's, or the tool's without a body.
445    fn gear_out(&self, s: &[f64]) -> (f64, f64) {
446        if self.has_body() { (s[self.n3 + 5], s[self.n3 + 6]) } else { self.turn(s) }
447    }
448
449    /// The torque the shaft's spring and damper pass from the gearbox's output to the tool, and the power the damper
450    /// takes. Both 0 without a body, where the two turn together.
451    fn shaft_torque(&self, s: &[f64]) -> (f64, f64) {
452        let ((c, w), (go, gw)) = (self.turn(s), self.gear_out(s));
453        (self.k_shaft * (go - c) + self.c_shaft * (gw - w), self.c_shaft * (gw - w).powi(2))
454    }
455
456    /// The platform's centre and speed.
457    fn platform(&self, s: &[f64]) -> (V3, V3) {
458        let (mut p, mut v) = ([0.0; 3], [0.0; 3]);
459        self.arms.tool_state(&s[..self.n3], &mut p, &mut v);
460        (p, v)
461    }
462
463    /// Rigid model: the turn's acceleration, and the torque into the gearbox (after the rotor's own acceleration)
464    /// and out of it, as the D3's arms (`Delta::rigid_solve`).
465    fn rigid_solve(&self, s: &[f64], torque: f64) -> (f64, f64, f64) {
466        let ((c, w), (rotor, speed)) = (self.turn(s), self.rotor(s));
467        let j = &self.tool;
468        let drive = j.rigid_drive(torque, rotor, speed, self.brake(s), self.brake_engaged).0;
469        let rest = j.output_torque(c, w) + self.turn_push;
470        let solve = |loss: f64| (loss * drive + rest) / (self.tool_inertia() + loss * j.reflected_inertia());
471        // The loss factor of the torque going in, at its fixed point (`mech::settled_loss`).
472        let [loss] = sim_components::mech::settled_loss([1.0], |&[loss]| {
473            [j.gearbox.loss_factor(drive - j.reflected_inertia() * solve(loss), w)]
474        });
475        let acc = solve(loss);
476        let into = drive - j.reflected_inertia() * acc;
477        (acc, into, loss * into)
478    }
479
480    /// The tool's derivatives into `out` (its part of the state).
481    fn tool_rates(&self, s: &[f64], torque: f64, out: &mut [f64]) {
482        let (c, w) = self.turn(s);
483        out[0] = w;
484        if self.elastic {
485            let o = self.n3;
486            let (go, gw) = self.gear_out(s);
487            let (gear, rotor_acc, brake_rate) =
488                self.tool.rotor(torque, s[o + 2], s[o + 3], go, gw, s[o + 4], self.brake_engaged);
489            let into_tool = if self.has_body() { self.shaft_torque(s).0 } else { gear.output };
490            out[1] = (into_tool + self.tool.output_torque(c, w) + self.turn_push) / self.tool_inertia();
491            out[2] = s[o + 3];
492            out[3] = rotor_acc;
493            out[4] = brake_rate;
494            if self.has_body() {
495                out[5] = gw;
496                out[6] = (gear.output - into_tool) / self.out_inertia;
497            }
498        } else {
499            out[1] = self.rigid_solve(s, torque).0;
500            let (_, speed) = self.rotor(s);
501            out[2] = self.tool.brake.torque(self.brake_engaged, speed, self.brake(s)).1;
502        }
503    }
504
505    /// The torque the tool's gearbox passes to the tool.
506    fn tool_gear_output(&self, s: &[f64], torque: f64) -> f64 {
507        let ((go, gw), (rotor, speed)) = (self.gear_out(s), self.rotor(s));
508        if self.elastic { self.tool.gearbox.torque(rotor, speed, go, gw).output } else { self.rigid_solve(s, torque).2 }
509    }
510
511    /// The tool's kinetic, potential (none) and elastic energy, the rotor's included.
512    fn tool_energy(&self, s: &[f64]) -> [f64; 3] {
513        let ((c, w), (rotor, speed)) = (self.turn(s), self.rotor(s));
514        let mut kinetic = 0.5 * self.tool_inertia() * w * w;
515        let mut elastic = self.tool.stop_energy(c);
516        if self.elastic {
517            let (go, gw) = self.gear_out(s);
518            kinetic += 0.5 * self.tool.rotor_inertia * speed * speed;
519            elastic += self.tool.gearbox.energy(rotor, go);
520            if self.has_body() {
521                kinetic += 0.5 * self.out_inertia * gw * gw;
522                elastic += 0.5 * self.k_shaft * (go - c).powi(2);
523            }
524        } else {
525            kinetic += 0.5 * self.tool.reflected_inertia() * w * w;
526        }
527        [kinetic, 0.0, elastic]
528    }
529
530    /// The telescope's sliding power, W: its friction times the rate at which it lengthens.
531    pub fn telescope_power(&self, s: &[f64]) -> f64 {
532        let Some(drag) = &self.drag else { return 0.0 };
533        let (p, v) = self.platform(s);
534        -dot(drag.force(p, v), v)
535    }
536
537    fn tool_losses(&self, s: &[f64], torque: f64) -> ToolLosses {
538        let ((c, w), (rotor, speed)) = (self.turn(s), self.rotor(s));
539        let j = &self.tool;
540        let [friction, stop, shaft, drag] = j.losses(c, w, speed, self.brake(s), self.brake_engaged);
541        let (gear, gear_at_rotor) = if self.elastic {
542            let (go, gw) = self.gear_out(s);
543            let g = j.gearbox.torque(rotor, speed, go, gw);
544            (j.gearbox.loss_power(rotor, speed, go, gw) + self.shaft_torque(s).1, g.rotor - g.output / j.ratio())
545        } else {
546            let (_, into, out) = self.rigid_solve(s, torque);
547            ((into - out) * w, (into - out) / j.ratio())
548        };
549        let other = (torque - j.ripple.apply(torque, rotor)) * speed;
550        ToolLosses { powers: [friction + stop, shaft, gear + drag, self.telescope_power(s), other], gear_at_rotor }
551    }
552
553    /// The torsional mode of the tool with its motor held: the gearbox's spring (with the shaft's in series,
554    /// effects.shaft_torsion) against J_c, w^2 = k / J_c, damping ratio c / (2 sqrt(k J_c)). `None` in the rigid model.
555    pub fn tool_mode(&self) -> Option<Mode> {
556        if !self.elastic {
557            return None;
558        }
559        if self.has_body() {
560            return self.body_modes().first().copied();
561        }
562        let (k, j) = (self.tool.gearbox.stiffness, self.tool_inertia());
563        Some(Mode {
564            hz: (k / j).sqrt() / std::f64::consts::TAU,
565            damping: self.tool.gearbox.damping / (2.0 * (k * j).sqrt()),
566        })
567    }
568
569    /// With the gearbox's output body, the two modes of the chain rotor (held), gearbox spring k_g, J_o, shaft spring
570    /// k_s, J_c, lowest first: the roots lambda of J_o J_c lambda^2 - b lambda + k_g k_s = 0, b = J_c (k_g + k_s) +
571    /// J_o k_s, each with the shape phi = ((k_s - lambda J_c) / k_s, 1) of the second row of (K - lambda M) phi = 0 and
572    /// the damping ratio phi^T C phi / (2 w phi^T M phi), C the gearbox's and the shaft's dampers. Empty without a body.
573    pub fn body_modes(&self) -> Vec<Mode> {
574        if !self.has_body() {
575            return Vec::new();
576        }
577        let (kg, cg) = (self.tool.gearbox.stiffness, self.tool.gearbox.damping);
578        let (ks, cs, jo, jc) = (self.k_shaft, self.c_shaft, self.out_inertia, self.tool_inertia());
579        let b = jc * (kg + ks) + jo * ks;
580        let root = (b * b - 4.0 * jo * jc * kg * ks).sqrt();
581        // The small root without the cancellation of b - root.
582        let lambdas = [2.0 * kg * ks / (b + root), (b + root) / (2.0 * jo * jc)];
583        lambdas
584            .map(|l| {
585                let (w, phi) = (l.sqrt(), (ks - l * jc) / ks);
586                let (damper, mass) = (cg * phi * phi + cs * (phi - 1.0).powi(2), jo * phi * phi + jc);
587                Mode { hz: w / std::f64::consts::TAU, damping: damper / (2.0 * w * mass) }
588            })
589            .to_vec()
590    }
591
592    /// The telescope as drawn with the platform's centre at p: the outer tube down from the upper joint and the inner
593    /// shaft up from the lower one, each as long as the shortest shaft less 50 mm (they overlap), with their widths.
594    fn telescope(&self, p: V3) -> [(V3, V3, f64); 2] {
595        let (upper, lower) = self.shaft.joints(p);
596        let (length, ..) = self.shaft.geometry(p);
597        let u: V3 = std::array::from_fn(|k| (lower[k] - upper[k]) / length);
598        let part = (self.shaft.min_length - 0.05).min(length);
599        [
600            (upper, std::array::from_fn(|k| upper[k] + part * u[k]), TUBE_WIDTH),
601            (lower, std::array::from_fn(|k| lower[k] - part * u[k]), INNER_WIDTH),
602        ]
603    }
604
605    /// The telescope's tube and inner shaft as collision capsules, each of half its width along the segment drawn.
606    fn shaft_capsules(&self, p: V3) -> Vec<sim_core::Capsule> {
607        self.telescope(p)
608            .into_iter()
609            .map(|(from, to, width)| sim_core::Capsule { from, to, radius: width / 2.0 })
610            .collect()
611    }
612}
613
614/// The telescope's outer tube and inner shaft as drawn and as collision capsules (twice their radius), m.
615const TUBE_WIDTH: f64 = 0.03;
616const INNER_WIDTH: f64 = 0.016;
617/// The tool motor and its gearbox on the base's axis as drawn and as collision boxes (centre and size, m).
618const MOTOR_BOX: sim_core::Aabb = sim_core::Aabb { centre: [0.0, 0.0, 0.16], size: [0.09, 0.09, 0.12] };
619const GEARBOX_BOX: sim_core::Aabb = sim_core::Aabb { centre: [0.0, 0.0, 0.065], size: [0.08, 0.08, 0.05] };
620
621impl Machine for Delta4 {
622    /// The D3's, plus the tool's turn (tool, gripper, payload and the shaft's spin) and its rotor about z.
623    fn frame_momentum(&self, s: &[f64]) -> Option<sim_core::FrameMomentum> {
624        let mut f = self.arms.frame_momentum(&s[..self.n3])?;
625        sim_components::base::add_spin(&mut f, [0.0, 0.0, 1.0], self.tool_inertia(), self.turn(s).1);
626        sim_components::base::add_spin(&mut f, [0.0, 0.0, 1.0], self.tool.rotor_inertia, self.rotor(s).1);
627        sim_components::base::add_spin(&mut f, [0.0, 0.0, 1.0], self.out_inertia, self.gear_out(s).1);
628        Some(f)
629    }
630
631    fn axes(&self) -> &[AxisInfo] {
632        &self.axes
633    }
634    fn motors(&self) -> &[MotorInfo] {
635        &self.motors
636    }
637
638    fn inverse(&self, tool: &[f64], motors: &mut [f64]) {
639        self.arms.inverse(&tool[..3], &mut motors[..3]);
640        motors[3] = self.tool.ratio() * tool[3];
641    }
642    fn forward(&self, motors: &[f64], tool: &mut [f64]) {
643        self.arms.forward(&motors[..3], &mut tool[..3]);
644        tool[3] = motors[3] / self.tool.ratio();
645    }
646
647    /// The arms' state (the D3's), then the turn and its speed, the rotor's angle and speed (elastic) and the brake.
648    fn state_len(&self) -> usize {
649        self.n3 + if self.elastic { 5 } else { 3 } + if self.has_body() { 2 } else { 0 }
650    }
651
652    fn equilibrium(&self, tool: &[f64], state: &mut Vec<f64>, torque: &mut [f64]) {
653        self.arms.equilibrium(&tool[..3], state, &mut torque[..3]);
654        // Nothing holds the turn at rest: no weight turns it.
655        let rotor = self.tool.ratio() * tool[3];
656        state.extend([tool[3], 0.0]);
657        if self.elastic {
658            state.extend([rotor, 0.0]);
659        }
660        state.push(0.0);
661        if self.has_body() {
662            state.extend([tool[3], 0.0]);
663        }
664        torque[3] = self.tool.ripple.invert(0.0, rotor);
665    }
666
667    fn derivatives(&self, s: &[f64], torque: &[f64], out: &mut [f64]) {
668        let n = self.n3;
669        self.arms.derivatives(&s[..n], &torque[..3], &mut out[..n]);
670        self.tool_rates(s, torque[3], &mut out[n..]);
671    }
672
673    fn tool_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
674        self.arms.tool_state(&s[..self.n3], &mut pos[..3], &mut vel[..3]);
675        (pos[3], vel[3]) = self.turn(s);
676    }
677    fn set_tool_velocity(&self, s: &mut [f64], vel: &[f64]) {
678        let n = self.n3;
679        self.arms.set_tool_velocity(&mut s[..n], &vel[..3]);
680        s[n + 1] = vel[3];
681        if self.elastic {
682            s[n + 3] = self.tool.ratio() * vel[3];
683        }
684        if self.has_body() {
685            s[n + 6] = vel[3];
686        }
687    }
688    fn motor_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
689        self.arms.motor_state(&s[..self.n3], &mut pos[..3], &mut vel[..3]);
690        (pos[3], vel[3]) = self.rotor(s);
691    }
692
693    /// The arms' (the D3's), and the turn's J_c c'' / i + J_rotor i c''.
694    fn feedforward_torque(&self, pos: &[f64], acc: &[f64], out: &mut [f64]) {
695        self.arms.feedforward_torque(&pos[..3], &acc[..3], &mut out[..3]);
696        let i = self.tool.ratio();
697        out[3] = (self.tool_inertia() + self.out_inertia) * acc[3] / i + self.tool.rotor_inertia * i * acc[3];
698    }
699    /// The arms' with the speed (the D3's, loss-free: without the telescope's friction), the turn's as without it.
700    fn feedforward_torque_moving(&self, pos: &[f64], vel: &[f64], acc: &[f64], out: &mut [f64]) {
701        self.arms.feedforward_torque_moving(&pos[..3], &vel[..3], &acc[..3], &mut out[..3]);
702        let i = self.tool.ratio();
703        out[3] = (self.tool_inertia() + self.out_inertia) * acc[3] / i + self.tool.rotor_inertia * i * acc[3];
704    }
705
706    /// The arms' (the D3's, the telescope's sliding included), and the turn's: the tool bearing's friction f(c') through
707    /// the gearbox, f / (i loss), plus the tool motor shaft's at i c'.
708    fn steady_friction(&self, pos: &[f64], vel: &[f64], out: &mut [f64]) {
709        self.arms.steady_friction(&pos[..3], &vel[..3], &mut out[..3]);
710        let (j, w) = (&self.tool, vel[3]);
711        let bearing = j.friction.torque(w);
712        out[3] = j.shaft.torque(j.ratio() * w) + bearing / (j.ratio() * j.gearbox.loss_factor(bearing, w));
713    }
714
715    fn energy(&self, s: &[f64]) -> f64 {
716        self.arms.energy(&s[..self.n3]) + self.tool_energy(s).iter().sum::<f64>()
717    }
718
719    fn set_payload_attached(&mut self, attached: bool) {
720        self.payload_attached = attached;
721        self.arms.set_payload_attached(attached);
722    }
723    fn set_brake_engaged(&mut self, engaged: bool) {
724        self.brake_engaged = engaged;
725        self.arms.set_brake_engaged(engaged);
726    }
727    /// The arms' stops (the tool's turn has none).
728    fn substeps_wanted(&self, s: &[f64], torque: &[f64], dt: f64, substeps: u32) -> u32 {
729        self.arms.substeps_wanted(&s[..self.n3], &torque[..3], dt, substeps)
730    }
731    /// The push on x, y and z goes to the arms (the D3's, at the platform); the torque about c turns the tool.
732    fn set_tool_force(&mut self, force: &[f64]) -> bool {
733        self.turn_push = force[3];
734        self.arms.set_tool_force(&force[..3])
735    }
736
737    /// The arms' gearboxes, then the tool's: their hysteresis states move on to where the step ended.
738    fn after_step(&mut self, s: &mut [f64], dt: f64) {
739        self.arms.after_step(&mut s[..self.n3], dt);
740        if self.elastic {
741            let ((c, _), (rotor, _)) = (self.gear_out(s), self.rotor(s));
742            self.tool.gearbox.commit(rotor, c);
743        }
744    }
745    /// The arms' gearboxes, then the tool's.
746    fn memory(&self) -> Vec<f64> {
747        [self.arms.memory(), self.tool.gearbox.anchor.to_vec()].concat()
748    }
749    fn set_memory(&mut self, memory: &[f64]) {
750        let arms = memory.len().saturating_sub(2);
751        self.arms.set_memory(&memory[..arms]);
752        sim_components::mech::Gearbox::set_anchors([&mut self.tool.gearbox], &memory[arms..]);
753    }
754
755    /// The arms' three gearboxes, then the tool's.
756    fn set_part_temperatures(&mut self, rises: &[f64]) {
757        self.arms.set_part_temperatures(&rises[..rises.len().min(3)]);
758        if let (Some(law), Some(rise)) = (&self.thermal, rises.get(3))
759            && !self.tool.gearbox.is_coupling()
760        {
761            self.tool.gearbox.efficiency = law.gearbox_efficiency(*rise);
762            self.tool.shaft.set_oil(law.viscosity_factor(*rise));
763        }
764    }
765
766    /// The arms' modes (the D3's) and the tool's torsion (`tool_mode`), lowest first.
767    fn modes(&self, tool_pose: &[f64]) -> Vec<Mode> {
768        let mut out = self.arms.modes(&tool_pose[..3]);
769        out.extend(self.tool_mode());
770        out.extend(self.body_modes().into_iter().skip(1));
771        out.sort_by(|a, b| a.hz.total_cmp(&b.hz));
772        out
773    }
774    /// The arms' (the D3's) and, with effects.joint_elasticity, the tool's gearbox spring between its rotor and the rest
775    /// of its rigid inertia; the shaft's torsion is left out.
776    fn trains(&self, tool_pose: &[f64]) -> Vec<Option<sim_core::Train>> {
777        if !self.elastic {
778            return Vec::new();
779        }
780        let mut out = self.arms.trains(&tool_pose[..3]);
781        out.resize(3, None);
782        out.push(self.tool.train(sim_components::control::rigid_inertias(self, tool_pose)[3]));
783        out
784    }
785    /// The arms' lowest mode, which an input shaper on the path is for; the tool's torsion is in `modes`.
786    fn resonance_hz(&self, tool_pose: &[f64]) -> Option<f64> {
787        self.arms.resonance_hz(&tool_pose[..3])
788    }
789    fn mode_shape(&self, tool_pose: &[f64]) -> Option<(f64, Vec<f64>)> {
790        let (hz, mut shape) = self.arms.mode_shape(&tool_pose[..3])?;
791        shape.resize(self.state_len(), 0.0);
792        Some((hz, shape))
793    }
794
795    fn unreachable(&self, tool: &[f64], slack: f64) -> Option<&'static str> {
796        if tool.len() != 4 {
797            return Some("error-target-out-of-range");
798        }
799        if let Some(why) = self.arms.unreachable(&tool[..3], slack) {
800            return Some(why);
801        }
802        let (length, beta, _) = self.shaft.geometry([tool[0], tool[1], tool[2]]);
803        if length < self.shaft.min_length - slack || length > self.shaft.max_length + slack {
804            return Some("error-delta-shaft-stroke");
805        }
806        (beta > self.shaft.max_angle).then_some("error-delta-cardan-angle")
807    }
808
809    fn condition(&self, tool: &[f64]) -> Option<f64> {
810        self.arms.condition(&tool[..3])
811    }
812
813    fn setpoint_slack(&self) -> f64 {
814        self.arms.setpoint_slack()
815    }
816
817    fn signal_infos(&self) -> Vec<SignalInfo> {
818        let arms = self.arms.signal_infos();
819        let (base, effects) = arms.split_at(self.arm_base_signals);
820        let mut out = base.to_vec();
821        out.push(SignalInfo::new("tool.angle", "group-tool", "quantity-tool-angle", "rad"));
822        out.push(SignalInfo::new("gearbox.4.output_torque", "motor-tool", "quantity-gearbox-torque", "N m"));
823        out.push(SignalInfo::new("shaft.length", "group-shaft", "quantity-shaft-length", "m"));
824        out.push(SignalInfo::new("shaft.cardan_angle", "group-shaft", "quantity-cardan-angle", "rad"));
825        out.push(SignalInfo::new("shaft.speed", "group-shaft", "quantity-shaft-speed", "rad/s"));
826        out.extend_from_slice(effects);
827        out.extend(TORQUE_PARTS.map(|part| {
828            SignalInfo::new(format!("motor.4.torque_{part}"), "motor-tool", &format!("quantity-torque-{part}"), "N m")
829        }));
830        let gear = if self.tool.gearbox.is_coupling() {
831            "quantity-coupling-loss-power"
832        } else {
833            "quantity-gearbox-loss-power"
834        };
835        out.push(SignalInfo::new(format!("{LOSS_PREFIX}joint_4"), "group-tool", "quantity-friction-power", "W"));
836        out.push(SignalInfo::new(format!("{LOSS_PREFIX}shaft_4"), "motor-tool", "quantity-shaft-friction-power", "W"));
837        out.push(SignalInfo::new(format!("{LOSS_PREFIX}gearbox_4"), "motor-tool", gear, "W"));
838        out.push(SignalInfo::new(format!("{LOSS_PREFIX}telescope"), "group-shaft", "quantity-friction-power", "W"));
839        out.push(SignalInfo::new(format!("{LOSS_PREFIX}other_4"), "loss-other", "quantity-power-given-off", "W"));
840        out
841    }
842
843    fn base_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
844        self.arms.base_signals(&s[..self.n3], &torque[..3], out);
845        let (c, w) = self.turn(s);
846        let (length, beta, azimuth) = self.shaft.geometry(self.platform(s).0);
847        out.extend([c, self.tool_gear_output(s, torque[3]), length, beta, w * cardan_speed_ratio(beta, c - azimuth)]);
848    }
849
850    /// The arms' effect signals with the tool's energy added to theirs, then the tool motor's torque parts and the
851    /// tool's losses.
852    fn effect_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
853        let at = out.len() + self.arm_energy_at;
854        self.arms.effect_signals(&s[..self.n3], &torque[..3], out);
855        for (k, e) in self.tool_energy(s).into_iter().enumerate() {
856            out[at + k] += e;
857        }
858        let j = &self.tool;
859        let ((_, w), (_, speed)) = (self.turn(s), self.rotor(s));
860        let mut rates = [0.0; 7];
861        self.tool_rates(s, torque[3], &mut rates);
862        let losses = self.tool_losses(s, torque[3]);
863        let held = j.brake.torque(self.brake_engaged, speed, self.brake(s)).0;
864        let parts = [
865            ((self.tool_inertia() + j.reflected_inertia()) * rates[1] + self.out_inertia * rates[6]) / j.ratio(),
866            0.0,
867            j.shaft.torque(speed) + held + losses.gear_at_rotor + j.friction.torque(w) / j.ratio(),
868        ];
869        out.extend(parts);
870        out.push(torque[3] - parts.iter().sum::<f64>());
871        out.extend(losses.powers);
872    }
873
874    fn loss_powers(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
875        self.arms.loss_powers(&s[..self.n3], &torque[..3], out);
876        out.extend(self.tool_losses(s, torque[3]).powers);
877    }
878
879    /// The arms' three gearboxes and the tool's (none on direct drives).
880    fn thermal_parts(&self) -> Vec<ThermalPart> {
881        let mut out = self.arms.thermal_parts();
882        if !self.tool.gearbox.is_coupling() {
883            out.push(ThermalPart {
884                id: "gearbox_4",
885                kind: "gearbox",
886                owner_key: "motor-tool",
887                scene_part: "gearbox",
888                scene_index: 3,
889            });
890        }
891        out
892    }
893
894    /// The D3's scene, then the tool's motor and gearbox in the base's centre, the telescope (outer tube from the upper
895    /// joint, inner shaft from the lower), the two joints, and a bar under the platform turned with the tool.
896    fn scene(&self, s: &[f64], out: &mut Scene) {
897        self.arms.scene(&s[..self.n3], out);
898        let (p, _) = self.platform(s);
899        let (c, _) = self.turn(s);
900        let (rotor, speed) = self.rotor(s);
901        let (upper, lower) = self.shaft.joints(p);
902        let [(tube_from, tube_to, tube), (inner_from, inner_to, inner)] = self.telescope(p);
903        let dark = [0.25, 0.25, 0.28];
904        out.parts.push(Part::new(
905            sim_core::scene::MOTOR_PART,
906            Shape::Box { size: MOTOR_BOX.size },
907            MOTOR_BOX.centre,
908            [0.9, 0.45, 0.1],
909        ));
910        out.parts.push(Part::new("gearbox", Shape::Box { size: GEARBOX_BOX.size }, GEARBOX_BOX.centre, dark));
911        out.parts.push(
912            Part::new("rotor-bar", Shape::Box { size: [0.07, 0.004, 0.012] }, [0.0, 0.0, 0.225], [0.1, 0.1, 0.1])
913                .turned(rotor),
914        );
915        out.parts.push(Part::new(
916            "shaft-tube",
917            Shape::Segment { to: tube_to, width: tube },
918            tube_from,
919            [0.7, 0.72, 0.75],
920        ));
921        out.parts.push(Part::new(
922            "shaft-inner",
923            Shape::Segment { to: inner_to, width: inner },
924            inner_from,
925            [0.5, 0.5, 0.52],
926        ));
927        for at in [upper, lower] {
928            out.parts.push(Part::new("cardan", Shape::Box { size: [0.035, 0.035, 0.035] }, at, dark));
929        }
930        let half = [0.06 * c.cos(), 0.06 * c.sin(), 0.0];
931        let under = [p[0], p[1], p[2] - 0.025];
932        out.parts.push(Part::new(
933            "tool",
934            Shape::Segment { to: std::array::from_fn(|k| under[k] + half[k]), width: 0.015 },
935            std::array::from_fn(|k| under[k] - half[k]),
936            [0.85, 0.75, 0.2],
937        ));
938        // The tool motor's speed after the arms' three (the D3's z label is not in rpm).
939        let rpm = Label {
940            pos: [0.0, 0.0, 0.3],
941            owner_key: "motor-tool",
942            value: speed * 60.0 / std::f64::consts::TAU,
943            unit_key: "unit-rpm",
944            decimals: 0,
945        };
946        let at = out.labels.iter().rposition(|l| l.unit_key == "unit-rpm").map_or(out.labels.len(), |i| i + 1);
947        out.labels.insert(at, rpm);
948    }
949
950    fn scene_point(&self, tool_pose: &[f64]) -> Option<[f64; 3]> {
951        self.arms.scene_point(&tool_pose[..3])
952    }
953
954    /// The D3's boxes (platform and payload) and the tool motor and its gearbox above the base's centre, where `scene`
955    /// draws them (they stand still with the base).
956    fn collision_bodies(&self, s: &[f64]) -> Vec<sim_core::Aabb> {
957        let mut out = self.arms.collision_bodies(&s[..self.n3]);
958        out.extend([MOTOR_BOX, GEARBOX_BOX]);
959        out
960    }
961
962    /// The D3's capsules (forearm rods, upper arms) and the telescopic shaft between its joints.
963    fn collision_capsules(&self, s: &[f64]) -> Vec<sim_core::Capsule> {
964        let mut out = self.arms.collision_capsules(&s[..self.n3]);
965        out.extend(self.shaft_capsules(self.platform(s).0));
966        out
967    }
968}
969
970#[cfg(test)]
971mod tests;