Skip to main content

sim_components/
control.rs

1//! Motion controller: plans in tool coordinates, transforms to motor setpoints, and runs one drive
2//! per motor. It works on any machine through the machine interface.
3
4use crate::conveyor::{Conveyor, Pass};
5use crate::drive::{Drive, DriveMode, DriveParams, Motor, WINDING_STATES, quantise, shared_dc_link};
6use crate::fault::{self, Fault, Monitor, Watch};
7use crate::path::{self, Piece};
8use crate::profile::{MotionLaw, Move, Shape};
9use crate::shaper;
10use sim_core::{CamMaster, Config, ConfigError, Machine};
11
12type Result<T> = std::result::Result<T, ConfigError>;
13
14#[derive(Debug, Clone, PartialEq)]
15pub enum Command {
16    /// Point-to-point move of all axes, synchronised.
17    MoveTo(Vec<f64>),
18    /// Run the configured pick-and-place cycle until stopped.
19    StartCycle,
20    /// Finish the current segment, then stay.
21    Stop,
22    /// A position setpoint from outside (the PLC). The controller interpolates towards it over one
23    /// setpoint interval, so slow and jittery updates do not arrive as steps.
24    Setpoint(Vec<f64>),
25    /// A path given as poses at times (seconds from its start, the first at 0 and at the present
26    /// setpoint, the last at rest). The controller runs a smooth curve through them.
27    Trajectory(Vec<(f64, Vec<f64>)>),
28    /// `Trajectory` with the speed and acceleration at every point given (`trace::replay` of a trace that carries the
29    /// tool's setpoints): a quintic through them (Hermite interpolation of position, speed and acceleration), so that at
30    /// the points the setpoints are exactly those given.
31    RatedTrajectory(Vec<(f64, Vec<f64>)>, Vec<Vec<f64>>, Vec<Vec<f64>>),
32    /// Switch the drives off: no torque, and a move or cycle under way is dropped. Machines with holding
33    /// brakes engage them. Until `Enable`, every other command is refused.
34    Disable,
35    /// Switch the drives on again, holding where the motors stand.
36    Enable,
37    /// A stop as a servo drive makes it, by its stop category (`StopCategory`); a move or cycle under way is dropped.
38    /// (`Stop` above ends the cycle after its segment.)
39    Halt(StopCategory),
40}
41
42/// The stop categories of IEC 60204-1 as servo drives make them (SINAMICS: STO / OFF2, OFF3, and a stop that holds).
43#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
44pub enum StopCategory {
45    /// 0: the torque off at once, as `Command::Disable`; the holding brakes engage after `brake.engage_delay_s`.
46    Zero,
47    /// 1: every drive brakes on its OFF3 ramp (`drive.off3_ramp_s`) within its torque and current limits; once all stand,
48    /// the brakes engage with the torque on, and after their engagement delay the torque goes off. When
49    /// `drive.ss1_time_s` runs out first, the torque goes off then (as SS1's timer).
50    One,
51    /// 2: the plan brakes along the direction it moves at the axes' acceleration limits and holds there, torque on.
52    Two,
53}
54
55impl StopCategory {
56    /// 0, 1 or 2.
57    pub fn from_number(n: u8) -> Option<Self> {
58        [Self::Zero, Self::One, Self::Two].get(n as usize).copied()
59    }
60}
61
62/// A category 1 stop under way (`StopCategory::One`): the time left on the SS1 timer, s, and how long all drives have
63/// stood with their brakes engaging, s (`None` while one still moves).
64#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
65struct Halt {
66    left: f64,
67    closing: Option<f64>,
68}
69
70/// A command the controller refuses; `key` is a translation key.
71#[derive(Debug, Clone, PartialEq)]
72pub struct CommandError {
73    pub key: &'static str,
74}
75
76#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
77struct Segment {
78    target: Vec<f64>,
79    dwell_ticks: u64,
80    /// Whether the payload is attached once this segment has arrived.
81    payload: bool,
82    /// With effects.gripper_time: how long the gripper takes to come to `payload` (`Gripper`), ticks; 0 without.
83    #[serde(default)]
84    grip_ticks: u64,
85    /// With `via`: the path to the target, planned where the segment starts (see `via_pieces`): by `path::plan`, or
86    /// with `profile.cycle_timing = "time_optimal"` by `path::plan_time_optimal`.
87    path: Option<Vec<Piece>>,
88    /// With `corners_m`: its via points joined by lines (`lines_through`) whose corners are rounded within this, in
89    /// place of `profile.corner_tolerance_m`.
90    #[serde(default)]
91    corner: Option<f64>,
92    /// The motion law of its move: `profile.shape`, or the segment's own `shape`.
93    law: MotionLaw,
94    /// `valves`: the commands it gives valves (`Machine::valves`, by index) once it has arrived, as the gripper acts.
95    #[serde(default)]
96    valves: Vec<(usize, f64)>,
97    /// `wait`: the end-position sensors ([valve, 0 retracted or 1 extended]) its dwell waits for before it counts.
98    #[serde(default)]
99    wait: Vec<(usize, usize)>,
100}
101
102/// One mode an input shaper cancels: its impulses (`shaper::impulses`, times in half damped periods), half its damped
103/// period in profile cycles as configured (0: none, the shaper of a single impulse), the mode of the machine it
104/// follows with `effects.shaper_follows_pose` (0 the lowest resonance, `Machine::resonance_hz`; k the k-th of
105/// `Machine::modes`) with half the damped period in profile cycles times the frequency, and the axes it acts on.
106#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
107struct ShaperMode {
108    impulses: Vec<(f64, f64)>,
109    half: f64,
110    follows: Option<(usize, f64)>,
111    axes: Vec<bool>,
112}
113
114/// The fastest the delays of a shaper change while its period goes over to the one of a changed machine (a payload
115/// gripped or let go): a tenth of the time passing. Each copy of the plan then runs at 0.9 to 1.1 times the plan's pace.
116const SHAPER_RAMP_RATE: f64 = 0.1;
117
118/// The motion that made the planned setpoints from the profile tick `first` on, its start ticks as it took them (on a
119/// conveyor with its pass and the simulated time at `first`, on a cam with the machine's cam curve then): the input
120/// shaper reads the plan off it between two cycles. `key` tells it from the one before without comparing their curves
121/// (`plan_key`).
122#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
123struct Plan {
124    first: u64,
125    key: [u64; 4],
126    motion: Motion,
127    pass: Option<(Pass, f64)>,
128    #[serde(skip)]
129    cam: KeptCurve,
130    /// Noted after a changed config: the profile tick, between two cycles, from which it holds, the moment of the
131    /// change. Before it the plan noted before holds, also in the cycle that ends with `first`.
132    #[serde(default)]
133    from: Option<f64>,
134}
135
136/// A cam's curve kept with a `Plan` (`Machine::cam_curve`), shared with every copy of the controller. A closure is not
137/// saved with the controller's state: a plan read back from it reads the machine's cam as it is then.
138#[derive(Clone, Default)]
139struct KeptCurve(Option<sim_core::CamCurve>);
140
141impl std::fmt::Debug for KeptCurve {
142    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
143        f.write_str(if self.0.is_some() { "KeptCurve(Some)" } else { "KeptCurve(None)" })
144    }
145}
146
147/// The path of a cycle segment through its via points (`via` in `[[cycle.segment]]`): a line to the first, a smooth
148/// curve (`Piece::Spline`) through the others, and a line from the last to the target. So the path leaves its start and
149/// arrives at its target on straight lines, and rounds the corners in between: with via points straight above the start
150/// and the target, a lift, traverse and lower without a stop. One via point alone is two lines, with a stop between.
151pub fn via_pieces(via: &[Vec<f64>], target: &[f64]) -> Vec<Piece> {
152    let mut pieces: Vec<Piece> = via
153        .iter()
154        .enumerate()
155        .map(|(i, point)| if i == 0 { Piece::Line(point.clone()) } else { Piece::Spline(point.clone()) })
156        .collect();
157    pieces.push(Piece::Line(target.to_vec()));
158    pieces
159}
160
161/// The path of a cycle segment with `corners_m`: lines through its via points to the target, whose corners the planner
162/// rounds within that tolerance (`path::round_corners`): a lift, traverse and lower through the two corners at the
163/// lift's height, passed without a stop.
164pub fn lines_through(via: &[Vec<f64>], target: &[f64]) -> Vec<Piece> {
165    via.iter().chain([&target.to_vec()]).map(|point| Piece::Line(point.clone())).collect()
166}
167
168/// The serde default of `Controller::feed_override` (a snapshot from before the key has none).
169fn no_override() -> f64 {
170    1.0
171}
172
173#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
174enum Motion {
175    Idle,
176    /// `tail` is the previous move still finishing while this one has already started (corner
177    /// blending): its remaining distance is added on top.
178    Moving {
179        mv: Move,
180        start_tick: u64,
181        tail: Option<(Move, u64)>,
182    },
183    Dwell {
184        until_tick: u64,
185    },
186    /// Linear interpolation from `from` to `to` between two ticks.
187    Following {
188        from: Vec<f64>,
189        to: Vec<f64>,
190        start_tick: u64,
191    },
192    /// A pass of the conveyor cycle (`Controller::pass`), waiting for its start and then run.
193    Conveyor,
194    /// The electronic cam of `Machine::cam` (`crate::cam`): the master started from `from` at `start_tick`, its speed
195    /// ramped from `from_speed` to `speed` over `ramp` seconds (`cam::master_change`), and runs down from `stop` seconds
196    /// after that; the slaves are the cam at the master plus `offset`. The next pass begins where the master reaches
197    /// `next_pass`. A config with another master speed or ramp starts a new ramp from where the master is.
198    Cam {
199        start_tick: u64,
200        stop: Option<f64>,
201        from: f64,
202        offset: Vec<f64>,
203        next_pass: f64,
204        from_speed: f64,
205        speed: f64,
206        ramp: f64,
207    },
208    /// A cubic curve through the points with the given speeds at them (Hermite interpolation; with the speeds of
209    /// `c2_speeds`, the cubic spline whose acceleration is continuous).
210    Trajectory {
211        points: Vec<(f64, Vec<f64>)>,
212        speeds: Vec<Vec<f64>>,
213        /// Given (`Command::RatedTrajectory`): the accelerations at the points, and a quintic in place of the cubic.
214        accelerations: Option<Vec<Vec<f64>>>,
215        start_tick: u64,
216    },
217    /// A category 2 stop (`StopCategory::Two`): from `from` at the speeds `vel`, every axis decelerating evenly to rest in
218    /// `time` seconds, so that the tool keeps the direction it moved in.
219    Halting {
220        from: Vec<f64>,
221        vel: Vec<f64>,
222        time: f64,
223        start_tick: u64,
224    },
225}
226
227#[derive(Clone, serde::Serialize, serde::Deserialize)]
228pub struct Controller {
229    params: DriveParams,
230    /// Each motor's drive: `params` with that motor's own values (`catalog::motor_config`).
231    motor_params: Vec<DriveParams>,
232    /// Loop cycles in base steps.
233    n_velocity: u64,
234    n_position: u64,
235    n_profile: u64,
236    profile_cycle: f64,
237    setpoint_ticks: u64,
238    /// How long before the end of a segment the next one may start; 0 with blending off.
239    blend_time: f64,
240    /// For a path timed as fast as the motors allow: the share of the torque limits it may use
241    /// (`profile.torque_reserve`), the belt tensions it may need (`ratings.belt_min_tension_n`, `belt_max_tension_n`, or the machine's
242    /// own `tension_band`, less `profile.tension_margin_n` on both; unbounded where the config has none) and the share of the room to them
243    /// (`profile.tension_reserve`), each gearbox's output torque rating and the guides' load rating (`path::PlanLimits`).
244    plan_limits: path::PlanLimits,
245    /// Each motor's DC link room above the bus, J (`dc_link_room`).
246    #[serde(default)]
247    dc_link_rooms: Vec<Option<f64>>,
248    /// Per motor where the machine's signals hold the friction its own model takes of that motor's torque at the
249    /// machine's state (`motor.<id>.torque_friction`, `TORQUE_PARTS`): what the torque-band monitor expects of friction.
250    #[serde(default)]
251    friction_signals: Vec<Option<usize>>,
252    /// How far a planned path may leave its lines and arcs for transition curves (`path`) and to round a corner between
253    /// two lines (`corner`).
254    path_tolerance: path::Tolerance,
255    /// `profile.feed_override`: the factor on the programmed feed of the moves of a program (`plan_program`); 1 where the
256    /// config has none.
257    #[serde(default = "no_override")]
258    feed_override: f64,
259    /// `profile.cycle_timing = "time_optimal"`: every cycle segment is timed as fast as the motors allow
260    /// (`path::plan_time_optimal`), rest to rest, not by the axis limits.
261    cycle_time_optimal: bool,
262    segments: Vec<Segment>,
263    motion: Motion,
264    /// Index of the cycle segment under way, while the cycle runs.
265    cycle: Option<usize>,
266    /// How often the cycle has started its first segment.
267    passes: u64,
268    stopping: bool,
269    enabled: bool,
270    pub payload_attached: bool,
271    /// The command of each valve of `Machine::valves` (+1 extend, -1 retract, 0 centre), set by the cycle's segments;
272    /// the simulation hands them to the machine every step.
273    #[serde(default)]
274    pub valves: Vec<f64>,
275    /// effects.gripper_time: the tick at which the gripper under way is done, and whether it then holds the payload.
276    #[serde(default)]
277    gripping: Option<(u64, bool)>,
278    /// The ticks of the dwell under way (`dwell_progress`): its segment's `dwell_s`, or the gripper's time if longer.
279    #[serde(default)]
280    dwell_ticks: u64,
281    pub drives: Vec<Drive>,
282    /// Tool-side setpoints and following error.
283    pub set_pos: Vec<f64>,
284    pub set_vel: Vec<f64>,
285    pub set_acc: Vec<f64>,
286    pub tool_error: Vec<f64>,
287    /// Added to the position setpoint only, not to the feedforward: a test signal for the closed
288    /// loop (step response, frequency response).
289    pub setpoint_offset: Vec<f64>,
290    motor_pos: Vec<f64>,
291    motor_vel: Vec<f64>,
292    /// The setpoints as planned. With input shaping, `set_pos` and its rates are these spread over time;
293    /// without, the same.
294    raw_pos: Vec<f64>,
295    raw_vel: Vec<f64>,
296    raw_acc: Vec<f64>,
297    /// Input shaper: the modes it cancels, the first and the second (`profile.shaper_frequency_hz`,
298    /// `shaper2_frequency_hz`; half period 0 without one) and those of `profile.shaper_modes`; on each axis the shapers
299    /// of the modes acting on it are convolved. `None` with input shaping off.
300    shaper: Option<Vec<ShaperMode>>,
301    /// A shaper setting from a changed config, waiting for the plan to stand still: taken under a moving plan it would
302    /// make the setpoint jump.
303    pending_shaper: Option<Option<Vec<ShaperMode>>>,
304    /// How many cycles of `history` the shaper has needed so far.
305    shaper_reach: usize,
306    /// Where the machine itself changed its modes (a payload gripped or let go), the shaper's half periods go over to
307    /// the new ones on a ramp: per change the half periods' step (old less new, cycles, one per mode), the tick it was
308    /// made at and the ramp's length in cycles (`shape`).
309    #[serde(default)]
310    shaper_ramps: Vec<(Vec<f64>, f64, f64)>,
311    /// The half periods the machine reported for the newest stored setpoint, to tell a change of the machine from
312    /// one of the pose.
313    #[serde(default)]
314    shaper_targets: Option<Vec<f64>>,
315    /// The motions that made the stored setpoints (`history`), oldest first.
316    #[serde(default)]
317    plans: std::collections::VecDeque<Plan>,
318    /// A config changed between two profile cycles: the moment, in profile ticks, from which the plan's next motion is
319    /// noted anew (`Plan::from`).
320    #[serde(default)]
321    plan_changed_at: Option<f64>,
322    /// The base step `update` ran last.
323    #[serde(default)]
324    base_step: u64,
325    /// The motion law of moves (`profile.shape`, `deceleration_ratio`, `vertical_axis`, `up_acceleration_ratio`).
326    law: MotionLaw,
327    /// A trajectory's curve: the C2 cubic spline (`profile.trajectory_spline = "c2"`), or the Hermite cubic with the
328    /// slopes of the neighbours ("hermite", as before 14 November 2026).
329    spline_c2: bool,
330    /// Fieldbus: profile cycles between computing the motor setpoints and the drives using them, and the
331    /// setpoints on their way, oldest first, each with the cycles it takes: per motor position, speed,
332    /// acceleration, torque feedforward and friction feedforward from the machine's model (`Drive::friction_ff`).
333    fieldbus_delay: usize,
334    fieldbus: std::collections::VecDeque<(usize, Vec<[f64; 5]>)>,
335    /// Frames pushed so far, and the number of the one the drives hold: a late frame leaves them the old one, whose
336    /// setpoint the drive carries on from (`since_setpoint` runs on).
337    fieldbus_pushed: u64,
338    fieldbus_held: u64,
339    /// Fieldbus jitter: a frame takes up to this many cycles more than the delay, drawn evenly from 0 to it per frame
340    /// from its own pseudo-random stream; 0 with the jitter off.
341    fieldbus_jitter: usize,
342    jitter: sim_core::testkit::Noise,
343    /// The profile cycle under way, counted here: the base step counter would count in another unit once
344    /// `profile.cycle_s` changes.
345    tick: u64,
346    /// Planned setpoints of the last cycles, newest last, as far back as the shaper reaches.
347    history: std::collections::VecDeque<[Vec<f64>; 3]>,
348    /// With `[conveyor]`: the cycle picks from the belt instead of running `segments`, one pass per part, and the pass
349    /// under way or last run.
350    conveyor: Option<Conveyor>,
351    pass: Option<Pass>,
352    /// The simulated time at the profile cycle under way, s.
353    clock: f64,
354    /// Each motor's moment of inertia in the rigid model at the start pose, for the constant-inertia torque
355    /// feedforward (`rigid_inertias`); empty while no drive uses it.
356    inertias: Vec<f64>,
357    /// effects.load_encoder: the step of the load-side scales (`drive.load_encoder_step`, in the tool axes' units, 0
358    /// ideal) on which the position loops close; `None` off, on the motor encoders.
359    load_encoder: Option<f64>,
360    /// `Machine::cam`: the cycle is the machine's electronic cam, and where its master stands (kept between runs).
361    cam: Option<sim_core::CamMaster>,
362    cam_master: f64,
363    /// effects.drive_monitoring: each drive's monitors (`fault::Watch`) trip all drives, which then stop by their
364    /// fault reactions. Per drive its settings and its monitors' running state.
365    monitoring: bool,
366    fault_settings: Vec<fault::Settings>,
367    watch: Vec<Watch>,
368    /// While the drives stop after a trip: per drive the speed setpoint of its stop ramp, `None` once its pulses are
369    /// off. The controller counts as enabled until the last is off, and refuses commands but `Enable` and `Disable`.
370    reacting: Option<Vec<Option<f64>>>,
371    /// The first trip since the drives were last enabled (effects.drive_monitoring).
372    pub fault: Option<Fault>,
373    /// A dual-drive gantry's synchronisation (`gantry.sync`, `Machine::gantry_motors`); `None` for the plain scheme,
374    /// in which each drive follows its own setpoint.
375    gantry_sync: Option<GantrySync>,
376    /// effects.brake_delay: the holding brakes' engagement and release delays, s (`brake.engage_delay_s`,
377    /// `release_delay_s`); both 0 with the effect off. Whether the brakes are engaged now, and how long they have been
378    /// asked to change (`step_brake`).
379    #[serde(default)]
380    brake_delays: [f64; 2],
381    #[serde(default)]
382    brake_on: bool,
383    #[serde(default)]
384    brake_timer: f64,
385    /// The SS1 timer of a category 1 stop, s (`drive.ss1_time_s`; infinite without the key), and such a stop under way.
386    #[serde(default)]
387    ss1_time: f64,
388    #[serde(default)]
389    halt: Option<Halt>,
390}
391
392/// How the two drives of a dual-drive gantry are kept in step, beyond each following the common setpoint.
393#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
394pub struct GantrySync {
395    pub master: usize,
396    pub slave: usize,
397    /// The slave motor's angle per unit of the master's (both drive the same axis).
398    pub ratio: f64,
399    /// `None`: master/slave, the slave's position loop follows the master's actual position (its setpoint less the
400    /// master's following error). `Some(k)`: cross-coupled, the synchronisation error (the slave's actual position
401    /// less the master's, in the slave's units) is fed back to both speed commands with the gain k, 1/s: the slave's
402    /// takes k e, the master's gets k e / ratio.
403    pub cross_gain: Option<f64>,
404}
405
406/// The gantry's synchronisation from `gantry.sync` ("plain", "master_slave" or "cross_coupled") and, cross-coupled,
407/// `gantry.sync_gain_1_s`; read only where the machine has a dual-drive gantry. The ratio of the two motors is that of
408/// their setpoints at the start pose.
409fn gantry_sync(cfg: &Config, machine: &dyn Machine) -> Result<Option<GantrySync>> {
410    let Some([master, slave]) = machine.gantry_motors() else { return Ok(None) };
411    let cross_gain = match text(cfg, "gantry.sync")? {
412        "plain" => return Ok(None),
413        "master_slave" => None,
414        "cross_coupled" => Some(cfg.non_negative("gantry.sync_gain_1_s")?),
415        _ => return Err(ConfigError::Invalid("gantry.sync".into())),
416    };
417    let pose = cfg.f64s("start.pose")?;
418    let (mut a, mut b) = (vec![0.0; machine.motors().len()], vec![0.0; machine.motors().len()]);
419    let h = 1e-4;
420    machine.inverse(&pose.iter().map(|p| p + h).collect::<Vec<_>>(), &mut a);
421    machine.inverse(&pose.iter().map(|p| p - h).collect::<Vec<_>>(), &mut b);
422    let ratio = (a[slave] - b[slave]) / (a[master] - b[master]);
423    if !ratio.is_finite() || ratio == 0.0 {
424        return Err(ConfigError::Invalid("gantry.sync".into()));
425    }
426    Ok(Some(GantrySync { master, slave, ratio, cross_gain }))
427}
428
429/// Each motor's moment of inertia in the rigid, loss-free model at a tool pose: the torque it needs for a unit
430/// acceleration of its own while the others stand, less what it needs at rest (gravity). What a drive's constant-inertia
431/// precontrol is set to (S120 p1498, the load's inertia, plus the motor's).
432pub fn rigid_inertias(machine: &dyn Machine, pose: &[f64]) -> Vec<f64> {
433    let motors = machine.motors().len();
434    let (mut angle, zero) = (vec![0.0; motors], vec![0.0; motors]);
435    let (mut rest, mut moved) = (vec![0.0; motors], vec![0.0; motors]);
436    machine.inverse(pose, &mut angle);
437    machine.rigid_motor_torque(&angle, &zero, &zero, &mut rest);
438    (0..motors)
439        .map(|k| {
440            let unit: Vec<f64> = (0..motors).map(|j| if j == k { 1.0 } else { 0.0 }).collect();
441            machine.rigid_motor_torque(&angle, &zero, &unit, &mut moved);
442            moved[k] - rest[k]
443        })
444        .collect()
445}
446
447/// Per motor the most jerk (motor units per s^3) the axes' jerk limits give it at a tool pose: sum over the axes of
448/// |d motor / d axis| times the axis's limit, the motor's travel per axis by central differences of the inverse
449/// kinematics (over 1e-6 of the axis's range). Linear at the pose: the speed and acceleration terms of a curved
450/// kinematics are left out, as the inertia of `rigid_inertias` is the pose's.
451pub(crate) fn motor_jerks(machine: &dyn Machine, pose: &[f64]) -> Vec<f64> {
452    let (axes, motors) = (machine.axes(), machine.motors().len());
453    let mut jerks = vec![0.0; motors];
454    let (mut ahead, mut behind) = (vec![0.0; motors], vec![0.0; motors]);
455    for (i, axis) in axes.iter().enumerate().take(pose.len()) {
456        let h = 1e-6 * (axis.max - axis.min).abs().max(1e-3);
457        let mut at = pose.to_vec();
458        at[i] = pose[i] + h;
459        machine.inverse(&at, &mut ahead);
460        at[i] = pose[i] - h;
461        machine.inverse(&at, &mut behind);
462        for k in 0..motors {
463            let per = (ahead[k] - behind[k]) / (2.0 * h);
464            if per.is_finite() {
465                jerks[k] += per.abs() * axis.max_jerk;
466            }
467        }
468    }
469    jerks
470}
471
472fn steps(cfg: &Config, path: &str, dt: f64) -> Result<u64> {
473    let n = (cfg.positive(path)? / dt).round();
474    // A loop cycle must be a whole number of base steps.
475    if n >= 1.0 && (n * dt - cfg.f64(path)?).abs() < 1e-6 * dt {
476        Ok(n as u64)
477    } else {
478        Err(ConfigError::Invalid(path.into()))
479    }
480}
481
482impl Controller {
483    /// A controller at rest at the machine's current state.
484    pub fn new(cfg: &Config, machine: &dyn Machine, state: &[f64]) -> Result<Self> {
485        let (axes, motors) = (machine.axes().len(), machine.motors().len());
486        let mut c = Self {
487            params: DriveParams::from_config(cfg, 1.0, 1.0)?,
488            motor_params: Vec::new(),
489            n_velocity: 1,
490            n_position: 1,
491            n_profile: 1,
492            profile_cycle: 1.0,
493            setpoint_ticks: 1,
494            blend_time: 0.0,
495            plan_limits: path::PlanLimits::new(1.0, [f64::NEG_INFINITY, f64::INFINITY, 1.0]),
496            dc_link_rooms: Vec::new(),
497            friction_signals: Vec::new(),
498            path_tolerance: path::Tolerance::default(),
499            feed_override: 1.0,
500            cycle_time_optimal: false,
501            segments: Vec::new(),
502            motion: Motion::Idle,
503            cycle: None,
504            passes: 0,
505            stopping: false,
506            enabled: true,
507            payload_attached: true,
508            valves: machine.valves().into_iter().map(|(_, command)| command).collect(),
509            gripping: None,
510            dwell_ticks: 0,
511            drives: Vec::new(),
512            set_pos: vec![0.0; axes],
513            set_vel: vec![0.0; axes],
514            set_acc: vec![0.0; axes],
515            tool_error: vec![0.0; axes],
516            setpoint_offset: vec![0.0; axes],
517            motor_pos: vec![0.0; motors],
518            motor_vel: vec![0.0; motors],
519            raw_pos: vec![0.0; axes],
520            raw_vel: vec![0.0; axes],
521            raw_acc: vec![0.0; axes],
522            shaper: None,
523            pending_shaper: None,
524            shaper_reach: 0,
525            shaper_ramps: Vec::new(),
526            shaper_targets: None,
527            plans: Default::default(),
528            plan_changed_at: None,
529            base_step: 0,
530            law: MotionLaw::default(),
531            spline_c2: true,
532            fieldbus_delay: 0,
533            fieldbus: Default::default(),
534            fieldbus_pushed: 0,
535            fieldbus_held: u64::MAX,
536            fieldbus_jitter: 0,
537            jitter: Default::default(),
538            tick: 0,
539            conveyor: None,
540            pass: None,
541            clock: 0.0,
542            history: Default::default(),
543            inertias: Vec::new(),
544            load_encoder: None,
545            cam: None,
546            cam_master: 0.0,
547            monitoring: false,
548            fault_settings: Vec::new(),
549            watch: Vec::new(),
550            reacting: None,
551            fault: None,
552            gantry_sync: None,
553            brake_delays: [0.0; 2],
554            brake_on: false,
555            brake_timer: 0.0,
556            ss1_time: f64::INFINITY,
557            halt: None,
558        };
559        c.apply_config(cfg, machine)?;
560        // Nothing moves yet: the shaper is in use from the first cycle on.
561        c.shaper = c.pending_shaper.take().flatten();
562        machine.motor_state(state, &mut c.motor_pos, &mut c.motor_vel);
563        let (mut tool, mut speed) = (vec![0.0; axes], vec![0.0; axes]);
564        machine.tool_state(state, &mut tool, &mut speed);
565        c.hold_here(machine, Some(&tool));
566        Ok(c)
567    }
568
569    /// Setpoints and drives at rest where the motors stand; holding the load at the tool pose `at` where it is known
570    /// (the start), else at the setpoint (`Command::Enable`).
571    fn hold_here(&mut self, machine: &dyn Machine, at: Option<&[f64]>) {
572        let motors = self.motor_pos.len();
573        // The setpoint starts where the motors are. With a stretched belt and a loaded gearbox that
574        // is a few micrometres from the tool pose, and starting there avoids a jolt at the first step.
575        machine.forward(&self.motor_pos, &mut self.set_pos);
576        self.raw_pos.clone_from(&self.set_pos);
577        for rate in [&mut self.set_vel, &mut self.set_acc, &mut self.raw_vel, &mut self.raw_acc] {
578            rate.fill(0.0);
579        }
580        self.history.clear();
581        self.plans.clear();
582        self.fieldbus.clear();
583        self.watch = vec![Watch::default(); motors];
584        // Start holding the load: the torque that keeps the pose, and the feedforward's share of it. At the tool's pose,
585        // not the setpoint's: the setpoint is where the motors' angles put the tool without the gears' twist (4 mm from
586        // it on the palletiser), and the hold there had its gravity, and its ripple and cogging at the rotor angle, of
587        // another pose; a machine built at rest moved 1.2 um in its first 0.2 s while its drives settled.
588        let (mut hold, mut ff) = (vec![0.0; motors], vec![0.0; motors]);
589        machine.equilibrium(at.unwrap_or(&self.set_pos), &mut Vec::new(), &mut hold);
590        self.torque_feedforward(machine, &self.set_pos, &self.set_vel, &self.set_acc, &vec![0.0; motors], &mut ff);
591        // A winding that was warm stays warm, and a DC link keeps its charge. The current that holds the load comes
592        // out of that charge (L i^2 / 2); below the bus level the rectifier makes it up at the next step. Without the DC
593        // link simulated the drive draws it from the supply in its first step (`Drive::enable_energy`).
594        // So does a housing (effects.motor_thermal_nodes), a drive's thermal image (effects.drive_overload) and a braking
595        // resistor's warmth (effects.braking_resistor_heating).
596        let kept: Vec<_> = self
597            .drives
598            .iter()
599            .map(|d| {
600                let heat = (d.temperature_rise, d.housing_rise, d.overload_image, d.overload_chip, d.overloaded);
601                (heat, d.resistor_rise, d.dc_voltage)
602            })
603            .collect();
604        // A stepper's electrical grid stays where it was across an enable (`Stepper::re_enabled`).
605        let origins: Vec<f64> = self.drives.iter().map(|d| d.phases.origin).collect();
606        self.drives =
607            (0..motors).map(|k| Drive::at_rest(&self.motor_params[k], self.motor_pos[k], hold[k], ff[k])).collect();
608        for (k, origin) in origins.into_iter().enumerate().take(motors) {
609            if let Motor::Stepper(s) = &self.motor_params[k].motor {
610                s.re_enabled(&mut self.drives[k], &self.motor_params[k], self.motor_pos[k], origin);
611            }
612        }
613        let held = self.holding_torque(machine, at.unwrap_or(&self.set_pos));
614        for (k, (drive, (heat, resistor_rise, voltage))) in self.drives.iter_mut().zip(kept).enumerate() {
615            let p = &self.motor_params[k];
616            drive.torque_hold = held[k];
617            (drive.temperature_rise, drive.housing_rise, drive.overload_image, drive.overload_chip, drive.overloaded) =
618                heat;
619            drive.resistor_rise = resistor_rise;
620            drive.hold_current(p);
621            let stored = 0.5 * p.inductance * drive.current * drive.current;
622            if p.dc_link {
623                drive.dc_voltage = (voltage * voltage - 2.0 * stored / p.dc_capacitance).max(0.0).sqrt();
624            } else {
625                drive.enable_energy = stored;
626            }
627        }
628        // Every drive has noise of its own; the multiplier spreads neighbouring seeds over the generator's cycle.
629        for (k, drive) in self.drives.iter_mut().enumerate() {
630            drive.noise.0 = self.params.noise_seed.wrapping_add(k as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
631        }
632        // The fieldbus jitter's stream, beside the drives' (no machine has a million motors).
633        self.jitter.0 = self.params.noise_seed.wrapping_add(1 << 20).wrapping_mul(0x9E37_79B9_7F4A_7C15);
634    }
635
636    /// Re-reads gains, switches, cycle times and the cycle; keeps the loops' running state.
637    /// A config with a refused value changes nothing.
638    pub fn apply_config(&mut self, cfg: &Config, machine: &dyn Machine) -> Result<()> {
639        let dt = cfg.positive("sim.dt_s")?;
640        if steps(cfg, "drive.current_cycle_s", dt)? != 1 {
641            // The current loop is the base step.
642            return Err(ConfigError::Invalid("drive.current_cycle_s".into()));
643        }
644        let n_velocity = steps(cfg, "drive.velocity_cycle_s", dt)?;
645        let n_position = steps(cfg, "drive.position_cycle_s", dt)?;
646        let n_profile = steps(cfg, "profile.cycle_s", dt)?;
647        let profile_cycle = n_profile as f64 * dt;
648        let setpoint_ticks = steps(cfg, "profile.setpoint_interval_s", profile_cycle)?;
649        let params = DriveParams::from_config(cfg, dt, n_velocity as f64 * dt)?;
650        let mut motor_params = machine
651            .motors()
652            .iter()
653            .map(|m| DriveParams::from_config(&crate::catalog::motor_config(cfg, m.id)?, dt, n_velocity as f64 * dt))
654            .collect::<Result<Vec<_>>>()?;
655        // The DC links are the machine's (`catalog::motor_config`): a drive named per motor (an S210 switches the shared
656        // link off, an S120 on) leaves them as the shared config has them, else its own link is stepped as well.
657        for p in &mut motor_params {
658            p.shared_dc_link = params.shared_dc_link;
659        }
660        let fault_settings = machine
661            .motors()
662            .iter()
663            .zip(&motor_params)
664            .map(|(m, p)| fault::Settings::from_config(&crate::catalog::motor_config(cfg, m.id)?, p))
665            .collect::<Result<Vec<_>>>()?;
666        // A config written before 14 November 2026 has no drive monitoring.
667        let monitoring = cfg.get("effects.drive_monitoring").is_ok() && cfg.bool("effects.drive_monitoring")?;
668        // A config written before 15 November 2026 has neither brake delays nor an SS1 timer.
669        let brake_delays = if cfg.get("effects.brake_delay").is_ok() && cfg.bool("effects.brake_delay")? {
670            [cfg.non_negative("brake.engage_delay_s")?, cfg.non_negative("brake.release_delay_s")?]
671        } else {
672            [0.0; 2]
673        };
674        let ss1_time =
675            if cfg.get("drive.ss1_time_s").is_ok() { cfg.positive("drive.ss1_time_s")? } else { f64::INFINITY };
676        let inertias = if motor_params.iter().any(|p| p.precontrol.constant_inertia) {
677            rigid_inertias(machine, &cfg.f64s("start.pose")?)
678        } else {
679            Vec::new()
680        };
681        let load_encoder = if cfg.get("effects.load_encoder").is_ok() && cfg.bool("effects.load_encoder")? {
682            Some(cfg.non_negative("drive.load_encoder_step")?)
683        } else {
684            None
685        };
686        let shaper = shaper_modes(cfg, machine, profile_cycle)?;
687        let law = motion_law(cfg, machine)?;
688        let sync = gantry_sync(cfg, machine)?;
689        let spline_c2 = match text(cfg, "profile.trajectory_spline")? {
690            "c2" => true,
691            "hermite" => false,
692            _ => return Err(ConfigError::Invalid("profile.trajectory_spline".into())),
693        };
694        let fieldbus_delay = cfg.f64("profile.fieldbus_delay_cycles")?;
695        if fieldbus_delay < 0.0 || fieldbus_delay.fract() != 0.0 || fieldbus_delay > 1000.0 {
696            return Err(ConfigError::Invalid("profile.fieldbus_delay_cycles".into()));
697        }
698        let fieldbus_delay = if cfg.bool("effects.fieldbus_delay")? { fieldbus_delay as usize } else { 0 };
699        let fieldbus_jitter = cfg.f64("profile.fieldbus_jitter_cycles")?;
700        if fieldbus_jitter < 0.0 || fieldbus_jitter.fract() != 0.0 || fieldbus_jitter > 1000.0 {
701            return Err(ConfigError::Invalid("profile.fieldbus_jitter_cycles".into()));
702        }
703        let fieldbus_jitter = if cfg.bool("effects.fieldbus_jitter")? { fieldbus_jitter as usize } else { 0 };
704        let blend_time = cfg.non_negative("profile.blend_time_s")?;
705        let blend_time = if cfg.bool("effects.corner_blending")? { blend_time } else { 0.0 };
706        let torque_reserve = cfg.positive("profile.torque_reserve")?;
707        if torque_reserve > 1.0 {
708            return Err(ConfigError::Invalid("profile.torque_reserve".into()));
709        }
710        let path_tolerance = path::Tolerance {
711            path: cfg.non_negative("profile.path_tolerance_m")?,
712            corner: cfg.non_negative("profile.corner_tolerance_m")?,
713        };
714        // 1 where a config leaves it out (no shipped one has it); 2 is this simulator's limit (Sinumerik and LinuxCNC's
715        // override switches go to 200 %), not a vendor figure.
716        let feed_override =
717            if cfg.get("profile.feed_override").is_ok() { cfg.f64("profile.feed_override")? } else { 1.0 };
718        if !(feed_override > 0.0 && feed_override <= 2.0) {
719            return Err(ConfigError::Invalid("profile.feed_override".into()));
720        }
721        let cycle_time_optimal = match cfg.get("profile.cycle_timing")?.as_str() {
722            Some("axis_limits") => false,
723            Some("time_optimal") => true,
724            _ => return Err(ConfigError::Invalid("profile.cycle_timing".into())),
725        };
726        let tension_reserve = cfg.positive("profile.tension_reserve")?;
727        if tension_reserve > 1.0 {
728            return Err(ConfigError::Invalid("profile.tension_reserve".into()));
729        }
730        let tension_margin = cfg.non_negative("profile.tension_margin_n")?;
731        // The ratings the time-optimal plan keeps beside the motors': each gearbox's output torque where the machine
732        // reports it, and the guides' load where it reports theirs (the verdicts judge the same signals); and what each
733        // gearbox loses, which its motor gives on top.
734        let reported = machine.signal_infos();
735        let reports = |id: &str| reported.iter().any(|s| s.id == id);
736        let gearbox = machine
737            .motors()
738            .iter()
739            .map(|m| -> Result<Option<[f64; 4]>> {
740                if !reports(&format!("gearbox.{}.output_torque", m.id)) {
741                    return Ok(None);
742                }
743                let own = crate::catalog::motor_config(cfg, m.id)?;
744                let rated = ["gearbox_max_torque_nm", "pulley_max_torque_nm"]
745                    .iter()
746                    .filter_map(|key| own.f64(&format!("ratings.{key}")).ok())
747                    .fold(f64::INFINITY, f64::min);
748                let inertia = own.f64("motor.rotor_inertia_kgm2").unwrap_or(0.0)
749                    + own.f64("gearbox.inertia_at_input_kgm2").unwrap_or(0.0);
750                let efficiency = match own.get("gearbox.efficiency") {
751                    Ok(_) => crate::mech::Gearbox::configured_efficiency(&own)?,
752                    Err(_) => 1.0,
753                };
754                Ok((rated.is_finite() || efficiency < 1.0).then_some([
755                    own.f64("gearbox.ratio").unwrap_or(1.0),
756                    inertia,
757                    rated,
758                    efficiency,
759                ]))
760            })
761            .collect::<Result<Vec<_>>>()?;
762        let guides = reported.iter().any(|s| s.id.ends_with(".guide_load"));
763        let guide = if guides { cfg.f64("ratings.guide_max_load_n").unwrap_or(f64::INFINITY) } else { f64::INFINITY };
764        let mut segments = Vec::new();
765        let gripper = crate::gripper::Gripper::from_config(cfg)?;
766        for (i, segment) in cfg.array("cycle.segment")?.iter().enumerate() {
767            let bad = || ConfigError::Invalid(format!("cycle.segment[{i}]"));
768            let number = |v: &toml::Value| v.as_float().or_else(|| v.as_integer().map(|i| i as f64));
769            let target: Vec<f64> =
770                segment.get("target").and_then(|t| t.as_array()).ok_or_else(bad)?.iter().filter_map(number).collect();
771            if !in_range(machine, &target) {
772                return Err(range_error(machine, &target, format!("cycle.segment[{i}]")));
773            }
774            let corner = match segment.get("corners_m") {
775                None => None,
776                Some(c) => Some(
777                    number(c)
778                        .filter(|c| c.is_finite() && *c >= 0.0)
779                        .ok_or_else(|| ConfigError::Invalid(format!("cycle.segment[{i}].corners_m")))?,
780                ),
781            };
782            let via = match segment.get("via") {
783                None => None,
784                Some(points) => {
785                    let bad = || ConfigError::Invalid(format!("cycle.segment[{i}].via"));
786                    let points: Vec<Vec<f64>> = points
787                        .as_array()
788                        .ok_or_else(bad)?
789                        .iter()
790                        .map(|p| Some(p.as_array()?.iter().filter_map(number).collect()))
791                        .collect::<Option<_>>()
792                        .ok_or_else(bad)?;
793                    if points.is_empty() {
794                        return Err(bad());
795                    }
796                    if let Some(p) = points.iter().find(|p| !in_range(machine, p)) {
797                        return Err(range_error(machine, p, format!("cycle.segment[{i}].via")));
798                    }
799                    Some(if corner.is_some() { lines_through(&points, &target) } else { via_pieces(&points, &target) })
800                }
801            };
802            let shape = match segment.get("shape") {
803                None => law.shape,
804                Some(name) => name
805                    .as_str()
806                    .and_then(Shape::from_name)
807                    .ok_or_else(|| ConfigError::Invalid(format!("cycle.segment[{i}].shape")))?,
808            };
809            // Valves by the id `Machine::valves` gives them: `valves = { z = "extend" }`, `wait = ["z.extended"]`.
810            let ids: Vec<String> = machine.valves().into_iter().map(|(id, _)| id).collect();
811            let valve = |id: &str| ids.iter().position(|v| v == id);
812            let mut valves = Vec::new();
813            if let Some(table) = segment.get("valves") {
814                let bad = || ConfigError::Invalid(format!("cycle.segment[{i}].valves"));
815                for (id, command) in table.as_table().ok_or_else(bad)? {
816                    let command = match command.as_str() {
817                        Some("extend") => 1.0,
818                        Some("retract") => -1.0,
819                        Some("centre") => 0.0,
820                        _ => return Err(bad()),
821                    };
822                    valves.push((valve(id).ok_or_else(bad)?, command));
823                }
824            }
825            let mut wait = Vec::new();
826            if let Some(list) = segment.get("wait") {
827                let bad = || ConfigError::Invalid(format!("cycle.segment[{i}].wait"));
828                for sensor in list.as_array().ok_or_else(bad)? {
829                    let (id, end) = sensor.as_str().and_then(|s| s.rsplit_once('.')).ok_or_else(bad)?;
830                    let end = ["retracted", "extended"].iter().position(|e| *e == end).ok_or_else(bad)?;
831                    wait.push((valve(id).ok_or_else(bad)?, end));
832                }
833            }
834            let payload = segment.get("payload").and_then(|p| p.as_bool()).ok_or_else(bad)?;
835            // Whole profile cycles, at least the gripper's time.
836            let grip_ticks = gripper
837                .map_or(0.0, |g| ((if payload { g.close_s } else { g.open_s }) / profile_cycle - 1e-9).ceil())
838                as u64;
839            segments.push(Segment {
840                valves,
841                wait,
842                target,
843                grip_ticks,
844                dwell_ticks: (segment
845                    .get("dwell_s")
846                    .and_then(number)
847                    .filter(|d| d.is_finite() && *d >= 0.0)
848                    .ok_or_else(bad)?
849                    / profile_cycle)
850                    .round() as u64,
851                payload,
852                path: via,
853                corner,
854                law: MotionLaw { shape, ..law.clone() },
855            });
856        }
857        // A pick (a segment that attaches the payload after one that left it off, the cycle running round) the machine
858        // refuses for its own reason, with the segment.
859        for (i, segment) in segments.iter().enumerate() {
860            let before = &segments[(i + segments.len() - 1) % segments.len()];
861            if let Some(why) =
862                (segment.payload && !before.payload).then(|| machine.refuses_pick(&segment.target)).flatten()
863            {
864                return Err(ConfigError::Part(why, format!("cycle.segment[{i}]")));
865            }
866        }
867        // The margin comes off both ratings before the share is taken: it is for what the rigid model leaves out
868        // whatever the room (friction, the belt's vibration), which is roughly absolute, not a share of the room.
869        // A machine with a band of its own (cables between winches and a platform) gives it; the ratings otherwise.
870        let band = machine.tension_band().map_or_else(
871            || [cfg.f64("ratings.belt_min_tension_n").ok(), cfg.f64("ratings.belt_max_tension_n").ok()],
872            |[low, high]| [Some(low), Some(high)],
873        );
874        let tension = [
875            band[0].map_or(f64::NEG_INFINITY, |t| t + tension_margin),
876            band[1].map_or(f64::INFINITY, |t| t - tension_margin),
877            tension_reserve,
878        ];
879        // Each motor's shaft friction and gearbox drag as its own config has them (`mech::ShaftFriction`); none where the
880        // config lacks their keys (an arm's joints, whose friction is the joint's).
881        let friction = machine
882            .motors()
883            .iter()
884            .map(|m| -> Result<[f64; 5]> {
885                let own = crate::catalog::motor_config(cfg, m.id)?;
886                Ok(crate::mech::ShaftFriction::from_config(&own)
887                    .map_or([0.0; 5], |f| [f.coulomb, f.viscous, f.smoothing, f.drag.torque, f.drag.speed]))
888            })
889            .collect::<Result<Vec<_>>>()?;
890        // 1 where a config (an older machine file) leaves it out.
891        let margin = if cfg.get("profile.time_optimal_margin").is_ok() {
892            cfg.positive("profile.time_optimal_margin")?
893        } else {
894            1.0
895        };
896        if margin > 1.0 {
897            return Err(ConfigError::Invalid("profile.time_optimal_margin".into()));
898        }
899        // Each motor's drive current, gearbox input speed and braking power as the verdicts judge them
900        // (`path::PlanLimits::ratings`); a line-up's one Braking Module shared out evenly over its motors.
901        let line_up = cfg.get("drive.braking_module").is_ok() && cfg.bool("drive.braking_module")?;
902        let ratings = machine
903            .motors()
904            .iter()
905            .map(|m| -> Result<[f64; 3]> {
906                let own = crate::catalog::motor_config(cfg, m.id)?;
907                let rating = |key: &str| own.f64(&format!("ratings.{key}")).unwrap_or(f64::INFINITY);
908                let dc_link = own.get("ratings.dc_link_capacitance_uf").is_ok();
909                let braking = if dc_link { rating("braking_resistor_peak_w") } else { f64::INFINITY };
910                let share = if line_up { machine.motors().len() as f64 } else { 1.0 };
911                Ok([
912                    rating("drive_max_current_a"),
913                    rating("gearbox_max_input_speed_rpm") * std::f64::consts::PI / 30.0,
914                    braking / share,
915                ])
916            })
917            .collect::<Result<Vec<_>>>()?;
918        // Each motor's DC link room above the bus, J, as the verdicts take it ("dc-link-energy"), for the tally's running
919        // account (`analysis::LinkAccount`); None without the capacitance or the threshold.
920        let dc_link_rooms = machine
921            .motors()
922            .iter()
923            .map(|m| -> Result<Option<f64>> {
924                let own = crate::catalog::motor_config(cfg, m.id)?;
925                let rating = |key: &str| own.f64(&format!("ratings.{key}")).ok();
926                let bus = own.f64("drive.bus_voltage_v")?;
927                Ok(rating("dc_link_capacitance_uf")
928                    .zip(rating("braking_threshold_v"))
929                    .map(|(capacitance, threshold)| 0.5 * capacitance * 1e-6 * (threshold * threshold - bus * bus)))
930            })
931            .collect::<Result<Vec<_>>>()?;
932        // The share of each speed rating the plan keeps back for the velocity loops (`path::speed_kept_of`): the most over
933        // the motors, each at the inertia its precontrol is tuned for (the rigid model's at the start pose), the most
934        // acceleration its torque reserve gives it and the top speed it is held to. Not less than the fixed share. On
935        // top, where the motor's drive train is elastic (`Machine::trains`), the speed its twist adds at the most jerk
936        // the axes' limits give the motor there, or at a step of that acceleration where the jerk limit is quicker than the
937        // train's swing (`path::train_speed`, `motor_jerks`).
938        // That is `PlanLimits::speed_kept`, at the start pose; the time-optimal plan keeps back each place's own
939        // (`PlanLimits::kept_at`: the train, the inertia and the jerk there).
940        let start_pose = cfg.f64s("start.pose")?;
941        let trains = machine.trains(&start_pose);
942        let jerks = motor_jerks(machine, &start_pose);
943        let speed_kept = rigid_inertias(machine, &start_pose)
944            .iter()
945            .zip(&motor_params)
946            .enumerate()
947            .filter(|(_, (inertia, _))| **inertia > 0.0)
948            .map(|(k, (&inertia, p))| {
949                let acc = torque_reserve * p.peak_torque / inertia;
950                let train = trains.get(k).copied().flatten().map_or(0.0, |t| path::train_speed(t, jerks[k], acc));
951                path::speed_kept_of(p.ki, inertia, p.torque_ff, acc, p.max_speed, train)
952            })
953            .fold(path::PlanLimits::new(1.0, [0.0; 3]).speed_kept, f64::max);
954        // What `PlanLimits::kept_at` takes of each motor at any other pose than the start's: the same figures per motor.
955        let loops: Vec<path::LoopKeep> = motor_params
956            .iter()
957            .map(|p| path::LoopKeep {
958                ki: p.ki,
959                torque_ff: p.torque_ff,
960                peak_torque: p.peak_torque,
961                max_speed: p.max_speed,
962            })
963            .collect();
964        let plan_limits = path::PlanLimits {
965            reserve: torque_reserve,
966            tension,
967            gearbox,
968            guide,
969            friction,
970            ratings,
971            margin,
972            hermite: !spline_c2,
973            speed_kept,
974            loops,
975        };
976        // A path through via points has to be one the planner times, from where the segment before ends; timed as fast as
977        // the motors allow, so has the straight way of every other segment.
978        for (i, segment) in segments.iter().enumerate() {
979            let from = &segments[(i + segments.len() - 1) % segments.len()].target;
980            let (straight, key) = (vec![Piece::Line(segment.target.clone())], format!("cycle.segment[{i}].via"));
981            let (pieces, key) = match &segment.path {
982                Some(pieces) => (pieces, key),
983                None if cycle_time_optimal && !at_target(from, &segment.target) => {
984                    (&straight, "profile.cycle_timing".to_string())
985                }
986                None => continue,
987            };
988            let tolerance =
989                path::Tolerance { corner: segment.corner.unwrap_or(path_tolerance.corner), ..path_tolerance };
990            let planned = if cycle_time_optimal {
991                path::plan_time_optimal(
992                    machine,
993                    &motor_params.iter().collect::<Vec<_>>(),
994                    &plan_limits,
995                    from,
996                    pieces,
997                    profile_cycle,
998                    tolerance,
999                    path::ARC_SLACK,
1000                )
1001            } else {
1002                path::plan(machine.axes(), from, pieces, profile_cycle, tolerance, path::ARC_SLACK)
1003            };
1004            if planned.map_or(true, |points| !points.iter().all(|(_, pose)| near_start(machine, from, pose))) {
1005                return Err(ConfigError::Invalid(key));
1006            }
1007        }
1008        // The belt goes on where it was: the parts picked and missed so far stay so.
1009        let mut conveyor = Conveyor::from_config(cfg, machine.axes().len())?;
1010        // Nothing fails from here on: a refused config leaves the controller as it was.
1011        if profile_cycle != self.profile_cycle {
1012            self.rescale_ticks(self.profile_cycle / profile_cycle);
1013        }
1014        if let (Some(new), Some(old)) = (&mut conveyor, &self.conveyor) {
1015            new.carry_on(old);
1016        }
1017        // A cycle under way goes on with a segment the new cycle has: the move in progress finishes where it
1018        // was going, and the next one starts from there. A cycle that lost all its segments ends; a conveyor cycle
1019        // goes on with the new conveyor's next pass.
1020        self.cycle = if conveyor.is_some() {
1021            self.cycle.map(|_| 0)
1022        } else {
1023            self.cycle.and_then(|i| Some(i.min(segments.len().checked_sub(1)?)))
1024        };
1025        if conveyor.is_none() && matches!(self.motion, Motion::Conveyor) {
1026            self.motion = Motion::Idle;
1027        }
1028        self.conveyor = conveyor;
1029        // A cam under way with another master speed or ramp: a ramp from the master's speed now to the new one, from
1030        // where it stands (a run-down under way goes on as it was).
1031        if let (Some(new), Motion::Cam { start_tick, stop: None, from, from_speed, speed, ramp, .. }) =
1032            (machine.cam(), &mut self.motion)
1033            && (new.speed != *speed || new.ramp_s != *ramp)
1034            && *start_tick != u64::MAX
1035        {
1036            let t = self.tick.saturating_sub(*start_tick) as f64 * self.profile_cycle;
1037            let now = crate::cam::master_change(*from_speed, *speed, *ramp, t, None);
1038            (*start_tick, *from, *from_speed) = (self.tick, *from + now[0], now[1]);
1039            (*speed, *ramp) = (new.speed, new.ramp_s);
1040        }
1041        self.cam = machine.cam();
1042        // The plan of the next cycle is noted anew with the new machine, as from the next base step: a cam's curve may
1043        // have changed under the same motion. (The profile cycle under way began at the base step of `clock`; in new
1044        // profile ticks with a changed cycle.) A controller being built has no plan yet.
1045        if !self.plans.is_empty() {
1046            let (old_steps, cycle_ratio) = (self.n_profile as f64, self.profile_cycle / profile_cycle);
1047            let tick_step = (self.clock * old_steps / self.profile_cycle).round();
1048            let into = ((self.base_step + 1) as f64 - tick_step).max(0.0);
1049            self.plan_changed_at = Some(self.tick as f64 + into / old_steps * cycle_ratio);
1050        }
1051        // The valves keep their commands; a machine with other valves starts them as it says.
1052        let valves = machine.valves();
1053        if valves.len() != self.valves.len() {
1054            self.valves = valves.into_iter().map(|(_, command)| command).collect();
1055        }
1056        self.gantry_sync = sync;
1057        (self.n_velocity, self.n_position, self.n_profile) = (n_velocity, n_position, n_profile);
1058        (self.profile_cycle, self.setpoint_ticks, self.params, self.segments) =
1059            (profile_cycle, setpoint_ticks, params, segments);
1060        self.motor_params = motor_params;
1061        (self.fault_settings, self.monitoring) = (fault_settings, monitoring);
1062        (self.brake_delays, self.ss1_time) = (brake_delays, ss1_time);
1063        self.watch.resize(self.motor_params.len(), Watch::default());
1064        (self.inertias, self.load_encoder) = (inertias, load_encoder);
1065        self.blend_time = blend_time;
1066        (self.path_tolerance, self.cycle_time_optimal, self.plan_limits) =
1067            (path_tolerance, cycle_time_optimal, plan_limits);
1068        self.feed_override = feed_override;
1069        self.dc_link_rooms = dc_link_rooms;
1070        self.friction_signals = machine
1071            .motors()
1072            .iter()
1073            .map(|m| reported.iter().position(|s| s.id == format!("motor.{}.torque_friction", m.id)))
1074            .collect();
1075        (self.law, self.spline_c2) = (law, spline_c2);
1076        (self.pending_shaper, self.fieldbus_delay, self.fieldbus_jitter) =
1077            (Some(shaper), fieldbus_delay, fieldbus_jitter);
1078        Ok(())
1079    }
1080
1081    /// A new profile cycle, `ratio` of them to an old one: every stored tick keeps its distance in time from
1082    /// now, to the nearest new cycle, and the shaper's past is read off at the new spacing. Without this a
1083    /// motion under way would jump to another point of its plan.
1084    fn rescale_ticks(&mut self, ratio: f64) {
1085        let now = self.tick;
1086        // The shaper in use counts its period in cycles too. (A pending one was worked out for the new cycle.)
1087        for mode in self.shaper.iter_mut().flatten() {
1088            mode.half *= ratio;
1089            if let Some((_, per_hz)) = &mut mode.follows {
1090                *per_hz *= ratio;
1091            }
1092        }
1093        for half in self.shaper_targets.iter_mut().flatten() {
1094            *half *= ratio;
1095        }
1096        self.tick = (now as f64 * ratio).round() as u64;
1097        let new_now = self.tick as f64;
1098        for (step, at, length) in &mut self.shaper_ramps {
1099            step.iter_mut().for_each(|half| *half *= ratio);
1100            (*at, *length) = (new_now + (*at - now as f64) * ratio, *length * ratio);
1101        }
1102        // A tick of u64::MAX is a motion not yet picked up.
1103        let scale = |tick: &mut u64| {
1104            if *tick != u64::MAX {
1105                *tick = (new_now + (*tick as f64 - now as f64) * ratio).round().max(0.0) as u64;
1106            }
1107        };
1108        let scale_motion = |motion: &mut Motion| match motion {
1109            // A conveyor pass runs on the simulated time, which a new profile cycle does not change.
1110            Motion::Idle | Motion::Conveyor => {}
1111            Motion::Moving { start_tick, tail, .. } => {
1112                scale(start_tick);
1113                if let Some((_, old_start)) = tail {
1114                    scale(old_start);
1115                }
1116            }
1117            Motion::Dwell { until_tick } => scale(until_tick),
1118            Motion::Following { start_tick, .. }
1119            | Motion::Trajectory { start_tick, .. }
1120            | Motion::Cam { start_tick, .. }
1121            | Motion::Halting { start_tick, .. } => scale(start_tick),
1122        };
1123        scale_motion(&mut self.motion);
1124        let scale_at = |at: &mut f64| *at = new_now + (*at - now as f64) * ratio;
1125        self.plan_changed_at.iter_mut().for_each(scale_at);
1126        for plan in &mut self.plans {
1127            plan.from.iter_mut().for_each(scale_at);
1128            scale(&mut plan.first);
1129            scale_motion(&mut plan.motion);
1130            plan.key = plan_key(&plan.motion, plan.pass.as_ref().map(|(pass, _)| pass), plan.first);
1131        }
1132        if let Some((at, _)) = &mut self.gripping {
1133            scale(at);
1134        }
1135        self.dwell_ticks = (self.dwell_ticks as f64 * ratio).round() as u64;
1136        if let Some(newest) = self.history.len().checked_sub(1) {
1137            let old = std::mem::take(&mut self.history);
1138            // From the oldest stored moment to now, in steps of the new cycle; between two stored cycles, in proportion.
1139            for back in (0..=(newest as f64 * ratio).floor() as usize).rev() {
1140                let (whole, part) = ((back as f64 / ratio).floor() as usize, (back as f64 / ratio).fract());
1141                let (a, b) = (&old[newest - whole.min(newest)], &old[newest - (whole + 1).min(newest)]);
1142                self.history.push_back(std::array::from_fn(|which| {
1143                    a[which].iter().zip(&b[which]).map(|(a, b)| a * (1.0 - part) + b * part).collect()
1144                }));
1145            }
1146            self.shaper_reach = 0;
1147        }
1148        // The fieldbus queue is resampled the same way, its delays (in cycles) scaled with it: the frames under way
1149        // arrive when they would have; the configured delay in the new cycles holds for the frames sent from now on.
1150        if !self.fieldbus.is_empty() {
1151            self.fieldbus = resample_fieldbus(&self.fieldbus, ratio);
1152            self.fieldbus_held = u64::MAX;
1153        }
1154    }
1155
1156    /// The setpoints `t` into a ramp down (`ramp_down`) from `from` at speeds `vel` to rest after `time`.
1157    fn halt_at(&mut self, from: &[f64], vel: &[f64], time: f64, t: f64) {
1158        halt(from, vel, time, t, [&mut self.set_pos, &mut self.set_vel, &mut self.set_acc]);
1159    }
1160
1161    /// The ramp down to rest from the setpoint's speed now (a category 2 stop, or a cam taken away under way).
1162    fn ramp_down(&self, machine: &dyn Machine) -> Motion {
1163        let axes = machine.axes();
1164        // The axis that needs longest to stop at its limit sets the time; the others decelerate in proportion.
1165        let mut time = self.raw_vel.iter().zip(axes).map(|(v, a)| v.abs() / a.max_acc).fold(0.0, f64::max);
1166        // A stop that would end beyond the range (a plan decelerating at its limit into an end) ends shorter; one that
1167        // starts beyond it (a cam's slave turning on past its range, as a rotary knife's does) at the limit.
1168        for _ in 0..if in_range(machine, &self.raw_pos) { 8 } else { 0 } {
1169            let end: Vec<f64> = self.raw_pos.iter().zip(&self.raw_vel).map(|(x, v)| x + 0.5 * v * time).collect();
1170            if in_range(machine, &end) {
1171                break;
1172            }
1173            time *= 0.5;
1174        }
1175        if time > 0.0 {
1176            Motion::Halting { from: self.raw_pos.clone(), vel: self.raw_vel.clone(), time, start_tick: u64::MAX }
1177        } else {
1178            Motion::Idle
1179        }
1180    }
1181
1182    pub fn command(&mut self, command: Command, machine: &dyn Machine) -> std::result::Result<(), CommandError> {
1183        let off = matches!(command, Command::Enable | Command::Disable | Command::Halt(StopCategory::Zero));
1184        if !self.enabled && !off {
1185            return Err(CommandError { key: "error-disabled" });
1186        }
1187        if self.reacting.is_some() && !off {
1188            return Err(CommandError { key: "error-fault" });
1189        }
1190        // A plan would act on the drives in position mode only, and be dropped when the others come back to it.
1191        let planning = !off && !matches!(command, Command::Stop | Command::Halt(_));
1192        if planning && self.drives.iter().any(|d| d.mode() != DriveMode::Position) {
1193            return Err(CommandError { key: "error-outside-mode" });
1194        }
1195        match command {
1196            Command::Disable | Command::Halt(StopCategory::Zero) => self.disable(),
1197            Command::Halt(StopCategory::One) => {
1198                (self.motion, self.cycle, self.stopping) = (Motion::Idle, None, false);
1199                let ramps = self.drives.iter_mut().map(|d| {
1200                    d.pulses_off = false;
1201                    Some(d.measured_speed())
1202                });
1203                self.reacting = Some(ramps.collect());
1204                self.halt = Some(Halt { left: self.ss1_time, closing: None });
1205            }
1206            Command::Halt(StopCategory::Two) => {
1207                (self.cycle, self.stopping) = (None, false);
1208                self.motion = self.ramp_down(machine);
1209            }
1210            Command::Enable => {
1211                // Enabling acknowledges a trip; drives still stopping are taken off and on again, holding where
1212                // they stand.
1213                if !self.enabled || self.reacting.is_some() {
1214                    (self.enabled, self.reacting, self.fault, self.halt) = (true, None, None, None);
1215                    self.hold_here(machine, None);
1216                }
1217            }
1218            Command::MoveTo(target) => {
1219                refuse_target(machine, &target)?;
1220                if !matches!(self.motion, Motion::Idle) || self.cycle.is_some() {
1221                    return Err(CommandError { key: "error-busy" });
1222                }
1223                // The tick is filled in when the profile generator picks the move up.
1224                self.motion = Motion::Moving {
1225                    mv: Move::with_law(&self.raw_pos, &target, machine.axes(), &self.law),
1226                    start_tick: u64::MAX,
1227                    tail: None,
1228                };
1229            }
1230            Command::StartCycle => {
1231                if !matches!(self.motion, Motion::Idle) || self.cycle.is_some() {
1232                    return Err(CommandError { key: "error-busy" });
1233                }
1234                if self.segments.is_empty() && self.conveyor.is_none() && self.cam.is_none() {
1235                    return Err(CommandError { key: "error-no-cycle" });
1236                }
1237                self.cycle = Some(self.segments.len().saturating_sub(1));
1238                self.stopping = false;
1239            }
1240            Command::Stop => self.stopping = true,
1241            Command::Setpoint(target) => {
1242                refuse_target(machine, &target)?;
1243                if self.busy() {
1244                    return Err(CommandError { key: "error-busy" });
1245                }
1246                // Further than an axis may travel in one setpoint interval: carried out, that is a jump, not a
1247                // setpoint to follow (a PLC that sends a stale or a wrong value).
1248                // Measured from the last setpoint, not from where the plan stands on its way there: a stream
1249                // whose setpoints come a cycle early would otherwise be refused from 10/11 of the speed limit on.
1250                let reach = self.setpoint_ticks as f64 * self.profile_cycle * (1.0 + 1e-9);
1251                if target
1252                    .iter()
1253                    .zip(self.external_setpoint())
1254                    .zip(machine.axes())
1255                    .any(|((to, from), axis)| (to - from).abs() > axis.max_vel * reach)
1256                {
1257                    return Err(CommandError { key: "error-setpoint-too-far" });
1258                }
1259                self.motion = Motion::Following { from: self.raw_pos.clone(), to: target, start_tick: u64::MAX };
1260            }
1261            Command::Trajectory(points) => self.command_trajectory(points, None, machine)?,
1262            Command::RatedTrajectory(points, speeds, accelerations) => {
1263                let fits = |rates: &[Vec<f64>]| {
1264                    rates.len() == points.len() && rates.iter().all(|r| r.len() == self.set_pos.len())
1265                };
1266                if !fits(&speeds) || !fits(&accelerations) {
1267                    return Err(CommandError { key: "error-trajectory" });
1268                }
1269                self.command_trajectory(points, Some((speeds, accelerations)), machine)?
1270            }
1271        }
1272        Ok(())
1273    }
1274
1275    /// `Command::Trajectory` and, with the speeds and accelerations at its points, `Command::RatedTrajectory`.
1276    fn command_trajectory(
1277        &mut self,
1278        points: Vec<(f64, Vec<f64>)>,
1279        rates: Option<(Vec<Vec<f64>>, Vec<Vec<f64>>)>,
1280        machine: &dyn Machine,
1281    ) -> std::result::Result<(), CommandError> {
1282        if !matches!(self.motion, Motion::Idle) || self.cycle.is_some() {
1283            return Err(CommandError { key: "error-busy" });
1284        }
1285        let rising = points.windows(2).all(|w| w[1].0 > w[0].0);
1286        // The setpoint of a machine at rest is where its motors stand, which under belt stretch and gear
1287        // twist is some hundredths of a millimetre from the tool: at an end of a stroke, beyond it. A
1288        // path from there starts that far outside the range (`near_start`). Judged from the path's own start,
1289        // which may be up to that slack off this setpoint (below): a path planned by another simulation from
1290        // where this machine's tool stands starts where that one's motors stand, on an arm some mrad beyond a
1291        // stop where this setpoint is on it, and was refused.
1292        if points.len() < 2
1293            || points[0].0 != 0.0
1294            || !rising
1295            || !points.iter().all(|(t, pose)| t.is_finite() && near_start(machine, &points[0].1, pose))
1296        {
1297            return Err(CommandError { key: "error-trajectory" });
1298        }
1299        // A path that starts elsewhere would make the setpoint jump.
1300        if points[0].1.iter().zip(&self.raw_pos).any(|(p, s)| (p - s).abs() > machine.setpoint_slack()) {
1301            return Err(CommandError { key: "error-trajectory-start" });
1302        }
1303        self.motion = match rates {
1304            Some((speeds, accelerations)) => {
1305                Motion::Trajectory { points, speeds, accelerations: Some(accelerations), start_tick: u64::MAX }
1306            }
1307            None => trajectory(points, self.spline_c2),
1308        };
1309        Ok(())
1310    }
1311
1312    /// Puts motor `k`'s drive in `mode` (`DriveMode`), `state` the machine's. Refused while the drives are off or
1313    /// stopping after a trip, and out of position mode while a move, cycle or path runs; while a drive is out of position
1314    /// mode, the plan commands are refused. A drive coming back to position mode takes the plan with it: the plan stands
1315    /// where the motors stand, at rest, and every drive starts its PI from the torque it asked for last
1316    /// (`Drive::set_mode`), so the torque does not jump; at speed, the position loop then brings the motors back to
1317    /// where they were at the switch. Enabling the drives puts them all in position mode.
1318    pub fn set_drive_mode(
1319        &mut self,
1320        k: usize,
1321        mode: DriveMode,
1322        machine: &dyn Machine,
1323        state: &[f64],
1324    ) -> std::result::Result<(), CommandError> {
1325        if !self.enabled {
1326            return Err(CommandError { key: "error-disabled" });
1327        }
1328        if self.reacting.is_some() {
1329            return Err(CommandError { key: "error-fault" });
1330        }
1331        // A stepper's step generator and a V/f converter take no torque setpoint.
1332        if matches!(mode, DriveMode::Torque(_)) && self.motor_params[k].motor.open_loop() {
1333            return Err(CommandError { key: "error-open-loop" });
1334        }
1335        let was = self.drives[k].mode();
1336        if mode != DriveMode::Position && was == DriveMode::Position && self.busy() {
1337            return Err(CommandError { key: "error-busy" });
1338        }
1339        self.drives[k].set_mode(mode);
1340        if mode == DriveMode::Position && was != DriveMode::Position {
1341            machine.motor_state(state, &mut self.motor_pos, &mut self.motor_vel);
1342            machine.forward(&self.motor_pos, &mut self.set_pos);
1343            self.raw_pos.clone_from(&self.set_pos);
1344            for rate in [&mut self.set_vel, &mut self.set_acc, &mut self.raw_vel, &mut self.raw_acc] {
1345                rate.fill(0.0);
1346            }
1347            (self.motion, self.cycle, self.stopping) = (Motion::Idle, None, false);
1348            self.history.clear();
1349            self.plans.clear();
1350            self.fieldbus.clear();
1351            for (drive, pos) in self.drives.iter_mut().zip(&self.motor_pos) {
1352                if drive.mode() == DriveMode::Position {
1353                    (drive.pos_set, drive.position_setpoint, drive.vel_set, drive.acc_set) = (*pos, *pos, 0.0, 0.0);
1354                }
1355                drive.retune();
1356            }
1357        }
1358        Ok(())
1359    }
1360
1361    /// Drives off: a move or cycle under way is dropped.
1362    fn disable(&mut self) {
1363        (self.motion, self.cycle, self.stopping, self.enabled) = (Motion::Idle, None, false, false);
1364        (self.reacting, self.halt) = (None, None);
1365    }
1366
1367    /// Whether the holding brakes are asked to hold: with the drives off, and at the end of a category 1 stop once all
1368    /// drives stand (`StopCategory::One`).
1369    fn brake_wanted(&self) -> bool {
1370        !self.enabled || self.halt.is_some_and(|h| h.closing.is_some())
1371    }
1372
1373    /// One base step of `dt` of the holding brakes' command: they engage `brake.engage_delay_s` after they are asked to
1374    /// hold and release `release_delay_s` after they are asked to let go (effects.brake_delay; at once without it).
1375    pub fn step_brake(&mut self, dt: f64) {
1376        let wanted = self.brake_wanted();
1377        if wanted == self.brake_on {
1378            self.brake_timer = 0.0;
1379            return;
1380        }
1381        self.brake_timer += dt;
1382        // To the nearest step: the summed steps come a rounding short of a delay of whole steps.
1383        if self.brake_timer >= self.brake_delays[usize::from(!wanted)] - 0.5 * dt {
1384            (self.brake_on, self.brake_timer) = (wanted, 0.0);
1385        }
1386    }
1387
1388    /// Whether the holding brakes hold (`step_brake`).
1389    pub fn brake_engaged(&self) -> bool {
1390        self.brake_on
1391    }
1392
1393    /// Whether the drives are stopping after a trip (`react`).
1394    pub fn reacting(&self) -> bool {
1395        self.reacting.is_some()
1396    }
1397
1398    /// Whether a category 2 stop (`StopCategory::Two`) is braking the plan.
1399    pub fn halting(&self) -> bool {
1400        matches!(self.motion, Motion::Halting { .. })
1401    }
1402
1403    /// Each drive's fault reaction (effects.drive_monitoring).
1404    pub fn fault_reaction(&self, k: usize) -> fault::Reaction {
1405        self.fault_settings[k].reaction
1406    }
1407
1408    /// A monitor of drive `k` has tripped at `time`: the motion is dropped and every drive stops by its own fault
1409    /// reaction (`react`). The first trip since the last enable is kept in `fault`.
1410    fn trip(&mut self, monitor: Monitor, k: usize, time: f64, machine: &dyn Machine, state: &[f64]) {
1411        if self.fault.is_none() {
1412            let axes = self.set_pos.len();
1413            let (mut pose, mut rate) = (vec![0.0; axes], vec![0.0; axes]);
1414            machine.tool_state(state, &mut pose, &mut rate);
1415            let stopping = vec![0.0; axes];
1416            self.fault = Some(Fault { monitor, drive: k, time, pose, stopping, stopped: None });
1417        }
1418        (self.motion, self.cycle, self.stopping) = (Motion::Idle, None, false);
1419        let ramps = self.drives.iter_mut().zip(&self.fault_settings).map(|(d, s)| {
1420            d.pulses_off = s.deceleration().is_none();
1421            (!d.pulses_off).then(|| d.measured_speed())
1422        });
1423        self.reacting = Some(ramps.collect());
1424    }
1425
1426    /// One base step of the drives stopping after a trip: each with a ramp has its speed setpoint taken down by it and
1427    /// its velocity and current loops follow (the position loop open); once the ramp is down and the motor below the
1428    /// pulse-off speed, its pulses go off, as an STO drive's did at the trip. A drive with its pulses off gives no
1429    /// torque (`disabled_step`; its winding is left out of the integration). When the last is off, the drives are
1430    /// disabled and the holding brakes engage.
1431    fn react(&mut self, step: u64, machine: &dyn Machine, state: &[f64], torque: &mut [f64]) {
1432        let Some(mut ramps) = self.reacting.take() else { return };
1433        let dt = self.profile_cycle / self.n_profile as f64;
1434        let velocity_due = step.is_multiple_of(self.n_velocity);
1435        // A category 1 stop: every drive on its OFF3 ramp, its pulses off only together, once all stand and their brakes
1436        // have had their engagement delay, or when the SS1 timer runs out.
1437        if let Some(halt) = &mut self.halt {
1438            halt.left -= dt;
1439            let standing = self
1440                .drives
1441                .iter()
1442                .zip(&ramps)
1443                .zip(&self.fault_settings)
1444                .all(|((d, r), s)| r.is_none_or(|v| v == 0.0) && d.measured_speed().abs() < s.pulse_off_speed);
1445            if standing {
1446                halt.closing = Some(halt.closing.unwrap_or(0.0) + dt);
1447            }
1448            let done = halt.closing.is_some_and(|t| t >= self.brake_delays[0] - 0.5 * dt);
1449            if halt.left <= 0.0 || done {
1450                ramps.iter_mut().for_each(|r| *r = None);
1451                self.drives.iter_mut().for_each(|d| d.pulses_off = true);
1452            }
1453        }
1454        for (k, drive) in self.drives.iter_mut().enumerate() {
1455            let p = &self.motor_params[k];
1456            if let Some(speed) = ramps[k] {
1457                let deceleration = match self.halt {
1458                    Some(_) => self.fault_settings[k].off3_deceleration,
1459                    None => self.fault_settings[k].deceleration().unwrap_or(f64::INFINITY),
1460                };
1461                let ramped = fault::ramp(speed, deceleration, dt);
1462                if self.halt.is_none()
1463                    && ramped == 0.0
1464                    && drive.measured_speed().abs() < self.fault_settings[k].pulse_off_speed
1465                {
1466                    (ramps[k], drive.pulses_off) = (None, true);
1467                } else {
1468                    (ramps[k], drive.fault_speed) = (Some(ramped), Some(ramped));
1469                    if velocity_due {
1470                        drive.read_encoder(p, self.motor_pos[k]);
1471                        drive.velocity_loop(p, self.motor_vel[k]);
1472                    }
1473                    drive.current_control(p, drive.measured_speed());
1474                    continue;
1475                }
1476            }
1477            drive.disabled_step(p, self.motor_vel[k]);
1478            // A stepper's magnets hold their detent without current (`Sim::advance_with_windings` integrates it).
1479            if let Motor::Stepper(s) = &p.motor {
1480                drive.torque += s.detent_torque(self.motor_pos[k], drive.phases.origin);
1481            }
1482            torque[k] = drive.torque;
1483        }
1484        if self.params.shared_dc_link {
1485            shared_dc_link(&self.params, &mut self.drives);
1486        }
1487        self.track_stop(step, machine, state);
1488        if ramps.iter().all(Option::is_none) {
1489            self.disable();
1490        } else {
1491            self.reacting = Some(ramps);
1492        }
1493    }
1494
1495    /// After a trip, until the machine stands: how far each tool axis has gone since (`Fault::stopping`), and when
1496    /// every drive is off and every motor below its pulse-off speed (`Fault::stopped`). An STO drive's motor coasts
1497    /// until then (or its holding brake stops it, once all drives are off).
1498    fn track_stop(&mut self, step: u64, machine: &dyn Machine, state: &[f64]) {
1499        let Some(fault) = self.fault.as_mut().filter(|f| f.stopped.is_none()) else { return };
1500        let axes = fault.pose.len();
1501        let (mut pose, mut rate) = (vec![0.0; axes], vec![0.0; axes]);
1502        machine.tool_state(state, &mut pose, &mut rate);
1503        fault.stopping = pose.iter().zip(&fault.pose).map(|(now, then)| (now - then).abs()).collect();
1504        let standing = self.motor_vel.iter().zip(&self.fault_settings).all(|(w, s)| w.abs() < s.pulse_off_speed);
1505        if !self.enabled && standing {
1506            fault.stopped = Some(step as f64 * self.profile_cycle / self.n_profile as f64);
1507        }
1508    }
1509
1510    /// The timing for a path of lines and arcs from where the setpoint stands, as the poses that
1511    /// `Command::Trajectory` runs: within the axis limits, or as fast as the motors allow (see `path`).
1512    pub fn plan_path(
1513        &self,
1514        machine: &dyn Machine,
1515        pieces: &[Piece],
1516        time_optimal: bool,
1517    ) -> std::result::Result<Vec<(f64, Vec<f64>)>, CommandError> {
1518        self.plan_from(machine, &self.raw_pos, pieces, time_optimal, None, self.path_tolerance)
1519    }
1520
1521    /// The tolerances a run of a program is planned within: the config's, with the corner tolerance a G61 or G64 gave it.
1522    fn run_tolerance(&self, run: &crate::program::Run) -> path::Tolerance {
1523        path::Tolerance { corner: run.corner.unwrap_or(self.path_tolerance.corner), ..self.path_tolerance }
1524    }
1525
1526    /// The caps of a run's pieces with `profile.feed_override` on the programmed feeds (a planner's limit still holds:
1527    /// the plan takes the lower of cap and axis limit).
1528    fn run_caps(&self, run: &crate::program::Run) -> Option<Vec<f64>> {
1529        run.caps().map(|caps| caps.into_iter().map(|f| f * self.feed_override).collect())
1530    }
1531
1532    /// The timing for a program (`program::read`) from where the setpoint stands, as the poses `Command::Trajectory`
1533    /// runs: each run planned from where the one before ends, at rest between them, within the corner tolerance of its
1534    /// G61 or G64. A run with a feed is planned within the axis limits with the speed along the path of each piece
1535    /// capped at its own feed times `profile.feed_override` (`path::plan_feeds`); one without as `plan_path` plans it, as
1536    /// fast as the motors allow with `time_optimal`. A dwell (G4) holds the last pose for its time, in whole profile
1537    /// cycles, as a cycle segment's dwell does. A program without a move is refused (`error-path`).
1538    pub fn plan_program(
1539        &self,
1540        machine: &dyn Machine,
1541        runs: &[crate::program::Run],
1542        time_optimal: bool,
1543    ) -> std::result::Result<Vec<(f64, Vec<f64>)>, CommandError> {
1544        let mut points = vec![(0.0, self.raw_pos.clone())];
1545        let mut moves = false;
1546        for run in runs {
1547            let (t0, start) = points[points.len() - 1].clone();
1548            if run.pieces.is_empty() {
1549                let ticks = (run.dwell_s / self.profile_cycle).round() as usize;
1550                points.extend((1..=ticks).map(|k| (t0 + k as f64 * self.profile_cycle, start.clone())));
1551                continue;
1552            }
1553            moves = true;
1554            let planned = self.plan_from(
1555                machine,
1556                &start,
1557                &run.pieces,
1558                time_optimal && run.feed.is_none(),
1559                self.run_caps(run).as_deref(),
1560                self.run_tolerance(run),
1561            )?;
1562            // Each plan starts at its start at 0 s, which the one before has as its end.
1563            points.extend(planned.into_iter().skip(1).map(|(t, pose)| (t0 + t, pose)));
1564        }
1565        if !moves {
1566            return Err(CommandError { key: "error-path" });
1567        }
1568        Ok(points)
1569    }
1570
1571    /// `plan_path` from `start` within `tolerance`, with the speed along the path of piece i capped at `feeds[i]` where
1572    /// there are any (then within the axis limits, also with `time_optimal`).
1573    fn plan_from(
1574        &self,
1575        machine: &dyn Machine,
1576        start: &[f64],
1577        pieces: &[Piece],
1578        time_optimal: bool,
1579        feeds: Option<&[f64]>,
1580        tolerance: path::Tolerance,
1581    ) -> std::result::Result<Vec<(f64, Vec<f64>)>, CommandError> {
1582        let time_optimal = time_optimal && feeds.is_none();
1583        // An arc or a spline can swing out of the range although every point given is inside. Said here,
1584        // because `Command::Trajectory` refuses such poses with a message about poses at times.
1585        let reachable = |points: &[(f64, Vec<f64>)]| {
1586            if points.iter().all(|(_, pose)| near_start(machine, start, pose)) {
1587                Ok(())
1588            } else {
1589                Err(CommandError { key: "error-path-range" })
1590            }
1591        };
1592        let within_axis_limits = || {
1593            let (cycle, slack) = (self.profile_cycle, machine.setpoint_slack());
1594            let (feeds, spin) = (feeds.unwrap_or(&[]), self.law.spin);
1595            path::plan_within(machine.axes(), spin, start, pieces, feeds, cycle, tolerance, slack)
1596        };
1597        if time_optimal {
1598            // A pose on the way that the machine cannot go to (an arm's singularity, where the motors would have to
1599            // turn infinitely fast) would time the plan to a standstill there: so the same path is checked first as
1600            // planned within the axis limits, where the timing does not depend on the kinematics (what that plan
1601            // refuses otherwise is left to the time-optimal one).
1602            if let Ok(points) = within_axis_limits() {
1603                reachable(&points)?;
1604            }
1605        }
1606        let points = if time_optimal {
1607            self.plan_time_optimal_from(machine, start, pieces, tolerance)
1608        } else {
1609            within_axis_limits()
1610        }?;
1611        reachable(&points)?;
1612        Ok(points)
1613    }
1614
1615    /// `path::plan_time_optimal` from `from` with this controller's drive, limits and cycle, within `tolerance`.
1616    fn plan_time_optimal_from(
1617        &self,
1618        machine: &dyn Machine,
1619        from: &[f64],
1620        pieces: &[Piece],
1621        tolerance: path::Tolerance,
1622    ) -> std::result::Result<Vec<(f64, Vec<f64>)>, CommandError> {
1623        path::plan_time_optimal(
1624            machine,
1625            &self.motor_drives(machine),
1626            &self.plan_limits,
1627            from,
1628            pieces,
1629            self.profile_cycle,
1630            tolerance,
1631            machine.setpoint_slack(),
1632        )
1633    }
1634
1635    /// How far the path `plan_path` plans for these pieces is from the pieces as given, at most (see
1636    /// `path::deviation`): zero unless `profile.path_tolerance_m` allows transition curves. The time-optimal plan's
1637    /// curves are as long as the motors' speeds need, so its deviation can differ. A path `plan_path` refuses is
1638    /// refused here the same way (it is planned for that).
1639    pub fn path_deviation(
1640        &self,
1641        machine: &dyn Machine,
1642        pieces: &[Piece],
1643        time_optimal: bool,
1644    ) -> std::result::Result<f64, CommandError> {
1645        self.plan_path(machine, pieces, time_optimal)?;
1646        if time_optimal {
1647            path::deviation_time_optimal(
1648                machine,
1649                &self.motor_drives(machine),
1650                &self.plan_limits,
1651                &self.raw_pos,
1652                pieces,
1653                self.path_tolerance,
1654                machine.setpoint_slack(),
1655            )
1656        } else {
1657            path::deviation(machine.axes(), &self.raw_pos, pieces, self.path_tolerance, machine.setpoint_slack())
1658        }
1659    }
1660
1661    /// `path_deviation` per run of a program (`plan_program`: each run from where the one before ends, a run with a
1662    /// feed within the axis limits). A run with a feed reads as without its feeds (`path::deviation`): never lower
1663    /// than its own path's.
1664    pub fn program_deviations(
1665        &self,
1666        machine: &dyn Machine,
1667        runs: &[crate::program::Run],
1668        time_optimal: bool,
1669    ) -> std::result::Result<Vec<f64>, CommandError> {
1670        let mut start = self.raw_pos.clone();
1671        let mut out = Vec::new();
1672        for run in runs.iter().filter(|run| !run.pieces.is_empty()) {
1673            let optimal = time_optimal && run.feed.is_none();
1674            let tolerance = self.run_tolerance(run);
1675            let planned =
1676                self.plan_from(machine, &start, &run.pieces, optimal, self.run_caps(run).as_deref(), tolerance)?;
1677            out.push(if optimal {
1678                path::deviation_time_optimal(
1679                    machine,
1680                    &self.motor_drives(machine),
1681                    &self.plan_limits,
1682                    &start,
1683                    &run.pieces,
1684                    tolerance,
1685                    machine.setpoint_slack(),
1686                )?
1687            } else {
1688                path::deviation(machine.axes(), &start, &run.pieces, tolerance, machine.setpoint_slack())?
1689            });
1690            if let Some((_, end)) = planned.last() {
1691                start.clone_from(end);
1692            }
1693        }
1694        Ok(out)
1695    }
1696
1697    /// True while a move, a dwell or the cycle is under way.
1698    pub fn busy(&self) -> bool {
1699        self.cycle.is_some()
1700            || matches!(
1701                self.motion,
1702                Motion::Moving { .. }
1703                    | Motion::Dwell { .. }
1704                    | Motion::Trajectory { .. }
1705                    | Motion::Conveyor
1706                    | Motion::Cam { .. }
1707                    | Motion::Halting { .. }
1708            )
1709    }
1710
1711    /// False between `Command::Disable` and `Command::Enable`.
1712    pub fn enabled(&self) -> bool {
1713        self.enabled
1714    }
1715
1716    pub fn cycle_segment(&self) -> Option<usize> {
1717        self.cycle
1718    }
1719
1720    /// The conveyor of `[conveyor]`, where the config has one, and the pass of its cycle under way or last run.
1721    pub fn conveyor(&self) -> Option<(&Conveyor, Option<&Pass>)> {
1722        self.conveyor.as_ref().map(|c| (c, self.pass.as_ref()))
1723    }
1724
1725    /// How often the cycle has started its first segment since the controller was made. The segment index
1726    /// alone does not tell one pass from the next when the cycle has a single segment.
1727    pub fn cycle_passes(&self) -> u64 {
1728        self.passes
1729    }
1730
1731    /// Where an electronic cam's master stands (`Machine::cam`), in its units; kept between runs.
1732    pub fn cam_master(&self) -> f64 {
1733        self.cam_master
1734    }
1735
1736    /// The torque the drives can give at a motor speed: (lowest, highest).
1737    pub fn torque_curve(&self, speed: f64) -> (f64, f64) {
1738        self.params.torque_curve(speed)
1739    }
1740
1741    /// The torque motor `k`'s drive can give at a motor speed: (lowest, highest).
1742    pub fn motor_torque_curve(&self, k: usize, speed: f64) -> (f64, f64) {
1743        self.drive_params_of(k).torque_curve(speed)
1744    }
1745
1746    /// How far a dwell of the cycle has run, from 0 to 1; `None` outside a dwell.
1747    pub fn dwell_progress(&self) -> Option<f64> {
1748        let (Motion::Dwell { until_tick }, Some(_)) = (&self.motion, self.cycle) else { return None };
1749        let total = self.dwell_ticks;
1750        (total > 0).then(|| 1.0 - until_tick.saturating_sub(self.tick) as f64 / total as f64)
1751    }
1752
1753    /// Segment `i` has arrived at `tick`: the dwell starts. Where the gripper changes its state, with
1754    /// effects.gripper_time it closes or opens for its time (`Segment::grip_ticks`), the dwell lasts at least that long
1755    /// and the payload comes or goes when the gripper is done; without, at once.
1756    fn arrive(&mut self, i: usize, tick: u64) -> Motion {
1757        let s = &self.segments[i];
1758        let grip = if s.payload != self.payload_attached { s.grip_ticks } else { 0 };
1759        if grip == 0 {
1760            self.payload_attached = s.payload;
1761        } else {
1762            self.gripping = Some((tick + grip, s.payload));
1763        }
1764        self.dwell_ticks = s.dwell_ticks.max(grip);
1765        self.arrived(i, tick)
1766    }
1767
1768    /// Whether the gripper is closing or opening (effects.gripper_time).
1769    pub fn gripper_acting(&self) -> bool {
1770        self.gripping.is_some()
1771    }
1772
1773    /// The setpoint as planned, before input shaping: during a dwell, the target.
1774    pub fn planned_pos(&self) -> &[f64] {
1775        &self.raw_pos
1776    }
1777
1778    /// Where a setpoint from outside would leave from: the target of the one the controller still
1779    /// interpolates towards, else where the plan stands. A link to a PLC shows this as its setpoint, so that
1780    /// an axis the PLC does not write stays where it is.
1781    pub fn external_setpoint(&self) -> &[f64] {
1782        match &self.motion {
1783            Motion::Following { to, .. } => to,
1784            _ => &self.raw_pos,
1785        }
1786    }
1787
1788    /// The torque the motors can give continuously.
1789    pub fn rated_torque(&self) -> f64 {
1790        self.params.rated_torque
1791    }
1792
1793    /// Motor and drive data, for the analysis.
1794    pub fn drive_params(&self) -> &DriveParams {
1795        &self.params
1796    }
1797
1798    /// The limits the time-optimal plan keeps beside the motors' (`path::PlanLimits`), as the config gives them.
1799    pub fn plan_limits(&self) -> &path::PlanLimits {
1800        &self.plan_limits
1801    }
1802
1803    /// Motor k's DC link room above the bus, J: 1/2 C (U_threshold^2 - U_bus^2) of its own ratings; None without them.
1804    pub fn dc_link_room(&self, k: usize) -> Option<f64> {
1805        self.dc_link_rooms.get(k).copied().flatten()
1806    }
1807
1808    /// Motor and drive data of motor `k`: `drive_params` with that motor's own values (`catalog::motor_config`).
1809    pub fn drive_params_of(&self, k: usize) -> &DriveParams {
1810        self.motor_params.get(k).unwrap_or(&self.params)
1811    }
1812
1813    /// Every motor encoder without its rounding to counts and its noise, the speed still their difference per cycle
1814    /// (`DriveParams::speed_from_positions`): for the small-signal loop measurement
1815    /// (`analysis::velocity_loop_response`), whose test swing at high frequencies is a fraction of a count (a mover's
1816    /// 3 N swings it 0.03 um at 1.6 kHz against 1 um counts): with them the rounding, not the loop, is measured.
1817    pub fn unrounded_encoders(&mut self) {
1818        for p in std::iter::once(&mut self.params).chain(&mut self.motor_params) {
1819            (p.encoder_step, p.encoder_noise) = (0.0, 0.0);
1820        }
1821    }
1822
1823    /// Each motor's own drive and motor data (`drive_params_of`), in the order of `Machine::motors`.
1824    pub fn motor_drives(&self, machine: &dyn Machine) -> Vec<&DriveParams> {
1825        (0..machine.motors().len()).map(|k| self.drive_params_of(k)).collect()
1826    }
1827
1828    /// The motors stand `shift` from where they stood without having turned there: the machine's model was
1829    /// exchanged, and belt stretch and gear twist came or went with it, or its ratio changed. The encoders'
1830    /// last readings move along, so that the step does not read as speed, and so do the position setpoints
1831    /// at the drives and on the fieldbus, so that it does not read as following error. The next profile
1832    /// cycle works them out anew.
1833    pub fn motors_shifted(&mut self, shift: &[f64]) {
1834        for (k, (drive, by)) in self.drives.iter_mut().zip(shift).enumerate() {
1835            drive.shift_encoder(*by);
1836            drive.shift_setpoint(*by);
1837            for (_, setpoints) in &mut self.fieldbus {
1838                setpoints[k][0] += by;
1839            }
1840        }
1841    }
1842
1843    /// One base step: runs whichever loops are due and sets the voltages the windings get over the step. Enabled, the
1844    /// simulation then takes windings and mechanics through the step together and hands the windings back
1845    /// (`winding_stepped`). Disabled, the drives give no torque, their windings cool and their DC links discharge,
1846    /// and `torque` is zero.
1847    pub fn update(&mut self, step: u64, machine: &dyn Machine, state: &[f64], torque: &mut [f64]) {
1848        self.base_step = step;
1849        machine.motor_state(state, &mut self.motor_pos, &mut self.motor_vel);
1850        if !self.enabled {
1851            for (k, (drive, torque)) in self.drives.iter_mut().zip(torque).enumerate() {
1852                drive.disabled_step(&self.motor_params[k], self.motor_vel[k]);
1853                // A stepper's magnets hold their detent without current too. Held over the step as the iron's drag is,
1854                // its work is booked as the shaft's and what the magnets gave (`Sim::step`'s disabled branch).
1855                if let Motor::Stepper(s) = &self.motor_params[k].motor {
1856                    drive.torque += s.detent_torque(self.motor_pos[k], drive.phases.origin);
1857                }
1858                *torque = drive.torque;
1859            }
1860            if self.params.shared_dc_link {
1861                shared_dc_link(&self.params, &mut self.drives);
1862            }
1863            self.track_stop(step, machine, state);
1864            return;
1865        }
1866        if self.reacting.is_some() {
1867            self.react(step, machine, state, torque);
1868            return;
1869        }
1870        if step.is_multiple_of(self.n_profile) {
1871            self.clock = step as f64 * self.profile_cycle / self.n_profile as f64;
1872            self.profile_tick(self.tick + 1, machine);
1873        }
1874        let (position_due, velocity_due) = (step.is_multiple_of(self.n_position), step.is_multiple_of(self.n_velocity));
1875        // One encoder sample per base step, which both loops use.
1876        if position_due || velocity_due {
1877            for (k, (drive, pos)) in self.drives.iter_mut().zip(&self.motor_pos).enumerate() {
1878                drive.read_encoder(&self.motor_params[k], *pos);
1879            }
1880        }
1881        if position_due {
1882            // With a load-side encoder (effects.load_encoder) the position loop measures the tool axes, in whole
1883            // steps of the scale, as motor angles through the rigid kinematics; the speed loop keeps the motor's.
1884            // The scale is mounted on the frame: it reads `Machine::scale_state`, the carriage against the frame.
1885            let load = self.load_encoder.map(|scale| {
1886                let axes = self.set_pos.len();
1887                let (mut tool, mut rate, mut motors) = (vec![0.0; axes], vec![0.0; axes], vec![0.0; self.drives.len()]);
1888                machine.scale_state(state, &mut tool, &mut rate);
1889                tool.iter_mut().for_each(|x| *x = quantise(*x, scale));
1890                machine.inverse(&tool, &mut motors);
1891                motors
1892            });
1893            let cycle = self.n_position as f64 * self.profile_cycle / self.n_profile as f64;
1894            let measured = |k: usize, drive: &Drive| load.as_ref().map_or(drive.encoder(), |l| l[k]);
1895            // A gantry's master first: master/slave, the slave measures itself against the master's actual position.
1896            let sync = self.gantry_sync;
1897            let mut lead = 0.0;
1898            if let Some(g) = sync {
1899                let drive = &mut self.drives[g.master];
1900                drive.position_loop(&self.motor_params[g.master], measured(g.master, drive), cycle);
1901                if g.cross_gain.is_none() {
1902                    lead = g.ratio * drive.following_error;
1903                }
1904            }
1905            for (k, drive) in self.drives.iter_mut().enumerate() {
1906                if sync.is_some_and(|g| g.master == k) {
1907                    continue;
1908                }
1909                let behind = if sync.is_some_and(|g| g.slave == k) { lead } else { 0.0 };
1910                drive.position_loop(&self.motor_params[k], measured(k, drive) + behind, cycle);
1911            }
1912            if let Some(GantrySync { master, slave, ratio, cross_gain: Some(gain) }) = sync {
1913                // The slave's actual less the master's, in the slave's units, from the following errors (their
1914                // setpoints stand in the ratio): ratio e_master - e_slave.
1915                let error = ratio * self.drives[master].following_error - self.drives[slave].following_error;
1916                for (k, by) in [(slave, -gain * error), (master, gain * error / ratio)] {
1917                    self.drives[k].position_part += by;
1918                    self.drives[k].speed_command += by;
1919                }
1920            }
1921            // Following error per motor, transformed back to the tool axes for display.
1922            let (set, actual): (Vec<f64>, Vec<f64>) =
1923                self.drives.iter().map(|d| (d.position_setpoint, d.position_setpoint - d.following_error)).unzip();
1924            let (mut tool_set, mut tool_actual) = (self.set_pos.clone(), self.set_pos.clone());
1925            machine.forward(&set, &mut tool_set);
1926            machine.forward(&actual, &mut tool_actual);
1927            for i in 0..self.tool_error.len() {
1928                self.tool_error[i] = tool_set[i] - tool_actual[i];
1929            }
1930        }
1931        let dt = self.profile_cycle / self.n_profile as f64;
1932        for (k, drive) in self.drives.iter_mut().enumerate() {
1933            if velocity_due {
1934                drive.velocity_loop(&self.motor_params[k], self.motor_vel[k]);
1935            }
1936            // The back-EMF the current loop adds, and the field weakening, at the speed the drive has measured.
1937            let speed = drive.measured_speed();
1938            drive.current_control(&self.motor_params[k], speed);
1939            drive.since_setpoint += dt;
1940        }
1941        if self.monitoring {
1942            // The friction the torque-band monitor expects: what the machine's own friction model takes of each motor's
1943            // torque at the machine's state (`friction_signals`), so with the guides' bristles and breakaway, the motor's
1944            // Stribeck curve and the gearbox's mesh friction as they act through a start or a reversal.
1945            let mut friction = vec![0.0; self.drives.len()];
1946            let banded = |k: usize| {
1947                self.fault_settings[k].torque_band > 0.0 && self.friction_signals.get(k).copied().flatten().is_some()
1948            };
1949            if (0..self.drives.len()).any(banded) {
1950                let torques: Vec<f64> = self.drives.iter().map(|d| d.torque).collect();
1951                let mut signals = Vec::new();
1952                machine.signals(state, &torques, &mut signals);
1953                for (k, f) in friction.iter_mut().enumerate().filter(|(k, _)| banded(*k)) {
1954                    *f = self.friction_signals[k].and_then(|i| signals.get(i).copied()).unwrap_or(0.0);
1955                }
1956            }
1957            let tripped = (0..self.drives.len()).find_map(|k| {
1958                let (s, peak) = (&self.fault_settings[k], self.motor_params[k].peak_torque);
1959                self.watch[k].check(s, &self.drives[k], friction[k], peak, dt).map(|m| (m, k))
1960            });
1961            if let Some((monitor, k)) = tripped {
1962                self.trip(monitor, k, step as f64 * dt, machine, state);
1963            }
1964        }
1965    }
1966
1967    /// The tool setpoint at `time`: the last profile cycle's run on by its speed and acceleration, as the drives' fine
1968    /// interpolation runs the motors' on (at most one profile cycle). What the analysis measures the tool against.
1969    pub fn plan_now(&self, time: f64, out: &mut [f64]) {
1970        let t = self.setpoint_age(time);
1971        for (i, x) in out.iter_mut().enumerate() {
1972            *x = self.set_pos[i] + (self.set_vel[i] + 0.5 * self.set_acc[i] * t) * t;
1973        }
1974    }
1975
1976    /// How long ago, at `time`, the profile cycle set `set_pos`, `set_vel` and `set_acc` (the signal `setpoint_age`):
1977    /// `plan_now` is those run on by it.
1978    pub fn setpoint_age(&self, time: f64) -> f64 {
1979        (time - self.clock).clamp(0.0, self.profile_cycle)
1980    }
1981
1982    /// The base step done (see `update`): per drive the current at its end and the electrical energy, copper loss and
1983    /// work on the shaft over it, `WINDING_STATES` numbers per drive in their order, and the rotors' angles and speeds at
1984    /// its end. Then the shared DC link, and the trip.
1985    pub fn winding_stepped(&mut self, windings: &[f64], angle: &[f64], speed: &[f64]) {
1986        for (k, (drive, w)) in self.drives.iter_mut().zip(windings.as_chunks::<WINDING_STATES>().0).enumerate() {
1987            // A drive whose pulses are off after a trip has had its disabled step (`react`); the iron's drag work over
1988            // the step is the integrated one (`Sim::advance_with_windings`), not the step start's speed times the step.
1989            if drive.pulses_off {
1990                let dt = self.motor_params[k].current_cycle;
1991                (drive.shaft_power, drive.emf_loss) = (w[3] / dt, -w[3] / dt);
1992            } else {
1993                (drive.phases.x, drive.phases.angle, drive.phases.speed) =
1994                    ([w[0], w[4], w[5], w[6]], angle[k], speed[k]);
1995                drive.winding_stepped(&self.motor_params[k], w[0], [w[1], w[2], w[3]]);
1996                // From the rotor's angle at the step's start (`update`), which an enable's `Drive::at_rest` may not have.
1997                drive.detent_moved(&self.motor_params[k], self.motor_pos[k]);
1998            }
1999        }
2000        if self.params.shared_dc_link {
2001            shared_dc_link(&self.params, &mut self.drives);
2002        }
2003        // A drive that trips on DC link overvoltage takes all drives off, as `Command::Disable` does. Its
2004        // `tripped` stays until `Command::Enable`; its DC link discharges as a disabled drive's does, and an enable
2005        // keeps what charge is left (`hold_here`).
2006        if self.drives.iter().any(|d| d.tripped) {
2007            self.disable();
2008        }
2009    }
2010
2011    /// Profile generator: new tool setpoints, then the inverse transformation to motor setpoints.
2012    fn profile_tick(&mut self, tick: u64, machine: &dyn Machine) {
2013        let dt = self.profile_cycle;
2014        self.tick = tick;
2015        // Plan on the setpoints as planned so far, not on their shaped version.
2016        self.set_pos.clone_from(&self.raw_pos);
2017        self.set_vel.clone_from(&self.raw_vel);
2018        self.set_acc.clone_from(&self.raw_acc);
2019        // effects.gripper_time: the grip is made or lost once the gripper has had its time (`arrive`).
2020        if let Some((at, holds)) = self.gripping
2021            && tick >= at
2022        {
2023            (self.payload_attached, self.gripping) = (holds, None);
2024        }
2025        if matches!(self.motion, Motion::Idle) {
2026            self.next_cycle_segment(machine);
2027        }
2028        let motion = std::mem::replace(&mut self.motion, Motion::Idle);
2029        self.record_plan(tick, &motion, machine);
2030        match motion {
2031            Motion::Idle => {
2032                self.set_vel.fill(0.0);
2033                self.set_acc.fill(0.0);
2034            }
2035            Motion::Moving { mv, start_tick, mut tail } => {
2036                let start_tick = if start_tick == u64::MAX { tick } else { start_tick };
2037                let t = (tick - start_tick) as f64 * dt;
2038                let old = tail.as_ref().map(|(old, old_start)| (old, (tick - old_start) as f64 * dt));
2039                move_at(&mv, t, old, [&mut self.set_pos, &mut self.set_vel, &mut self.set_acc]);
2040                if old.is_some_and(|(old, t_old)| t_old >= old.duration()) {
2041                    tail = None;
2042                }
2043                // With input shaping the setpoint arrives after the plan. Where the gripper acts or the cycle
2044                // dwells, both wait for the setpoint: the tool is not there before.
2045                let waits = self.cycle.is_some_and(|i| {
2046                    self.segments[i].dwell_ticks > 0 || self.segments[i].payload != self.payload_attached
2047                });
2048                // The shaper's oldest copy is its whole length old, read between two stored cycles.
2049                let lag = if waits { self.shaper_span(machine, &self.set_pos).ceil() } else { 0.0 };
2050                let arrival = mv.duration() + lag * dt;
2051                self.motion = if t >= arrival && tail.is_none() {
2052                    match self.cycle {
2053                        Some(i) => self.arrive(i, tick),
2054                        None => Motion::Idle,
2055                    }
2056                } else {
2057                    match self.blend_into_next(&mv, t, tail.is_some(), machine) {
2058                        Some(next) => Motion::Moving { mv: next, start_tick: tick, tail: Some((mv, start_tick)) },
2059                        None => Motion::Moving { mv, start_tick, tail },
2060                    }
2061                };
2062            }
2063            Motion::Conveyor => {
2064                // The pass was planned for the shaped setpoint (`Conveyor::plan`): its grip begins once the shaped
2065                // setpoint is on the part, so the gripper acts on the plan's time.
2066                if let Some(pass) = &self.pass {
2067                    let t = self.clock - pass.start;
2068                    if t < 0.0 {
2069                        // Waiting for the part, at rest where the last pass ended.
2070                        self.set_vel.fill(0.0);
2071                        self.set_acc.fill(0.0);
2072                        self.motion = Motion::Conveyor;
2073                    } else {
2074                        pass.at(t, &mut self.set_pos, &mut self.set_vel, &mut self.set_acc);
2075                        self.payload_attached = pass.holds(t);
2076                        if t < pass.duration() {
2077                            self.motion = Motion::Conveyor;
2078                        } else {
2079                            self.set_vel.fill(0.0);
2080                            self.set_acc.fill(0.0);
2081                        }
2082                    }
2083                }
2084            }
2085            Motion::Cam { start_tick, mut stop, from, offset, mut next_pass, from_speed, speed, ramp } => {
2086                let start_tick = if start_tick == u64::MAX { tick } else { start_tick };
2087                let t = (tick - start_tick) as f64 * dt;
2088                if let Some(master) = self.cam {
2089                    if self.stopping && stop.is_none() {
2090                        stop = Some(t);
2091                    }
2092                    let run = crate::cam::master_change(from_speed, speed, ramp, t, stop);
2093                    self.cam_master = from + run[0];
2094                    // Passes count whole periods of the master from where it is up to speed.
2095                    if t >= ramp && next_pass.is_nan() {
2096                        next_pass = self.cam_master + master.period;
2097                    } else if self.cam_master >= next_pass && stop.is_none() {
2098                        next_pass += master.period;
2099                        self.passes += 1;
2100                    }
2101                    let out = [&mut self.set_pos, &mut self.set_vel, &mut self.set_acc];
2102                    cam_slaves(&|m, cam| machine.cam_at(m, cam), self.cam_master, run, &offset, out);
2103                    if stop.is_some_and(|s| t >= s.max(ramp) + ramp) {
2104                        // Run down: at rest where the cam has brought the slaves.
2105                        self.set_vel.fill(0.0);
2106                        self.set_acc.fill(0.0);
2107                        (self.cycle, self.stopping) = (None, false);
2108                    } else {
2109                        self.motion =
2110                            Motion::Cam { start_tick, stop, from, offset, next_pass, from_speed, speed, ramp };
2111                    }
2112                } else {
2113                    // A config without the cam now: the slaves ramp down from the speeds they have, every axis within
2114                    // its acceleration limit, as in a category 2 stop, instead of a step in their speed. (The cam's
2115                    // curve went with the config, so they decelerate along their last direction.) Its first cycle is
2116                    // this one, so the setpoint does not stand still for a cycle.
2117                    (self.cycle, self.stopping) = (None, false);
2118                    self.set_acc.fill(0.0);
2119                    if let Motion::Halting { from, vel, time, .. } = self.ramp_down(machine) {
2120                        self.halt_at(&from, &vel, time, dt.min(time));
2121                        // This cycle is the stop's, not the cam's.
2122                        let halting =
2123                            Motion::Halting { from: from.clone(), vel: vel.clone(), time, start_tick: tick - 1 };
2124                        self.record_plan(tick, &halting, machine);
2125                        if dt < time {
2126                            self.motion = Motion::Halting { from, vel, time, start_tick: tick - 1 };
2127                        }
2128                    }
2129                }
2130            }
2131            Motion::Dwell { mut until_tick } => {
2132                // Waiting for end-position sensors (`arrived`): the dwell counts from when they all report.
2133                if until_tick == u64::MAX
2134                    && let Some(i) = self.cycle
2135                    && self.segments[i].wait.iter().all(|&(valve, end)| machine.end_sensors(valve)[end])
2136                {
2137                    until_tick = tick + self.segments[i].dwell_ticks;
2138                }
2139                if tick >= until_tick {
2140                    self.next_cycle_segment(machine);
2141                } else {
2142                    self.motion = Motion::Dwell { until_tick };
2143                }
2144            }
2145            Motion::Trajectory { points, speeds, accelerations, start_tick } => {
2146                let start_tick = if start_tick == u64::MAX { tick } else { start_tick };
2147                let t = (tick - start_tick) as f64 * dt;
2148                let last = points.len() - 1;
2149                let out = [&mut self.set_pos, &mut self.set_vel, &mut self.set_acc];
2150                path_at(&points, &speeds, accelerations.as_deref(), t, dt, out);
2151                if t >= points[last].0 {
2152                    // A cycle segment's path arrives as a move does (see above): the gripper acts and the dwell starts
2153                    // once the shaped setpoint is there, where the segment waits for it.
2154                    if let Some(i) = self.cycle {
2155                        let waits =
2156                            self.segments[i].dwell_ticks > 0 || self.segments[i].payload != self.payload_attached;
2157                        let lag = if waits { self.shaper_span(machine, &self.set_pos).ceil() } else { 0.0 };
2158                        self.motion = if t >= points[last].0 + lag * dt {
2159                            self.arrive(i, tick)
2160                        } else {
2161                            Motion::Trajectory { points, speeds, accelerations, start_tick }
2162                        };
2163                    }
2164                } else {
2165                    self.motion = Motion::Trajectory { points, speeds, accelerations, start_tick };
2166                }
2167            }
2168            Motion::Following { from, to, start_tick } => {
2169                // The setpoint came during the cycle before this one, and the way to it starts there. Counted
2170                // from this cycle, the plan stood still for a cycle at every setpoint of a stream and made up
2171                // for it a ninth faster than the stream.
2172                let start_tick = if start_tick == u64::MAX { tick - 1 } else { start_tick };
2173                let n = self.setpoint_ticks as f64;
2174                let done = ((tick - start_tick) as f64 / n).min(1.0);
2175                line_at(&from, &to, done, n * dt, [&mut self.set_pos, &mut self.set_vel, &mut self.set_acc]);
2176                if done < 1.0 {
2177                    self.motion = Motion::Following { from, to, start_tick };
2178                }
2179            }
2180            Motion::Halting { from, vel, time, start_tick } => {
2181                // From the cycle the stop came in, as a setpoint from outside is (`Following`).
2182                let start_tick = if start_tick == u64::MAX { tick - 1 } else { start_tick };
2183                let t = ((tick - start_tick) as f64 * dt).min(time);
2184                self.halt_at(&from, &vel, time, t);
2185                if t < time {
2186                    self.motion = Motion::Halting { from, vel, time, start_tick };
2187                }
2188            }
2189        }
2190
2191        // A changed shaper is taken once the plan stands still and the shaper's store holds nothing but where
2192        // it stands: then the setpoint is the plan, with the old shaper and with the new, and does not step.
2193        if self.raw_pos == self.set_pos
2194            && self.history.iter().all(|past| past[0] == self.raw_pos)
2195            && let Some(next) = self.pending_shaper.take()
2196        {
2197            self.shaper = next;
2198            (self.shaper_ramps, self.shaper_targets) = (Vec::new(), None);
2199        }
2200        self.raw_pos.clone_from(&self.set_pos);
2201        self.raw_vel.clone_from(&self.set_vel);
2202        self.raw_acc.clone_from(&self.set_acc);
2203        self.shape(machine);
2204
2205        let motors = self.drives.len();
2206        let (mut pos, mut ahead, mut behind, mut ff) =
2207            (vec![0.0; motors], vec![0.0; motors], vec![0.0; motors], vec![0.0; motors]);
2208        let offset_pos: Vec<f64> = self.set_pos.iter().zip(&self.setpoint_offset).map(|(p, o)| p + o).collect();
2209        machine.inverse(&offset_pos, &mut pos);
2210        // Motor speed and acceleration setpoints: the inverse transformation along the plan a moment ahead and behind,
2211        // x(s) = x + v s + a s^2 / 2. The second difference is the motors' whole acceleration, J^-1 a and the part a
2212        // kinematics that is not linear adds at speed (d/dt J^-1 times v), for the drives' fine interpolation.
2213        let (h, mut here) = (1e-3, vec![0.0; motors]);
2214        let along = |s: f64| -> Vec<f64> {
2215            (0..self.set_pos.len())
2216                .map(|i| self.set_pos[i] + s * self.set_vel[i] + 0.5 * s * s * self.set_acc[i])
2217                .collect()
2218        };
2219        machine.inverse(&along(h), &mut ahead);
2220        machine.inverse(&along(-h), &mut behind);
2221        machine.inverse(&self.set_pos, &mut here);
2222        let motor_acc: Vec<f64> = (0..motors).map(|k| (ahead[k] - 2.0 * here[k] + behind[k]) / (h * h)).collect();
2223        self.torque_feedforward(machine, &self.set_pos, &self.set_vel, &self.set_acc, &motor_acc, &mut ff);
2224        let hold = self.holding_torque(machine, &self.set_pos);
2225        // The friction of the machine's own model at the planned speed, for the drives that take it and for the
2226        // torque-band monitor of a machine that does not report its friction torque (`friction_signals`; one that does
2227        // has the monitor take it at its state every step, `update`), which expects it as it expects the held load.
2228        let mut friction = vec![0.0; motors];
2229        let banded: Vec<bool> = (0..motors)
2230            .map(|k| {
2231                self.monitoring
2232                    && self.fault_settings.get(k).is_some_and(|s| s.torque_band > 0.0)
2233                    && self.friction_signals.get(k).is_none_or(|s| s.is_none())
2234            })
2235            .collect();
2236        if self.motor_params.iter().any(|p| p.precontrol.machine_friction) || banded.contains(&true) {
2237            machine.steady_friction(&self.set_pos, &self.set_vel, &mut friction);
2238        }
2239        for k in 0..motors {
2240            let p = &self.motor_params[k];
2241            // The friction the config's feedforward model gives (its characteristic where it has one), else the machine's.
2242            let expected = if p.precontrol.friction.is_empty() {
2243                friction[k]
2244            } else {
2245                p.precontrol.friction_at((ahead[k] - behind[k]) / (2.0 * h))
2246            };
2247            self.drives[k].torque_hold = hold[k] + if banded[k] { expected } else { 0.0 };
2248            if !p.precontrol.machine_friction {
2249                friction[k] = 0.0;
2250            }
2251        }
2252        let setpoints = (0..motors)
2253            .map(|k| [pos[k], (ahead[k] - behind[k]) / (2.0 * h), motor_acc[k], ff[k], friction[k]])
2254            .collect();
2255        // Fieldbus: the drives get the newest frame that has arrived, one the controller computed some cycles ago. With
2256        // jitter each frame takes its own number of cycles, and a late one leaves the drives the frame before. Frames
2257        // older than the longest delay have arrived and are dropped; before any has arrived, the oldest.
2258        let late = if self.fieldbus_jitter > 0 {
2259            (self.jitter.uniform() * (self.fieldbus_jitter + 1) as f64) as usize
2260        } else {
2261            0
2262        };
2263        self.fieldbus.push_back((self.fieldbus_delay + late, setpoints));
2264        self.fieldbus_pushed += 1;
2265        // (The longest stamp in the queue, not the configured delay: after a cycle change the queue drains by itself.)
2266        let longest =
2267            self.fieldbus.iter().map(|f| f.0).max().unwrap_or(0).max(self.fieldbus_delay + self.fieldbus_jitter);
2268        while self.fieldbus.len() > longest + 1 {
2269            self.fieldbus.pop_front();
2270        }
2271        let newest = self.fieldbus.len() - 1;
2272        let arrived = (0..=newest).find(|&age| self.fieldbus[newest - age].0 <= age).map_or(0, |age| newest - age);
2273        let number = self.fieldbus_pushed - (self.fieldbus.len() - arrived) as u64;
2274        let fresh = number != self.fieldbus_held;
2275        self.fieldbus_held = number;
2276        for (drive, &[pos, vel, acc, ff, friction]) in self.drives.iter_mut().zip(&self.fieldbus[arrived].1) {
2277            (drive.pos_set, drive.vel_set, drive.acc_set, drive.torque_ff) = (pos, vel, acc, ff);
2278            drive.friction_ff = friction;
2279            if fresh {
2280                drive.since_setpoint = 0.0;
2281            }
2282        }
2283    }
2284
2285    /// What the torque-band monitor expects besides the feedforward at `pose`: for a motor with the constant-inertia
2286    /// feedforward (no gravity in it) the rigid model's torque at rest there, the weight; 0 for the others and without
2287    /// the monitor.
2288    fn holding_torque(&self, machine: &dyn Machine, pose: &[f64]) -> Vec<f64> {
2289        let wanted = |k: usize| {
2290            self.monitoring
2291                && self.motor_params[k].precontrol.constant_inertia
2292                && self.fault_settings.get(k).is_some_and(|s| s.torque_band > 0.0)
2293        };
2294        let mut out = vec![0.0; self.drives.len()];
2295        if (0..out.len()).any(wanted) {
2296            let still = vec![0.0; pose.len()];
2297            machine.feedforward_torque_moving(pose, &still, &still, &mut out);
2298            for (k, torque) in out.iter_mut().enumerate() {
2299                if !wanted(k) {
2300                    *torque = 0.0;
2301                }
2302            }
2303        }
2304        out
2305    }
2306
2307    /// The torque feedforward per motor (before its weight): the rigid model's inverse dynamics, or, for a motor whose
2308    /// drive has `drive.torque_feedforward_model = "inertia"`, its constant moment of inertia (`rigid_inertias`) times
2309    /// its acceleration setpoint.
2310    fn torque_feedforward(
2311        &self,
2312        machine: &dyn Machine,
2313        pos: &[f64],
2314        vel: &[f64],
2315        acc: &[f64],
2316        motor_acc: &[f64],
2317        out: &mut [f64],
2318    ) {
2319        machine.feedforward_torque_moving(pos, vel, acc, out);
2320        for (k, torque) in out.iter_mut().enumerate() {
2321            if self.motor_params[k].precontrol.constant_inertia {
2322                *torque = self.inertias[k] * motor_acc[k];
2323            }
2324        }
2325    }
2326
2327    /// Half the period in profile cycles of the first shaper and of the second (0 without one) with the plan at `pose`:
2328    /// as configured, or, when the shaper follows the pose, that of the resonance the machine reports there for the
2329    /// first and that of its second mode (`Machine::sway_modes`) for the second; one the machine does not report stays as
2330    /// configured. `None` with the shaper off.
2331    pub fn shaper_halves(&self, machine: &dyn Machine, pose: &[f64]) -> Option<(f64, f64)> {
2332        let halves = self.mode_halves(machine, pose)?;
2333        Some((halves[0], halves[1]))
2334    }
2335
2336    /// Half the period in profile cycles of every mode of the shaper with the plan at `pose` (see `shaper_halves`; the
2337    /// modes of `profile.shaper_modes` keep theirs).
2338    fn mode_halves(&self, machine: &dyn Machine, pose: &[f64]) -> Option<Vec<f64>> {
2339        let modes = self.shaper.as_ref()?;
2340        let following = modes.iter().any(|m| m.follows.is_some());
2341        let reported = if following { machine.sway_modes(pose) } else { Vec::new() };
2342        Some(
2343            modes
2344                .iter()
2345                .map(|m| match m.follows {
2346                    Some((0, per_hz)) if m.half > 0.0 => machine.resonance_hz(pose).map_or(m.half, |f| per_hz / f),
2347                    Some((k, per_hz)) if m.half > 0.0 => reported.get(k).map_or(m.half, |mode| per_hz / mode.hz),
2348                    _ => m.half,
2349                })
2350                .collect(),
2351        )
2352    }
2353
2354    /// Per axis the impulses of the shaper with the modes at the half periods `halves`: the modes acting on the axis
2355    /// convolved, times in profile cycles, amplitudes adding up to one.
2356    fn trains(&self, halves: &[f64]) -> Vec<Vec<(f64, f64)>> {
2357        let modes = self.shaper.as_deref().unwrap_or_default();
2358        (0..self.set_pos.len())
2359            .map(|axis| {
2360                modes.iter().zip(halves).filter(|(m, half)| m.axes[axis] && **half > 0.0).fold(
2361                    vec![(0.0, 1.0)],
2362                    |train, (m, half)| {
2363                        let scaled: Vec<(f64, f64)> = m.impulses.iter().map(|(t, a)| (t * half, *a)).collect();
2364                        shaper::convolve(&train, &scaled)
2365                    },
2366                )
2367            })
2368            .collect()
2369    }
2370
2371    /// How many profile cycles the shaped setpoint arrives after the plan with the plan at `pose`: the longest of the
2372    /// axes' shapers; on the ramp to a changed machine's period (`shape`) with the longer of the two. 0 with the shaper
2373    /// off.
2374    pub fn shaper_span(&self, machine: &dyn Machine, pose: &[f64]) -> f64 {
2375        self.mode_halves(machine, pose).map_or(0.0, |halves| {
2376            let ramp = self.ramp_offset(self.tick as f64);
2377            span(&self.trains(&halves.iter().zip(ramp).map(|(h, e)| h.max(h + e)).collect::<Vec<_>>()))
2378        })
2379    }
2380
2381    /// With the plan at `pose`: per axis how far the shaped setpoint lags a plan at a constant speed (the mean of the
2382    /// shaper's delays, s), and how long after the plan it arrives (`shaper_span`, s). Zeros with the shaper off.
2383    pub fn shaper_delays(&self, machine: &dyn Machine, pose: &[f64]) -> (Vec<f64>, f64) {
2384        let Some(halves) = self.mode_halves(machine, pose) else { return (vec![0.0; self.set_pos.len()], 0.0) };
2385        let dt = self.profile_cycle;
2386        let trains = self.trains(&halves);
2387        let mean = trains.iter().map(|train| train.iter().map(|(t, a)| t * a).sum::<f64>() * dt).collect();
2388        (mean, self.shaper_span(machine, pose) * dt)
2389    }
2390
2391    /// Per mode what the ramps to a changed machine's period (`shaper_ramps`) still add to the half period at the
2392    /// profile tick `x`: each step from where the period was to where it is now, going over by `smoothstep`.
2393    fn ramp_offset(&self, x: f64) -> Vec<f64> {
2394        let mut offset = vec![0.0; self.shaper.as_ref().map_or(0, Vec::len)];
2395        for (step, at, length) in &self.shaper_ramps {
2396            let left = 1.0 - smoothstep((x - at) / length);
2397            offset.iter_mut().zip(step).for_each(|(o, s)| *o += s * left);
2398        }
2399        offset
2400    }
2401
2402    /// Notes the motion that makes the setpoints of the profile tick `tick` (`plans`), unless it is the one before.
2403    fn record_plan(&mut self, tick: u64, motion: &Motion, machine: &dyn Machine) {
2404        if self.shaper.is_none() {
2405            self.plan_changed_at = None;
2406            return;
2407        }
2408        let pass = self.pass.as_ref().filter(|_| matches!(motion, Motion::Conveyor));
2409        let key = plan_key(motion, pass, tick);
2410        let from = self.plan_changed_at.take();
2411        if from.is_none() && self.plans.back().is_some_and(|plan| plan.key == key) {
2412            return;
2413        }
2414        let mut motion = motion.clone();
2415        // Its start as it takes it (`profile_tick`).
2416        match &mut motion {
2417            Motion::Moving { start_tick, .. }
2418            | Motion::Cam { start_tick, .. }
2419            | Motion::Trajectory { start_tick, .. }
2420                if *start_tick == u64::MAX =>
2421            {
2422                *start_tick = tick
2423            }
2424            Motion::Following { start_tick, .. } | Motion::Halting { start_tick, .. } if *start_tick == u64::MAX => {
2425                *start_tick = tick - 1
2426            }
2427            _ => {}
2428        }
2429        let pass = pass.map(|pass| (pass.clone(), self.clock));
2430        let cam = KeptCurve(if matches!(motion, Motion::Cam { .. }) { machine.cam_curve() } else { None });
2431        self.plans.push_back(Plan { first: tick, key, motion, pass, cam, from });
2432    }
2433
2434    /// The plan as `plan` makes it at the profile tick `x`, also between two cycles: position, speed and acceleration,
2435    /// worked out as the profile does at a cycle (`profile_tick`). `None` where the plan stands where the cycle before
2436    /// left it (idle, a dwell, waiting for a part).
2437    fn plan_at(&self, machine: &dyn Machine, plan: &Plan, x: f64) -> Option<[Vec<f64>; 3]> {
2438        let dt = self.profile_cycle;
2439        let n = self.set_pos.len();
2440        let (mut pos, mut vel, mut acc) = (vec![0.0; n], vec![0.0; n], vec![0.0; n]);
2441        let since = |start: u64| (x - start as f64) * dt;
2442        match &plan.motion {
2443            Motion::Idle | Motion::Dwell { .. } => return None,
2444            Motion::Moving { mv, start_tick, tail } => {
2445                let old = tail.as_ref().map(|(old, start)| (old, since(*start)));
2446                move_at(mv, since(*start_tick), old, [&mut pos, &mut vel, &mut acc]);
2447            }
2448            Motion::Conveyor => {
2449                // The simulated time runs with the profile cycles.
2450                let (pass, clock) = plan.pass.as_ref()?;
2451                let t = clock + since(plan.first) - pass.start;
2452                if t < 0.0 {
2453                    return None;
2454                }
2455                pass.at(t, &mut pos, &mut vel, &mut acc);
2456                if t >= pass.duration() {
2457                    vel.fill(0.0);
2458                    acc.fill(0.0);
2459                }
2460            }
2461            Motion::Cam { start_tick, stop, from, offset, from_speed, speed, ramp, .. } => {
2462                let t = since(*start_tick);
2463                let run = crate::cam::master_change(*from_speed, *speed, *ramp, t, *stop);
2464                // The cam as it was when the plan was noted, also after a config has changed it.
2465                let curve = |m: f64, cam: &mut [[f64; 4]]| match &plan.cam.0 {
2466                    Some(curve) => curve(m, cam),
2467                    None => machine.cam_at(m, cam),
2468                };
2469                cam_slaves(&curve, from + run[0], run, offset, [&mut pos, &mut vel, &mut acc]);
2470                if stop.is_some_and(|s| t >= s.max(*ramp) + ramp) {
2471                    vel.fill(0.0);
2472                    acc.fill(0.0);
2473                }
2474            }
2475            Motion::Trajectory { points, speeds, accelerations, start_tick } => {
2476                let t = since(*start_tick);
2477                path_at(points, speeds, accelerations.as_deref(), t, dt, [&mut pos, &mut vel, &mut acc]);
2478            }
2479            Motion::Following { from, to, start_tick } => {
2480                let ticks = self.setpoint_ticks as f64;
2481                let done = ((x - *start_tick as f64) / ticks).clamp(0.0, 1.0);
2482                line_at(from, to, done, ticks * dt, [&mut pos, &mut vel, &mut acc]);
2483            }
2484            Motion::Halting { from, vel: speed, time, start_tick } => {
2485                halt(from, speed, *time, since(*start_tick).clamp(0.0, *time), [&mut pos, &mut vel, &mut acc]);
2486            }
2487        }
2488        Some([pos, vel, acc])
2489    }
2490
2491    /// Input shaping: on each axis the setpoints become a weighted sum of copies of the plan at the delays of its
2492    /// shaper (`shaper::impulses`): ZVD three copies, now, half a period and a whole period ago, weighted 1 : 2K : K^2;
2493    /// ZV, ZVDD, EI and the two-hump EI likewise with their own (`profile.shaper_type`). The vibration each copy starts
2494    /// is cancelled by the others, also when the resonance is some percent off the frequency the shaper was set to.
2495    /// Every further mode's shaper is convolved with it (the second shaper, `profile.shaper_modes`): copies at the sums
2496    /// of the delays with the products of the weights, so that each mode's vibration is cancelled. An axis takes the
2497    /// modes that act on it (`profile.shaper_axes`, a mode's `axes`). A copy between two cycles is the plan itself
2498    /// there (`plan_at`), not an interpolation of the cycles around it.
2499    ///
2500    /// Following the pose, the half period is that of the resonance the machine reports where the plan
2501    /// stands, and the second shaper's that of the machine's second mode there. The weights always add up to one, so
2502    /// once the plan has stood still for a whole period the setpoint is the plan exactly, whatever the period did on the
2503    /// way. Where the machine itself changes its modes (the gripper takes its payload), the period does not step with
2504    /// it: a step in the delays would move the copies to other points of the plan at once, a step in the setpoint
2505    /// wherever the plan has not stood still for the whole period. The step goes over on a quintic smoothstep instead,
2506    /// long enough that no delay changes faster than `SHAPER_RAMP_RATE` of the time passing.
2507    fn shape(&mut self, machine: &dyn Machine) {
2508        // The shaped position is x_s(t) = sum w_i x(t - D_i(t)) / sum w_i (D_i the impulses' delays in seconds, which
2509        // change with the period). Its exact rates are x_s' = sum w_i v (1 - D_i') / W and x_s'' = sum w_i (a (1 - D_i')^2
2510        // - v D_i'') / W, v and a the plan's D_i ago. With steady delays this is the plain weighted sum of the plan's rates.
2511        let Some(target) = self.mode_halves(machine, &self.raw_pos) else {
2512            self.history.clear();
2513            self.plans.clear();
2514            self.shaper_reach = 0;
2515            (self.shaper_ramps, self.shaper_targets) = (Vec::new(), None);
2516            return;
2517        };
2518        let following = self.shaper.iter().flatten().any(|m| m.follows.is_some());
2519        let now = self.tick as f64;
2520        // The machine itself changed since the last cycle where its modes at the last cycle's pose did: from that cycle
2521        // on, the half periods go over from where they were. (At a pose that stands, the modes now are `target`.)
2522        if following
2523            && let (Some(before), Some(past)) = (self.shaper_targets.take(), self.history.back())
2524            && let Some(after) =
2525                if past[0] == self.raw_pos { Some(target.clone()) } else { self.mode_halves(machine, &past[0]) }
2526            && after.len() == before.len()
2527            && before != after
2528        {
2529            let step: Vec<f64> = before.iter().zip(&after).map(|(b, a)| b - a).collect();
2530            // The longest delay's change bounds every delay's; the smoothstep's steepest slope is 1.875.
2531            let reach = span(&self.trains(&step.iter().map(|s| s.abs()).collect::<Vec<_>>()));
2532            self.shaper_ramps.push((step, now - 1.0, 1.875 * reach / SHAPER_RAMP_RATE));
2533        }
2534        self.shaper_ramps.retain(|(_, at, length)| now - 1.0 - at < *length);
2535        let ramped = |halves: Vec<f64>, x: f64| -> Vec<f64> {
2536            halves.iter().zip(self.ramp_offset(x)).map(|(h, e)| h + e).collect()
2537        };
2538        let trains = self.trains(&ramped(target.clone(), now));
2539        // D_i' and D_i'' where the period follows the pose: the delays (cycles) with the plan one cycle ahead and one
2540        // behind on its own Taylor expansion and the ramps there, central differences: D' = (d+ - d-) / 2,
2541        // D'' = (d+ - 2 d + d-) / T (1/s).
2542        let cycle = self.profile_cycle;
2543        let zeros = || trains.iter().map(|train| [vec![0.0; train.len()], vec![0.0; train.len()]]).collect();
2544        let changes: Vec<[Vec<f64>; 2]> = if !following {
2545            zeros()
2546        } else {
2547            // A plan at rest is there a cycle ahead and behind too.
2548            let resting = self.raw_vel.iter().chain(&self.raw_acc).all(|r| *r == 0.0);
2549            let off = |sign: f64| -> Option<Vec<Vec<(f64, f64)>>> {
2550                if resting {
2551                    return Some(self.trains(&ramped(target.clone(), now + sign)));
2552                }
2553                let pose: Vec<f64> = (self.raw_pos.iter().zip(&self.raw_vel).zip(&self.raw_acc))
2554                    .map(|((x, v), a)| x + sign * v * cycle + 0.5 * a * cycle * cycle)
2555                    .collect();
2556                Some(self.trains(&ramped(self.mode_halves(machine, &pose)?, now + sign)))
2557            };
2558            match (off(1.0), off(-1.0)) {
2559                (Some(ahead), Some(behind)) => (trains.iter().zip(ahead.iter().zip(&behind)))
2560                    .map(|(now, (ahead, behind))| {
2561                        if ahead.len() != now.len() || behind.len() != now.len() {
2562                            return [vec![0.0; now.len()], vec![0.0; now.len()]];
2563                        }
2564                        let d = |k: usize| (ahead[k].0, now[k].0, behind[k].0);
2565                        let rate = (0..now.len()).map(|k| (d(k).0 - d(k).2) / 2.0).collect();
2566                        [rate, (0..now.len()).map(|k| (d(k).0 - 2.0 * d(k).1 + d(k).2) / cycle).collect()]
2567                    })
2568                    .collect(),
2569                _ => zeros(),
2570            }
2571        };
2572        if following {
2573            self.shaper_targets = Some(target);
2574        }
2575        self.history.push_back([self.raw_pos.clone(), self.raw_vel.clone(), self.raw_acc.clone()]);
2576        // The store keeps the longest span met so far: a period that grows again finds its past.
2577        self.shaper_reach = self.shaper_reach.max(span(&trains).ceil() as usize + 2);
2578        while self.history.len() > self.shaper_reach {
2579            self.history.pop_front();
2580        }
2581        let newest = self.history.len() - 1;
2582        // The motions of the stored cycles but the oldest, which is read only as stored.
2583        let oldest = self.tick - newest as u64;
2584        while self.plans.len() > 1
2585            && self.plans[1].first <= oldest + 1
2586            && self.plans[1].from.is_none_or(|from| from <= oldest as f64)
2587        {
2588            self.plans.pop_front();
2589        }
2590        // The plan `delay` cycles ago: at a whole cycle as stored, between two the plan itself there; before the store
2591        // reaches back that far, its oldest.
2592        let ago = |delay: f64| -> [Vec<f64>; 3] {
2593            let whole = delay.floor() as usize;
2594            if whole >= newest {
2595                return self.history[0].clone();
2596            }
2597            let owner = newest - whole;
2598            if delay == delay.floor() {
2599                return self.history[owner].clone();
2600            }
2601            let (tick, x) = (self.tick - whole as u64, now - delay);
2602            let plan =
2603                self.plans.iter().rev().find(|plan| plan.first <= tick && plan.from.is_none_or(|from| from <= x));
2604            plan.and_then(|plan| self.plan_at(machine, plan, x)).unwrap_or_else(|| {
2605                let n = self.set_pos.len();
2606                [self.history[owner - 1][0].clone(), vec![0.0; n], vec![0.0; n]]
2607            })
2608        };
2609        // Each delay read once: the axes that share their modes share their delays.
2610        let mut read: Vec<(f64, [Vec<f64>; 3])> = Vec::new();
2611        for (delay, _) in trains.iter().flatten() {
2612            if !read.iter().any(|(d, _)| d == delay) {
2613                read.push((*delay, ago(*delay)));
2614            }
2615        }
2616        let at = |delay: f64| &read.iter().find(|(d, _)| *d == delay).expect("every delay is read").1;
2617        let shaped = |which: usize, axis: usize| {
2618            let train = &trains[axis];
2619            let [rate, second] = &changes[axis];
2620            // The plan's position, speed and acceleration `delay` ago, and what the delay's own change does to each.
2621            let term = |k: usize, delay: f64| match which {
2622                0 => at(delay)[0][axis],
2623                1 => at(delay)[1][axis] * (1.0 - rate[k]),
2624                _ => at(delay)[2][axis] * (1.0 - rate[k]).powi(2) - at(delay)[1][axis] * second[k],
2625            };
2626            train.iter().enumerate().map(|(k, (delay, weight))| weight * term(k, *delay)).sum::<f64>()
2627                / train.iter().map(|(_, weight)| weight).sum::<f64>()
2628        };
2629        let axes = self.set_pos.len();
2630        let (pos, vel, acc): (Vec<f64>, Vec<f64>, Vec<f64>) = (
2631            (0..axes).map(|a| shaped(0, a)).collect(),
2632            (0..axes).map(|a| shaped(1, a)).collect(),
2633            (0..axes).map(|a| shaped(2, a)).collect(),
2634        );
2635        (self.set_pos, self.set_vel, self.set_acc) = (pos, vel, acc);
2636    }
2637
2638    /// Corner blending: the next cycle segment, if it should start now, while `current` still has
2639    /// time `t` behind it and its braking ahead. The corner is rounded instead of stopped at.
2640    ///
2641    /// Only where the machine does not have to stop anyway (no dwell, no gripper action), where no
2642    /// axis reverses, and only while both moves are on their ramps, so the speeds add up to no
2643    /// more than either cruise speed.
2644    fn blend_into_next(
2645        &mut self,
2646        current: &Move,
2647        t: f64,
2648        blending_already: bool,
2649        machine: &dyn Machine,
2650    ) -> Option<Move> {
2651        let i = self.cycle?;
2652        let segment = &self.segments[i];
2653        if self.blend_time <= 0.0
2654            || self.stopping
2655            || blending_already
2656            || segment.dwell_ticks > 0
2657            || segment.payload != self.payload_attached
2658        {
2659            return None;
2660        }
2661        let next_index = (i + 1) % self.segments.len();
2662        if self.segments[next_index].path.is_some() {
2663            return None;
2664        }
2665        let next = Move::with_law(
2666            &segment.target,
2667            &self.segments[next_index].target,
2668            machine.axes(),
2669            &self.segments[next_index].law,
2670        );
2671        if current.delta().iter().zip(next.delta()).any(|(a, b)| a * b < 0.0) || next.duration() == 0.0 {
2672            return None;
2673        }
2674        let lead = self.blend_time.min(current.brake()).min(next.ramp());
2675        if t < current.duration() - lead {
2676            return None;
2677        }
2678        self.cycle = Some(next_index);
2679        self.passes += (next_index == 0) as u64;
2680        Some(next)
2681    }
2682
2683    /// Cycle segment `i` has arrived at tick `tick`: its valve commands go out, and its dwell starts, or waits for its
2684    /// end-position sensors first (a dwell until `u64::MAX`, see `Motion::Dwell`).
2685    fn arrived(&mut self, i: usize, tick: u64) -> Motion {
2686        for &(valve, command) in &self.segments[i].valves {
2687            if let Some(v) = self.valves.get_mut(valve) {
2688                *v = command;
2689            }
2690        }
2691        // The dwell as `arrive` set it: the segment's, or the gripper's time if longer.
2692        let until_tick = if self.segments[i].wait.is_empty() { tick + self.dwell_ticks } else { u64::MAX };
2693        Motion::Dwell { until_tick }
2694    }
2695
2696    fn next_cycle_segment(&mut self, machine: &dyn Machine) {
2697        let Some(last) = self.cycle else { return };
2698        if self.stopping {
2699            self.cycle = None;
2700            self.stopping = false;
2701            return;
2702        }
2703        if let Some(CamMaster { speed, ramp_s: ramp, .. }) = self.cam {
2704            // The cam starts from where its master stands, the slaves from where they stand: the offset keeps them there.
2705            let mut cam = vec![[0.0; 4]; self.set_pos.len()];
2706            machine.cam_at(self.cam_master, &mut cam);
2707            let offset = self.set_pos.iter().zip(&cam).map(|(p, c)| p - c[0]).collect();
2708            self.cycle = Some(0);
2709            self.passes += 1;
2710            self.motion = Motion::Cam {
2711                start_tick: u64::MAX,
2712                stop: None,
2713                from: self.cam_master,
2714                offset,
2715                next_pass: f64::NAN,
2716                from_speed: 0.0,
2717                speed,
2718                ramp,
2719            };
2720            return;
2721        }
2722        if self.conveyor.is_some() {
2723            // Planned for the shaped setpoint: the part each axis's mean shaper delay ahead, and its grip and release
2724            // longer by the shaper's span (see `Conveyor::plan`).
2725            let shaping = self.shaper_delays(machine, &self.set_pos);
2726            let reachable = |pose: &[f64]| in_range(machine, pose);
2727            let Some(conveyor) = &mut self.conveyor else { return };
2728            self.pass = conveyor.plan(machine.axes(), self.clock, &self.set_pos, &reachable, &shaping);
2729            if self.pass.is_some() {
2730                self.passes += 1;
2731                self.motion = Motion::Conveyor;
2732            } else {
2733                // No part can be picked: the cycle ends.
2734                self.cycle = None;
2735            }
2736            return;
2737        }
2738        let next = (last + 1) % self.segments.len();
2739        self.cycle = Some(next);
2740        self.passes += (next == 0) as u64;
2741        // A path through via points, planned from where the plan stands; were it refused from there (the first segment,
2742        // from the start pose), the straight move. Timed as fast as the motors allow, the straight way too; refused, as
2743        // the axis limits time it.
2744        let segment = &self.segments[next];
2745        let straight = [Piece::Line(segment.target.clone())];
2746        let tolerance =
2747            path::Tolerance { corner: segment.corner.unwrap_or(self.path_tolerance.corner), ..self.path_tolerance };
2748        let time_optimal = (self.cycle_time_optimal && !at_target(&self.set_pos, &segment.target))
2749            .then(|| {
2750                let pieces = segment.path.as_deref().unwrap_or(&straight);
2751                self.plan_time_optimal_from(machine, &self.set_pos, pieces, tolerance)
2752            })
2753            .and_then(|planned| planned.ok());
2754        let planned = time_optimal.or_else(|| {
2755            self.segments[next].path.as_ref().and_then(|pieces| {
2756                let (cycle, slack) = (self.profile_cycle, machine.setpoint_slack());
2757                let spin = self.segments[next].law.spin;
2758                path::plan_within(machine.axes(), spin, &self.set_pos, pieces, &[], cycle, tolerance, slack).ok()
2759            })
2760        });
2761        self.motion = match planned {
2762            Some(points) if points.iter().all(|(_, pose)| near_start(machine, &self.set_pos, pose)) => {
2763                trajectory(points, self.spline_c2)
2764            }
2765            _ => Motion::Moving {
2766                mv: Move::with_law(
2767                    &self.set_pos,
2768                    &self.segments[next].target,
2769                    machine.axes(),
2770                    &self.segments[next].law,
2771                ),
2772                start_tick: u64::MAX,
2773                tail: None,
2774            },
2775        };
2776    }
2777}
2778
2779/// A path given as poses at times as the controller runs it: a cubic through them, at rest at both ends. With `c2`
2780/// the cubic spline whose acceleration is continuous at every point (`c2_speeds`); without, the speed at each point is
2781/// the slope between its neighbours (of the four around it where they are evenly spaced), and the acceleration steps at
2782/// each point.
2783fn trajectory(points: Vec<(f64, Vec<f64>)>, c2: bool) -> Motion {
2784    let speeds = if c2 { c2_speeds(&points) } else { neighbour_speeds(&points) };
2785    Motion::Trajectory { points, speeds, accelerations: None, start_tick: u64::MAX }
2786}
2787
2788/// The speeds at the points of the Hermite cubics through them that make one C2 spline, clamped at rest at both ends:
2789/// with h the spacing before and h' after point i, the acceleration of the cubic before (6 (p_i-1 - p_i) / h^2 +
2790/// (2 m_i-1 + 4 m_i) / h) equals that of the cubic after (6 (p_i+1 - p_i) / h'^2 - (4 m_i + 2 m_i+1) / h'), which is
2791/// m_i-1 / h + 2 m_i (1/h + 1/h') + m_i+1 / h' = 3 ((p_i - p_i-1) / h^2 + (p_i+1 - p_i) / h'^2) for every inner point:
2792/// a tridiagonal system, diagonally dominant, solved by elimination (Thomas).
2793pub(crate) fn c2_speeds(points: &[(f64, Vec<f64>)]) -> Vec<Vec<f64>> {
2794    let (n, axes) = (points.len(), points[0].1.len());
2795    let mut speeds = vec![vec![0.0; axes]; n];
2796    if n < 3 {
2797        return speeds;
2798    }
2799    let h = |i: usize| points[i + 1].0 - points[i].0;
2800    for a in 0..axes {
2801        let p = |i: usize| points[i].1[a];
2802        // Forward elimination over the inner points 1 ..= n - 2: c' and d' of the Thomas algorithm.
2803        let (mut c, mut d) = (vec![0.0; n], vec![0.0; n]);
2804        for i in 1..n - 1 {
2805            let (lower, upper) = (1.0 / h(i - 1), 1.0 / h(i));
2806            let diagonal = 2.0 * (lower + upper);
2807            let rhs = 3.0 * ((p(i) - p(i - 1)) * lower * lower + (p(i + 1) - p(i)) * upper * upper);
2808            // Point 0 is at rest: no lower term for i = 1.
2809            let (l, c_prev, d_prev) = if i == 1 { (0.0, 0.0, 0.0) } else { (lower, c[i - 1], d[i - 1]) };
2810            let pivot = diagonal - l * c_prev;
2811            c[i] = upper / pivot;
2812            d[i] = (rhs - l * d_prev) / pivot;
2813        }
2814        // Back substitution; the last point is at rest.
2815        let mut next = 0.0;
2816        for i in (1..n - 1).rev() {
2817            next = d[i] - c[i] * next;
2818            speeds[i][a] = next;
2819        }
2820    }
2821    speeds
2822}
2823
2824/// The speeds as before 14 November 2026 (`profile.trajectory_spline = "hermite"`): at each inner point the slope
2825/// between its neighbours, of the five points around it where they are evenly spaced.
2826fn neighbour_speeds(points: &[(f64, Vec<f64>)]) -> Vec<Vec<f64>> {
2827    let axes = points[0].1.len();
2828    let mut speeds = vec![vec![0.0; axes]; points.len()];
2829    let n = points.len();
2830    for i in 1..n - 1 {
2831        // Evenly spaced on both sides (rows of a trace, a plan's profile cycles): the slope of the five points around it,
2832        // exact for a cubic, so that the acceleration at each point is the curve's own. The slope of the two neighbours
2833        // is off by jerk x spacing^2 / 6, which put the acceleration off by jerk x spacing.
2834        let even = i >= 2 && i + 2 < n && {
2835            let h = points[i + 1].0 - points[i].0;
2836            (1..=4).all(|k| ((points[i + k - 2].0 - points[i + k - 3].0) - h).abs() <= 1e-6 * h)
2837        };
2838        for a in 0..axes {
2839            speeds[i][a] = if even {
2840                let p = |k: usize| points[k].1[a];
2841                (p(i - 2) - 8.0 * p(i - 1) + 8.0 * p(i + 1) - p(i + 2)) / (3.0 * (points[i + 2].0 - points[i - 2].0))
2842            } else {
2843                (points[i + 1].1[a] - points[i - 1].1[a]) / (points[i + 1].0 - points[i - 1].0)
2844            };
2845        }
2846    }
2847    speeds
2848}
2849
2850/// Position, speed and acceleration of axis `a` at time `t` on the cubic from point i to point i + 1 with the speeds
2851/// there (Hermite interpolation).
2852pub(crate) fn hermite(points: &[(f64, Vec<f64>)], speeds: &[Vec<f64>], i: usize, a: usize, t: f64) -> [f64; 3] {
2853    let h = points[i + 1].0 - points[i].0;
2854    let s = (t - points[i].0) / h;
2855    let basis = [
2856        [
2857            2.0 * s * s * s - 3.0 * s * s + 1.0,
2858            s * s * s - 2.0 * s * s + s,
2859            -2.0 * s * s * s + 3.0 * s * s,
2860            s * s * s - s * s,
2861        ],
2862        [6.0 * s * s - 6.0 * s, 3.0 * s * s - 4.0 * s + 1.0, -6.0 * s * s + 6.0 * s, 3.0 * s * s - 2.0 * s],
2863        [12.0 * s - 6.0, 6.0 * s - 4.0, -12.0 * s + 6.0, 6.0 * s - 2.0],
2864    ];
2865    let at = |b: [f64; 4]| {
2866        b[0] * points[i].1[a] + b[1] * h * speeds[i][a] + b[2] * points[i + 1].1[a] + b[3] * h * speeds[i + 1][a]
2867    };
2868    [at(basis[0]), at(basis[1]) / h, at(basis[2]) / (h * h)]
2869}
2870
2871/// The fieldbus queue (frames of setpoints newest last, each with the cycles it takes to arrive) for a profile cycle
2872/// `ratio` of the old ones to a new one: at age `b` new cycles stands what the old queue had at age `b / ratio` old
2873/// cycles, between two frames in proportion (as the shaper's history), and the delay is scaled with it, so every frame
2874/// arrives at the same time in seconds. Interpolated, not repeated: the drives take every frame as a fresh setpoint.
2875fn resample_fieldbus(
2876    old: &std::collections::VecDeque<(usize, Vec<[f64; 5]>)>,
2877    ratio: f64,
2878) -> std::collections::VecDeque<(usize, Vec<[f64; 5]>)> {
2879    let Some(newest) = old.len().checked_sub(1) else { return Default::default() };
2880    (0..=(newest as f64 * ratio).floor() as usize)
2881        .rev()
2882        .map(|back| {
2883            let (whole, part) = ((back as f64 / ratio).floor() as usize, (back as f64 / ratio).fract());
2884            let (a, b) = (&old[newest - whole.min(newest)], &old[newest - (whole + 1).min(newest)]);
2885            let stamp = ((a.0 as f64 * (1.0 - part) + b.0 as f64 * part) * ratio).round() as usize;
2886            let frames = a.1.iter().zip(&b.1).map(|(a, b)| std::array::from_fn(|k| a[k] * (1.0 - part) + b[k] * part));
2887            (stamp, frames.collect())
2888        })
2889        .collect()
2890}
2891
2892/// A move `t` s after its start; with corner blending the previous move's remaining way to the corner on top, `old` with
2893/// its own time.
2894fn move_at(mv: &Move, t: f64, old: Option<(&Move, f64)>, [pos, vel, acc]: [&mut Vec<f64>; 3]) {
2895    mv.at(t, pos, vel, acc);
2896    if let Some((old, t_old)) = old {
2897        let n = pos.len();
2898        let (mut p, mut v, mut a, mut end) = (vec![0.0; n], vec![0.0; n], vec![0.0; n], vec![0.0; n]);
2899        old.at(t_old, &mut p, &mut v, &mut a);
2900        old.at(f64::INFINITY, &mut end, &mut vec![0.0; n], &mut vec![0.0; n]);
2901        for i in 0..n {
2902            pos[i] += p[i] - end[i];
2903            vel[i] += v[i];
2904            acc[i] += a[i];
2905        }
2906    }
2907}
2908
2909/// The ramp to rest from `from` at the speeds `vel` over `time` s, `t` s into it.
2910fn halt(from: &[f64], vel: &[f64], time: f64, t: f64, [pos, speed, acc]: [&mut Vec<f64>; 3]) {
2911    for i in 0..from.len() {
2912        pos[i] = from[i] + vel[i] * (t - 0.5 * t * t / time);
2913        speed[i] = vel[i] * (1.0 - t / time);
2914        acc[i] = if t < time { -vel[i] / time } else { 0.0 };
2915    }
2916}
2917
2918/// The cam's slaves (`curve`, as `Machine::cam_at`) with the master at `master` and its speed and acceleration in `run`,
2919/// each from its `offset`.
2920fn cam_slaves(
2921    curve: &dyn Fn(f64, &mut [[f64; 4]]),
2922    master: f64,
2923    run: [f64; 3],
2924    offset: &[f64],
2925    [pos, vel, acc]: [&mut Vec<f64>; 3],
2926) {
2927    let mut cam = vec![[0.0; 4]; pos.len()];
2928    curve(master, &mut cam);
2929    for (i, c) in cam.iter().enumerate() {
2930        let [p, v, a] = crate::cam::slave_motion(*c, run);
2931        (pos[i], vel[i], acc[i]) = (p + offset[i], v, a);
2932    }
2933}
2934
2935/// A trajectory through `points` `t` s after its start (profile cycle `dt`), at its end its last point at rest.
2936fn path_at(
2937    points: &[(f64, Vec<f64>)],
2938    speeds: &[Vec<f64>],
2939    accelerations: Option<&[Vec<f64>]>,
2940    t: f64,
2941    dt: f64,
2942    [pos, vel, acc]: [&mut Vec<f64>; 3],
2943) {
2944    let last = points.len() - 1;
2945    if t >= points[last].0 {
2946        pos.copy_from_slice(&points[last].1);
2947        vel.fill(0.0);
2948        acc.fill(0.0);
2949        return;
2950    }
2951    // A point a rounding error after `t` counts as at `t`: at a point the cubic that starts there is taken, not by the
2952    // rounding of the two times the end of the one before, whose acceleration differs. Before the start, the start.
2953    let i = points.partition_point(|(time, _)| *time <= t + 1e-6 * dt).saturating_sub(1).min(last - 1);
2954    let t = t.max(points[0].0);
2955    for a in 0..pos.len() {
2956        [pos[a], vel[a], acc[a]] = match accelerations {
2957            Some(accelerations) => quintic(points, speeds, accelerations, i, a, t),
2958            None => hermite(points, speeds, i, a, t),
2959        };
2960    }
2961}
2962
2963/// A setpoint from outside approached on a straight line, `done` of the way from `from` to `to` in `time` s.
2964fn line_at(from: &[f64], to: &[f64], done: f64, time: f64, [pos, vel, acc]: [&mut Vec<f64>; 3]) {
2965    for i in 0..to.len() {
2966        // At the end the target itself, not from + (to - from), which can be a rounding off it.
2967        pos[i] = if done < 1.0 { from[i] + (to[i] - from[i]) * done } else { to[i] };
2968        // The speed of the cycle that ends here, also on arrival: in a stream the next setpoint is on its way, and a
2969        // speed of zero for this one cycle would be a dip in every interval.
2970        vel[i] = (to[i] - from[i]) / time;
2971    }
2972    acc.fill(0.0);
2973}
2974
2975/// What tells a motion that makes the setpoints from one taken over by another (`Plan`): its kind and its start ticks
2976/// (`u64::MAX`, not yet taken, counts as `tick`), a cam's stop, a conveyor's pass by its start. Idle and a dwell are
2977/// the same: the plan stands.
2978fn plan_key(motion: &Motion, pass: Option<&Pass>, tick: u64) -> [u64; 4] {
2979    let at = |start: u64, before: u64| if start == u64::MAX { tick - before } else { start };
2980    match motion {
2981        Motion::Idle | Motion::Dwell { .. } => [0, 0, 0, 0],
2982        Motion::Moving { start_tick, tail, .. } => {
2983            [1, at(*start_tick, 0), tail.as_ref().map_or(u64::MAX, |(_, start)| *start), 0]
2984        }
2985        Motion::Following { start_tick, .. } => [2, at(*start_tick, 1), 0, 0],
2986        Motion::Conveyor => [3, pass.map_or(u64::MAX, |pass| pass.start.to_bits()), 0, 0],
2987        Motion::Cam { start_tick, stop, .. } => [4, at(*start_tick, 0), stop.map_or(u64::MAX, f64::to_bits), 0],
2988        Motion::Trajectory { start_tick, .. } => [5, at(*start_tick, 0), 0, 0],
2989        Motion::Halting { start_tick, .. } => [6, at(*start_tick, 1), 0, 0],
2990    }
2991}
2992
2993/// The longest delay of per-axis impulse trains (`Controller::trains`), cycles.
2994fn span(trains: &[Vec<(f64, f64)>]) -> f64 {
2995    trains.iter().flatten().fold(0.0, |m: f64, (t, _)| m.max(*t))
2996}
2997
2998/// The quintic smoothstep 10 u^3 - 15 u^4 + 6 u^5 from 0 to 1, held at its ends: no step in its slope or its
2999/// curvature, the steepest slope 1.875 at u = 1/2.
3000fn smoothstep(u: f64) -> f64 {
3001    let u = u.clamp(0.0, 1.0);
3002    u * u * u * (10.0 - 15.0 * u + 6.0 * u * u)
3003}
3004
3005/// Position, speed and acceleration of axis `a` at time `t` on the quintic from point i to point i + 1 with the speeds
3006/// and accelerations there (Hermite interpolation of the fifth degree): at the points exactly those given.
3007fn quintic(
3008    points: &[(f64, Vec<f64>)],
3009    speeds: &[Vec<f64>],
3010    accelerations: &[Vec<f64>],
3011    i: usize,
3012    a: usize,
3013    t: f64,
3014) -> [f64; 3] {
3015    let h = points[i + 1].0 - points[i].0;
3016    let s = (t - points[i].0) / h;
3017    let (s2, s3, s4, s5) = (s * s, s * s * s, s.powi(4), s.powi(5));
3018    // The basis functions of p0, h v0, h² a0, h² a1, h v1, p1 and their first and second derivatives in s.
3019    let basis = [
3020        [
3021            1.0 - 10.0 * s3 + 15.0 * s4 - 6.0 * s5,
3022            s - 6.0 * s3 + 8.0 * s4 - 3.0 * s5,
3023            0.5 * s2 - 1.5 * s3 + 1.5 * s4 - 0.5 * s5,
3024            0.5 * s3 - s4 + 0.5 * s5,
3025            -4.0 * s3 + 7.0 * s4 - 3.0 * s5,
3026            10.0 * s3 - 15.0 * s4 + 6.0 * s5,
3027        ],
3028        [
3029            -30.0 * s2 + 60.0 * s3 - 30.0 * s4,
3030            1.0 - 18.0 * s2 + 32.0 * s3 - 15.0 * s4,
3031            s - 4.5 * s2 + 6.0 * s3 - 2.5 * s4,
3032            1.5 * s2 - 4.0 * s3 + 2.5 * s4,
3033            -12.0 * s2 + 28.0 * s3 - 15.0 * s4,
3034            30.0 * s2 - 60.0 * s3 + 30.0 * s4,
3035        ],
3036        [
3037            -60.0 * s + 180.0 * s2 - 120.0 * s3,
3038            -36.0 * s + 96.0 * s2 - 60.0 * s3,
3039            1.0 - 9.0 * s + 18.0 * s2 - 10.0 * s3,
3040            3.0 * s - 12.0 * s2 + 10.0 * s3,
3041            -24.0 * s + 84.0 * s2 - 60.0 * s3,
3042            60.0 * s - 180.0 * s2 + 120.0 * s3,
3043        ],
3044    ];
3045    let given = [
3046        points[i].1[a],
3047        h * speeds[i][a],
3048        h * h * accelerations[i][a],
3049        h * h * accelerations[i + 1][a],
3050        h * speeds[i + 1][a],
3051        points[i + 1].1[a],
3052    ];
3053    let at = |b: &[f64; 6]| b.iter().zip(&given).map(|(b, g)| b * g).sum::<f64>();
3054    [at(&basis[0]), at(&basis[1]) / h, at(&basis[2]) / (h * h)]
3055}
3056
3057/// A string of the config.
3058fn text<'a>(cfg: &'a Config, path: &str) -> Result<&'a str> {
3059    cfg.get(path)?.as_str().ok_or_else(|| ConfigError::Type(path.into()))
3060}
3061
3062/// The axes a list of axis ids names (`profile.shaper_axes`, a mode's `axes`): every axis for an empty list.
3063fn named_axes(machine: &dyn Machine, ids: Option<&toml::Value>, path: &str) -> Result<Vec<bool>> {
3064    let bad = || ConfigError::Invalid(path.into());
3065    let axes = machine.axes();
3066    let ids: Vec<&str> = match ids {
3067        None => Vec::new(),
3068        Some(list) => {
3069            list.as_array().ok_or_else(bad)?.iter().map(|v| v.as_str()).collect::<Option<_>>().ok_or_else(bad)?
3070        }
3071    };
3072    if ids.iter().any(|id| !axes.iter().any(|a| a.id == *id)) {
3073        return Err(bad());
3074    }
3075    Ok(axes.iter().map(|a| ids.is_empty() || ids.contains(&a.id)).collect())
3076}
3077
3078/// The input shaper of a config (see `Controller::shape`), `None` with `effects.input_shaping` off: the first mode
3079/// (`profile.shaper_frequency_hz`, `shaper_damping`), the second (`shaper2_frequency_hz`, `shaper2_damping`; half period
3080/// 0 at 0 Hz), both of `profile.shaper_type` on `profile.shaper_axes`, following the pose with
3081/// `effects.shaper_follows_pose`; then each entry of `profile.shaper_modes` (`frequency_hz`, `damping`, and `type` and
3082/// `axes` where it has them), fixed. A value out of its range is refused also with shaping off.
3083fn shaper_modes(cfg: &Config, machine: &dyn Machine, profile_cycle: f64) -> Result<Option<Vec<ShaperMode>>> {
3084    let kind_of = |name: Option<&str>, path: &str| {
3085        name.and_then(shaper::Kind::from_name).ok_or_else(|| ConfigError::Invalid(path.into()))
3086    };
3087    let kind = kind_of(Some(text(cfg, "profile.shaper_type")?), "profile.shaper_type")?;
3088    let tolerance = cfg.positive("profile.shaper_ei_tolerance")?;
3089    if tolerance >= 1.0 {
3090        return Err(ConfigError::Invalid("profile.shaper_ei_tolerance".into()));
3091    }
3092    let axes = named_axes(machine, Some(cfg.get("profile.shaper_axes")?), "profile.shaper_axes")?;
3093    let (frequency, damping) =
3094        (cfg.positive("profile.shaper_frequency_hz")?, cfg.non_negative("profile.shaper_damping")?);
3095    if damping >= 1.0 {
3096        return Err(ConfigError::Invalid("profile.shaper_damping".into()));
3097    }
3098    let (frequency2, damping2) =
3099        (cfg.non_negative("profile.shaper2_frequency_hz")?, cfg.non_negative("profile.shaper2_damping")?);
3100    if damping2 >= 1.0 {
3101        return Err(ConfigError::Invalid("profile.shaper2_damping".into()));
3102    }
3103    let follows = cfg.bool("effects.shaper_follows_pose")?;
3104    // Half the damped period in profile cycles, per Hz.
3105    let per_hz = |damping: f64| 0.5 / (1.0 - damping * damping).sqrt() / profile_cycle;
3106    let mode = |kind, frequency: f64, damping: f64, axes: Vec<bool>, follow: Option<usize>| ShaperMode {
3107        impulses: shaper::impulses(kind, damping, tolerance),
3108        half: if frequency > 0.0 { per_hz(damping) / frequency } else { 0.0 },
3109        follows: follow.filter(|_| follows).map(|k| (k, per_hz(damping))),
3110        axes,
3111    };
3112    let mut modes =
3113        vec![mode(kind, frequency, damping, axes.clone(), Some(0)), mode(kind, frequency2, damping2, axes, Some(1))];
3114    for (i, entry) in cfg.array("profile.shaper_modes")?.iter().enumerate() {
3115        let path = format!("profile.shaper_modes[{i}]");
3116        let bad = || ConfigError::Invalid(path.clone());
3117        let number = |key: &str| entry.get(key).and_then(|v| v.as_float().or_else(|| v.as_integer().map(|i| i as f64)));
3118        let frequency = number("frequency_hz").filter(|f| f.is_finite() && *f > 0.0).ok_or_else(bad)?;
3119        let damping = number("damping").filter(|d| (0.0..1.0).contains(d)).ok_or_else(bad)?;
3120        let kind = match entry.get("type") {
3121            None => kind,
3122            Some(name) => kind_of(name.as_str(), &path)?,
3123        };
3124        modes.push(mode(kind, frequency, damping, named_axes(machine, entry.get("axes"), &path)?, None));
3125    }
3126    Ok(cfg.bool("effects.input_shaping")?.then_some(modes))
3127}
3128
3129/// The motion law of a config's moves (`profile.shape`, `deceleration_ratio`, and `vertical_axis` with
3130/// `up_acceleration_ratio`: an axis id, "-" before it where up is its minus direction, "" for none). The ratios are
3131/// shares of the axes' limits, above 0 and at most 1.
3132fn motion_law(cfg: &Config, machine: &dyn Machine) -> Result<MotionLaw> {
3133    let shape =
3134        Shape::from_name(text(cfg, "profile.shape")?).ok_or_else(|| ConfigError::Invalid("profile.shape".into()))?;
3135    let share = |path: &str| {
3136        let v = cfg.positive(path)?;
3137        if v <= 1.0 { Ok(v) } else { Err(ConfigError::Invalid(path.into())) }
3138    };
3139    let (deceleration_ratio, up_ratio) =
3140        (share("profile.deceleration_ratio")?, share("profile.up_acceleration_ratio")?);
3141    let vertical = match text(cfg, "profile.vertical_axis")? {
3142        "" => None,
3143        name => {
3144            let (up, id) = name.strip_prefix('-').map_or((1.0, name), |id| (-1.0, id));
3145            let axis = machine.axes().iter().position(|a| a.id == id);
3146            Some((axis.ok_or_else(|| ConfigError::Invalid("profile.vertical_axis".into()))?, up, up_ratio))
3147        }
3148    };
3149    // The flange's own limits, where the machine has them as limits of the plan (an arm in tool space).
3150    let checks = machine.rating_checks();
3151    let limit = |name: &str| checks.iter().find(|c| c.check == name && c.signal.starts_with("plan.")).map(|c| c.limit);
3152    let spin = limit("tool-angular-speed").zip(limit("tool-angular-acceleration")).map(|(w, a)| [w, a]);
3153    Ok(MotionLaw { shape, deceleration_ratio, vertical, spin })
3154}
3155
3156/// A segment that starts on its target (within 1 nm on every axis) has no way to time: it is a move of no length.
3157fn at_target(from: &[f64], target: &[f64]) -> bool {
3158    from.iter().zip(target).all(|(f, t)| (f - t).abs() < 1e-9)
3159}
3160
3161pub(crate) fn in_range(machine: &dyn Machine, target: &[f64]) -> bool {
3162    near_range(machine, target, 0.0)
3163}
3164
3165/// A config's pose at `path` that `in_range` refuses: with the machine's own reason where it gives one (out of reach,
3166/// beyond a joint's stop), so that every front end shows the place and the reason; outside an axis range, as a value
3167/// out of range.
3168fn range_error(machine: &dyn Machine, target: &[f64], path: String) -> ConfigError {
3169    let axes = machine.axes();
3170    let within =
3171        target.len() == axes.len() && target.iter().zip(axes).all(|(t, a)| t.is_finite() && *t >= a.min && *t <= a.max);
3172    match within.then(|| machine.unreachable(target, 0.0)).flatten() {
3173        Some(why) => ConfigError::Part(why, path),
3174        None => ConfigError::Invalid(path),
3175    }
3176}
3177
3178/// A pose a path from `start` may go to. The setpoint at rest is where the motors stand, up to
3179/// `Machine::setpoint_slack` from the tool (at an end of a stroke, beyond it), so a path may start that far outside
3180/// the range or the envelope, and no further: a pose within the slack of the start is judged with the slack; any other
3181/// within the range, except that on an axis whose start lies beyond an end it may stay as far beyond as the start is
3182/// (a path along that end), and within the envelope, with the slack only if the start is outside it. Until 13 November 2026 every pose had the slack,
3183/// which let a delta's path run 1.4 mm beyond its 0.6 m range where a move there was refused.
3184fn near_start(machine: &dyn Machine, start: &[f64], pose: &[f64]) -> bool {
3185    let slack = machine.setpoint_slack();
3186    if pose.len() == start.len() && pose.iter().zip(start).map(|(p, s)| (p - s) * (p - s)).sum::<f64>().sqrt() <= slack
3187    {
3188        return near_range(machine, pose, slack);
3189    }
3190    let axes = machine.axes();
3191    let beyond = |s: f64, a: &sim_core::AxisInfo| ((a.min - s).clamp(0.0, slack), (s - a.max).clamp(0.0, slack));
3192    pose.len() == axes.len()
3193        && start.len() == axes.len()
3194        && pose.iter().zip(start).zip(axes).all(|((t, s), a)| {
3195            t.is_finite() && *t >= a.min - beyond(*s, a).0 - ROUNDING && *t <= a.max + beyond(*s, a).1 + ROUNDING
3196        })
3197        && machine
3198            .unreachable(pose, ROUNDING + if machine.unreachable(start, 0.0).is_some() { slack } else { 0.0 })
3199            .is_none()
3200}
3201
3202/// What a pose away from the start may be off the range by rounding alone: an arc along the rim of a cylindrical
3203/// range samples points a hair beyond it, and was refused with no allowance.
3204const ROUNDING: f64 = 1e-9;
3205
3206/// `in_range`, with every axis range wider by `slack` at both ends, and the machine's own envelope too
3207/// (`Machine::unreachable`).
3208fn near_range(machine: &dyn Machine, target: &[f64], slack: f64) -> bool {
3209    let axes = machine.axes();
3210    target.len() == axes.len()
3211        && target.iter().zip(axes).all(|(t, a)| t.is_finite() && *t >= a.min - slack && *t <= a.max + slack)
3212        && machine.unreachable(target, slack).is_none()
3213}
3214
3215/// A target that a move or a setpoint cannot go to, with the reason: outside an axis range, or where the machine says
3216/// it cannot reach (out of reach, outside its envelope, beyond a joint's stop), in its own words. Up to `ROUNDING`
3217/// beyond is rounding: a pose read back through the kinematics at an end of a stroke lies that far out (the planar
3218/// delta's tool at rest at x = 0.4 m reads 0.40000000000000013), and a move back there was refused.
3219fn refuse_target(machine: &dyn Machine, target: &[f64]) -> std::result::Result<(), CommandError> {
3220    let axes = machine.axes();
3221    if target.len() != axes.len()
3222        || !target.iter().zip(axes).all(|(t, a)| t.is_finite() && *t >= a.min - ROUNDING && *t <= a.max + ROUNDING)
3223    {
3224        return Err(CommandError { key: "error-target-out-of-range" });
3225    }
3226    machine.unreachable(target, ROUNDING).map_or(Ok(()), |key| Err(CommandError { key }))
3227}
3228
3229/// With `Machine::cam`: per tool axis (a slave) the highest speed, acceleration and jerk the cam asks of it at the
3230/// master's steady speed (the cam's first three rates over the master times v, v^2 and v^3) over a period, at 4000 points; empty
3231/// without a cam. `check_limits` reports them against the axis limits, the verdicts judge them (`analysis`).
3232pub fn cam_peaks(machine: &dyn Machine) -> Vec<[f64; 3]> {
3233    let Some(master) = machine.cam() else { return Vec::new() };
3234    let axes = machine.axes().len();
3235    let n = 4000;
3236    let mut peak = vec![[0f64; 3]; axes];
3237    let mut cam = vec![[0.0; 4]; axes];
3238    for i in 0..=n {
3239        machine.cam_at(master.period * i as f64 / n as f64, &mut cam);
3240        for (p, c) in peak.iter_mut().zip(&cam) {
3241            for k in 0..3 {
3242                p[k] = p[k].max(c[k + 1].abs() * master.speed.powi(k as i32 + 1));
3243            }
3244        }
3245    }
3246    peak
3247}
3248
3249/// An axis limit that asks more of a motor than the drive allows; `key` is a translation key.
3250#[derive(Debug, Clone, PartialEq)]
3251pub struct LimitViolation {
3252    pub key: &'static str,
3253    pub motor: usize,
3254    pub needed: f64,
3255    pub allowed: f64,
3256}
3257
3258/// Checks that the axis limits do not ask more of a motor than its drive and motor allow (`drives`, each motor's own, in
3259/// the order of `Machine::motors`): the motor speed at the highest axis speeds against the motor's maximum speed
3260/// (`DriveParams::max_speed`), and the torque of the rigid machine at the highest axis accelerations against its
3261/// torque-speed curve at that speed (or the torque of the drive's maximum current, where lower). A diagonal move loads
3262/// one motor with both axes, so every combination of axis directions is tried, at the middle pose.
3263///
3264/// A warning about the axis limits, not a verdict: it takes every axis at its highest speed and acceleration at once,
3265/// which a cycle need not ask. So nothing is refused by it; the search simulates every candidate and the verdicts judge
3266/// what the cycle asks ("motor-peak" against the curve, "motor-speed" against the maximum speed).
3267pub fn check_limits(machine: &dyn Machine, drives: &[&DriveParams]) -> Vec<LimitViolation> {
3268    let (axes, motors) = (machine.axes(), machine.motors().len());
3269    let pose = sim_core::testkit::mid_pose(machine);
3270    let (mut speed, mut torque) = (vec![0f64; motors], vec![0f64; motors]);
3271    let (mut a, mut b) = (vec![0.0; motors], vec![0.0; motors]);
3272    for combo in 0..1u32 << axes.len() {
3273        let sign = |i: usize| if combo >> i & 1 == 1 { 1.0 } else { -1.0 };
3274        let h = 1e-3;
3275        let shifted = |s: f64| -> Vec<f64> {
3276            axes.iter().enumerate().map(|(i, ax)| pose[i] + s * h * sign(i) * ax.max_vel).collect()
3277        };
3278        machine.inverse(&shifted(1.0), &mut a);
3279        machine.inverse(&shifted(-1.0), &mut b);
3280        let acc: Vec<f64> = axes.iter().enumerate().map(|(i, ax)| sign(i) * ax.max_acc).collect();
3281        for k in 0..motors {
3282            speed[k] = speed[k].max(((a[k] - b[k]) / (2.0 * h)).abs());
3283        }
3284        machine.feedforward_torque(&pose, &acc, &mut a);
3285        for k in 0..motors {
3286            torque[k] = torque[k].max(a[k].abs());
3287        }
3288    }
3289    let mut out = Vec::new();
3290    // An electronic cam asks of its slaves what it asks at the master's speed, whatever the axis limits say.
3291    for (i, (p, axis)) in cam_peaks(machine).iter().zip(axes).enumerate() {
3292        let keys = ["limit-cam-speed", "limit-cam-acceleration", "limit-cam-jerk"];
3293        for (k, allowed) in [axis.max_vel, axis.max_acc, axis.max_jerk].into_iter().enumerate() {
3294            if p[k] > allowed * (1.0 + 1e-9) {
3295                out.push(LimitViolation { key: keys[k], motor: i.min(motors - 1), needed: p[k], allowed });
3296            }
3297        }
3298    }
3299    for (k, drive) in drives.iter().enumerate().take(motors) {
3300        if speed[k] > drive.max_speed {
3301            out.push(LimitViolation { key: "limit-motor-speed", motor: k, needed: speed[k], allowed: drive.max_speed });
3302        }
3303        // Accelerating at that speed: the curve there, driving.
3304        let curve = drive.torque_curve(speed[k].min(drive.max_speed)).1;
3305        let allowed = if drive.drive_max_current.is_finite() {
3306            curve.min(drive.torque_of(drive.drive_max_current))
3307        } else {
3308            curve
3309        };
3310        if torque[k] > allowed {
3311            out.push(LimitViolation { key: "limit-motor-torque", motor: k, needed: torque[k], allowed });
3312        }
3313    }
3314    out
3315}
3316
3317#[cfg(test)]
3318mod tests {
3319    use super::*;
3320
3321    /// Acceleration of axis 0 just before and just after point i of a curve through `points` with `speeds`.
3322    fn around(points: &[(f64, Vec<f64>)], speeds: &[Vec<f64>], i: usize) -> (f64, f64) {
3323        (hermite(points, speeds, i - 1, 0, points[i].0)[2], hermite(points, speeds, i, 0, points[i].0)[2])
3324    }
3325
3326    /// The fieldbus queue of four frames, oldest first setpoints 0, 1, 2, 3 and delays 3, 2, 1, 0 cycles, after the
3327    /// profile cycle halves (ratio 2): seven frames (3 * 2 + 1); newest first the new ages 0..6 read the old ages 0,
3328    /// 0.5, .., 3, so the setpoints are 3, 2.5, .., 0 and the delays (old 0, 0.5, .., 3 doubled) 0, 1, .., 6: every
3329    /// frame arrives at the same time in seconds, and none repeats its neighbour (the drives take each as fresh).
3330    #[test]
3331    fn the_fieldbus_queue_keeps_its_delay_in_seconds_across_a_cycle_change() {
3332        let queue: std::collections::VecDeque<(usize, Vec<[f64; 5]>)> =
3333            (0..4).map(|k| (3 - k, vec![[k as f64; 5]])).collect();
3334        let new = resample_fieldbus(&queue, 2.0);
3335        assert_eq!(new.iter().rev().map(|f| f.0).collect::<Vec<_>>(), [0, 1, 2, 3, 4, 5, 6]);
3336        let set: Vec<f64> = new.iter().rev().map(|f| f.1[0][0]).collect();
3337        assert_eq!(set, [3.0, 2.5, 2.0, 1.5, 1.0, 0.5, 0.0]);
3338        // The same ratio back: the original stamps and frames (new ages 0, 2, 4, 6).
3339        let back = resample_fieldbus(&new, 0.5);
3340        assert_eq!(back, queue);
3341    }
3342
3343    /// The quintic of `Command::RatedTrajectory` is a polynomial of the fifth degree where the points' positions, speeds
3344    /// and accelerations are its own: p(t) = 1 - 2 t + 3 t^2 + t^3 - 4 t^4 + 0.5 t^5, points at 0.2 s and 0.7 s, by hand
3345    /// at 0.45 s (position, speed and acceleration of the polynomial), and the given values at both points.
3346    #[test]
3347    fn the_quintic_reproduces_a_fifth_degree_polynomial() {
3348        let c = [1.0, -2.0, 3.0, 1.0, -4.0, 0.5];
3349        let p = |t: f64, d: usize| -> f64 {
3350            (d..6).map(|k| c[k] * (k - d + 1..=k).map(|f| f as f64).product::<f64>() * t.powi((k - d) as i32)).sum()
3351        };
3352        let points = vec![(0.2, vec![p(0.2, 0)]), (0.7, vec![p(0.7, 0)])];
3353        let (speeds, accelerations) = (vec![vec![p(0.2, 1)], vec![p(0.7, 1)]], vec![vec![p(0.2, 2)], vec![p(0.7, 2)]]);
3354        for t in [0.2, 0.45, 0.7] {
3355            let got = quintic(&points, &speeds, &accelerations, 0, 0, t);
3356            for d in 0..3 {
3357                assert!((got[d] - p(t, d)).abs() < 1e-12, "at {t} s, derivative {d}: {} against {}", got[d], p(t, d));
3358            }
3359        }
3360    }
3361
3362    /// The C2 spline through (0 s, 0 m), (1 s, 1 m) and (3 s, 1 m), at rest at both ends. Its one inner speed m solves
3363    /// m 2 (1/1 + 1/2) = 3 ((1 - 0) / 1^2 + (1 - 1) / 2^2): m = 1 m/s. The acceleration before the point,
3364    /// 6 (0 - 1) / 1 + (2 * 0 + 4 * 1) / 1 = -2 m/s^2, equals that after it, 6 (1 - 1) / 4 - (4 * 1 + 0) / 2 = -2 m/s^2.
3365    /// The slope of the neighbours (1 - 0) / 3 = 1/3 m/s gives -4.667 before and -0.667 after: a step of 4 m/s^2.
3366    #[test]
3367    fn the_c2_import_has_a_continuous_acceleration_at_a_knot() {
3368        let points = vec![(0.0, vec![0.0]), (1.0, vec![1.0]), (3.0, vec![1.0])];
3369        let c2 = c2_speeds(&points);
3370        assert!((c2[1][0] - 1.0).abs() < 1e-12 && c2[0][0] == 0.0 && c2[2][0] == 0.0, "{c2:?}");
3371        let (before, after) = around(&points, &c2, 1);
3372        assert!((before + 2.0).abs() < 1e-12 && (after + 2.0).abs() < 1e-12, "{before} {after}");
3373        let old = neighbour_speeds(&points);
3374        let (before, after) = around(&points, &old, 1);
3375        assert!((before + 14.0 / 3.0).abs() < 1e-12 && (after + 2.0 / 3.0).abs() < 1e-12, "{before} {after}");
3376        // Uneven spacing and two axes: continuous at every inner point, and through every point.
3377        let points: Vec<(f64, Vec<f64>)> = [(0.0, 0.0), (0.3, 0.2), (0.5, 0.25), (1.2, -0.1), (1.3, 0.0), (2.0, 0.4)]
3378            .iter()
3379            .map(|&(t, x)| (t, vec![x, 2.0 * x * x]))
3380            .collect();
3381        let c2 = c2_speeds(&points);
3382        for i in 1..points.len() - 1 {
3383            for a in 0..2 {
3384                let (before, after) =
3385                    (hermite(&points, &c2, i - 1, a, points[i].0)[2], hermite(&points, &c2, i, a, points[i].0)[2]);
3386                assert!((before - after).abs() < 1e-9 * (1.0 + before.abs()), "point {i}, axis {a}: {before} {after}");
3387                assert!((hermite(&points, &c2, i, a, points[i].0)[0] - points[i].1[a]).abs() < 1e-15);
3388            }
3389        }
3390    }
3391}