1use 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#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
13pub struct HeatedPart {
14 #[serde(skip)]
16 pub part: ThermalPart,
17 loss: usize,
19 pub loss_power: f64,
21 pub resistance: f64,
23 pub time_constant: f64,
24 pub max_rise: f64,
25 pub rise: f64,
27}
28
29fn 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
49const PUSH_RANGE: f64 = 0.01;
53
54const PUSH_SUBSTEPS: u32 = 4;
60const SLOPE_STEP: f64 = 1e-6;
63
64#[derive(Debug, Clone, PartialEq)]
68struct Push {
69 depth: f64,
70 slope: Vec<f64>,
71 stiffness: f64,
72 damping: f64,
73}
74
75impl Push {
76 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
86fn 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
100fn 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
115fn 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
135use 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 rk_joint: Rk4,
152 joint: Vec<f64>,
153 motor_buffers: [Vec<f64>; 4],
154 tool_buffers: [Vec<f64>; 3],
156 payload_attached: bool,
157 pub payload_energy: f64,
161 pub crash_energy: f64,
164 pub pick_refused: Option<&'static str>,
166 pub limit_violations: Vec<LimitViolation>,
168 pub heated: Vec<HeatedPart>,
172 pub part_heating: bool,
173 pub thermal_feedback: bool,
175 pub warm_start: bool,
178 losses: Vec<f64>,
180 pub obstacles: Vec<Obstacle>,
182 pub crash: bool,
186 pub min_clearance: f64,
188 pub path: Option<PathRun>,
191 pub clearance: f64,
194 pub least_clearance: f64,
195 pub contact: Option<Contact>,
197 pub own_parts: crate::collision::PlanCheck,
201 own_at: Option<f64>,
203 pub crashed: bool,
206 pub contact_force: f64,
208 gaps: Vec<f64>,
210 pushes: Vec<Push>,
212 push_from: Vec<f64>,
213 tool_push: bool,
216 absorbed: f64,
218 cuts: u32,
220 pub refined_steps: u64,
222}
223
224#[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#[derive(Clone, serde::Serialize, serde::Deserialize)]
245pub struct Snapshot {
246 control: Controller,
247 state: Vec<f64>,
248 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#[derive(Debug, Clone, PartialEq)]
274pub struct PathRun {
275 pub file: String,
276 pub program: String,
277 pub time_optimal: bool,
278 pub orientation_speed: f64,
281}
282
283pub 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
297fn 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
317pub fn heats(cfg: &Config) -> Result<bool, ConfigError> {
320 Ok(cfg.bool("effects.part_heating")? || cfg.bool("effects.thermal_feedback")?)
321}
322
323fn 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 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
337pub 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
346pub 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
358pub 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
368pub 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
374pub 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 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
418pub(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
425pub const OWN_PARTS_EVERY_S: f64 = 1e-3;
429
430impl Sim {
431 pub fn new(entry: &MachineEntry, cfg: &Config) -> Result<Self, ConfigError> {
433 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 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 return Err(ConfigError::Invalid("sim.dt_s".into()));
501 }
502 let start = start_pose(cfg, machine.as_ref())?;
505 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 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 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 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 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 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 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 self.pushes.clear();
615 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 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 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 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 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 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 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 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 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 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 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 self.feed_temperatures_back();
754 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 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 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 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 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 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 fn pushes(&mut self) {
871 self.pushes.clear();
872 let (axes, contact) = (self.machine.axes().len(), self.machine.contact_axes());
873 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 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 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 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 pub fn machine_torque(&self) -> Vec<f64> {
963 let mut out = self.torque.clone();
964 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 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 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 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 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 if d.pulses_off {
1078 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 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 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 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 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 ("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 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 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 pub fn signal_index(&self, id: &str) -> Option<usize> {
1261 self.signal_infos().iter().position(|s| s.id == id)
1262 }
1263
1264 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 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 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 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 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}