Skip to main content

sim_components/
sim.rs

1//! A machine, its controller and the integrator, stepped together. Every front end runs this.
2
3use crate::control::{Command, CommandError, Controller, LimitViolation, check_limits, in_range};
4use sim_core::{
5    Config, ConfigError, LOSS_PREFIX, Machine, MachineEntry, Obstacle, Rk4, Scene, SignalInfo, TEMPERATURE_PREFIX,
6    ThermalPart, advance,
7};
8
9/// A part of the machine that warms with its loss power (`Machine::thermal_parts`, effects.part_heating): one thermal
10/// mass with a thermal resistance R to its surroundings, so that its temperature rise follows
11/// tau d(rise)/dt = R P - rise and settles at R P under a steady loss P.
12#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
13pub struct HeatedPart {
14    /// The machine's, not written: a simulation built from the same config has it (`Sim::restore`).
15    #[serde(skip)]
16    pub part: ThermalPart,
17    /// Where its loss power is among the machine's loss powers (`Machine::loss_powers`).
18    loss: usize,
19    /// Its loss power at the end of the last step, W; kept up to date only while it warms (effects.part_heating).
20    pub loss_power: f64,
21    /// K/W, s, and the rise it is rated for, K.
22    pub resistance: f64,
23    pub time_constant: f64,
24    pub max_rise: f64,
25    /// Temperature above the surroundings, K.
26    pub rise: f64,
27}
28
29/// The parts of `machine` that warm, with their values from the config; the rises start at zero.
30fn heated_parts(cfg: &Config, machine: &dyn Machine) -> Result<Vec<HeatedPart>, ConfigError> {
31    let infos: Vec<SignalInfo> = machine.signal_infos().into_iter().filter(|s| s.id.starts_with(LOSS_PREFIX)).collect();
32    let mut parts = Vec::new();
33    for part in machine.thermal_parts() {
34        let key = |name: &str| format!("thermal.{}_{name}", part.kind);
35        let loss = infos
36            .iter()
37            .position(|s| s.id == format!("{LOSS_PREFIX}{}", part.id))
38            .ok_or_else(|| ConfigError::Invalid(format!("{LOSS_PREFIX}{}", part.id)))?;
39        let (resistance, time_constant) = match machine.thermal_values(part.id) {
40            Some(own) => own,
41            None => (cfg.non_negative(&key("resistance_k_w"))?, cfg.positive(&key("time_constant_s"))?),
42        };
43        let max_rise = cfg.positive(&key("max_rise_k"))?;
44        parts.push(HeatedPart { part, loss, loss_power: 0.0, resistance, time_constant, max_rise, rise: 0.0 });
45    }
46    Ok(parts)
47}
48
49/// How near an obstacle a part has to come before the obstacle's push is worked out (effects.crash, `Sim::pushes`), m:
50/// the push acts on the motors through the rigid kinematics, whose parts may be some millimetres from the real ones
51/// (a carriage swinging on its belt).
52const PUSH_RANGE: f64 = 0.01;
53
54/// How many times finer the integration's sub-steps are over a base step with a push at the tool: the contact's
55/// spring then acts on the load's own coordinates (not through the transmission's give), the highest frequency of the
56/// machine, and with `sim.substeps` = 4 the fourth-order steps took 3.5e-4 of the supply out of the budget of a belt
57/// gantry's move into a slab (2.8e-4 on a six-leg platform; falling with the third and second power of the sub-step),
58/// 5e-6 and 1.9e-5 four times finer (`sim-machines`' collision tests).
59const PUSH_SUBSTEPS: u32 = 4;
60/// The step in a motor's angle (or a linear motor's position) by which the slope of a clearance is worked out, by
61/// central differences.
62const SLOPE_STEP: f64 = 1e-6;
63
64/// An obstacle's push on the machine over one base step (effects.crash), linear in the motors' angles about where the
65/// step starts: the depth of the machine in it there (the clearance of the rigid kinematics at those angles, negated),
66/// how the clearance grows with each motor's angle (m/rad), and the obstacle's stiffness and damping.
67#[derive(Debug, Clone, PartialEq)]
68struct Push {
69    depth: f64,
70    slope: Vec<f64>,
71    stiffness: f64,
72    damping: f64,
73}
74
75impl Push {
76    /// The obstacle's force at the motor angles `angle` and speeds `speed`, N: the stiffness times the depth there plus
77    /// the damping times the speed into it, pushing only (an obstacle does not pull a part back).
78    fn force(&self, from: &[f64], angle: &[f64], speed: &[f64]) -> f64 {
79        let moved: f64 = self.slope.iter().zip(angle.iter().zip(from)).map(|(g, (a, f))| g * (a - f)).sum();
80        let into = -self.slope.iter().zip(speed).map(|(g, w)| g * w).sum::<f64>();
81        let depth = self.depth - moved;
82        if depth > 0.0 { (self.stiffness * depth + self.damping * into).max(0.0) } else { 0.0 }
83    }
84}
85
86/// The motor torques of the pushes, added to `out`: each force times its clearance's slope at the motor, which is the
87/// force's virtual work per radian. Returns the sum of the forces, N.
88fn push_torques(pushes: &[Push], from: &[f64], angle: &[f64], speed: &[f64], out: &mut [f64]) -> f64 {
89    let mut total = 0.0;
90    for push in pushes {
91        let force = push.force(from, angle, speed);
92        total += force;
93        for (torque, g) in out.iter_mut().zip(&push.slope) {
94            *torque += force * g;
95        }
96    }
97    total
98}
99
100/// The pushes' force on the contact coordinates (`Machine::contact_state`, the tool's by default) at `state`, one per
101/// coordinate (the generalised force: each push's force times its clearance's slope along it), the coordinates they
102/// were worked out at, and the sum of the forces, N.
103fn tool_push_forces(machine: &dyn Machine, pushes: &[Push], from: &[f64], state: &[f64]) -> (Vec<f64>, Vec<f64>, f64) {
104    let n = machine.contact_axes();
105    let (mut pos, mut vel, mut force, mut total) = (vec![0.0; n], vec![0.0; n], vec![0.0; n], 0.0);
106    machine.contact_state(state, &mut pos, &mut vel);
107    for push in pushes {
108        let f = push.force(from, &pos, &vel);
109        total += f;
110        force.iter_mut().zip(&push.slope).for_each(|(t, g)| *t += f * g);
111    }
112    (force, pos, total)
113}
114
115/// At one stage of the integration: the pushes' force on the tool at the mechanical state `mech`, given to the machine
116/// (`Machine::set_tool_force`), as the motors' pushes are worked out at every stage; returns the power they take out of
117/// the machine, -F . v, W. `pos`, `vel` and `force` are buffers as long as the contact coordinates.
118fn tool_push_stage(
119    machine: &mut dyn Machine,
120    pushes: &[Push],
121    from: &[f64],
122    mech: &[f64],
123    [pos, vel, force]: [&mut Vec<f64>; 3],
124) -> f64 {
125    machine.contact_state(mech, pos, vel);
126    force.fill(0.0);
127    for push in pushes {
128        let f = push.force(from, pos, vel);
129        force.iter_mut().zip(&push.slope).for_each(|(t, g)| *t += f * g);
130    }
131    machine.set_tool_force(force);
132    -force.iter().zip(vel.iter()).map(|(f, v)| f * v).sum::<f64>()
133}
134
135// Per drive in the integrated state: winding current, and since the start of the step the electrical energy, the
136// copper loss and the work on the shaft; then a stepper's or an induction motor's further states.
137use crate::drive::WINDING_STATES;
138
139pub struct Sim {
140    pub machine: Box<dyn Machine>,
141    pub control: Controller,
142    pub state: Vec<f64>,
143    pub torque: Vec<f64>,
144    pub step: u64,
145    pub dt: f64,
146    substeps: u32,
147    rk: Rk4,
148    /// For the steps with the drives enabled: the machine's state and per drive its winding current and the energies
149    /// of the step (`DriveParams::winding_rates`), integrated together; with the motors' angles and speeds and
150    /// torques at a stage of the integration.
151    rk_joint: Rk4,
152    joint: Vec<f64>,
153    motor_buffers: [Vec<f64>; 4],
154    /// The tool's pose, speed and push force at a stage of the integration (`tool_push_stage`), as long as the axes.
155    tool_buffers: [Vec<f64>; 3],
156    payload_attached: bool,
157    /// What switching the payload has added to the machine's energy since the start: a payload picked up brings
158    /// its energy along, one put down takes it away, unless the machine keeps it as a free body (the crane's with the
159    /// hook block and the floor: letting go books the sling's elastic energy alone, a pick of it where it lies nothing).
160    pub payload_energy: f64,
161    /// The work the obstacles' pushes took out of the machine since the start (effects.crash, `pushes`): what the
162    /// contacts' damping lost and their springs hold. For the energy budget.
163    pub crash_energy: f64,
164    /// Why the last pick was refused at the moment of the grip (`Machine::refuses_pick` at the tool's real pose).
165    pub pick_refused: Option<&'static str>,
166    /// Axis limits that exceed what the drives allow, found when the config was applied.
167    pub limit_violations: Vec<LimitViolation>,
168    /// The parts that warm with their losses, and whether they do (effects.part_heating, or effects.thermal_feedback,
169    /// which feeds back what this computes: `heats`). Their rises are signals
170    /// whether or not; switched off they stay as they are.
171    pub heated: Vec<HeatedPart>,
172    pub part_heating: bool,
173    /// Whether the machine's friction and losses follow the parts' rises (effects.thermal_feedback).
174    pub thermal_feedback: bool,
175    /// effects.thermal_warm_start: the cycle analysis measures its pass with the windings and parts at the rises they
176    /// settle at (`analysis::analyse_cycle_with`), not from cold.
177    pub warm_start: bool,
178    /// The machine's loss powers, for the heated parts.
179    losses: Vec<f64>,
180    /// The obstacles of the config (`collision::obstacles`), each marked while a part of the machine touches it.
181    pub obstacles: Vec<Obstacle>,
182    /// effects.crash: an obstacle pushes back on a part that goes into it, with its contact stiffness and damping
183    /// (`pushes`), so that the axes in contact are blocked; what trips the drives then is their monitoring
184    /// (effects.drive_monitoring).
185    pub crash: bool,
186    /// `profile.min_clearance_m`: the least clearance to the obstacles a time-optimal path may keep (`plan_path`).
187    pub min_clearance: f64,
188    /// The path the config's `[path]` gives in place of the cycle (`with_path`): what the analysis of the cycle runs
189    /// instead (`analysis::analyse_cycle_with`), and so the verdicts, the search and the optimiser. `None`: the cycle.
190    pub path: Option<PathRun>,
191    /// The clearance to the nearest obstacle after the last step, and the least since the start, m; infinite without
192    /// obstacles. Checked every base step.
193    pub clearance: f64,
194    pub least_clearance: f64,
195    /// The first contact with an obstacle since the start.
196    pub contact: Option<Contact>,
197    /// The machine's own parts against each other (`collision::PlanCheck::own`): joined as they are at the start pose,
198    /// looked at after the first base step and then every `OWN_PARTS_EVERY_S`, in the simulated state (a load that
199    /// swings, a machine that coasts); its least since the start is the verdict "self-collision".
200    pub own_parts: crate::collision::PlanCheck,
201    /// When the own parts were last looked at (s), `None` before the first look.
202    own_at: Option<f64>,
203    /// Whether the drives tripped (effects.drive_monitoring) while a part touched an obstacle, and have not been
204    /// enabled since. Which monitor, and the stopping distances, are in `control.fault`.
205    pub crashed: bool,
206    /// The obstacles' force on the machine over the last step (at its end), N.
207    pub contact_force: f64,
208    /// Per obstacle the clearance after the last step (`check_obstacles`).
209    gaps: Vec<f64>,
210    /// The obstacles' pushes over the step under way, and the motor angles they are linear about.
211    pushes: Vec<Push>,
212    push_from: Vec<f64>,
213    /// Whether the pushes of the step under way act on the tool's coordinates (`Machine::set_tool_force`; `push_from` and
214    /// the slopes are then about the tool pose) and not on the motors.
215    tool_push: bool,
216    /// The work the pushes have taken since the first contact, J.
217    absorbed: f64,
218    /// How many parts each sub-step of the step under way is cut into (`Machine::substeps_wanted`, at most `MOST_CUTS`).
219    cuts: u32,
220    /// How many base steps were cut finer for the machine (`cuts` above 1) since the start.
221    pub refined_steps: u64,
222}
223
224/// The first contact of a run with an obstacle: when (the end of the base step that found it, s), at which tool pose,
225/// how fast the tool went into it (the length of its speed vector at the start of that step, before a push braked it,
226/// axis units per second) and which obstacle. With
227/// effects.crash, from then on: the largest force of the obstacles on the machine (N) and the impact energy, the most
228/// work their pushes had taken out of the machine at any time (J; at the deepest point of a blocked impact, the
229/// kinetic energy the impact took).
230#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
231pub struct Contact {
232    pub time: f64,
233    pub pose: Vec<f64>,
234    pub speed: f64,
235    pub obstacle: usize,
236    pub peak_force: f64,
237    pub impact_energy: f64,
238}
239
240/// What a running simulation has come to apart from its machine (`Sim::snapshot`): the integrated state, the controller
241/// with its drives (loops, filters, windings, thermal and overload images), the parts' warmth and the obstacle record.
242/// `Sim::restore` takes it back into a simulation built from the same machine and config; what the machine itself keeps
243/// between steps (payload, brakes, dwelling, the parts' temperatures, its `memory`) is set again from it.
244#[derive(Clone, serde::Serialize, serde::Deserialize)]
245pub struct Snapshot {
246    control: Controller,
247    state: Vec<f64>,
248    /// `Machine::memory`: the gearboxes' hysteresis anchors, a tool-space arm's last inverse solution. Without them a
249    /// restored delta ran on some micrometres off the run it was taken from, the palletiser by rounding.
250    memory: Vec<f64>,
251    torque: Vec<f64>,
252    step: u64,
253    payload_attached: bool,
254    payload_energy: f64,
255    crash_energy: f64,
256    heated: Vec<HeatedPart>,
257    obstacles: Vec<Obstacle>,
258    clearance: f64,
259    least_clearance: f64,
260    contact: Option<Contact>,
261    #[serde(default)]
262    own: Option<crate::collision::SelfClearance>,
263    #[serde(default)]
264    own_at: Option<f64>,
265    crashed: bool,
266    contact_force: f64,
267    gaps: Vec<f64>,
268    absorbed: f64,
269}
270
271/// A path in place of the cycle (`[path]` of a config, see `with_path`): the text of a path file or a program
272/// (`program::read`), the file name that says which reader takes it, and whether it is timed as fast as the motors allow.
273#[derive(Debug, Clone, PartialEq)]
274pub struct PathRun {
275    pub file: String,
276    pub program: String,
277    pub time_optimal: bool,
278    /// `program.orientation_speed_rad_s`: how fast a robot program turns the tool (rad/s), 500 degrees per second where
279    /// the config has no key (`program::ORIENTATION_SPEED`).
280    pub orientation_speed: f64,
281}
282
283/// The config with `[path]` set: the analysis of the cycle runs this path (file name and text, as `--path FILE` reads
284/// it) instead, timed within the axis limits or with `time_optimal` as fast as the motors allow. An optional table
285/// (`analysis::RATINGS_BEYOND_DEFAULT`): a config without it runs its cycle.
286pub fn with_path(cfg: &Config, file: &str, program: &str, time_optimal: bool) -> Result<Config, ConfigError> {
287    let mut table: toml::Table =
288        cfg.to_text()?.parse().map_err(|e: toml::de::Error| ConfigError::Parse(e.to_string()))?;
289    let mut path = toml::Table::new();
290    path.insert("file".into(), file.into());
291    path.insert("program".into(), program.into());
292    path.insert("time_optimal".into(), time_optimal.into());
293    table.insert("path".into(), toml::Value::Table(path));
294    Config::parse(&toml::to_string(&table).map_err(|e| ConfigError::Parse(e.to_string()))?)
295}
296
297/// The config's `[path]` (`with_path`), `None` without it or with no program text.
298fn path_run(cfg: &Config) -> Result<Option<PathRun>, ConfigError> {
299    let text = |key: &str| -> Result<String, ConfigError> {
300        let path = format!("path.{key}");
301        Ok(cfg
302            .get(&path)
303            .ok()
304            .map(|v| v.as_str().map(str::to_string).ok_or(ConfigError::Type(path)))
305            .transpose()?
306            .unwrap_or_default())
307    };
308    let program = text("program")?;
309    if program.trim().is_empty() {
310        return Ok(None);
311    }
312    let time_optimal = cfg.get("path.time_optimal").is_ok() && cfg.bool("path.time_optimal")?;
313    let orientation_speed = crate::program::orientation_speed_of(cfg)?;
314    Ok(Some(PathRun { file: text("file")?, program, time_optimal, orientation_speed }))
315}
316
317/// Whether the parts warm with their losses: effects.part_heating, or effects.thermal_feedback, which needs their
318/// temperatures.
319pub fn heats(cfg: &Config) -> Result<bool, ConfigError> {
320    Ok(cfg.bool("effects.part_heating")? || cfg.bool("effects.thermal_feedback")?)
321}
322
323/// effects.thermal_warm_start; a config without the key (one written before 13 November 2026) starts cold.
324fn warm_start(cfg: &Config) -> Result<bool, ConfigError> {
325    Ok(cfg.get("effects.thermal_warm_start").is_ok() && cfg.bool("effects.thermal_warm_start")?)
326}
327
328fn timing(cfg: &Config) -> Result<(f64, u32), ConfigError> {
329    let substeps = cfg.positive("sim.substeps")?;
330    // The configs ship 2 to 4; a huge count (1e30 saturated to 4e9 a step) made every step hang.
331    if substeps.fract() != 0.0 || substeps > 1000.0 {
332        return Err(ConfigError::Invalid("sim.substeps".into()));
333    }
334    Ok((cfg.positive("sim.dt_s")?, substeps as u32))
335}
336
337/// A config file for a machine, as a front end loads it. The machine's default config is the schema: a key
338/// it does not have is refused by name, so that a misspelt key cannot pass silently. `[bounds]` has its own
339/// check (`analysis::bounds`), and a rating that the default config leaves out may be there.
340pub fn load_config(entry: &MachineEntry, text: &str) -> Result<Config, ConfigError> {
341    let cfg = Config::parse(text)?;
342    cfg.check_keys(&schema(entry, &cfg)?, &crate::analysis::RATINGS_BEYOND_DEFAULT)?;
343    Ok(cfg)
344}
345
346/// `Config::set_text` on a config of `entry`, which also adds a key the config has not got where a file of it may have
347/// it (`load_config`): a motor's own value of a shared key (`drive.<id>.velocity_kp_nm_s_rad`), a key of
348/// `analysis::RATINGS_BEYOND_DEFAULT`. A misspelt key is refused as by `set_text`.
349pub fn set_config_text(entry: &MachineEntry, cfg: &mut Config, assignment: &str) -> Result<(), ConfigError> {
350    match cfg.set_text(assignment) {
351        Err(ConfigError::Missing(_)) => {
352            cfg.set_text_within(assignment, &schema(entry, cfg)?, &crate::analysis::RATINGS_BEYOND_DEFAULT)
353        }
354        done => done,
355    }
356}
357
358/// `set_config_text` for `Config::set`.
359pub fn set_config(entry: &MachineEntry, cfg: &mut Config, path: &str, value: toml::Value) -> Result<(), ConfigError> {
360    match cfg.set(path, value.clone()) {
361        Err(ConfigError::Missing(_)) => {
362            cfg.set_within(path, value, &schema(entry, cfg)?, &crate::analysis::RATINGS_BEYOND_DEFAULT)
363        }
364        done => done,
365    }
366}
367
368/// `Config::hint` with the keys `set_config_text` may add among those a misspelt one is near.
369pub fn config_hint(entry: &MachineEntry, cfg: &Config, error: &ConfigError) -> Option<sim_core::ConfigHint> {
370    let schema = schema(entry, cfg).unwrap_or_else(|_| entry.config());
371    cfg.hint_within(error, &schema, &crate::analysis::RATINGS_BEYOND_DEFAULT)
372}
373
374/// The keys a config for `entry` may have: its default config's, and a motor's own table (`[motor.<id>]` and the rest
375/// of `catalog::PER_MOTOR_TABLES`) for every motor of the machine `cfg` builds and any motor `cfg` gives one, with the
376/// shared table's keys, though the default has none for that motor (a seven-joint URDF on the arm whose default has six).
377/// An id of a table that the machine built from `cfg` has no motor of is refused (`ConfigError::Invalid` with
378/// `<table>.<id>`), so a misspelt one is not silently unread. Where `cfg` does not build, the ids are not checked here:
379/// building it reports that error itself.
380pub fn schema(entry: &MachineEntry, cfg: &Config) -> Result<Config, ConfigError> {
381    let mut text = entry.default_config.to_string();
382    let default = entry.config();
383    let motors: Option<Vec<String>> = crate::catalog::resolve(entry, cfg)
384        .and_then(|resolved| (entry.build)(&resolved))
385        .ok()
386        .map(|machine| machine.motors().iter().map(|m| m.id.to_string()).collect());
387    for table in crate::catalog::PER_MOTOR_TABLES {
388        let Some(shared) = default.get(table).ok().and_then(|v| v.as_table()) else { continue };
389        let own = cfg.get(table).ok().and_then(|v| v.as_table()).into_iter().flatten();
390        // The tables `cfg` gives a motor, and one for every motor it could give one (what `set_within` may add).
391        let mut ids: Vec<&str> = own.filter(|(_, v)| v.is_table()).map(|(id, _)| id.as_str()).collect();
392        ids.extend(motors.iter().flatten().map(String::as_str).filter(|id| !id.is_empty()));
393        ids.sort_unstable();
394        ids.dedup();
395        for id in ids {
396            if shared.contains_key(id) {
397                continue;
398            }
399            if motors.as_ref().is_some_and(|m| !m.iter().any(|m| m == id)) {
400                return Err(ConfigError::Invalid(format!("{table}.{id}")));
401            }
402            text.push_str(&format!(
403                "
404[{table}.{id}]
405"
406            ));
407            for (key, value) in shared.iter().filter(|(_, v)| !v.is_table()) {
408                text.push_str(&format!(
409                    "{key} = {value}
410"
411                ));
412            }
413        }
414    }
415    Config::parse(&text)
416}
417
418/// The configured start pose: one finite position per axis, within its range. A machine set up beyond its
419/// stroke stands in its end stops, and one set up nowhere (NaN) has no state at all.
420pub(crate) fn start_pose(cfg: &Config, machine: &dyn Machine) -> Result<Vec<f64>, ConfigError> {
421    let pose = cfg.f64s("start.pose")?;
422    if in_range(machine, &pose) { Ok(pose) } else { Err(ConfigError::Invalid("start.pose".into())) }
423}
424
425/// How often the run looks at the machine's own parts (`Sim::own_parts`), s: a look draws the machine's parts, which on
426/// an arm costs about as much as a step. At 1 m/s the machine moves a millimetre in this time, the planned path's
427/// spacing.
428pub const OWN_PARTS_EVERY_S: f64 = 1e-3;
429
430impl Sim {
431    /// The machine at rest at its configured start pose.
432    pub fn new(entry: &MachineEntry, cfg: &Config) -> Result<Self, ConfigError> {
433        // Parts the config names bring their catalogue values; the caller's config keeps the names.
434        let cfg = &crate::catalog::resolve(entry, cfg)?;
435        let machine = (entry.build)(cfg)?;
436        let (dt, substeps) = timing(cfg)?;
437        let start = start_pose(cfg, machine.as_ref())?;
438        let min_clearance = cfg.non_negative("profile.min_clearance_m")?;
439        let mut state = Vec::new();
440        let mut torque = vec![0.0; machine.motors().len()];
441        machine.equilibrium(&start, &mut state, &mut torque);
442        let build = || (entry.build)(cfg);
443        let own_parts = crate::collision::PlanCheck::at_start(min_clearance, machine.as_ref(), &state, &start, build)?;
444        let control = Controller::new(cfg, machine.as_ref(), &state)?;
445        let limit_violations = check_limits(machine.as_ref(), &control.motor_drives(machine.as_ref()));
446        let (heated, part_heating) = (heated_parts(cfg, machine.as_ref())?, heats(cfg)?);
447        let motors = torque.len();
448        Ok(Self {
449            rk: Rk4::new(state.len()),
450            rk_joint: Rk4::new(state.len() + WINDING_STATES * motors + 1),
451            joint: Vec::new(),
452            motor_buffers: std::array::from_fn(|_| vec![0.0; motors]),
453            tool_buffers: Default::default(),
454            machine,
455            control,
456            state,
457            torque,
458            step: 0,
459            dt,
460            substeps,
461            payload_attached: true,
462            payload_energy: 0.0,
463            crash_energy: 0.0,
464            pick_refused: None,
465            limit_violations,
466            heated,
467            part_heating,
468            thermal_feedback: cfg.bool("effects.thermal_feedback")?,
469            warm_start: warm_start(cfg)?,
470            losses: Vec::new(),
471            obstacles: crate::collision::obstacles(cfg)?,
472            crash: cfg.bool("effects.crash")?,
473            min_clearance,
474            path: path_run(cfg)?,
475            clearance: f64::INFINITY,
476            least_clearance: f64::INFINITY,
477            contact: None,
478            own_parts,
479            own_at: None,
480            crashed: false,
481            contact_force: 0.0,
482            gaps: Vec::new(),
483            pushes: Vec::new(),
484            push_from: Vec::new(),
485            tool_push: false,
486            absorbed: 0.0,
487            cuts: 1,
488            refined_steps: 0,
489        })
490    }
491
492    /// Applies a changed config to the running simulation: parameters and effect switches take
493    /// effect from the next step, without a restart.
494    pub fn reconfigure(&mut self, entry: &MachineEntry, cfg: &Config) -> Result<(), ConfigError> {
495        let cfg = &crate::catalog::resolve(entry, cfg)?;
496        let mut machine = (entry.build)(cfg)?;
497        let (dt, substeps) = timing(cfg)?;
498        if dt != self.dt {
499            // The step counter is the clock; a new base step would make time jump.
500            return Err(ConfigError::Invalid("sim.dt_s".into()));
501        }
502        // Not used by a running simulation but for the own parts' joints, and a config it would not start with is
503        // refused all the same.
504        let start = start_pose(cfg, machine.as_ref())?;
505        // Everything that can refuse the config runs before anything changes: a refused reload leaves the old sim.
506        let mut heated = heated_parts(cfg, machine.as_ref())?;
507        let part_heating = heats(cfg)?;
508        let thermal_feedback = cfg.bool("effects.thermal_feedback")?;
509        let warm_start = warm_start(cfg)?;
510        let path = path_run(cfg)?;
511        let (obstacles, crash, min_clearance) = (
512            crate::collision::obstacles(cfg)?,
513            cfg.bool("effects.crash")?,
514            cfg.non_negative("profile.min_clearance_m")?,
515        );
516        // On a machine of their own: this one's state is adopted below, not taken at the start pose.
517        let spare = (entry.build)(cfg)?;
518        let (mut at, mut torque) = (Vec::new(), vec![0.0; spare.motors().len()]);
519        spare.equilibrium(&start, &mut at, &mut torque);
520        let build = || (entry.build)(cfg);
521        let mut own_parts = crate::collision::PlanCheck::at_start(min_clearance, spare.as_ref(), &at, &start, build)?;
522        // The last fallible step; it changes the controller only once it has checked all it reads.
523        self.control.apply_config(cfg, machine.as_ref())?;
524        own_parts.own = self.own_parts.own.take();
525        self.own_parts = own_parts;
526        machine.set_payload_attached(self.payload_attached);
527        let motors = machine.motors().len();
528        let (mut before, mut after, mut speed) = (vec![0.0; motors], vec![0.0; motors], vec![0.0; motors]);
529        self.machine.motor_state(&self.state, &mut before, &mut speed);
530        self.state = machine.adopt_state(self.machine.as_ref(), &self.state);
531        machine.motor_state(&self.state, &mut after, &mut speed);
532        for k in 0..motors {
533            after[k] -= before[k];
534        }
535        self.control.motors_shifted(&after);
536        self.rk = Rk4::new(self.state.len());
537        self.rk_joint = Rk4::new(self.state.len() + WINDING_STATES * motors + 1);
538        self.motor_buffers = std::array::from_fn(|_| vec![0.0; motors]);
539        self.limit_violations = check_limits(machine.as_ref(), &self.control.motor_drives(machine.as_ref()));
540        // A part that is still there keeps its warmth.
541        for part in &mut heated {
542            part.rise = self.heated.iter().find(|old| old.part.id == part.part.id).map_or(0.0, |old| old.rise);
543        }
544        (self.heated, self.part_heating) = (heated, part_heating);
545        self.thermal_feedback = thermal_feedback;
546        (self.warm_start, self.path) = (warm_start, path);
547        (self.obstacles, self.crash, self.min_clearance) = (obstacles, crash, min_clearance);
548        self.machine = machine;
549        self.feed_temperatures_back();
550        self.substeps = substeps;
551        Ok(())
552    }
553
554    pub fn time(&self) -> f64 {
555        self.step as f64 * self.dt
556    }
557
558    /// Everything but the machine, to go back to with `restore`: a copy, as long as the simulation's state takes to copy.
559    pub fn snapshot(&self) -> Snapshot {
560        Snapshot {
561            control: self.control.clone(),
562            state: self.state.clone(),
563            memory: self.machine.memory(),
564            torque: self.torque.clone(),
565            step: self.step,
566            payload_attached: self.payload_attached,
567            payload_energy: self.payload_energy,
568            crash_energy: self.crash_energy,
569            heated: self.heated.clone(),
570            obstacles: self.obstacles.clone(),
571            clearance: self.clearance,
572            least_clearance: self.least_clearance,
573            contact: self.contact.clone(),
574            own: self.own_parts.own.clone(),
575            own_at: self.own_at,
576            crashed: self.crashed,
577            contact_force: self.contact_force,
578            gaps: self.gaps.clone(),
579            absorbed: self.absorbed,
580        }
581    }
582
583    /// Back to a snapshot of a simulation of the same machine and config (this one, or one built as it was): its next
584    /// steps are bit for bit those the snapshot's simulation took. A snapshot of another machine (other state, motor,
585    /// part or obstacle counts) is refused and changes nothing. What a machine works out per step for its signals alone
586    /// (a belt tooth jump's loss) reads as the machine has it until the next step: sample before restoring if the
587    /// signals at the snapshot are wanted.
588    pub fn restore(&mut self, s: &Snapshot) -> Result<(), ConfigError> {
589        if s.state.len() != self.state.len()
590            || s.memory.len() != self.machine.memory().len()
591            || s.torque.len() != self.torque.len()
592            || s.control.drives.len() != self.control.drives.len()
593            || s.heated.len() != self.heated.len()
594            || s.obstacles.len() != self.obstacles.len()
595        {
596            return Err(ConfigError::Invalid("snapshot".into()));
597        }
598        self.control = s.control.clone();
599        self.state.clone_from(&s.state);
600        self.torque.clone_from(&s.torque);
601        (self.step, self.payload_energy, self.crash_energy) = (s.step, s.payload_energy, s.crash_energy);
602        // Each part as this machine has it, warmed as the snapshot's (a deserialized one carries no part).
603        for (mine, theirs) in self.heated.iter_mut().zip(&s.heated) {
604            *mine = HeatedPart { part: std::mem::take(&mut mine.part), ..theirs.clone() };
605        }
606        self.obstacles.clone_from(&s.obstacles);
607        (self.clearance, self.least_clearance, self.crashed) = (s.clearance, s.least_clearance, s.crashed);
608        self.contact.clone_from(&s.contact);
609        self.own_parts.own.clone_from(&s.own);
610        self.own_at = s.own_at;
611        self.gaps.clone_from(&s.gaps);
612        (self.contact_force, self.absorbed) = (s.contact_force, s.absorbed);
613        // The pushes are those of the next step, which works them out afresh; until then the restored state has none.
614        self.pushes.clear();
615        // What the machine keeps between steps, as `step` sets it.
616        self.payload_attached = s.payload_attached;
617        self.machine.set_memory(&s.memory);
618        self.machine.set_payload_attached(s.payload_attached);
619        self.machine.set_dwelling(self.control.dwell_progress().is_some());
620        self.machine.set_brake_engaged(self.control.brake_engaged());
621        self.feed_temperatures_back();
622        Ok(())
623    }
624
625    pub fn command(&mut self, command: Command) -> Result<(), CommandError> {
626        self.control.command(command, self.machine.as_ref())
627    }
628
629    /// Puts motor `k`'s drive in `mode`: torque or speed setpoints from an outside controller (`Controller::set_drive_mode`).
630    pub fn set_drive_mode(&mut self, k: usize, mode: crate::DriveMode) -> Result<(), CommandError> {
631        self.control.set_drive_mode(k, mode, self.machine.as_ref(), &self.state)
632    }
633
634    /// The config's `[path]` (`with_path`) planned from where the machine stands, as `sim-cli run --path` plans a file:
635    /// one run at the axes' limits as a path, a program with feeds run by run (`plan_program`). `None` without one.
636    pub fn plan_configured_path(&self) -> Option<Result<Vec<(f64, Vec<f64>)>, CommandError>> {
637        let run = self.path.as_ref()?;
638        let start = self.control.planned_pos();
639        let runs =
640            match crate::program::read_with(&run.file, &run.program, self.machine.axes(), start, run.orientation_speed)
641            {
642                Ok(runs) => runs,
643                Err(e) => return Some(Err(CommandError { key: e.key })),
644            };
645        Some(match crate::program::as_path(&runs) {
646            Some(pieces) => self.plan_path(pieces, run.time_optimal),
647            None => self.plan_program(&runs, run.time_optimal),
648        })
649    }
650
651    /// The timing for a path from where the machine stands, to run with `Command::Trajectory`.
652    /// A time-optimal path that comes nearer to an obstacle than `profile.min_clearance_m`, or touches one, is refused
653    /// (`error-path-collision`), and so is one that brings two of the machine's own parts as near
654    /// (`error-path-self-collision`); one timed within the axis limits is planned all the same, and `check_plan` tells.
655    pub fn plan_path(
656        &self,
657        pieces: &[crate::path::Piece],
658        time_optimal: bool,
659    ) -> Result<Vec<(f64, Vec<f64>)>, CommandError> {
660        let points = self.control.plan_path(self.machine.as_ref(), pieces, time_optimal)?;
661        self.refuse_near(&points, time_optimal)?;
662        Ok(points)
663    }
664
665    /// The timing for a program (`program::read`) from where the machine stands (`Controller::plan_program`), refused
666    /// as `plan_path` refuses a time-optimal path near an obstacle.
667    pub fn plan_program(
668        &self,
669        runs: &[crate::program::Run],
670        time_optimal: bool,
671    ) -> Result<Vec<(f64, Vec<f64>)>, CommandError> {
672        let points = self.control.plan_program(self.machine.as_ref(), runs, time_optimal)?;
673        self.refuse_near(&points, time_optimal)?;
674        Ok(points)
675    }
676
677    /// `plan_path`'s refusal of a time-optimal plan that comes nearer than `profile.min_clearance_m` to an obstacle or
678    /// brings two of the machine's own parts that near, or touches; nothing to look at without obstacles or own parts.
679    fn refuse_near(&self, points: &[(f64, Vec<f64>)], time_optimal: bool) -> Result<(), CommandError> {
680        if !time_optimal || (self.obstacles.is_empty() && !self.own_parts.has_pairs()) {
681            return Ok(());
682        }
683        let Some(check) = self.check_plan(&points.iter().map(|(_, pose)| pose.clone()).collect::<Vec<_>>()) else {
684            return Ok(());
685        };
686        if check.clearance < self.min_clearance || check.contact.is_some() {
687            return Err(CommandError { key: "error-path-collision" });
688        }
689        if check.own_fails(self.min_clearance) {
690            return Err(CommandError { key: "error-path-self-collision" });
691        }
692        Ok(())
693    }
694
695    /// The path through `poses` checked against the obstacles before it runs, with the payload as it is now
696    /// (`collision::check_path`), and the machine's own parts against each other (`PlanCheck::own`, joined as at the
697    /// start pose). `None` without obstacles where nothing of the machine's own was checked.
698    pub fn check_plan(&self, poses: &[Vec<f64>]) -> Option<crate::collision::PlanCheck> {
699        if self.obstacles.is_empty() && !self.own_parts.has_pairs() {
700            return None;
701        }
702        let mut check = self.own_parts.anew();
703        crate::collision::check_path(self.machine.as_ref(), &self.obstacles, poses, &mut check);
704        (!self.obstacles.is_empty() || check.own.is_some()).then_some(check)
705    }
706
707    /// How far that planned path is from the pieces as given, at most.
708    pub fn path_deviation(&self, pieces: &[crate::path::Piece], time_optimal: bool) -> Result<f64, CommandError> {
709        self.control.path_deviation(self.machine.as_ref(), pieces, time_optimal)
710    }
711
712    /// `path_deviation` per run of a program (`Controller::program_deviations`).
713    pub fn program_deviations(
714        &self,
715        runs: &[crate::program::Run],
716        time_optimal: bool,
717    ) -> Result<Vec<f64>, CommandError> {
718        self.control.program_deviations(self.machine.as_ref(), runs, time_optimal)
719    }
720
721    /// One base step: the controller sets the windings' voltages, then windings and mechanics go through the step
722    /// together (with the drives disabled, the mechanics alone without torque).
723    pub fn step(&mut self) {
724        self.control.update(self.step, self.machine.as_ref(), &self.state, &mut self.torque);
725        if self.control.payload_attached != self.payload_attached {
726            // A pick the machine cannot make where the tool really is (a hook block that hangs inside the payload) is
727            // refused as the cycle's segment is at load (`Machine::refuses_pick`): the payload stays off.
728            if self.control.payload_attached {
729                let motors = self.machine.motors().len();
730                let (mut angle, mut speed) = (vec![0.0; motors], vec![0.0; motors]);
731                self.machine.motor_state(&self.state, &mut angle, &mut speed);
732                let mut tool = vec![0.0; self.machine.axes().len()];
733                self.machine.forward(&angle, &mut tool);
734                if let Some(why) = self.machine.refuses_pick(&tool) {
735                    (self.pick_refused, self.control.payload_attached) = (Some(why), false);
736                }
737            }
738        }
739        if self.control.payload_attached != self.payload_attached {
740            self.payload_attached = self.control.payload_attached;
741            let before = self.machine.energy(&self.state);
742            self.machine.set_payload_attached(self.payload_attached);
743            self.payload_energy += self.machine.energy(&self.state) - before;
744        }
745        self.machine.set_dwelling(self.control.dwell_progress().is_some());
746        self.control.step_brake(self.dt);
747        self.machine.set_brake_engaged(self.control.brake_engaged());
748        for (k, &command) in self.control.valves.iter().enumerate() {
749            self.machine.set_valve(k, command);
750        }
751        // The temperatures the last step ended with; fed back here and not after the parts warm, so that the losses
752        // the parts warmed with are those the machine reports after the step.
753        self.feed_temperatures_back();
754        // The tool's speed before the step, the impact's if it finds the first contact (its push may brake the tool in
755        // the step already, where it acts at the tool).
756        let approach = (self.contact.is_none() && !self.obstacles.is_empty()).then(|| {
757            let n = self.machine.axes().len();
758            let (mut pos, mut vel) = (vec![0.0; n], vec![0.0; n]);
759            self.machine.tool_state(&self.state, &mut pos, &mut vel);
760            vel.iter().map(|v| v * v).sum::<f64>().sqrt()
761        });
762        self.pushes();
763        self.cuts = (self.machine.substeps_wanted(&self.state, &self.torque, self.dt, self.substeps))
764            .clamp(1, sim_core::MOST_CUTS);
765        self.refined_steps += u64::from(self.cuts > 1);
766        if self.control.enabled() {
767            self.advance_with_windings();
768        } else {
769            // A disabled drive's torque (the iron's drag, `Drive::disabled_step`) is held over the step: its work is that
770            // torque times the angle turned, which the drive's books take in place of the step start's speed.
771            let dragged = self.control.drives.iter().any(|d| d.torque != 0.0).then(|| {
772                let [angle, speed, ..] = &mut self.motor_buffers;
773                self.machine.motor_state(&self.state, angle, speed);
774                angle.clone()
775            });
776            if self.pushes.is_empty() {
777                let substeps = self.substeps * self.cuts;
778                advance(self.machine.as_ref(), &mut self.rk, &mut self.state, &self.torque, self.dt, substeps);
779            } else {
780                self.advance_pushed();
781            }
782            if let Some(before) = dragged {
783                let [angle, speed, ..] = &mut self.motor_buffers;
784                self.machine.motor_state(&self.state, angle, speed);
785                for ((d, a), b) in self.control.drives.iter_mut().zip(angle.iter()).zip(&before) {
786                    if d.torque != 0.0 {
787                        let work = d.torque * (a - b) / self.dt;
788                        (d.shaft_power, d.emf_loss) = (work, -work);
789                    }
790                }
791            }
792        }
793        self.machine.after_step(&mut self.state, self.dt);
794        let taken = self.pushed();
795        if !self.obstacles.is_empty() {
796            self.check_obstacles(approach.unwrap_or(0.0));
797        }
798        if self.own_parts.has_pairs() {
799            self.look_at_own_parts();
800        }
801        if let Some(contact) = &mut self.contact {
802            self.absorbed += taken;
803            contact.peak_force = contact.peak_force.max(self.contact_force);
804            contact.impact_energy = contact.impact_energy.max(self.absorbed);
805        }
806        self.crashed = self.control.fault.is_some() && (self.crashed || self.obstacles.iter().any(|o| o.contact));
807        if self.part_heating && !self.heated.is_empty() {
808            // The loss at the end of the step, held over it: the exact answer of the first-order lag to a held input.
809            self.losses.clear();
810            let torque = self.machine_torque();
811            self.machine.loss_powers(&self.state, &torque, &mut self.losses);
812            for part in &mut self.heated {
813                part.loss_power = self.losses[part.loss];
814                let settled = part.resistance * part.loss_power;
815                part.rise += (1.0 - (-self.dt / part.time_constant).exp()) * (settled - part.rise);
816            }
817        }
818        self.step += 1;
819    }
820
821    /// The machine's own parts after a base step (`own_parts`), where `OWN_PARTS_EVERY_S` has passed since the last look
822    /// or there was none. The pose said with a finding is the setpoint's.
823    fn look_at_own_parts(&mut self) {
824        let now = self.time();
825        if self.own_at.is_some_and(|at| now - at < OWN_PARTS_EVERY_S) {
826            return;
827        }
828        let boxes = self.machine.collision_bodies(&self.state);
829        self.own_parts.look_at_own(self.machine.as_ref(), &self.state, &boxes, &self.control.set_pos);
830        self.own_at = Some(now);
831    }
832
833    /// The clearance to the obstacles after a base step, which obstacles a part touches, and the first contact, the tool
834    /// at `speed` before the step.
835    fn check_obstacles(&mut self, speed: f64) {
836        let bodies = crate::collision::Bodies::of(self.machine.as_ref(), &self.state);
837        let mut nearest = (f64::INFINITY, 0);
838        self.gaps.clear();
839        for (k, obstacle) in self.obstacles.iter_mut().enumerate() {
840            let gap = bodies.gap(&obstacle.aabb).map_or(f64::INFINITY, |g| g.2);
841            obstacle.contact = gap <= 0.0;
842            if gap < nearest.0 {
843                nearest = (gap, k);
844            }
845            self.gaps.push(gap);
846        }
847        self.clearance = nearest.0;
848        self.least_clearance = self.least_clearance.min(nearest.0);
849        if nearest.0 <= 0.0 && self.contact.is_none() {
850            let n = self.machine.axes().len();
851            let (mut pos, mut vel) = (vec![0.0; n], vec![0.0; n]);
852            self.machine.tool_state(&self.state, &mut pos, &mut vel);
853            // The step counter moves on after this check.
854            let time = (self.step + 1) as f64 * self.dt;
855            let (peak_force, impact_energy) = (self.contact_force, 0.0);
856            self.contact = Some(Contact { time, pose: pos, speed, obstacle: nearest.1, peak_force, impact_energy });
857        }
858    }
859
860    /// effects.crash: the obstacles' pushes over the coming step (`Push`), for each obstacle a part comes within
861    /// `PUSH_RANGE` of. The depth and its slopes are those of the rigid kinematics at the motors' angles (`forward`,
862    /// then `equilibrium`), so that the push is a spring on the motors' angles, which the step integrates with the rest.
863    /// A machine that takes a force at its tool (`Machine::set_tool_force`) is pushed there: the push's slopes are then
864    /// the clearance's along the tool's coordinates, its depth the clearance of the parts where they are, its force the
865    /// generalised force of the contact on them (its virtual work per unit of each, wherever on the moving parts it
866    /// touches), worked out at every stage of the integration, and a load on a soft belt stops at the obstacle's face.
867    /// A machine without it is pushed at its
868    /// motors through the rigid kinematics, so that a load on a soft transmission swings on into the obstacle by the
869    /// transmission's give. Either way the work the pushes take is the budget's crash row.
870    fn pushes(&mut self) {
871        self.pushes.clear();
872        let (axes, contact) = (self.machine.axes().len(), self.machine.contact_axes());
873        // The probe also clears the force of the last step.
874        let tool_route = self.crash && self.machine.set_tool_force(&vec![0.0; contact]);
875        self.tool_push = false;
876        let near: Vec<usize> =
877            (0..self.obstacles.len()).filter(|&k| self.gaps.get(k).is_some_and(|g| *g < PUSH_RANGE)).collect();
878        if !self.crash || near.is_empty() {
879            return;
880        }
881        let machine = self.machine.as_ref();
882        let motors = machine.motors().len();
883        let dim = if tool_route { contact } else { motors };
884        let (mut angle, mut speed) = (vec![0.0; dim.max(motors)], vec![0.0; dim.max(motors)]);
885        if tool_route {
886            machine.contact_state(&self.state, &mut angle[..contact], &mut speed[..contact]);
887        } else {
888            machine.motor_state(&self.state, &mut angle, &mut speed);
889        }
890        angle.truncate(dim);
891        let (mut tool, mut state, mut torque) = (vec![0.0; axes], Vec::new(), vec![0.0; motors]);
892        let mut gaps_at = |at: &[f64]| -> Vec<f64> {
893            if tool_route {
894                machine.contact_placed(&self.state, at, &mut state);
895            } else {
896                machine.forward(at, &mut tool);
897                machine.equilibrium(&tool, &mut state, &mut torque);
898            }
899            let bodies = crate::collision::Bodies::of(machine, &state);
900            near.iter().map(|&k| bodies.gap(&self.obstacles[k].aabb).map_or(f64::INFINITY, |g| g.2)).collect()
901        };
902        // At the tool the depth is that of the parts where they are (the clearance after the last step), not where the
903        // rigid kinematics put them about the tool: a payload on a leaning axis stands back from its tool point by the
904        // lean, and is held at its face where it touches.
905        let depths: Vec<f64> = if tool_route {
906            near.iter().map(|&k| -self.gaps[k]).collect()
907        } else {
908            gaps_at(&angle).into_iter().map(|g| -g).collect()
909        };
910        let mut slopes = vec![vec![0.0; dim]; near.len()];
911        for m in 0..dim {
912            let mut at = angle.clone();
913            at[m] += SLOPE_STEP;
914            let up = gaps_at(&at);
915            at[m] -= 2.0 * SLOPE_STEP;
916            let down = gaps_at(&at);
917            for (j, slope) in slopes.iter_mut().enumerate() {
918                slope[m] = (up[j] - down[j]) / (2.0 * SLOPE_STEP);
919            }
920        }
921        for ((&k, depth), slope) in near.iter().zip(depths).zip(slopes) {
922            let (stiffness, damping) = (self.obstacles[k].stiffness, self.obstacles[k].damping);
923            if depth.is_finite() && slope.iter().all(|g| g.is_finite()) {
924                self.pushes.push(Push { depth, slope, stiffness, damping });
925            }
926        }
927        self.push_from = angle;
928        self.tool_push = tool_route && !self.pushes.is_empty();
929        if self.tool_push {
930            self.tool_buffers = std::array::from_fn(|_| vec![0.0; contact]);
931        }
932    }
933
934    /// The step done: the obstacles' force at its end (`contact_force`), and the work their pushes took out of the
935    /// machine over it (J), integrated with the motion (the last entry of `joint`), which goes to `crash_energy`.
936    fn pushed(&mut self) -> f64 {
937        if self.pushes.is_empty() {
938            self.contact_force = 0.0;
939            return 0.0;
940        }
941        self.contact_force = if self.tool_push {
942            let (force, _, total) = tool_push_forces(self.machine.as_ref(), &self.pushes, &self.push_from, &self.state);
943            // What is sampled after the step (the losses of a gearbox or a guide the push loads) sees the push at its
944            // end, not at the integration's last stage.
945            self.machine.set_tool_force(&force);
946            total
947        } else {
948            let motors = self.push_from.len();
949            let (mut angle, mut speed, mut torque) = (vec![0.0; motors], vec![0.0; motors], vec![0.0; motors]);
950            self.machine.motor_state(&self.state, &mut angle, &mut speed);
951            push_torques(&self.pushes, &self.push_from, &angle, &speed, &mut torque)
952        };
953        let taken = self.joint.last().copied().unwrap_or(0.0);
954        self.crash_energy += taken;
955        taken
956    }
957
958    /// The torques the machine's mechanics take at the end of the last step: the drives' plus the obstacles' pushes
959    /// (`push_torques`), as the step integrated them. What a machine works out of its torques (a guide's load from the
960    /// acceleration they command, its friction and so its loss) is to be sampled with these, or the losses booked and
961    /// those the motion had part ways while a part touches an obstacle.
962    pub fn machine_torque(&self) -> Vec<f64> {
963        let mut out = self.torque.clone();
964        // (Pushes at the tool are the machine's own force, not torques at its motors.)
965        if !self.pushes.is_empty() && !self.tool_push {
966            let motors = out.len();
967            let (mut angle, mut speed) = (vec![0.0; motors], vec![0.0; motors]);
968            self.machine.motor_state(&self.state, &mut angle, &mut speed);
969            push_torques(&self.pushes, &self.push_from, &angle, &speed, &mut out);
970        }
971        out
972    }
973
974    /// A step with the drives disabled and the obstacles pushing: the mechanics alone, the pushes' torques worked out at
975    /// every stage of the integration, and the work they take out of the machine integrated with it (as with the
976    /// windings, whose entries rest at zero here).
977    fn advance_pushed(&mut self) {
978        let Self {
979            machine,
980            rk_joint,
981            joint,
982            state,
983            torque,
984            pushes,
985            push_from,
986            tool_push,
987            cuts,
988            tool_buffers,
989            motor_buffers: [angle, speed, stage, push],
990            dt,
991            substeps,
992            ..
993        } = self;
994        let (on_tool, motor_pushes): (bool, &[Push]) = if *tool_push { (true, &[]) } else { (false, pushes) };
995        let n = state.len();
996        joint.clear();
997        joint.extend_from_slice(state);
998        joint.resize(n + WINDING_STATES * torque.len() + 1, 0.0);
999        let finer = if *tool_push { PUSH_SUBSTEPS * machine.push_substeps().max(1) } else { 1 };
1000        let substeps = *substeps * finer.max(*cuts);
1001        let h = *dt / substeps as f64;
1002        let [pos, vel, force] = tool_buffers;
1003        for _ in 0..substeps {
1004            rk_joint.step(
1005                |y, dy| {
1006                    let (mech, (dmech, rest)) = (&y[..n], dy.split_at_mut(n));
1007                    machine.motor_state(mech, angle, speed);
1008                    push.fill(0.0);
1009                    push_torques(motor_pushes, push_from, angle, speed, push);
1010                    for k in 0..stage.len() {
1011                        stage[k] = torque[k] + push[k];
1012                    }
1013                    rest.fill(0.0);
1014                    rest[rest.len() - 1] = -push.iter().zip(speed.iter()).map(|(t, w)| t * w).sum::<f64>();
1015                    if on_tool {
1016                        let buffers = [&mut *pos, &mut *vel, &mut *force];
1017                        let last = rest.len() - 1;
1018                        rest[last] += tool_push_stage(machine.as_mut(), pushes, push_from, mech, buffers);
1019                    }
1020                    machine.derivatives(mech, stage, dmech);
1021                },
1022                joint,
1023                h,
1024            );
1025        }
1026        state.copy_from_slice(&joint[..n]);
1027    }
1028
1029    /// With effects.thermal_feedback, tells the machine its parts' rises (`Machine::set_part_temperatures`).
1030    pub fn feed_temperatures_back(&mut self) {
1031        if self.thermal_feedback {
1032            let rises: Vec<f64> = self.heated.iter().map(|h| h.rise).collect();
1033            self.machine.set_part_temperatures(&rises);
1034        }
1035    }
1036
1037    /// Windings and mechanics over one base step in one integration, the voltages held as the controller set them: the
1038    /// motor torque follows the winding current within the step, and the electrical power, the copper loss and the
1039    /// shaft's work come from the same stages as the motion. The core's integrator sees one state vector.
1040    fn advance_with_windings(&mut self) {
1041        let Self {
1042            machine,
1043            control,
1044            state,
1045            torque,
1046            rk_joint,
1047            joint,
1048            motor_buffers: [angle, speed, stage_torque, push],
1049            dt,
1050            substeps,
1051            pushes,
1052            push_from,
1053            tool_push,
1054            cuts,
1055            tool_buffers: [pos, vel, force],
1056            ..
1057        } = self;
1058        let (on_tool, motor_pushes): (bool, &[Push]) = if *tool_push { (true, &[]) } else { (false, pushes) };
1059        let (n, drives) = (state.len(), &control.drives);
1060        joint.clear();
1061        joint.extend_from_slice(state);
1062        for (k, d) in drives.iter().enumerate() {
1063            joint.extend(d.winding_states(control.drive_params_of(k)));
1064        }
1065        // The work the obstacles' pushes take out of the machine over the step (`pushed`).
1066        joint.push(0.0);
1067        let finer = if *tool_push { PUSH_SUBSTEPS * machine.push_substeps().max(1) } else { 1 };
1068        let substeps = *substeps * finer.max(*cuts);
1069        let h = *dt / substeps as f64;
1070        for _ in 0..substeps {
1071            rk_joint.step(
1072                |y, dy| {
1073                    let ((mech, windings), (dmech, dwindings)) = (y.split_at(n), dy.split_at_mut(n));
1074                    machine.motor_state(mech, angle, speed);
1075                    for (k, d) in drives.iter().enumerate() {
1076                        // A drive whose pulses are off after a trip: no current, no torque (`Controller::react`).
1077                        if d.pulses_off {
1078                            // Only the iron's drag acts (`DriveParams::iron_drag`), and a stepper's magnets hold their
1079                            // detent without current, at the stage's angle; their work is integrated in the winding's
1080                            // work slot, which `Controller::winding_stepped` books as the shaft's and what the magnets
1081                            // and the iron gave, as with the drives disabled.
1082                            let p = control.drive_params_of(k);
1083                            stage_torque[k] = -p.iron_drag(speed[k]);
1084                            if let crate::drive::Motor::Stepper(s) = &p.motor {
1085                                stage_torque[k] += s.detent_torque(angle[k], d.phases.origin);
1086                            }
1087                            dwindings[WINDING_STATES * k..WINDING_STATES * (k + 1)].fill(0.0);
1088                            dwindings[WINDING_STATES * k + 3] = stage_torque[k] * speed[k];
1089                            continue;
1090                        }
1091                        let range = WINDING_STATES * k..WINDING_STATES * (k + 1);
1092                        stage_torque[k] = control.drive_params_of(k).motor_rates(
1093                            d,
1094                            &windings[range.clone()],
1095                            angle[k],
1096                            speed[k],
1097                            &mut dwindings[range],
1098                        );
1099                    }
1100                    push.fill(0.0);
1101                    push_torques(motor_pushes, push_from, angle, speed, push);
1102                    for (stage, push) in stage_torque.iter_mut().zip(push.iter()) {
1103                        *stage += push;
1104                    }
1105                    let work = dwindings.len() - 1;
1106                    dwindings[work] = -push.iter().zip(speed.iter()).map(|(t, w)| t * w).sum::<f64>();
1107                    if on_tool {
1108                        let buffers = [&mut *pos, &mut *vel, &mut *force];
1109                        dwindings[work] += tool_push_stage(machine.as_mut(), pushes, push_from, mech, buffers);
1110                    }
1111                    machine.derivatives(mech, stage_torque, dmech);
1112                },
1113                joint,
1114                h,
1115            );
1116        }
1117        state.copy_from_slice(&joint[..n]);
1118        // The rotors where the step leaves them, for a stepper's torque at its end.
1119        machine.motor_state(state, angle, speed);
1120        control.winding_stepped(&joint[n..], angle, speed);
1121        for (torque, d) in torque.iter_mut().zip(&control.drives) {
1122            *torque = d.torque;
1123        }
1124    }
1125
1126    pub fn run(&mut self, seconds: f64, mut each: impl FnMut(&Self)) {
1127        for _ in 0..(seconds / self.dt).round() as u64 {
1128            self.step();
1129            each(self);
1130        }
1131    }
1132
1133    /// Every signal of the simulation. Scopes, CSV columns and PLC variables are generated from
1134    /// this list, never written per machine.
1135    pub fn signal_infos(&self) -> Vec<SignalInfo> {
1136        let mut out = vec![
1137            SignalInfo::new("time", "group-sim", "quantity-time", "s"),
1138            SignalInfo::new("payload", "effect-payload", "quantity-attached", ""),
1139            // How long the axes' setpoints have been held: the plan now is `position_setpoint` run on by it.
1140            SignalInfo::new("setpoint_age", "group-sim", "quantity-setpoint-age", "s"),
1141        ];
1142        for axis in self.machine.axes() {
1143            let (unit, rate, rate2) = (axis.unit, format!("{}/s", axis.unit), format!("{}/s²", axis.unit));
1144            for (name, unit) in [
1145                ("position", unit),
1146                ("velocity", rate.as_str()),
1147                ("position-setpoint", unit),
1148                ("velocity-setpoint", rate.as_str()),
1149                ("acceleration-setpoint", rate2.as_str()),
1150                ("following-error", unit),
1151            ] {
1152                out.push(SignalInfo::new(
1153                    format!("axis.{}.{}", axis.id, name.replace('-', "_")),
1154                    axis.key,
1155                    &format!("quantity-{name}"),
1156                    unit,
1157                ));
1158            }
1159        }
1160        for (k, motor) in self.machine.motors().iter().enumerate() {
1161            // A linear motor's angle is a position (m), its speed m/s, its torque a force (N).
1162            let (pos, rate, load) =
1163                if self.machine.motor_linear(k) { ("m", "m/s", "N") } else { ("rad", "rad/s", "N m") };
1164            for (name, unit) in [
1165                ("angle", pos),
1166                ("speed", rate),
1167                ("torque", load),
1168                ("torque-command", load),
1169                ("current", "A"),
1170                ("voltage", "V"),
1171                ("electrical-power", "W"),
1172                ("winding-temperature", "K"),
1173                ("dc-link-voltage", "V"),
1174                ("braking-resistor-power", "W"),
1175                ("speed-command", rate),
1176                ("following-error", pos),
1177                ("angle-setpoint", pos),
1178                ("torque-feedforward", load),
1179                ("torque-feedback", load),
1180                ("speed-from-position", rate),
1181                // The electrical and thermal states, 0 where their effect is off.
1182                ("d-current", "A"),
1183                ("housing-temperature", "K"),
1184                ("drive-overload-image", ""),
1185                ("drive-overload-chip", ""),
1186                ("iron-loss", "W"),
1187                ("braking-resistor-temperature", "K"),
1188            ] {
1189                out.push(SignalInfo::new(
1190                    format!("motor.{}.{}", motor.id, name.replace('-', "_")),
1191                    motor.key,
1192                    &format!("quantity-{name}"),
1193                    unit,
1194                ));
1195            }
1196        }
1197        out.extend(self.machine.signal_infos());
1198        out.extend(self.heated.iter().map(|h| {
1199            SignalInfo::new(
1200                format!("{TEMPERATURE_PREFIX}{}", h.part.id),
1201                h.part.owner_key,
1202                &format!("quantity-{}-temperature", h.part.kind),
1203                "K",
1204            )
1205        }));
1206        out
1207    }
1208
1209    /// The current value of every signal, in the order of `signal_infos`.
1210    pub fn sample(&self, out: &mut Vec<f64>) {
1211        self.sample_base(out);
1212        self.machine.effect_signals(&self.state, &self.machine_torque(), out);
1213        out.extend(self.heated.iter().map(|h| h.rise));
1214    }
1215
1216    /// The signals of `sample` up to the end of the machine's `base_signals`, in the same places: without those of the
1217    /// effect views (which cost about one more evaluation of the machine) and the parts' temperatures after them.
1218    pub fn sample_base(&self, out: &mut Vec<f64>) {
1219        let (axes, motors) = (self.machine.axes().len(), self.machine.motors().len());
1220        let (mut pos, mut vel) = (vec![0.0; axes], vec![0.0; axes]);
1221        let (mut angle, mut speed) = (vec![0.0; motors], vec![0.0; motors]);
1222        self.machine.tool_state(&self.state, &mut pos, &mut vel);
1223        self.machine.motor_state(&self.state, &mut angle, &mut speed);
1224        let c = &self.control;
1225        out.clear();
1226        out.extend([self.time(), if self.payload_attached { 1.0 } else { 0.0 }, c.setpoint_age(self.time())]);
1227        for i in 0..axes {
1228            out.extend([pos[i], vel[i], c.set_pos[i], c.set_vel[i], c.set_acc[i], c.tool_error[i]]);
1229        }
1230        for (k, d) in c.drives.iter().enumerate() {
1231            out.extend([
1232                angle[k],
1233                speed[k],
1234                d.torque,
1235                d.torque_command,
1236                d.current,
1237                d.phase_voltage(c.drive_params_of(k)),
1238                d.power,
1239                d.temperature_rise,
1240                d.dc_voltage,
1241                d.resistor_power,
1242                d.speed_command,
1243                d.following_error,
1244                d.position_setpoint,
1245                d.feedforward_torque,
1246                d.controller_torque,
1247                d.position_part,
1248                d.d_current,
1249                d.housing_rise,
1250                d.overload_image,
1251                d.overload_chip,
1252                d.iron_loss,
1253                d.resistor_rise,
1254            ]);
1255        }
1256        self.machine.base_signals(&self.state, &self.machine_torque(), out);
1257    }
1258
1259    /// Position of a signal in a sample.
1260    pub fn signal_index(&self, id: &str) -> Option<usize> {
1261        self.signal_infos().iter().position(|s| s.id == id)
1262    }
1263
1264    /// The machine's scene, with where the tool is in it.
1265    /// Where the windings warm (effects.winding_heating), the k-th motor housing (`scene::MOTOR_PART`) is coloured by
1266    /// motor k's winding rise over its rise at rated current; where the parts warm, each heated part by its rise over
1267    /// its rated rise.
1268    pub fn scene(&self, out: &mut Scene) {
1269        self.machine.scene(&self.state, out);
1270        out.tool = self.tool_point();
1271        out.obstacles.clone_from(&self.obstacles);
1272        let bodies = crate::collision::Bodies::of(self.machine.as_ref(), &self.state);
1273        out.clearance = crate::collision::nearest(&bodies, &self.obstacles).map(|(_, gap)| gap);
1274        out.first_contact = self.contact.as_ref().map(|c| c.time);
1275        let mut colour = |id: &str, index: usize, heat: f64| {
1276            if let Some(part) = out.parts.iter_mut().filter(|p| p.id == id).nth(index) {
1277                part.heat = Some(heat as f32);
1278            }
1279        };
1280        if self.control.drive_params().heating {
1281            for (k, d) in self.control.drives.iter().enumerate() {
1282                colour(sim_core::scene::MOTOR_PART, k, d.temperature_rise / self.control.drive_params_of(k).rated_rise);
1283            }
1284        }
1285        if self.part_heating {
1286            for h in &self.heated {
1287                colour(h.part.scene_part, h.part.scene_index, h.rise / h.max_rise);
1288            }
1289        }
1290        self.conveyor_scene(out);
1291    }
1292
1293    /// With `[conveyor]`: the belt as a band under the grip poses, slats across it that run with it, and the parts on
1294    /// it, where the machine maps tool poses into the scene.
1295    fn conveyor_scene(&self, out: &mut Scene) {
1296        use sim_core::scene::{Part, Shape};
1297        let Some((conveyor, pass)) = self.control.conveyor() else { return };
1298        let along =
1299            |s: f64| -> Vec<f64> { conveyor.origin.iter().zip(&conveyor.direction).map(|(o, d)| o + d * s).collect() };
1300        let (Some(start), Some(end)) =
1301            (self.machine.scene_point(&along(0.0)), self.machine.scene_point(&along(conveyor.length)))
1302        else {
1303            return;
1304        };
1305        // The parts are 50 mm cubes under the grip pose; the band lies under them, 300 mm wide.
1306        let (part, width) = (0.05, 0.3);
1307        let below = |p: [f64; 3], by: f64| [p[0], p[1], p[2] - by];
1308        out.parts.push(Part::new(
1309            "conveyor-belt",
1310            Shape::Segment { to: below(end, part), width },
1311            below(start, part),
1312            [0.15, 0.15, 0.17],
1313        ));
1314        // Each slat a strip 10 mm wide square across the belt, however the belt runs in the floor's plane.
1315        let unit = [end[0] - start[0], end[1] - start[1]];
1316        let norm = unit[0].hypot(unit[1]).max(1e-9);
1317        let across = [-unit[1] / norm * width / 2.0, unit[0] / norm * width / 2.0];
1318        let spacing = 0.1;
1319        let shift = conveyor.belt(self.time()) % spacing;
1320        for i in 0..(conveyor.length / spacing).floor() as usize {
1321            if let Some(p) = self.machine.scene_point(&along(shift + i as f64 * spacing)) {
1322                let [x, y, z] = below(p, part);
1323                let (from, to) = ([x - across[0], y - across[1], z], [x + across[0], y + across[1], z]);
1324                out.parts.push(Part::new(
1325                    "conveyor-slat",
1326                    Shape::Segment { to, width: 0.01 },
1327                    from,
1328                    [0.35, 0.35, 0.38],
1329                ));
1330            }
1331        }
1332        for (k, _) in conveyor.parts_on_belt(self.time(), pass) {
1333            if let Some(p) = self.machine.scene_point(&conveyor.part_pose(k, self.time())) {
1334                let size = [part; 3];
1335                out.parts.push(Part::new("conveyor-part", Shape::Box { size }, below(p, part / 2.0), [0.9, 0.55, 0.1]));
1336            }
1337        }
1338    }
1339
1340    /// Where the tool is in the scene right now; `None` where the machine has no mapping.
1341    pub fn tool_point(&self) -> Option<[f64; 3]> {
1342        let axes = self.machine.axes().len();
1343        let (mut pos, mut vel) = (vec![0.0; axes], vec![0.0; axes]);
1344        self.machine.tool_state(&self.state, &mut pos, &mut vel);
1345        self.machine.scene_point(&pos)
1346    }
1347}