Skip to main content

machine_mover_track/
lib.rs

1//! A linear transport system with independent movers on a closed track, as Beckhoff XTS or B&R ACOPOStrak: motor
2//! segments (modules) of linear-motor coils in a loop of two straights and two 180 degree curves, and on them movers,
3//! each a mass on rollers carrying the magnet plate, each driven by the coils under it with a position loop of its own.
4//!
5//! Each mover is a joint of `sim_components::chain::JointMachine`: its coordinate is s, the distance along the track's
6//! centre line (m), unwrapped (one loop adds the track's length L); its "motor" the coils under it, read in N for N m
7//! and m for rad as on the linear motor axis (force constant in N/A, the magnet plate's mass as the rotor's inertia, the
8//! cogging once per pole pitch). The rollers' rolling resistance is the joint's friction, with the attraction between
9//! magnet plate and coils pressing on them as the linear motor axis has it. The track lies level: its movers' weight
10//! does no work, M = m (body plus payload) per mover, no bias.
11//!
12//! The track (`Track`): straight, curve, straight, curve, the movers running anticlockwise seen from above, on the
13//! outside of the loop with the magnet plate facing the coils. A curve turns by pi either at a constant radius R or with
14//! a clothoid at each end (curvature rising linearly over `track.clothoid_m`, an arc of R between). A mover's rollers
15//! span its wheelbase w, so the curvature its body follows is the mean over it, k(s) = (theta(s + w/2) - theta(s -
16//! w/2)) / w with theta the heading: the lateral acceleration v^2 k rises over the wheelbase where a constant-radius
17//! curve begins, over the clothoid where one has it, and its rate, the lateral jerk 2 v a k + v^3 dk/ds, is what the
18//! clothoid takes down.
19//!
20//! The rollers carry the attraction F_a less the centrifugal force m v^2 k across the track (the mover sits outside the
21//! curve, so the centrifugal force pulls it off the coils) and the weight m g along the rollers' other axis: guide load
22//! sqrt((F_a - m v^2 k)^2 + (m g)^2). Above m v^2 k = F_a the mover lifts off its rollers (`mover.<k>.liftoff_ratio`).
23//! The mass centre sits `mass.centre_offset_m` = e outside the centre line (0 ships, the drawn mover is 35 mm out):
24//! it runs on R + e at v (1 + e k), the lateral acceleration is v^2 k (1 + e k) and the mass m (1 + e k)^2.
25//!
26//! The coils (`MoverTrack`): a mover's current is that of its force, I = F / k_t less what saturation takes towards the
27//! maximum current (`DriveParams::current_for`), and it flows in the
28//! coils under its magnet plate, shared among the segments by the plate's length on each. A segment's current is the sum
29//! of |I| of the movers on it in those shares; its copper loss R I^2 per mover in those shares (R the coil set under one
30//! mover, `motor.resistance_ohm`). Each segment warms with its loss through one thermal resistance and time constant
31//! (`segment.temperature_rise`); the verdict judges the rise it settles at, the loss averaged over about one pass of the
32//! cycle times the thermal resistance: several movers stopping on one segment heat it.
33//!
34//! The cycle is an electronic cam (`[cam]`, `track.cycle`): "index" moves every mover on by one station pitch L / n
35//! (`track.index_law`) and stands it at its station for the rest of the period, at `track.index_rate_hz`; "flying" runs
36//! each mover once round the loop per n products of a conveyor (the master, m), synchronous with it over
37//! `track.process_length_m` and back to the start of the process along the rest of the loop, the movers a product apart.
38//! With `cam.run = false` (default.toml, as the crank and cam machines ship) the config's `[[cycle.segment]]` move the
39//! movers instead, as on every machine; `flying.toml` runs its cam, and `--set cam.run=true` the index cam.
40
41use sim_components::cam::{Cam, Law, Segment};
42use sim_components::chain::{JointMachine, JointSpec, MOTOR_IDS, Mechanism};
43use sim_components::drive::DriveParams;
44use sim_components::joint::RotaryJoint;
45use sim_components::mech::ThermalFeedback;
46use sim_components::transmission::LinearMotor;
47use sim_core::{
48    AxisInfo, BeltSection, CamMaster, Config, ConfigError, FrameMomentum, FrictionContact, Label, Machine,
49    MachineEntry, Mode, MotorInfo, Part, RatingCheck, Scene, Shape, SignalInfo, ThermalPart,
50};
51use std::f64::consts::{PI, TAU};
52use std::sync::Mutex;
53use std::sync::atomic::{AtomicU64, Ordering};
54
55pub static ENTRY: MachineEntry = MachineEntry {
56    id: "mover-track",
57    key: "machine-mover-track",
58    default_config: include_str!("../default.toml"),
59    i18n: &[("en", include_str!("../i18n/en.ftl")), ("de", include_str!("../i18n/de.ftl"))],
60    build,
61    suite_configs,
62};
63
64/// The flying-process cycle: the default config with `track.cycle = "flying"` and its start poses (a test keeps the two
65/// files the same but for those). Load it as a whole config with `--config`.
66pub const FLYING_CONFIG: &str = include_str!("../flying.toml");
67
68const G: f64 = 9.80665;
69/// Steps of the curve's table of points (drawing only).
70const CURVE_POINTS: usize = 2000;
71/// Strips a curve segment is drawn with.
72const CURVE_STRIPS: usize = 12;
73/// Bins of the moving average of the segment's loss over one pass.
74const BINS: usize = 256;
75
76pub const MAX_MOVERS: usize = 7;
77/// How far a mover's axis range reaches behind and ahead of its cycle's targets, m: as far as one mover alone at an end
78/// of its range keeps from its neighbours at their starts (the shipped 0.503 m pitch less a body and, ahead, the 0.3 m of
79/// jog: 0.433 m and 0.133 m), a little less. The 0.8 m range gives one mover alone a stroke of some 0.25 s at its top
80/// speed; at the middles of the box's faces the shipped movers keep 0.103 m.
81const BEHIND: f64 = 0.37;
82const AHEAD: f64 = 0.13;
83const AXIS_IDS: [&str; MAX_MOVERS] = ["s1", "s2", "s3", "s4", "s5", "s6", "s7"];
84const AXIS_KEYS: [&str; MAX_MOVERS] =
85    ["axis-mover-1", "axis-mover-2", "axis-mover-3", "axis-mover-4", "axis-mover-5", "axis-mover-6", "axis-mover-7"];
86const MOVER_KEYS: [&str; MAX_MOVERS] = ["mover-1", "mover-2", "mover-3", "mover-4", "mover-5", "mover-6", "mover-7"];
87const MOTOR_KEYS: [&str; MAX_MOVERS] = [
88    "motor-mover-1",
89    "motor-mover-2",
90    "motor-mover-3",
91    "motor-mover-4",
92    "motor-mover-5",
93    "motor-mover-6",
94    "motor-mover-7",
95];
96
97/// Effects that take energy out or put it in; the standard suite runs with them off.
98pub const LOSSY_EFFECTS: [&str; 7] = [
99    "joint_friction",
100    "motor_friction",
101    "gearbox_drag",
102    "gearbox_lost_motion",
103    "gearbox_efficiency",
104    "torque_ripple",
105    "holding_brake",
106];
107
108/// The movers have no links to bend: `effects.link_bending` (and its reaction) on is refused.
109fn build(cfg: &Config) -> Result<Box<dyn Machine>, ConfigError> {
110    sim_components::refuse_unmodelled(cfg, &["link_bending", "link_bending_reaction"])?;
111    sim_components::base::mount(cfg, Box::new(MoverTrack::new(cfg)?))
112}
113
114/// The default config with every loss switched off.
115pub fn lossless_config() -> Config {
116    let mut cfg = ENTRY.config();
117    for effect in LOSSY_EFFECTS {
118        cfg.set_text(&format!("effects.{effect} = false")).unwrap();
119    }
120    cfg.set_text("gearbox.damping_nm_s_rad = 0.0").unwrap();
121    cfg
122}
123
124/// Loss-free rigid and elastic models (the magnet plate on its mount), with and without the payload.
125fn suite_configs() -> Vec<Config> {
126    [(false, true), (false, false), (true, true), (true, false)]
127        .into_iter()
128        .map(|(elastic, payload)| {
129            let mut cfg = lossless_config();
130            cfg.set_text(&format!("effects.joint_elasticity = {elastic}")).unwrap();
131            cfg.set_text(&format!("effects.payload = {payload}")).unwrap();
132            cfg
133        })
134        .collect()
135}
136
137/// The closed track's centre line: straight 1 from the origin along +x, curve 1, straight 2 back along -x at the
138/// track's width, curve 2; and its motor segments (each straight cut into modules, each curve one).
139#[derive(Debug, Clone)]
140pub struct Track {
141    pub straight: f64,
142    pub radius: f64,
143    pub clothoid: f64,
144    /// One curve's length, pi R + clothoid.
145    pub curve: f64,
146    /// The loop, 2 straight + 2 curve.
147    pub length: f64,
148    /// The distance between the straights (the curve's "diameter" in Beckhoff's catalogue).
149    pub width: f64,
150    /// Where each segment starts along the loop, rising from 0; the last ends at `length`.
151    pub segments: Vec<f64>,
152    /// The curve's points in its own frame (x along straight 1, y towards straight 2) every curve / CURVE_POINTS.
153    points: Vec<[f64; 2]>,
154}
155
156impl Track {
157    pub fn new(straight: f64, module: f64, radius: f64, clothoid: f64) -> Result<Self, ConfigError> {
158        if clothoid < 0.0 || clothoid >= PI * radius {
159            return Err(ConfigError::Invalid("track.clothoid_m".into()));
160        }
161        let modules = (straight / module).round();
162        if modules < 1.0 || (modules * module - straight).abs() > 1e-9 {
163            return Err(ConfigError::Invalid("track.straight_m".into()));
164        }
165        let curve = PI * radius + clothoid;
166        let mut t = Self {
167            straight,
168            radius,
169            clothoid,
170            curve,
171            length: 2.0 * (straight + curve),
172            width: 0.0,
173            segments: Vec::new(),
174            points: Vec::with_capacity(CURVE_POINTS + 1),
175        };
176        // The curve's points by the midpoint rule along its heading.
177        let h = curve / CURVE_POINTS as f64;
178        let mut p = [0.0, 0.0];
179        t.points.push(p);
180        for i in 0..CURVE_POINTS {
181            let theta = t.curve_heading((i as f64 + 0.5) * h);
182            p = [p[0] + h * theta.cos(), p[1] + h * theta.sin()];
183            t.points.push(p);
184        }
185        t.width = p[1];
186        let n = modules as usize;
187        for start in [0.0, straight + curve] {
188            t.segments.extend((0..n).map(|k| start + k as f64 * module));
189            t.segments.push(start + straight);
190        }
191        Ok(t)
192    }
193
194    /// The heading within a curve at `u` from its start: 0 to pi.
195    fn curve_heading(&self, u: f64) -> f64 {
196        let (r, lc, c) = (self.radius, self.clothoid, self.curve);
197        let u = u.clamp(0.0, c);
198        if lc == 0.0 {
199            u / r
200        } else if u < lc {
201            u * u / (2.0 * r * lc)
202        } else if u <= c - lc {
203            lc / (2.0 * r) + (u - lc) / r
204        } else {
205            PI - (c - u).powi(2) / (2.0 * r * lc)
206        }
207    }
208    fn curve_curvature(&self, u: f64) -> f64 {
209        let (r, lc, c) = (self.radius, self.clothoid, self.curve);
210        if !(0.0..c).contains(&u) {
211            0.0
212        } else if lc == 0.0 || (lc..=c - lc).contains(&u) {
213            1.0 / r
214        } else if u < lc {
215            u / (r * lc)
216        } else {
217            (c - u) / (r * lc)
218        }
219    }
220
221    /// `s` on the loop (0 to L) and whole loops before it.
222    fn wrap(&self, s: f64) -> (f64, f64) {
223        let turns = (s / self.length).floor();
224        ((s - turns * self.length).clamp(0.0, self.length), turns)
225    }
226
227    /// The heading at `s`, unwrapped (2 pi more per loop).
228    pub fn heading(&self, s: f64) -> f64 {
229        let (r, turns) = self.wrap(s);
230        let (a, c) = (self.straight, self.curve);
231        TAU * turns
232            + if r < a {
233                0.0
234            } else if r < a + c {
235                self.curve_heading(r - a)
236            } else if r < 2.0 * a + c {
237                PI
238            } else {
239                PI + self.curve_heading(r - 2.0 * a - c)
240            }
241    }
242
243    /// The curvature at `s`, 1/m, positive turning left.
244    pub fn curvature(&self, s: f64) -> f64 {
245        let (r, _) = self.wrap(s);
246        let (a, c) = (self.straight, self.curve);
247        if r < a + c { self.curve_curvature(r - a) } else { self.curve_curvature(r - 2.0 * a - c) }
248    }
249
250    /// The curvature a body on rollers `w` apart follows at `s`, its mean over [s - w/2, s + w/2], and its rate along s.
251    pub fn mean_curvature(&self, s: f64, w: f64) -> (f64, f64) {
252        if w <= 0.0 {
253            return (self.curvature(s), 0.0);
254        }
255        let (a, b) = (s - 0.5 * w, s + 0.5 * w);
256        ((self.heading(b) - self.heading(a)) / w, (self.curvature(b) - self.curvature(a)) / w)
257    }
258
259    /// The heading of a body on rollers `w` apart at `s`, its mean over [s - w/2, s + w/2]: its rate along s is
260    /// `mean_curvature`'s, the curvature the body follows.
261    pub fn mean_heading(&self, s: f64, w: f64) -> f64 {
262        if w <= 0.0 {
263            return self.heading(s);
264        }
265        // The integral of the heading from 0 to s, unwrapped (each loop adds 2 pi to the heading).
266        let integral = |s: f64| {
267            let (r, turns) = self.wrap(s);
268            let loop_ = self.heading_integral(self.length);
269            turns * loop_ + TAU * self.length * turns * (turns - 1.0) / 2.0 + TAU * turns * r + self.heading_integral(r)
270        };
271        (integral(s + 0.5 * w) - integral(s - 0.5 * w)) / w
272    }
273
274    /// The integral of the heading over the loop from 0 to `r` (0 to L), closed form piece by piece.
275    fn heading_integral(&self, r: f64) -> f64 {
276        let (a, c, rad, lc) = (self.straight, self.curve, self.radius, self.clothoid);
277        // Within a curve, from its start to u.
278        let curve = |u: f64| {
279            let u = u.clamp(0.0, c);
280            if lc == 0.0 {
281                return u * u / (2.0 * rad);
282            }
283            let entry = |u: f64| u.powi(3) / (6.0 * rad * lc);
284            let arc = |u: f64| entry(lc) + lc / (2.0 * rad) * (u - lc) + (u - lc).powi(2) / (2.0 * rad);
285            if u < lc {
286                entry(u)
287            } else if u <= c - lc {
288                arc(u)
289            } else {
290                arc(c - lc) + PI * (u - c + lc) - (lc.powi(3) - (c - u).powi(3)) / (6.0 * rad * lc)
291            }
292        };
293        if r < a {
294            0.0
295        } else if r < a + c {
296            curve(r - a)
297        } else if r < 2.0 * a + c {
298            curve(c) + PI * (r - a - c)
299        } else {
300            curve(c) + PI * a + PI * (r - 2.0 * a - c) + curve(r - 2.0 * a - c)
301        }
302    }
303
304    /// The centre line's point at `s` (m, in the track's plane).
305    pub fn point(&self, s: f64) -> [f64; 2] {
306        let (r, _) = self.wrap(s);
307        let (a, c, d) = (self.straight, self.curve, self.width);
308        let local = |u: f64| {
309            let x = (u / c * CURVE_POINTS as f64).clamp(0.0, CURVE_POINTS as f64);
310            let i = (x.floor() as usize).min(CURVE_POINTS - 1);
311            let (p, q, f) = (self.points[i], self.points[i + 1], x - i as f64);
312            [p[0] + f * (q[0] - p[0]), p[1] + f * (q[1] - p[1])]
313        };
314        if r < a {
315            [r, 0.0]
316        } else if r < a + c {
317            let p = local(r - a);
318            [a + p[0], p[1]]
319        } else if r < 2.0 * a + c {
320            [a - (r - a - c), d]
321        } else {
322            let p = local(r - 2.0 * a - c);
323            [-p[0], d - p[1]]
324        }
325    }
326
327    /// The centre line's direction at `s`, d `point` / ds: a unit vector, along the curve's chord between two of its
328    /// table's points, where `point` runs.
329    pub fn tangent(&self, s: f64) -> [f64; 2] {
330        let (r, _) = self.wrap(s);
331        let (a, c) = (self.straight, self.curve);
332        let local = |u: f64| {
333            let x = (u / c * CURVE_POINTS as f64).clamp(0.0, CURVE_POINTS as f64);
334            let i = (x.floor() as usize).min(CURVE_POINTS - 1);
335            let (p, q, h) = (self.points[i], self.points[i + 1], c / CURVE_POINTS as f64);
336            [(q[0] - p[0]) / h, (q[1] - p[1]) / h]
337        };
338        if r < a {
339            [1.0, 0.0]
340        } else if r < a + c {
341            local(r - a)
342        } else if r < 2.0 * a + c {
343            [-1.0, 0.0]
344        } else {
345            let t = local(r - 2.0 * a - c);
346            [-t[0], -t[1]]
347        }
348    }
349
350    /// Segment `j`'s start and end along the loop.
351    pub fn segment(&self, j: usize) -> (f64, f64) {
352        (self.segments[j], self.segments.get(j + 1).copied().unwrap_or(self.length))
353    }
354    /// Whether segment `j` is a curve (one segment each), else a straight module.
355    pub fn is_curve(&self, j: usize) -> bool {
356        let (start, end) = self.segment(j);
357        (end - start - self.curve).abs() < 1e-12
358            && (start == self.straight || start == 2.0 * self.straight + self.curve)
359    }
360
361    /// The share of a plate of length `plate` centred at `s` that lies over segment `j`.
362    pub fn share(&self, s: f64, plate: f64, j: usize) -> f64 {
363        let (r, _) = self.wrap(s);
364        let (a, b) = (r - 0.5 * plate, r + 0.5 * plate);
365        let (start, end) = self.segment(j);
366        let on: f64 = [-self.length, 0.0, self.length]
367            .iter()
368            .map(|shift| (b.min(end + shift) - a.max(start + shift)).max(0.0))
369            .sum();
370        on / plate
371    }
372}
373
374#[derive(Debug, Clone, Copy, PartialEq)]
375pub enum Kind {
376    Index,
377    Flying,
378}
379
380/// The cycle's cam: every mover's (`Movers::cam_at`), its master and which cycle it is; `pitch` the master's travel
381/// between neighbouring movers ("flying"), 0 where all run the same cam ("index").
382#[derive(Debug, Clone)]
383pub struct Cycle {
384    pub kind: Kind,
385    pub cam: Cam,
386    pub master: CamMaster,
387    pub pitch: f64,
388}
389
390impl Cycle {
391    fn from_config(cfg: &Config, track: &Track, n: usize) -> Result<Self, ConfigError> {
392        let law = |key: &str| {
393            cfg.get(key)?
394                .as_str()
395                .and_then(Law::from_name)
396                .filter(|l| !matches!(l, Law::Dwell | Law::Linear))
397                .ok_or_else(|| ConfigError::Invalid(key.into()))
398        };
399        let ramp_s = cfg.positive("cam.ramp_s")?;
400        let kind = match cfg.get("track.cycle")?.as_str() {
401            Some("index") => Kind::Index,
402            Some("flying") => Kind::Flying,
403            _ => return Err(ConfigError::Invalid("track.cycle".into())),
404        };
405        // Both cycles' keys are read whichever runs, so that a config is checked whole.
406        let (rate, share) = (cfg.positive("track.index_rate_hz")?, cfg.positive("track.index_share")?);
407        let index_law = law("track.index_law")?;
408        let (speed, pitch) = (cfg.positive("track.conveyor_speed_m_s")?, cfg.positive("track.product_pitch_m")?);
409        let process = cfg.positive("track.process_length_m")?;
410        let return_law = law("track.return_law")?;
411        let period = n as f64 * pitch;
412        Ok(match kind {
413            Kind::Index => {
414                if share >= 1.0 {
415                    return Err(ConfigError::Invalid("track.index_share".into()));
416                }
417                let segments = [
418                    Segment { master: 1.0 - share, slave: 0.0, law: Law::Dwell },
419                    Segment { master: share, slave: track.length / n as f64, law: index_law },
420                ];
421                let cam =
422                    Cam::from_segments(&segments).map_err(|_| ConfigError::Invalid("track.index_share".into()))?;
423                Self { kind, cam, master: CamMaster { speed: rate, period: 1.0, ramp_s }, pitch: 0.0 }
424            }
425            Kind::Flying => {
426                if process >= period || process >= track.length {
427                    return Err(ConfigError::Invalid("track.process_length_m".into()));
428                }
429                let segments = [
430                    Segment { master: process, slave: process, law: Law::Linear },
431                    Segment { master: period - process, slave: track.length - process, law: return_law },
432                ];
433                let cam =
434                    Cam::from_segments(&segments).map_err(|_| ConfigError::Invalid("track.process_length_m".into()))?;
435                // One pass is every mover once round: each takes its neighbour's place after a pitch, but the drives' heat and
436                // the verdicts per mover need the whole loop.
437                Self { kind, cam, master: CamMaster { speed, period, ramp_s }, pitch }
438            }
439        })
440    }
441
442    /// Mover `k` from `start` at the master `m`: [s, s', s'', s'''] over the master.
443    pub fn at(&self, k: usize, start: f64, m: f64) -> [f64; 4] {
444        let phase = k as f64 * self.pitch;
445        let mut c = self.cam.at(m + phase);
446        c[0] += start - self.cam.at(phase)[0];
447        c
448    }
449}
450
451/// The ratings the movers' own checks judge (infinite where the config has none).
452#[derive(Debug, Clone, Copy)]
453struct Limits {
454    guide: f64,
455    liftoff: f64,
456    gap: f64,
457    station: f64,
458}
459
460/// The load the `JointMachine` drives: the movers on the track.
461pub struct Movers {
462    pub track: Track,
463    /// A mover's body without its magnet plate (whose mass is the joint's rotor inertia), its payload, the plate.
464    pub body: f64,
465    pub payload: f64,
466    /// The mass centre's distance outside the centre line, m.
467    pub centre_offset: f64,
468    pub plate_mass: f64,
469    attached: bool,
470    pub attraction: f64,
471    pub g: f64,
472    pub wheelbase: f64,
473    /// The body's length along the track (for the gaps) and the magnet plate's (for the segments' shares).
474    pub length: f64,
475    pub plate: f64,
476    pub start: Vec<f64>,
477    pub cycle: Option<Cycle>,
478    /// The cam's master as the controller last asked for it (`cam_at`), f64 bits: where the setpoints stand.
479    master: AtomicU64,
480    limits: Limits,
481}
482
483impl Movers {
484    fn n(&self) -> usize {
485        self.start.len()
486    }
487    /// What a mover's body moves along the track: body and payload (the plate is the joint's rotor).
488    pub fn moving(&self) -> f64 {
489        self.body + if self.attached { self.payload } else { 0.0 }
490    }
491    /// What the rollers hold across the track: the whole mover.
492    pub fn total(&self) -> f64 {
493        self.moving() + self.plate_mass
494    }
495
496    /// Mover `k`'s figures at s, v, a: [lateral acceleration, lateral jerk, guide load, lift-off ratio].
497    pub fn curve_loads(&self, s: f64, v: f64, a: f64) -> [f64; 4] {
498        let (k, dk) = self.track.mean_curvature(s, self.wheelbase);
499        // The mass centre runs on R + e at the speed v (1 + e k): v^2 k (1 + e k) across the track.
500        let (e, m) = (self.centre_offset, self.total());
501        let lateral = v * v * k * (1.0 + e * k);
502        let radial = self.attraction - m * lateral;
503        let jerk = 2.0 * v * a * (k + e * k * k) + v * v * v * dk * (1.0 + 2.0 * e * k);
504        [lateral, jerk, radial.hypot(m * self.g), m * lateral / self.attraction]
505    }
506
507    /// The gap from mover `k` to the one ahead of it, m: along the centre line, less a body's length.
508    pub fn gap(&self, q: &[f64], k: usize) -> f64 {
509        let ahead = if k + 1 < self.n() { q[k + 1] } else { q[0] + self.track.length };
510        ahead - q[k] - self.length
511    }
512
513    /// While the index cam stands mover `k` at a station: how far it is off the nearest station (its start plus whole
514    /// station pitches, so that a pass the controller starts from a station further on counts the same); 0 while it
515    /// moves.
516    fn station_error(&self, q: &[f64], k: usize) -> f64 {
517        match &self.cycle {
518            Some(c) if c.kind == Kind::Index => {
519                let set = c.at(k, self.start[k], f64::from_bits(self.master.load(Ordering::Relaxed)));
520                let (pitch, off) = (c.cam.advance, q[k] - self.start[k]);
521                if set[1] == 0.0 { (off - pitch * (off / pitch).round()).abs() } else { 0.0 }
522            }
523            _ => 0.0,
524        }
525    }
526
527    /// Mover `k`'s point in the scene and the track's heading there.
528    fn place(&self, s: f64) -> ([f64; 3], f64) {
529        let (p, theta) = (self.track.point(s), self.track.heading(s));
530        // Outside the loop: to the right of the direction of travel.
531        let out = 0.035;
532        ([p[0] + out * theta.sin(), p[1] - out * theta.cos(), 0.03], theta)
533    }
534
535    fn all_checks(&self) -> Vec<RatingCheck> {
536        let check = |check, signal: String, motor, limit| RatingCheck { check, signal, motor, limit, life: false };
537        let mut out = Vec::new();
538        let index = self.cycle.as_ref().is_some_and(|c| c.kind == Kind::Index);
539        for k in 0..self.n() {
540            let id = k + 1;
541            out.push(check("mover-guide-load", format!("mover.{id}.guide_load"), Some(k), self.limits.guide));
542            out.push(check("curve-holding", format!("mover.{id}.liftoff_ratio"), Some(k), self.limits.liftoff));
543            if index {
544                out.push(check("station-settling", format!("mover.{id}.station_error"), Some(k), self.limits.station));
545            }
546        }
547        let gap = if self.limits.gap.is_finite() { 1.0 } else { f64::INFINITY };
548        out.push(check("mover-gap", "track.gap_ratio".into(), None, gap));
549        out
550    }
551}
552
553impl Mechanism for Movers {
554    fn linear_motor(&self) -> bool {
555        true
556    }
557    /// The mass centre runs at v (1 + e k(s)) with the centre line's speed v: T = m (1 + e k)^2 v^2 / 2, so the mass is
558    /// m (1 + e k)^2 and the bias (the energy kept, the clothoid's tangential force) m (1 + e k) e k' v^2. The plate's
559    /// inertia stays on the centre line: the plate faces the coils, which lie on it (the drawn mover sits outside it, its
560    /// body and payload with it), so only they move out with e.
561    fn dynamics(&self, q: &[f64], qd: &[f64], mass: &mut [f64], bias: &mut [f64]) {
562        let n = self.n();
563        mass.fill(0.0);
564        bias.fill(0.0);
565        for k in 0..n {
566            let (c, dc) = self.track.mean_curvature(q[k], self.wheelbase);
567            let f = 1.0 + self.centre_offset * c;
568            mass[k * n + k] = self.moving() * f * f;
569            bias[k] = self.moving() * f * self.centre_offset * dc * qd[k] * qd[k];
570        }
571    }
572    fn potential(&self, _q: &[f64]) -> f64 {
573        0.0
574    }
575    /// For effects.base_compliance, in the track's frame (x, y in its plane, z up): each mover's body and payload at
576    /// its mass centre, e outside the centre line square to the body's heading, the mean over its rollers
577    /// (`Track::mean_heading`), which turns at the curvature the dynamics have (`mean_curvature`): it runs at
578    /// v t + e k v along that heading, v (1 + e k) where the two headings agree (a constant radius, a straight). The
579    /// magnet plate on the centre line at the rotor's speed (`rotor_spin`, its mass times that speed), as a linear
580    /// motor's forcer. The track lies level: the weight does no work and the first moment stays at its height.
581    fn frame_momentum(&self, q: &[f64], qd: &[f64], rotor_spin: &[f64]) -> Option<FrameMomentum> {
582        let mut f = FrameMomentum { gravity: [0.0, 0.0, -self.g], ..Default::default() };
583        let (track, e, w) = (&self.track, self.centre_offset, self.wheelbase);
584        for k in 0..self.n() {
585            let (v, [px, py], [tx, ty]) = (qd[k], track.point(q[k]), track.tangent(q[k]));
586            let ((sin, cos), turn) = (track.mean_heading(q[k], w).sin_cos(), track.mean_curvature(q[k], w).0);
587            let at = [px + e * sin, py - e * cos, 0.0];
588            let speed = [v * (tx + e * turn * cos), v * (ty + e * turn * sin), 0.0];
589            sim_components::base::add_point(&mut f, self.moving(), at, speed);
590            let plate = [rotor_spin[k] * tx, rotor_spin[k] * ty];
591            f.linear[0] += plate[0];
592            f.linear[1] += plate[1];
593            f.angular[2] += px * plate[1] - py * plate[0];
594            f.first_moment[0] += self.plate_mass * px;
595            f.first_moment[1] += self.plate_mass * py;
596            f.mass += self.plate_mass;
597        }
598        Some(f)
599    }
600    fn set_payload_attached(&mut self, attached: bool) {
601        self.attached = attached;
602    }
603
604    fn cam(&self) -> Option<CamMaster> {
605        self.cycle.as_ref().map(|c| c.master)
606    }
607    fn cam_at(&self, master: f64, out: &mut [[f64; 4]]) {
608        let Some(cycle) = &self.cycle else { return };
609        self.master.store(master.to_bits(), Ordering::Relaxed);
610        for (k, o) in out.iter_mut().enumerate().take(self.n()) {
611            *o = cycle.at(k, self.start[k], master);
612        }
613    }
614    fn cam_curve(&self) -> Option<sim_core::CamCurve> {
615        let (cycle, start) = (self.cycle.clone()?, self.start.clone());
616        Some(std::sync::Arc::new(move |master, out: &mut [[f64; 4]]| {
617            for (k, o) in out.iter_mut().enumerate().take(start.len()) {
618                *o = cycle.at(k, start[k], master);
619            }
620        }))
621    }
622
623    fn signal_infos(&self) -> Vec<SignalInfo> {
624        let mut out = Vec::new();
625        for k in 0..self.n() {
626            let (id, key) = (k + 1, MOVER_KEYS[k]);
627            for (what, quantity, unit) in [
628                ("track_position", "quantity-track-position", "m"),
629                ("lateral_acceleration", "quantity-lateral-acceleration", "m/s²"),
630                ("lateral_jerk", "quantity-lateral-jerk", "m/s³"),
631                ("guide_load", "quantity-guide-load", "N"),
632                ("liftoff_ratio", "quantity-liftoff-ratio", ""),
633                ("gap_ahead", "quantity-gap-ahead", "m"),
634                ("station_error", "quantity-station-error", "m"),
635            ] {
636                out.push(SignalInfo::new(format!("mover.{id}.{what}"), key, quantity, unit));
637            }
638        }
639        out.push(SignalInfo::new("track.min_gap", "group-track", "quantity-min-gap", "m"));
640        out.push(SignalInfo::new("track.gap_ratio", "group-track", "quantity-gap-ratio", ""));
641        out
642    }
643    fn signals(&self, q: &[f64], qd: &[f64], qdd: &[f64], _force: &[f64], out: &mut Vec<f64>) {
644        let mut least = f64::INFINITY;
645        for k in 0..self.n() {
646            let [lateral, jerk, guide, lift] = self.curve_loads(q[k], qd[k], qdd[k]);
647            let gap = self.gap(q, k);
648            least = least.min(gap);
649            out.extend([self.track.wrap(q[k]).0, lateral, jerk, guide, lift, gap, self.station_error(q, k)]);
650        }
651        let limit = if self.limits.gap.is_finite() { self.limits.gap } else { 0.0 };
652        out.push(least);
653        out.push(if least > 0.0 { (limit / least).min(1e9) } else { 1e9 });
654    }
655    fn rating_checks(&self) -> Vec<RatingCheck> {
656        self.all_checks().into_iter().filter(|c| c.limit.is_finite()).collect()
657    }
658
659    /// A pose that puts a mover on the one ahead of it (closer than a body's length along the loop) cannot be stood in.
660    fn unreachable(&self, tool: &[f64], _slack: f64) -> Option<&'static str> {
661        let n = self.n().min(tool.len());
662        let behind = (0..n).any(|k| self.gap(tool, k) < 0.0);
663        behind.then_some("error-target-out-of-range")
664    }
665
666    fn collision_parts(&self) -> &'static [&'static str] {
667        &[sim_core::scene::MOTOR_PART, "payload"]
668    }
669
670    /// From above: the motor segments along the centre line (`MoverTrack::scene` shades them by their warmth), the
671    /// movers outside it as the motor parts (their coils' warmth shows on them), each with its payload.
672    fn scene(&self, q: &[f64], _rotors: &[f64], _rotor_speeds: &[f64], out: &mut Scene) {
673        let t = &self.track;
674        let at = |s: f64| {
675            let p = t.point(s);
676            [p[0], p[1], 0.0]
677        };
678        for j in 0..t.segments.len() {
679            let (start, end) = t.segment(j);
680            let strips = if t.is_curve(j) { CURVE_STRIPS } else { 1 };
681            let colour = if j % 2 == 0 { [0.3, 0.32, 0.36] } else { [0.4, 0.42, 0.46] };
682            for i in 0..strips {
683                let (a, b) = (
684                    start + (end - start) * i as f64 / strips as f64,
685                    start + (end - start) * (i + 1) as f64 / strips as f64,
686                );
687                out.parts.push(Part::new("segment", Shape::Segment { to: at(b), width: 0.04 }, at(a), colour));
688            }
689        }
690        let colours = [[0.85, 0.45, 0.1], [0.2, 0.5, 0.85], [0.25, 0.7, 0.3], [0.8, 0.25, 0.3], [0.6, 0.35, 0.75]];
691        for (k, &s) in q.iter().enumerate().take(self.n()) {
692            let (p, _) = self.place(s);
693            out.parts.push(Part::new(
694                sim_core::scene::MOTOR_PART,
695                Shape::Box { size: [0.06, 0.06, 0.05] },
696                p,
697                colours[k % colours.len()],
698            ));
699            if self.attached && self.payload > 0.0 {
700                out.parts.push(Part::new(
701                    "payload",
702                    Shape::Box { size: [0.04, 0.04, 0.04] },
703                    [p[0], p[1], p[2] + 0.045],
704                    [0.2, 0.7, 0.3],
705                ));
706            }
707        }
708    }
709    fn scene_point(&self, tool: &[f64]) -> Option<[f64; 3]> {
710        Some(self.place(tool[0]).0)
711    }
712}
713
714/// The machine: the movers' `JointMachine`, with the coils' currents and the segments' warmth around it.
715pub struct MoverTrack {
716    pub inner: JointMachine<Movers>,
717    inner_base: usize,
718    inner_memory: usize,
719    /// The drive as the controller reads it: `current_for` gives the current of a force with the torque constant
720    /// falling towards the maximum current (`effects.torque_saturation`).
721    drive: DriveParams,
722    resistance: f64,
723    thermal_resistance: f64,
724    time_constant: f64,
725    /// The averaging time of the settled rise: one pass of the cycle (1 s without a cam).
726    window: f64,
727    current_limit: f64,
728    rise_limit: f64,
729    /// Per segment: its temperature rise, and the rise its loss of about the last pass settles at, K.
730    pub rises: Vec<f64>,
731    pub settled: Vec<f64>,
732    /// Per segment the loss energy of the last window in `BINS` bins (ring, `cursor` the newest, `fill` s of it written).
733    energy: Vec<f64>,
734    cursor: usize,
735    fill: f64,
736    /// The motor forces of the last `derivatives`: those of the step (`after_step` warms the segments with them).
737    last_force: Mutex<Vec<f64>>,
738}
739
740impl MoverTrack {
741    pub fn new(cfg: &Config) -> Result<Self, ConfigError> {
742        let track = Track::new(
743            cfg.positive("track.straight_m")?,
744            cfg.positive("track.module_m")?,
745            cfg.positive("track.curve_radius_m")?,
746            cfg.non_negative("track.clothoid_m")?,
747        )?;
748        let start = cfg.f64s("start.pose")?;
749        let n = start.len();
750        let length = cfg.positive("mover.length_m")?;
751        if n == 0
752            || n > MAX_MOVERS
753            || start.windows(2).any(|w| w[1] - w[0] < length)
754            || start[n - 1] - start[0] > track.length - length
755        {
756            return Err(ConfigError::Invalid("start.pose".into()));
757        }
758        let mut joint = RotaryJoint::linear_from_config(cfg)?;
759        let motor = LinearMotor::from_config(cfg)?;
760        joint.ripple.cogging_order = motor.cogging_order();
761        if cfg.bool("effects.joint_friction")? {
762            let pressed = cfg.non_negative("linear_motor.guide_friction_coefficient")? * motor.attraction;
763            joint.friction.coulomb += pressed;
764            if joint.friction.presliding > 0.0 {
765                joint.friction.stiction += pressed;
766            }
767        }
768        // A closed track has no ends: no stops (slide.stroke_m is read, not used).
769        joint.range = (-1e12, 1e12);
770        let cycle = Cycle::from_config(cfg, &track, n)?;
771        let rating = |key: &str| cfg.f64(key).unwrap_or(f64::INFINITY);
772        let movers = Movers {
773            body: cfg.positive("mass.mover_kg")?,
774            payload: if cfg.bool("effects.payload")? { cfg.non_negative("mass.payload_kg")? } else { 0.0 },
775            centre_offset: cfg.f64("mass.centre_offset_m")?,
776            plate_mass: joint.rotor_inertia,
777            attached: true,
778            attraction: motor.attraction.max(1e-9),
779            g: if cfg.bool("effects.gravity")? { G } else { 0.0 },
780            wheelbase: cfg.non_negative("mover.wheelbase_m")?,
781            length,
782            plate: cfg.positive("mover.magnet_length_m")?,
783            start,
784            cycle: if cfg.bool("cam.run")? { Some(cycle) } else { None },
785            master: AtomicU64::new(0f64.to_bits()),
786            limits: Limits {
787                guide: rating("ratings.mover_guide_max_load_n"),
788                liftoff: rating("ratings.mover_max_liftoff_ratio"),
789                gap: rating("ratings.min_gap_m"),
790                station: rating("ratings.station_tolerance_m"),
791            },
792            track,
793        };
794        // Each mover's axis its own limits, `axis.s<k>.max_*`, as every machine's axes have theirs. Its range spans its
795        // cycle's targets, BEHIND m behind and AHEAD m ahead of them (a cam runs on beyond it anyway): each mover's range
796        // its own stretch of the loop, so that the middles of the ranges keep the movers in order and apart, and the
797        // middles of the box's faces too (the shipped movers 0.103 m apart there); two poses in it are never a whole loop
798        // apart, the same place on the track. Poses that put movers on each other are `unreachable`. The start pose
799        // widens a range only as far as it lies outside it (a cam's start, a cycle cut short), without the reach: a start
800        // pose on a range's end moves no range, as on every machine.
801        let mut stretch: Vec<Vec<f64>> = cfg
802            .array("cycle.segment")
803            .map(|segments| {
804                let targets = segments.iter().filter_map(|s| s.get("target")?.as_array());
805                targets
806                    .map(|t| t.iter().filter_map(|v| v.as_float()).collect())
807                    .filter(|t: &Vec<f64>| t.len() == n)
808                    .collect()
809            })
810            .unwrap_or_default();
811        if stretch.is_empty() {
812            stretch.push(movers.start.clone());
813        }
814        let reach = |k: usize, pick: fn(f64, f64) -> f64, by: f64| {
815            pick(stretch.iter().map(|t| t[k]).reduce(pick).unwrap_or(0.0) + by, movers.start[k])
816        };
817        let get = |k: usize, what: &str, rate: &str| cfg.positive(&format!("axis.{}.max_{what}_m_{rate}", AXIS_IDS[k]));
818        let axes = (0..n)
819            .map(|k| -> Result<AxisInfo, ConfigError> {
820                Ok(AxisInfo {
821                    id: AXIS_IDS[k],
822                    key: AXIS_KEYS[k],
823                    unit: "m",
824                    min: reach(k, f64::min, -BEHIND),
825                    max: reach(k, f64::max, AHEAD),
826                    max_vel: get(k, "velocity", "s")?,
827                    max_acc: get(k, "acceleration", "s2")?,
828                    max_jerk: get(k, "jerk", "s3")?,
829                })
830            })
831            .collect::<Result<_, _>>()?;
832        let specs = (0..n)
833            .map(|k| JointSpec {
834                drive: joint.clone(),
835                id: MOTOR_IDS[k],
836                key: MOVER_KEYS[k],
837                gear_lever: None,
838                unit: "m",
839            })
840            .collect();
841        let motors = (0..n).map(|k| MotorInfo { id: MOTOR_IDS[k], key: MOTOR_KEYS[k] }).collect();
842        let window = movers.cycle.as_ref().map_or(1.0, |c| c.master.period / c.master.speed);
843        let inner = JointMachine::new(
844            movers,
845            specs,
846            cfg.bool("effects.joint_elasticity")?,
847            ThermalFeedback::from_config(cfg)?,
848            axes,
849            motors,
850        );
851        let segments = inner.mechanism.track.segments.len();
852        let mut m = Self {
853            inner_base: 0,
854            inner_memory: inner.memory().len(),
855            inner,
856            // The base step and velocity cycle only set the filters, which `current_for` does not use.
857            drive: DriveParams::from_config(cfg, 1.0, 1.0)?,
858            resistance: cfg.non_negative("motor.resistance_ohm")?,
859            thermal_resistance: cfg.positive("segment.thermal_resistance_k_w")?,
860            time_constant: cfg.positive("segment.thermal_time_constant_s")?,
861            window,
862            current_limit: rating("ratings.segment_max_current_a"),
863            rise_limit: rating("ratings.segment_max_rise_k"),
864            rises: vec![0.0; segments],
865            settled: vec![0.0; segments],
866            energy: vec![0.0; segments * BINS],
867            cursor: 0,
868            fill: 0.0,
869            last_force: Mutex::new(vec![0.0; n]),
870        };
871        let (mut state, mut torque) = (Vec::new(), vec![0.0; n]);
872        m.inner.equilibrium(&m.inner.mechanism.start.clone(), &mut state, &mut torque);
873        let mut signals = Vec::new();
874        m.inner.base_signals(&state, &torque, &mut signals);
875        m.inner_base = signals.len();
876        Ok(m)
877    }
878
879    pub fn movers(&self) -> &Movers {
880        &self.inner.mechanism
881    }
882
883    /// Per segment its current (A, the movers' currents for their forces, `DriveParams::current_for`, in their plates' shares on it) and its copper loss (W), at the
884    /// movers' positions `q` and motor forces `force`.
885    pub fn segment_load(&self, q: &[f64], force: &[f64]) -> (Vec<f64>, Vec<f64>) {
886        let t = &self.movers().track;
887        let (mut current, mut loss) = (vec![0.0; t.segments.len()], vec![0.0; t.segments.len()]);
888        for (k, f) in force.iter().enumerate() {
889            let i = self.drive.current_for(*f);
890            for j in 0..t.segments.len() {
891                let share = t.share(q[k], self.movers().plate, j);
892                current[j] += share * i.abs();
893                loss[j] += share * self.resistance * i * i;
894            }
895        }
896        (current, loss)
897    }
898
899    fn positions(&self, s: &[f64]) -> Vec<f64> {
900        let n = self.movers().n();
901        let (mut pos, mut vel) = (vec![0.0; n], vec![0.0; n]);
902        self.inner.tool_state(s, &mut pos, &mut vel);
903        pos
904    }
905
906    /// The segments judged by the highest of them (`track.max_segment_current`, `track.max_settled_rise`): one verdict
907    /// each, as a check without a motor is one row of the verdicts.
908    fn own_checks(&self) -> Vec<RatingCheck> {
909        let check =
910            |check, signal: &str, limit| RatingCheck { check, signal: signal.into(), motor: None, limit, life: false };
911        [
912            check("segment-current", "track.max_segment_current", self.current_limit),
913            check("segment-temperature", "track.max_settled_rise", self.rise_limit),
914        ]
915        .into_iter()
916        .filter(|c| c.limit.is_finite())
917        .collect()
918    }
919}
920
921impl Machine for MoverTrack {
922    fn frame_momentum(&self, state: &[f64]) -> Option<FrameMomentum> {
923        self.inner.frame_momentum(state)
924    }
925    fn base_shift(&self, tool_pose: &[f64], pivot: [f64; 3], shift: &[f64; 6], out: &mut [f64]) {
926        self.inner.base_shift(tool_pose, pivot, shift, out)
927    }
928    fn rating_checks(&self) -> Vec<RatingCheck> {
929        let mut out = self.inner.rating_checks();
930        out.extend(self.own_checks());
931        out
932    }
933    fn axes(&self) -> &[AxisInfo] {
934        self.inner.axes()
935    }
936    fn motors(&self) -> &[MotorInfo] {
937        self.inner.motors()
938    }
939    fn motor_linear(&self, motor: usize) -> bool {
940        self.inner.motor_linear(motor)
941    }
942    fn inverse(&self, tool: &[f64], motors: &mut [f64]) {
943        self.inner.inverse(tool, motors)
944    }
945    fn forward(&self, motors: &[f64], tool: &mut [f64]) {
946        self.inner.forward(motors, tool)
947    }
948    fn state_len(&self) -> usize {
949        self.inner.state_len()
950    }
951    fn equilibrium(&self, tool: &[f64], state: &mut Vec<f64>, torque: &mut [f64]) {
952        self.inner.equilibrium(tool, state, torque)
953    }
954    fn derivatives(&self, state: &[f64], torque: &[f64], out: &mut [f64]) {
955        if let Ok(mut last) = self.last_force.lock() {
956            last.copy_from_slice(torque);
957        }
958        self.inner.derivatives(state, torque, out)
959    }
960    fn tool_state(&self, state: &[f64], pos: &mut [f64], vel: &mut [f64]) {
961        self.inner.tool_state(state, pos, vel)
962    }
963    fn set_tool_velocity(&self, state: &mut [f64], vel: &[f64]) {
964        self.inner.set_tool_velocity(state, vel)
965    }
966    fn motor_state(&self, state: &[f64], pos: &mut [f64], vel: &mut [f64]) {
967        self.inner.motor_state(state, pos, vel)
968    }
969    fn feedforward_torque(&self, tool_pos: &[f64], tool_acc: &[f64], out: &mut [f64]) {
970        self.inner.feedforward_torque(tool_pos, tool_acc, out)
971    }
972    fn feedforward_torque_moving(&self, tool_pos: &[f64], tool_vel: &[f64], tool_acc: &[f64], out: &mut [f64]) {
973        self.inner.feedforward_torque_moving(tool_pos, tool_vel, tool_acc, out)
974    }
975    fn rigid_motor_torque(&self, angle: &[f64], speed: &[f64], acc: &[f64], out: &mut [f64]) {
976        self.inner.rigid_motor_torque(angle, speed, acc, out)
977    }
978    fn twist(&self, torque: &[f64], acc: &[f64], out: &mut [f64]) {
979        self.inner.twist(torque, acc, out)
980    }
981    fn rigid_split_torque(&self, angle: &[f64], speed: &[f64], acc: &[f64], rotor_acc: &[f64], out: &mut [f64]) {
982        self.inner.rigid_split_torque(angle, speed, acc, rotor_acc, out)
983    }
984    fn rigid_tensions(&self, tool_pos: &[f64], tool_acc: &[f64], out: &mut Vec<f64>) {
985        self.inner.rigid_tensions(tool_pos, tool_acc, out)
986    }
987    fn rigid_tensions_moving(&self, tool_pos: &[f64], tool_vel: &[f64], tool_acc: &[f64], out: &mut Vec<f64>) {
988        self.inner.rigid_tensions_moving(tool_pos, tool_vel, tool_acc, out)
989    }
990    fn rigid_guide_loads(&self, tool_pos: &[f64], tool_acc: &[f64], out: &mut Vec<[f64; 2]>) {
991        self.inner.rigid_guide_loads(tool_pos, tool_acc, out)
992    }
993    fn steady_friction(&self, tool_pos: &[f64], tool_vel: &[f64], out: &mut [f64]) {
994        self.inner.steady_friction(tool_pos, tool_vel, out)
995    }
996    fn rigid_friction(&self, tool_pos: &[f64], tool_dir: &[f64], out: &mut Vec<[f64; 2]>) {
997        self.inner.rigid_friction(tool_pos, tool_dir, out)
998    }
999    fn rigid_friction_rise(&self, tool_pos: &[f64], tool_dir: &[f64], out: &mut Vec<Vec<[f64; 2]>>) {
1000        self.inner.rigid_friction_rise(tool_pos, tool_dir, out)
1001    }
1002    /// The inner machine's, but NaN for the station error (a mover's error while its cam stands, which no planned pose
1003    /// has), then NaN for each own check (the rigid model tells no segment's warmth).
1004    fn rigid_checks(&self, tool_pos: &[f64], tool_vel: &[f64], tool_acc: &[f64], out: &mut Vec<f64>) {
1005        let start = out.len();
1006        self.inner.rigid_checks(tool_pos, tool_vel, tool_acc, out);
1007        for (check, value) in self.inner.rating_checks().iter().zip(&mut out[start..]) {
1008            if check.check == "station-settling" {
1009                *value = f64::NAN;
1010            }
1011        }
1012        out.extend(self.own_checks().iter().map(|_| f64::NAN));
1013    }
1014    fn energy(&self, state: &[f64]) -> f64 {
1015        self.inner.energy(state)
1016    }
1017    fn set_payload_attached(&mut self, attached: bool) {
1018        self.inner.set_payload_attached(attached)
1019    }
1020    fn links(&self) -> Vec<String> {
1021        self.inner.links()
1022    }
1023    fn set_link_change(&mut self, link: usize, factor: f64, moment: [f64; 3]) {
1024        self.inner.set_link_change(link, factor, moment)
1025    }
1026    fn set_dwelling(&mut self, dwelling: bool) {
1027        self.inner.set_dwelling(dwelling)
1028    }
1029    fn set_tool_force(&mut self, force: &[f64]) -> bool {
1030        self.inner.set_tool_force(force)
1031    }
1032    fn set_brake_engaged(&mut self, engaged: bool) {
1033        self.inner.set_brake_engaged(engaged)
1034    }
1035    fn substeps_wanted(&self, state: &[f64], torque: &[f64], dt: f64, substeps: u32) -> u32 {
1036        self.inner.substeps_wanted(state, torque, dt, substeps)
1037    }
1038    fn valves(&self) -> Vec<(String, f64)> {
1039        self.inner.valves()
1040    }
1041    fn set_valve(&mut self, valve: usize, command: f64) {
1042        self.inner.set_valve(valve, command)
1043    }
1044    fn end_sensors(&self, valve: usize) -> [bool; 2] {
1045        self.inner.end_sensors(valve)
1046    }
1047    /// The inner machine's, then each segment's warmth: the rise moves towards R_th P over the thermal time constant
1048    /// (first order, the loss of the step's forces held over it, exact for a held input, as `sim` warms the parts); the
1049    /// settled rise is R_th times the loss averaged over the last pass (a moving average of the energy in `BINS` bins).
1050    fn after_step(&mut self, state: &mut [f64], dt: f64) {
1051        self.inner.after_step(state, dt);
1052        let force = self.last_force.lock().map(|f| f.clone()).unwrap_or_default();
1053        if force.len() != self.movers().n() {
1054            return;
1055        }
1056        let (_, loss) = self.segment_load(&self.positions(state), &force);
1057        let slow = 1.0 - (-dt / self.time_constant).exp();
1058        // BINS - 1 whole bins make the window; the newest is being filled, so the oldest counts by what is left of it.
1059        let bin = self.window / (BINS - 1) as f64;
1060        for (j, p) in loss.iter().enumerate() {
1061            self.rises[j] += slow * (self.thermal_resistance * p - self.rises[j]);
1062            let ring = &mut self.energy[j * BINS..(j + 1) * BINS];
1063            if dt >= self.window {
1064                // A step longer than the window replaces the whole history.
1065                ring.fill(p * bin);
1066                ring[self.cursor] = 0.0;
1067            }
1068        }
1069        // The window as BINS bins of energy; the newest is partly filled, the average runs over what the ring covers.
1070        let mut left = if dt >= self.window { 0.0 } else { dt };
1071        if dt >= self.window {
1072            self.fill = 0.0;
1073        }
1074        while left > 1e-15 {
1075            let take = left.min(bin - self.fill);
1076            for (j, p) in loss.iter().enumerate() {
1077                self.energy[j * BINS + self.cursor] += p * take;
1078            }
1079            (self.fill, left) = (self.fill + take, left - take);
1080            if self.fill >= bin * (1.0 - 1e-12) {
1081                self.cursor = (self.cursor + 1) % BINS;
1082                self.fill = 0.0;
1083                for j in 0..self.rises.len() {
1084                    self.energy[j * BINS + self.cursor] = 0.0;
1085                }
1086            }
1087        }
1088        let (oldest, gone) = ((self.cursor + 1) % BINS, self.fill / bin);
1089        for j in 0..self.rises.len() {
1090            let ring = &self.energy[j * BINS..(j + 1) * BINS];
1091            let sum: f64 = ring.iter().sum::<f64>() - gone * ring[oldest];
1092            self.settled[j] = self.thermal_resistance * sum / self.window;
1093        }
1094    }
1095    fn memory(&self) -> Vec<f64> {
1096        [
1097            self.inner.memory(),
1098            self.rises.clone(),
1099            self.settled.clone(),
1100            self.energy.clone(),
1101            vec![self.cursor as f64, self.fill],
1102        ]
1103        .concat()
1104    }
1105    fn set_memory(&mut self, memory: &[f64]) {
1106        let (inner, own) = memory.split_at(self.inner_memory.min(memory.len()));
1107        self.inner.set_memory(inner);
1108        let n = self.rises.len();
1109        if own.len() == 2 * n + n * BINS + 2 {
1110            self.rises.copy_from_slice(&own[..n]);
1111            self.settled.copy_from_slice(&own[n..2 * n]);
1112            self.energy.copy_from_slice(&own[2 * n..2 * n + n * BINS]);
1113            (self.cursor, self.fill) = (own[2 * n + n * BINS] as usize % BINS, own[2 * n + n * BINS + 1]);
1114        }
1115    }
1116    fn set_part_temperatures(&mut self, rises: &[f64]) {
1117        self.inner.set_part_temperatures(rises)
1118    }
1119    fn resonance_hz(&self, tool_pose: &[f64]) -> Option<f64> {
1120        self.modes(tool_pose).first().map(|m| m.hz)
1121    }
1122    fn mode_shape(&self, tool_pose: &[f64]) -> Option<(f64, Vec<f64>)> {
1123        self.inner.mode_shape(tool_pose)
1124    }
1125    /// With the motors held, as `Machine::modes` has them and the planner's `trains`: each mover's body and payload on
1126    /// its coupling to the held plate, sqrt(k / m (1 + e k)^2) (694.28 Hz on the shipped mover, its damping c w / 2k).
1127    /// `JointMachine` lists two movers and more so (`held_modes`), one alone as a single joint's two-mass mode with the
1128    /// plate free (1736.39 Hz), which the shaper then followed while the plan's train was the held one.
1129    fn modes(&self, tool_pose: &[f64]) -> Vec<Mode> {
1130        if self.movers().n() > 1 {
1131            return self.inner.modes(tool_pose);
1132        }
1133        // Rigid couplings: none, as for six.
1134        if !self.inner.elastic {
1135            return Vec::new();
1136        }
1137        let (mut mass, mut bias) = ([0.0], [0.0]);
1138        self.movers().dynamics(tool_pose, &[0.0], &mut mass, &mut bias);
1139        let gear = self.inner.joints[0].drive.gearbox.at(tool_pose[0]);
1140        let w = (gear.stiffness / mass[0]).sqrt();
1141        vec![Mode { hz: w / TAU, damping: gear.damping_at(w) * w / (2.0 * gear.stiffness) }]
1142    }
1143    fn trains(&self, tool_pose: &[f64]) -> Vec<Option<sim_core::Train>> {
1144        self.inner.trains(tool_pose)
1145    }
1146    fn belt_wraps(&self, tool_pose: &[f64]) -> Vec<f64> {
1147        self.inner.belt_wraps(tool_pose)
1148    }
1149    fn unreachable(&self, tool_pose: &[f64], slack: f64) -> Option<&'static str> {
1150        self.inner.unreachable(tool_pose, slack)
1151    }
1152    fn refuses_pick(&self, tool_pose: &[f64]) -> Option<&'static str> {
1153        self.inner.refuses_pick(tool_pose)
1154    }
1155    fn condition(&self, tool_pose: &[f64]) -> Option<f64> {
1156        self.inner.condition(tool_pose)
1157    }
1158    fn setpoint_slack(&self) -> f64 {
1159        self.inner.setpoint_slack()
1160    }
1161    fn cam(&self) -> Option<CamMaster> {
1162        self.inner.cam()
1163    }
1164    fn cam_at(&self, master: f64, out: &mut [[f64; 4]]) {
1165        self.inner.cam_at(master, out)
1166    }
1167    fn cam_curve(&self) -> Option<sim_core::CamCurve> {
1168        self.inner.cam_curve()
1169    }
1170    fn gantry_motors(&self) -> Option<[usize; 2]> {
1171        self.inner.gantry_motors()
1172    }
1173    /// The inner machine's base signals, then per segment its current, copper loss, temperature rise and settled rise,
1174    /// the highest current and settled rise of them, then the inner machine's effect signals.
1175    fn signal_infos(&self) -> Vec<SignalInfo> {
1176        let mut infos = self.inner.signal_infos();
1177        let own = (1..=self.rises.len()).flat_map(|id| {
1178            [
1179                ("current", "quantity-segment-current", "A"),
1180                ("copper_loss", "quantity-copper-loss", "W"),
1181                ("temperature_rise", "quantity-segment-rise", "K"),
1182                ("settled_rise", "quantity-segment-settled-rise", "K"),
1183            ]
1184            .map(|(what, quantity, unit)| {
1185                SignalInfo::new(format!("segment.{id}.{what}"), &format!("segment-{id}"), quantity, unit)
1186            })
1187        });
1188        let highest = [
1189            SignalInfo::new("track.max_segment_current", "group-track", "quantity-segment-current", "A"),
1190            SignalInfo::new("track.max_settled_rise", "group-track", "quantity-segment-settled-rise", "K"),
1191        ];
1192        infos.splice(self.inner_base..self.inner_base, own.chain(highest));
1193        infos
1194    }
1195    fn base_signals(&self, state: &[f64], torque: &[f64], out: &mut Vec<f64>) {
1196        self.inner.base_signals(state, torque, out);
1197        let (current, loss) = self.segment_load(&self.positions(state), torque);
1198        for j in 0..self.rises.len() {
1199            out.extend([current[j], loss[j], self.rises[j], self.settled[j]]);
1200        }
1201        out.push(current.iter().fold(0.0, |a: f64, b| a.max(*b)));
1202        out.push(self.settled.iter().fold(0.0, |a: f64, b| a.max(*b)));
1203    }
1204    fn effect_signals(&self, state: &[f64], torque: &[f64], out: &mut Vec<f64>) {
1205        self.inner.effect_signals(state, torque, out)
1206    }
1207    fn loss_powers(&self, state: &[f64], torque: &[f64], out: &mut Vec<f64>) {
1208        self.inner.loss_powers(state, torque, out)
1209    }
1210    /// The movers' scene, each segment shaded by its temperature rise over its rating, and each mover's speed.
1211    fn scene(&self, state: &[f64], out: &mut Scene) {
1212        self.inner.scene(state, out);
1213        let t = &self.movers().track;
1214        let limit = if self.rise_limit.is_finite() { self.rise_limit } else { 60.0 };
1215        let shades: Vec<f32> = (0..t.segments.len())
1216            .flat_map(|j| {
1217                let shade = (self.rises[j] / limit).clamp(-1.0, 1.0) as f32;
1218                std::iter::repeat_n(shade, if t.is_curve(j) { CURVE_STRIPS } else { 1 })
1219            })
1220            .collect();
1221        out.parts.iter_mut().filter(|p| p.id == "segment").zip(shades).for_each(|(p, shade)| p.highlight = shade);
1222        let n = self.movers().n();
1223        let (mut pos, mut vel) = (vec![0.0; n], vec![0.0; n]);
1224        self.inner.tool_state(state, &mut pos, &mut vel);
1225        for k in 0..n {
1226            let (p, _) = self.movers().place(pos[k]);
1227            out.labels.push(Label {
1228                pos: [p[0], p[1], p[2] + 0.1],
1229                owner_key: MOVER_KEYS[k],
1230                value: vel[k],
1231                unit_key: "unit-m-s",
1232                decimals: 2,
1233            });
1234        }
1235    }
1236    fn scene_point(&self, tool_pose: &[f64]) -> Option<[f64; 3]> {
1237        self.inner.scene_point(tool_pose)
1238    }
1239    fn collision_bodies(&self, state: &[f64]) -> Vec<sim_core::Aabb> {
1240        self.inner.collision_bodies(state)
1241    }
1242    fn collision_capsules(&self, state: &[f64]) -> Vec<sim_core::Capsule> {
1243        self.inner.collision_capsules(state)
1244    }
1245    fn self_collision_capsules(&self, state: &[f64]) -> Vec<sim_core::Capsule> {
1246        self.inner.self_collision_capsules(state)
1247    }
1248    fn connected_bodies(&self, state: &[f64], boxes: usize, capsules: usize) -> Option<Vec<(usize, usize)>> {
1249        self.inner.connected_bodies(state, boxes, capsules)
1250    }
1251    fn friction_contacts(&self) -> Vec<FrictionContact> {
1252        self.inner.friction_contacts()
1253    }
1254    fn friction_curve(&self, i: usize, speed: f64, load_scale: f64) -> [f64; 3] {
1255        self.inner.friction_curve(i, speed, load_scale)
1256    }
1257    fn friction_rotary(&self, i: usize) -> bool {
1258        self.inner.friction_rotary(i)
1259    }
1260    fn friction_speed_limit(&self, i: usize, motor_speed: &[f64]) -> Option<f64> {
1261        self.inner.friction_speed_limit(i, motor_speed)
1262    }
1263    fn belt_sections(&self) -> Vec<BeltSection> {
1264        self.inner.belt_sections()
1265    }
1266    fn thermal_parts(&self) -> Vec<ThermalPart> {
1267        self.inner.thermal_parts()
1268    }
1269}
1270
1271#[cfg(test)]
1272mod tests;