1use sim_components::catalog::motor_config;
40use sim_components::joint::RotaryJoint;
41use sim_components::mech::{GearTorque, HardStop, ShaftFriction, ThermalFeedback};
42use sim_components::transmission::BallScrew;
43use sim_core::{
44 AxisInfo, Config, ConfigError, ENERGY_PARTS, LOSS_PREFIX, Label, Machine, MachineEntry, MotorInfo, Part,
45 RatingCheck, Scene, Shape, SignalInfo, TORQUE_PARTS, ThermalPart,
46};
47
48const I18N: &[(&str, &str)] = &[("en", include_str!("../i18n/en.ftl")), ("de", include_str!("../i18n/de.ftl"))];
49
50pub static ENTRY: MachineEntry = MachineEntry {
51 id: "parallel-scara",
52 key: "machine-parallel-scara",
53 default_config: include_str!("../default.toml"),
54 i18n: I18N,
55 build,
56 suite_configs,
57};
58
59const G: f64 = 9.80665;
60
61pub const LOSSY_EFFECTS: [&str; 7] = [
64 "joint_friction",
65 "motor_friction",
66 "gearbox_drag",
67 "gearbox_lost_motion",
68 "gearbox_efficiency",
69 "torque_ripple",
70 "holding_brake",
71];
72
73fn build(cfg: &Config) -> Result<Box<dyn Machine>, ConfigError> {
74 sim_components::base::mount(cfg, Box::new(ParallelScara::new(cfg)?))
75}
76
77pub fn lossless_config() -> Config {
79 let mut cfg = ENTRY.config();
80 for effect in LOSSY_EFFECTS {
81 cfg.set_text(&format!("effects.{effect} = false")).unwrap();
82 }
83 for key in ["gearbox.damping_nm_s_rad", "joint.stop_damping_nm_s_rad", "slide.stop_damping_n_s_m"] {
84 cfg.set_text(&format!("{key} = 0.0")).unwrap();
85 }
86 cfg
87}
88
89fn suite_configs() -> Vec<Config> {
92 let mut out = Vec::new();
93 for (elastic, payload) in [(false, true), (false, false), (true, true), (true, false)] {
94 let mut cfg = lossless_config();
95 cfg.set_text(&format!("effects.joint_elasticity = {elastic}")).unwrap();
96 cfg.set_text(&format!("effects.payload = {payload}")).unwrap();
97 cfg.set_text(&format!("effects.part_heating = {}", elastic && payload)).unwrap();
98 cfg.set_text(&format!("effects.thermal_feedback = {}", elastic && payload)).unwrap();
99 out.push(cfg);
100 }
101 out
102}
103
104type V2 = [f64; 2];
106type M2 = [[f64; 2]; 2];
107
108fn dot(a: V2, b: V2) -> f64 {
109 a[0] * b[0] + a[1] * b[1]
110}
111
112fn sub(a: V2, b: V2) -> V2 {
113 [a[0] - b[0], a[1] - b[1]]
114}
115
116fn norm(a: V2) -> f64 {
117 dot(a, a).sqrt()
118}
119
120fn mul(m: &M2, v: V2) -> V2 {
121 [dot(m[0], v), dot(m[1], v)]
122}
123
124fn transpose(m: &M2) -> M2 {
125 [[m[0][0], m[1][0]], [m[0][1], m[1][1]]]
126}
127
128fn inverse(m: &M2) -> Option<M2> {
130 let det = m[0][0] * m[1][1] - m[0][1] * m[1][0];
131 if !(det.abs() > 1e-300) || !det.is_finite() {
132 return None;
133 }
134 Some([[m[1][1] / det, -m[0][1] / det], [-m[1][0] / det, m[0][0] / det]])
135}
136
137pub fn condition_number(j: &M2) -> f64 {
140 let (a, b, c) = (
141 j[0][0] * j[0][0] + j[1][0] * j[1][0],
142 j[0][0] * j[0][1] + j[1][0] * j[1][1],
143 j[0][1] * j[0][1] + j[1][1] * j[1][1],
144 );
145 let (mean, half) = ((a + c) / 2.0, ((a - c) / 2.0).hypot(b));
146 if mean - half <= 0.0 { f64::INFINITY } else { ((mean + half) / (mean - half)).sqrt() }
147}
148
149fn spring(g: &sim_components::mech::Gearbox, small: bool) -> f64 {
152 g.stiffness + if small && g.hysteresis > 0.0 { g.dahl_stiffness } else { 0.0 }
153}
154
155fn mode_vector(k: V2, m: &M2, lambda: f64) -> V2 {
158 let rows = [[k[0] - lambda * m[0][0], -lambda * m[0][1]], [-lambda * m[1][0], k[1] - lambda * m[1][1]]];
159 let row = if norm(rows[0]) >= norm(rows[1]) { rows[0] } else { rows[1] };
160 if norm(row) > 0.0 { [-row[1], row[0]] } else { [1.0, 0.0] }
161}
162
163#[derive(Debug, Clone)]
165pub struct Legs {
166 pub e: f64,
168 pub la: f64,
169 pub lb: f64,
170}
171
172pub const SIDE: [f64; 2] = [1.0, -1.0];
174
175impl Legs {
176 pub fn new(e: f64, la: f64, lb: f64) -> Self {
177 Self { e, la, lb }
178 }
179
180 pub fn elbow(&self, i: usize, t: f64) -> [V2; 3] {
182 let (s, c) = t.sin_cos();
183 let (la, side) = (self.la, SIDE[i]);
184 [[side * (self.e + la * c), -la * s], [-side * la * s, -la * c], [-side * la * c, la * s]]
185 }
186
187 pub fn inverse(&self, p: V2) -> Option<V2> {
189 let mut out = [0.0; 2];
190 for (i, t) in out.iter_mut().enumerate() {
191 let (x, y) = (SIDE[i] * p[0], p[1]);
192 let (a, b, c) = (
193 -2.0 * self.la * (x - self.e),
194 2.0 * self.la * y,
195 (x - self.e).powi(2) + y * y + self.la * self.la - self.lb * self.lb,
196 );
197 let d = a * a + b * b - c * c;
198 if !(d >= 0.0) {
199 return None;
200 }
201 *t = 2.0 * ((-b - d.sqrt()) / (c - a)).atan();
202 }
203 Some(out)
204 }
205
206 pub fn forward(&self, t: V2) -> Option<V2> {
209 let (c0, c1) = (self.elbow(0, t[0])[0], self.elbow(1, t[1])[0]);
210 let along = sub(c1, c0);
211 let d = norm(along);
212 let h2 = self.lb * self.lb - d * d / 4.0;
213 if !(d > 1e-12 && h2 >= 0.0) {
214 return None;
215 }
216 let (mid, h) = ([0.5 * (c0[0] + c1[0]), 0.5 * (c0[1] + c1[1])], h2.sqrt());
218 let normal = [-along[1] / d, along[0] / d];
219 let (one, other) =
220 ([mid[0] + h * normal[0], mid[1] + h * normal[1]], [mid[0] - h * normal[0], mid[1] - h * normal[1]]);
221 Some(if one[1] < other[1] { one } else { other })
222 }
223
224 fn constraint(&self, t: V2, p: V2) -> (M2, V2) {
226 let rows = [self.elbow(0, t[0]), self.elbow(1, t[1])];
227 let jx = rows.map(|e| sub(p, e[0]));
228 (jx, [dot(jx[0], rows[0][1]), dot(jx[1], rows[1][1])])
229 }
230
231 pub fn jacobian(&self, t: V2, p: V2) -> Option<M2> {
234 let (jx, jq) = self.constraint(t, p);
235 let inv = inverse(&jx)?;
236 Some(std::array::from_fn(|i| std::array::from_fn(|j| inv[i][j] * jq[j])))
237 }
238
239 pub fn velocity_term(&self, t: V2, p: V2, wt: V2, pv: V2) -> Option<V2> {
241 let (jx, _) = self.constraint(t, p);
242 let inv = inverse(&jx)?;
243 let w: V2 = std::array::from_fn(|i| {
244 let [_, d1, d2] = self.elbow(i, t[i]);
245 let rel = sub(pv, d1.map(|v| v * wt[i]));
246 wt[i] * wt[i] * dot(jx[i], d2) - dot(rel, rel)
247 });
248 Some(mul(&inv, w))
249 }
250}
251
252struct Extra {
262 elastic: bool,
263 joint: RotaryJoint,
264 load: f64,
266 payload: f64,
267 g: f64,
269 screw: Option<BallScrew>,
271 thermal: Option<ThermalFeedback>,
272 push: f64,
274}
275
276impl Extra {
277 fn mass(&self, attached: bool) -> f64 {
278 self.load + if attached { self.payload } else { 0.0 }
279 }
280
281 fn weight(&self, attached: bool) -> f64 {
283 -self.g * self.mass(attached)
284 }
285
286 fn ratio(&self) -> f64 {
287 self.joint.ratio()
288 }
289
290 fn rotor(&self, x: &[f64]) -> (f64, f64) {
292 if self.elastic { (x[3], x[4]) } else { (x[0] * self.ratio(), x[1] * self.ratio()) }
293 }
294
295 fn relaxes(&self) -> bool {
297 self.elastic && self.joint.gearbox.relax_stiffness > 0.0
298 }
299
300 fn arm(&self, x: &[f64]) -> f64 {
301 if self.relaxes() { x[5] } else { 0.0 }
302 }
303
304 fn gear(&self, x: &[f64]) -> GearTorque {
306 self.joint.gearbox.torque_with(x[3], x[4], x[0], x[1], self.arm(x))
307 }
308
309 fn solve(&self, x: &[f64], torque: f64, engaged: bool, attached: bool) -> (f64, f64, f64) {
313 let (j, i) = (&self.joint, self.ratio());
314 if self.elastic {
315 let gear = self.gear(x);
316 let acc =
317 (gear.output + j.output_torque(x[0], x[1]) + self.weight(attached) + self.push) / self.mass(attached);
318 return (acc, gear.rotor * i, gear.output);
319 }
320 let drive = j.rigid_drive(torque, x[0] * i, x[1] * i, x[2], engaged).0;
321 let rest = self.weight(attached) + j.output_torque(x[0], x[1]) + self.push;
322 let (m, r) = (self.mass(attached), j.reflected_inertia());
323 let solve = |loss: f64| (loss * drive + rest) / (m + loss * r);
325 let [loss] =
326 sim_components::mech::settled_loss([1.0], |&[loss]| [j.gearbox.loss_factor(drive - r * solve(loss), x[1])]);
327 let acc = (loss * drive + rest) / (m + loss * r);
328 let into = drive - r * acc;
329 (acc, into, loss * into)
330 }
331
332 fn energy(&self, x: &[f64], attached: bool) -> [f64; 3] {
334 if self.elastic {
335 let kinetic = 0.5 * self.mass(attached) * x[1] * x[1] + 0.5 * self.joint.rotor_inertia * x[4] * x[4];
336 let spring = self.joint.stop_energy(x[0]) + self.joint.gearbox.energy_with(x[3], x[0], self.arm(x));
337 return [kinetic, -self.weight(attached) * x[0], spring];
338 }
339 let kinetic = 0.5 * (self.mass(attached) + self.joint.reflected_inertia()) * x[1] * x[1];
340 [kinetic, -self.weight(attached) * x[0], self.joint.stop_energy(x[0])]
341 }
342
343 fn losses(&self, x: &[f64], torque: f64, engaged: bool, attached: bool) -> ([f64; 5], f64) {
346 let i = self.ratio();
347 let (rotor, speed) = self.rotor(x);
348 let [friction, stop, shaft, drag] = self.joint.losses(x[0], x[1], speed, x[2], engaged);
349 let other = (torque - self.joint.ripple.apply(torque, rotor)) * speed;
350 if self.elastic {
351 let g = self.gear(x);
352 let loss = self.joint.gearbox.loss_power_with(rotor, speed, x[0], x[1], self.arm(x));
353 return ([friction, shaft, loss + drag, stop, other], g.rotor - g.output / i);
354 }
355 let (_, into, out) = self.solve(x, torque, engaged, attached);
356 ([friction, shaft, (into - out) * x[1] + drag, stop, other], (into - out) / i)
357 }
358
359 fn torque_parts(&self, x: &[f64], torque: f64, engaged: bool, attached: bool) -> [f64; 4] {
361 let (j, i) = (&self.joint, self.ratio());
362 let (acc, ..) = self.solve(x, torque, engaged, attached);
363 let (_, gear_at_rotor) = self.losses(x, torque, engaged, attached);
364 let speed = self.rotor(x).1;
365 let held = j.brake.torque(engaged, speed, x[2]).0;
366 let inertia = if self.elastic {
368 let rotor_acc = j.rotor_under(torque, x[3], x[4], self.gear(x), x[2], engaged).0;
369 self.mass(attached) * acc / i + j.rotor_inertia * rotor_acc
370 } else {
371 (self.mass(attached) + j.reflected_inertia()) * acc / i
372 };
373 let parts = [
374 inertia,
375 -self.weight(attached) / i,
376 j.shaft.torque(speed) + held + gear_at_rotor + j.friction.torque(x[1]) / i,
377 ];
378 [parts[0], parts[1], parts[2], torque - parts.iter().sum::<f64>()]
379 }
380
381 fn feedforward(&self, acc: f64, attached: bool) -> f64 {
384 (self.mass(attached) * acc - self.weight(attached)) / self.ratio()
385 + self.joint.rotor_inertia * self.ratio() * acc
386 }
387}
388
389const TOOL_DROP: f64 = 0.1;
391
392pub struct ParallelScara {
393 legs: Legs,
394 base_radius: f64,
396 platform_radius: f64,
397 rod_spacing: f64,
398 elastic: bool,
399 extras: Vec<Extra>,
401 required_life: Option<f64>,
402 arm_inertia: f64,
404 arm_moment: f64,
406 g: f64,
407 m_platform: f64,
408 m_forearms: f64,
411 forearm_share: f64,
412 m_payload: f64,
413 payload_attached: bool,
414 brake_engaged: bool,
415 push: V2,
418 joints: [RotaryJoint; 2],
419 thermal: Option<ThermalFeedback>,
420 half_width: f64,
423 top: f64,
424 circle: (f64, f64),
425 max_condition: f64,
426 axes: Vec<AxisInfo>,
427 motors: Vec<MotorInfo>,
428 rest_slack: f64,
430}
431
432const N_ELASTIC: usize = 10;
434const N_RIGID: usize = 6;
436
437struct Losses {
440 powers: [f64; 8],
441 gear_at_rotor: V2,
442}
443
444impl ParallelScara {
445 fn on_platform(&self, tool: &[f64]) -> Vec<Part> {
448 let (p, size) = ([tool[0], tool[1]], 2.4 * self.platform_radius.max(0.03));
449 {
450 let flange = self.flange_z(tool);
451 let mut parts = vec![
452 Part::new(
453 "platform",
454 Shape::Box { size: [size, 0.06, self.rod_spacing.max(0.06) + 0.03] },
455 [p[0], p[1], 0.0],
456 [0.55, 0.55, 0.6],
457 ),
458 Part::new("quill", Shape::Box { size: [0.025, 0.025, -flange] }, [p[0], p[1], 0.5 * flange], [0.7; 3]),
459 Part::new("tool", Shape::Box { size: [0.06, 0.06, 0.02] }, [p[0], p[1], flange - 0.01], [0.3; 3]),
460 ];
461 if self.payload_attached && self.m_payload > 0.0 {
462 parts.push(Part::new(
463 "payload",
464 Shape::Box { size: [0.12, 0.12, 0.1] },
465 [p[0], p[1], flange - 0.07],
466 [0.2, 0.7, 0.3],
467 ));
468 }
469 parts
470 }
471 }
472
473 fn flange_z(&self, tool: &[f64]) -> f64 {
475 match self.extras.iter().position(|x| x.screw.is_some()) {
476 Some(e) => tool[2 + e] - self.axes[2 + e].max - TOOL_DROP,
477 None => -TOOL_DROP,
478 }
479 }
480
481 fn tool_pose(&self, s: &[f64]) -> Vec<f64> {
483 let (p, _) = self.pose(self.arms(s).0);
484 let mut tool = p.to_vec();
485 tool.extend((0..self.extras.len()).map(|e| self.extra_state(s, e)[0]));
486 tool
487 }
488
489 fn extra_state<'a>(&self, s: &'a [f64], e: usize) -> &'a [f64] {
492 let at = self.planar_len() + self.extra_len() * e;
493 &s[at..at + self.extra_len()]
494 }
495
496 fn extra_len(&self) -> usize {
498 if self.extras.iter().any(Extra::relaxes) {
499 6
500 } else if self.elastic {
501 5
502 } else {
503 3
504 }
505 }
506
507 fn planar_len(&self) -> usize {
508 if self.elastic { N_ELASTIC } else { N_RIGID }
509 }
510
511 fn z_axis(cfg: &Config, payload: f64, g: f64) -> Result<(Extra, AxisInfo, f64), ConfigError> {
514 let own = motor_config(cfg, "3")?;
515 let mut joint = RotaryJoint::linear_from_config(&own)?;
516 let screw = BallScrew::from_config(&own)?;
517 if screw.length < joint.range.1 {
518 return Err(ConfigError::Invalid("screw.length_m".into()));
519 }
520 let carriage = cfg.non_negative("z_axis.carriage_kg")?;
521 screw.converter(screw.softest_position()).apply_to(&own, &mut joint, carriage)?;
523 if own.bool("effects.joint_friction")? {
525 joint.friction.coulomb += screw.preload_torque() * screw.ratio();
526 }
527 let axis = Self::axis_info(cfg, "z", "axis-z", "m", joint.range)?;
528 let carried = cfg.non_negative("z_axis.unit_kg")? + carriage;
529 let elastic = cfg.bool("effects.joint_elasticity")?;
530 let extra = Extra { elastic, joint, load: carriage, payload, g, screw: Some(screw), thermal: None, push: 0.0 };
531 Ok((extra, axis, carried))
532 }
533
534 fn tool_turn(cfg: &Config, payload: bool) -> Result<(Extra, AxisInfo, f64), ConfigError> {
537 let own = motor_config(cfg, "4")?;
538 let on = cfg.bool("effects.joint_friction")?;
539 let friction = ShaftFriction {
540 coulomb: if on { cfg.non_negative("tool_turn.friction_coulomb_nm")? } else { 0.0 },
541 viscous: if on { cfg.non_negative("tool_turn.friction_viscous_nm_s_rad")? } else { 0.0 },
542 smoothing: cfg.positive("tool_turn.friction_smoothing_rad_s")?,
543 ..ShaftFriction::NONE
544 };
545 let range = (cfg.f64("axis.c.min_angle_deg")?.to_radians(), cfg.f64("axis.c.max_angle_deg")?.to_radians());
546 if range.0 >= range.1 {
547 return Err(ConfigError::Invalid("axis.c.max_angle_deg".into()));
548 }
549 let joint = RotaryJoint::with(&own, friction, HardStop { stiffness: 0.0, damping: 0.0 }, range)?;
550 let extra = Extra {
551 elastic: cfg.bool("effects.joint_elasticity")?,
552 joint,
553 load: cfg.positive("tool_turn.inertia_kgm2")?,
554 payload: if payload { cfg.non_negative("tool_turn.payload_inertia_kgm2")? } else { 0.0 },
555 g: 0.0,
556 screw: None,
557 thermal: ThermalFeedback::from_config(&own)?,
558 push: 0.0,
559 };
560 Ok((extra, Self::axis_info(cfg, "c", "axis-c", "rad", range)?, cfg.non_negative("tool_turn.unit_kg")?))
561 }
562
563 fn axis_info(
565 cfg: &Config,
566 id: &'static str,
567 key: &'static str,
568 unit: &'static str,
569 (min, max): (f64, f64),
570 ) -> Result<AxisInfo, ConfigError> {
571 Ok(AxisInfo {
572 id,
573 key,
574 unit,
575 min,
576 max,
577 max_vel: cfg.positive(&format!("axis.{id}.max_velocity_{unit}_s"))?,
578 max_acc: cfg.positive(&format!("axis.{id}.max_acceleration_{unit}_s2"))?,
579 max_jerk: cfg.positive(&format!("axis.{id}.max_jerk_{unit}_s3"))?,
580 })
581 }
582
583 pub fn new(cfg: &Config) -> Result<Self, ConfigError> {
584 let base_radius = cfg.positive("geometry.base_radius_m")?;
585 let platform_radius = cfg.non_negative("geometry.platform_radius_m")?;
586 let (la, lb) = (cfg.positive("geometry.upper_arm_m")?, cfg.positive("geometry.forearm_m")?);
587 if lb <= la {
588 return Err(ConfigError::Invalid("geometry.forearm_m".into()));
589 }
590 let share = cfg.non_negative("mass.forearm_elbow_share")?;
591 if share > 1.0 {
592 return Err(ConfigError::Invalid("mass.forearm_elbow_share".into()));
593 }
594 let i_arm = cfg.positive("mass.upper_arm_inertia_kgm2")?;
595 let (m_elbow, m_fb) = (cfg.non_negative("mass.elbow_kg")?, cfg.non_negative("mass.forearm_pair_kg")?);
596 let elbow = m_elbow + share * m_fb;
597 let (half_width, top) = (cfg.positive("workspace.half_width_m")?, cfg.f64("workspace.near_y_m")?);
598 let (edge, centre) = (cfg.positive("workspace.depth_edge_m")?, cfg.positive("workspace.depth_centre_m")?);
599 if centre < edge {
600 return Err(ConfigError::Invalid("workspace.depth_centre_m".into()));
601 }
602 let sag = centre - edge;
605 let circle = if sag > 0.0 {
606 let r = (half_width * half_width + sag * sag) / (2.0 * sag);
607 (top - centre + r, r)
608 } else {
609 (f64::INFINITY, f64::INFINITY)
610 };
611 let joint = RotaryJoint::from_config(cfg)?;
612 let g = if cfg.bool("effects.gravity")? { G } else { 0.0 };
613 let payload = cfg.bool("effects.payload")?;
614 let m_payload = if payload { cfg.non_negative("mass.payload_kg")? } else { 0.0 };
615 let mut axes = vec![
616 Self::axis_info(cfg, "x", "axis-x", "m", (-half_width, half_width))?,
617 Self::axis_info(cfg, "y", "axis-y", "m", (top - centre, top))?,
618 ];
619 let mut motors = vec![MotorInfo { id: "1", key: "motor-arm-1" }, MotorInfo { id: "2", key: "motor-arm-2" }];
620 let (mut extras, mut carried) = (Vec::new(), 0.0);
621 let mut add = |(extra, axis, mass): (Extra, AxisInfo, f64), motor: MotorInfo| {
622 extras.push(extra);
623 axes.push(axis);
624 motors.push(motor);
625 carried += mass;
626 };
627 if cfg.bool("z_axis.enabled")? {
628 add(Self::z_axis(cfg, m_payload, g)?, MotorInfo { id: "3", key: "motor-z" });
629 }
630 if cfg.bool("tool_turn.enabled")? {
631 add(Self::tool_turn(cfg, payload)?, MotorInfo { id: "4", key: "motor-tool" });
632 }
633 let mut scara = Self {
634 legs: Legs::new(base_radius - platform_radius, la, lb),
635 base_radius,
636 platform_radius,
637 rod_spacing: cfg.non_negative("geometry.forearm_spacing_m")?,
638 elastic: cfg.bool("effects.joint_elasticity")?,
639 extras,
640 required_life: cfg.f64("ratings.required_life_h").ok(),
641 arm_inertia: i_arm + la * la * elbow,
642 arm_moment: cfg.positive("mass.upper_arm_kg")? * cfg.non_negative("mass.upper_arm_cg_m")? + la * elbow,
645 g,
646 m_platform: cfg.positive("mass.platform_kg")? + 2.0 * (1.0 - share) * m_fb + carried,
647 m_forearms: m_fb,
648 forearm_share: share,
649 m_payload,
650 payload_attached: true,
651 brake_engaged: false,
652 push: [0.0; 2],
653 joints: [joint.clone(), joint],
654 thermal: ThermalFeedback::from_config(cfg)?,
655 half_width,
656 top,
657 circle,
658 max_condition: cfg.positive("workspace.max_condition_number")?,
659 axes,
660 motors,
661 rest_slack: 0.0,
662 };
663 scara.rest_slack = scara.rest_sag();
664 Ok(scara)
665 }
666
667 fn rest_sag(&self) -> f64 {
675 if !self.elastic {
676 return 1e-4;
677 }
678 let twist = |x: &Extra| {
679 let gear = x.joint.gearbox.softest(x.joint.range);
680 gear.static_twist(-x.weight(true)).abs().max(gear.half_backlash)
681 };
682 let mut most = self.extras.iter().map(twist).fold(0f64, f64::max);
683 for column in 0..=40 {
684 let x = self.half_width * (column as f64 / 20.0 - 1.0);
685 let lowest = self.bottom(x);
686 for z in (0..=8).map(|k| lowest + (self.top - lowest) * k as f64 / 8.0) {
687 let p = [x, z];
688 if !self.in_envelope(&p, 1e-9) {
689 continue;
690 }
691 let Some(t) = self.legs.inverse(p) else { continue };
692 for signs in 0..4 {
693 let half =
694 |k: usize| if signs >> k & 1 == 1 { 1.0 } else { -1.0 } * self.joints[k].gearbox.half_backlash;
695 if let Some(q) = self.legs.forward(std::array::from_fn(|k| t[k] + half(k))) {
696 most = most.max(norm(sub(q, p)));
697 }
698 }
699 }
700 }
701 (1.1 * most).max(1e-4)
702 }
703
704 fn plane_modes(&self, tool: &[f64], small: bool) -> Vec<sim_core::Mode> {
710 let Some(t) = self.legs.inverse([tool[0], tool[1]]).filter(|_| self.elastic) else { return Vec::new() };
711 let (m, _) = self.load(t, [0.0; 2]);
712 let k: V2 = std::array::from_fn(|i| spring(&self.joints[i].gearbox, small));
713 let (det, b) = (m[0][0] * m[1][1] - m[0][1] * m[1][0], k[0] * m[1][1] + k[1] * m[0][0]);
714 let root = (b * b - 4.0 * det * k[0] * k[1]).max(0.0).sqrt();
715 [2.0 * k[0] * k[1] / (b + root), (b + root) / (2.0 * det)]
717 .map(|lambda| {
718 let v = mode_vector(k, &m, lambda);
719 let w = lambda.sqrt();
720 let damped: f64 = (0..2).map(|i| self.joints[i].gearbox.damping * v[i] * v[i]).sum();
721 sim_core::Mode { hz: w / std::f64::consts::TAU, damping: damped / (2.0 * w * dot(v, mul(&m, v))) }
722 })
723 .into_iter()
724 .filter(|mode| mode.hz.is_finite())
725 .collect()
726 }
727
728 fn modes_at(&self, tool: &[f64], small: bool) -> Vec<sim_core::Mode> {
733 let mut modes = self.plane_modes(tool, small);
734 if self.elastic {
735 modes.extend(self.extras.iter().enumerate().map(|(e, x)| {
736 let (k, m) = (spring(&x.joint.gearbox.at(tool[2 + e]), small), x.mass(self.payload_attached));
737 sim_core::Mode {
738 hz: (k / m).sqrt() / std::f64::consts::TAU,
739 damping: x.joint.gearbox.at(tool[2 + e]).damping_at((k / m).sqrt()) / (2.0 * (k * m).sqrt()),
740 }
741 }));
742 }
743 modes.retain(|mode| mode.hz.is_finite());
744 modes.sort_by(|a, b| a.hz.total_cmp(&b.hz));
745 modes
746 }
747
748 pub fn legs(&self) -> &Legs {
749 &self.legs
750 }
751
752 fn ratio(&self) -> f64 {
753 self.joints[0].ratio()
754 }
755
756 pub fn m_nt(&self) -> f64 {
758 self.m_platform + if self.payload_attached { self.m_payload } else { 0.0 }
759 }
760
761 pub fn arm_inertia(&self) -> f64 {
763 self.arm_inertia
764 }
765
766 fn arms(&self, s: &[f64]) -> (V2, V2) {
768 ([s[0], s[1]], [s[2], s[3]])
769 }
770
771 fn rotors(&self, s: &[f64]) -> (V2, V2) {
773 if self.elastic {
774 ([s[4], s[5]], [s[6], s[7]])
775 } else {
776 let i = self.ratio();
777 ([s[0] * i, s[1] * i], [s[2] * i, s[3] * i])
778 }
779 }
780
781 fn brakes(&self, s: &[f64]) -> V2 {
782 let at = if self.elastic { 8 } else { 4 };
783 [s[at], s[at + 1]]
784 }
785
786 fn pose(&self, t: V2) -> (V2, M2) {
788 self.legs
789 .forward(t)
790 .and_then(|p| Some((p, self.legs.jacobian(t, p)?)))
791 .unwrap_or(([f64::NAN; 2], [[f64::NAN; 2]; 2]))
792 }
793
794 fn load(&self, t: V2, w: V2) -> (M2, V2) {
796 let (p, j) = self.pose(t);
797 let jt = transpose(&j);
798 let m = self.m_nt();
799 let mass: M2 = std::array::from_fn(|r| {
800 std::array::from_fn(|c| m * dot(jt[r], jt[c]) + if r == c { self.arm_inertia } else { 0.0 })
801 });
802 let pv = mul(&j, w);
803 let velocity = self.legs.velocity_term(t, p, w, pv).map_or([f64::NAN; 2], |a| mul(&jt, a.map(|v| m * v)));
804 (mass, velocity)
805 }
806
807 fn pushed(&self, s: &[f64]) -> V2 {
812 let force = [self.push[0], self.push[1], 0.0, 0.0];
813 let force = &force[..2 + self.extras.len()];
814 sim_core::tool_force_on_rates(self, s, force, 2..4).map_or([0.0; 2], |q| [q[0], q[1]])
815 }
816
817 fn rigid_solve(&self, s: &[f64], torque: &[f64]) -> (V2, V2, V2) {
818 let (t, w) = self.arms(s);
819 let (rotor, rotor_speed) = self.rotors(s);
820 let brakes = self.brakes(s);
821 let (mass, velocity) = self.load(t, w);
822 let drive: V2 = std::array::from_fn(|k| {
823 self.joints[k].rigid_drive(torque[k], rotor[k], rotor_speed[k], brakes[k], self.brake_engaged).0
824 });
825 let push = self.pushed(s);
826 let rest: V2 = std::array::from_fn(|k| self.joints[k].output_torque(t[k], w[k]) - velocity[k] + push[k]);
827 let solve = |loss: V2| -> V2 {
828 let m: M2 = std::array::from_fn(|r| {
829 std::array::from_fn(|c| {
830 mass[r][c] + if r == c { loss[r] * self.joints[r].reflected_inertia() } else { 0.0 }
831 })
832 });
833 let rhs: V2 = std::array::from_fn(|k| loss[k] * drive[k] + rest[k]);
834 inverse(&m).map_or([f64::NAN; 2], |inv| mul(&inv, rhs))
835 };
836 let loss = sim_components::mech::settled_loss([1.0; 2], |loss| {
838 let acc = solve(*loss);
839 std::array::from_fn(|k| {
840 self.joints[k].gearbox.loss_factor(drive[k] - self.joints[k].reflected_inertia() * acc[k], w[k])
841 })
842 });
843 let acc = solve(loss);
844 let into: V2 = std::array::from_fn(|k| drive[k] - self.joints[k].reflected_inertia() * acc[k]);
845 (acc, into, std::array::from_fn(|k| loss[k] * into[k]))
846 }
847
848 fn arm_acceleration(&self, s: &[f64], torque: &[f64]) -> V2 {
850 if self.elastic {
851 let mut d = vec![0.0; self.state_len()];
852 self.derivatives(s, torque, &mut d);
853 [d[2], d[3]]
854 } else {
855 self.rigid_solve(s, torque).0
856 }
857 }
858
859 fn gear_output(&self, s: &[f64], torque: &[f64]) -> V2 {
861 if self.elastic {
862 std::array::from_fn(|k| self.joints[k].gearbox.torque(s[4 + k], s[6 + k], s[k], s[2 + k]).output)
863 } else {
864 self.rigid_solve(s, torque).2
865 }
866 }
867
868 fn energy_parts(&self, s: &[f64]) -> [f64; 3] {
869 let (t, w) = self.arms(s);
870 let (mass, ..) = self.load(t, w);
871 let mut kinetic = 0.5 * dot(w, mul(&mass, w));
872 let potential = 0.0;
874 let mut elastic: f64 = (0..2).map(|k| self.joints[k].stop_energy(t[k])).sum();
875 if self.elastic {
876 for k in 0..2 {
877 kinetic += 0.5 * self.joints[k].rotor_inertia * s[6 + k] * s[6 + k];
878 elastic += self.joints[k].gearbox.energy(s[4 + k], s[k]);
879 }
880 } else {
881 kinetic += 0.5 * (0..2).map(|k| self.joints[k].reflected_inertia() * w[k] * w[k]).sum::<f64>();
882 }
883 let mut parts = [kinetic, potential, elastic];
884 for (e, x) in self.extras.iter().enumerate() {
885 let own = x.energy(self.extra_state(s, e), self.payload_attached);
886 (0..3).for_each(|i| parts[i] += own[i]);
887 }
888 parts
889 }
890
891 fn losses(&self, s: &[f64], torque: &[f64]) -> Losses {
892 let (t, w) = self.arms(s);
893 let (rotor, rotor_speed) = self.rotors(s);
894 let brakes = self.brakes(s);
895 let mut powers = [0.0; 8];
896 let mut gear_at_rotor = [0.0; 2];
897 let rigid = (!self.elastic).then(|| self.rigid_solve(s, torque));
898 let (mut stops, mut other) = (0.0, 0.0);
899 for k in 0..2 {
900 let joint = &self.joints[k];
901 let [friction, stop, shaft, drag] = joint.losses(t[k], w[k], rotor_speed[k], brakes[k], self.brake_engaged);
902 let gear = match &rigid {
903 Some((_, into, out)) => {
904 gear_at_rotor[k] = (into[k] - out[k]) / joint.ratio();
905 (into[k] - out[k]) * w[k]
906 }
907 None => {
908 let g = joint.gearbox.torque(s[4 + k], s[6 + k], s[k], s[2 + k]);
909 gear_at_rotor[k] = g.rotor - g.output / joint.ratio();
910 joint.gearbox.loss_power(s[4 + k], s[6 + k], s[k], s[2 + k])
911 }
912 };
913 powers[3 * k..3 * k + 3].copy_from_slice(&[friction, shaft, gear + drag]);
914 stops += stop;
915 other += (torque[k] - joint.ripple.apply(torque[k], rotor[k])) * rotor_speed[k];
916 }
917 for (e, x) in self.extras.iter().enumerate() {
919 let ([.., stop, ripple], _) =
920 x.losses(self.extra_state(s, e), torque[2 + e], self.brake_engaged, self.payload_attached);
921 stops += stop;
922 other += ripple;
923 }
924 powers[6] = stops;
925 powers[7] = other;
926 Losses { powers, gear_at_rotor }
927 }
928
929 fn bottom(&self, x: f64) -> f64 {
931 let (centre, r) = self.circle;
932 if centre.is_finite() { centre - (r * r - x * x).max(0.0).sqrt() } else { self.axes[1].min }
933 }
934
935 fn in_envelope(&self, p: &[f64], slack: f64) -> bool {
938 let (centre, r) = self.circle;
939 let above =
940 if centre.is_finite() { p[0].hypot(p[1] - centre) <= r + slack } else { p[1] >= self.axes[1].min - slack };
941 p[0].abs() <= self.half_width + slack && p[1] <= self.top + slack && above
942 }
943
944 fn view_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
946 let (t, w) = self.arms(s);
947 let (_, rotor_speed) = self.rotors(s);
948 let brakes = self.brakes(s);
949 let (mass, velocity) = self.load(t, w);
950 let acc = self.arm_acceleration(s, torque);
951 let moving = mul(&mass, acc);
952 let losses = self.losses(s, torque);
953 for k in 0..2 {
954 let joint = &self.joints[k];
955 let i = joint.ratio();
956 let held = joint.brake.torque(self.brake_engaged, rotor_speed[k], brakes[k]).0;
957 let parts = [
958 (moving[k] + velocity[k] + joint.reflected_inertia() * acc[k]) / i,
959 0.0,
961 joint.shaft.torque(rotor_speed[k]) + held + losses.gear_at_rotor[k] + joint.friction.torque(w[k]) / i,
962 ];
963 out.extend(parts);
964 out.push(torque[k] - parts.iter().sum::<f64>());
965 }
966 out.extend(losses.powers);
967 out.extend(self.energy_parts(s));
968 for (e, x) in self.extras.iter().enumerate() {
969 let (state, at) = (self.extra_state(s, e), (torque[2 + e], self.brake_engaged, self.payload_attached));
970 out.extend(x.torque_parts(state, at.0, at.1, at.2));
971 out.extend(&x.losses(state, at.0, at.1, at.2).0[..3]);
972 }
973 for k in 0..2 {
974 out.extend(self.joints[k].friction_signals(w[k]));
975 }
976 }
977
978 fn extra_losses(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
980 for (e, x) in self.extras.iter().enumerate() {
981 let state = self.extra_state(s, e);
982 out.extend(&x.losses(state, torque[2 + e], self.brake_engaged, self.payload_attached).0[..3]);
983 }
984 }
985
986 fn motor_infos(motor: &MotorInfo, joint: &str, coupled: bool) -> (Vec<SignalInfo>, Vec<SignalInfo>) {
988 let parts = TORQUE_PARTS.map(|part| {
989 SignalInfo::new(
990 format!("motor.{}.torque_{part}", motor.id),
991 motor.key,
992 &format!("quantity-torque-{part}"),
993 "N m",
994 )
995 });
996 let gear = if coupled { "quantity-coupling-loss-power" } else { "quantity-gearbox-loss-power" };
997 let losses = vec![
998 SignalInfo::new(format!("{LOSS_PREFIX}joint_{}", motor.id), joint, "quantity-friction-power", "W"),
999 SignalInfo::new(
1000 format!("{LOSS_PREFIX}shaft_{}", motor.id),
1001 motor.key,
1002 "quantity-shaft-friction-power",
1003 "W",
1004 ),
1005 SignalInfo::new(format!("{LOSS_PREFIX}gearbox_{}", motor.id), motor.key, gear, "W"),
1006 ];
1007 (parts.to_vec(), losses)
1008 }
1009
1010 fn effect_infos(&self, out: &mut Vec<SignalInfo>) {
1011 let arms: Vec<_> = (0..2)
1012 .map(|k| Self::motor_infos(&self.motors[k], ["arm-1", "arm-2"][k], self.joints[k].gearbox.is_coupling()))
1013 .collect();
1014 out.extend(arms.iter().flat_map(|(parts, _)| parts.clone()));
1015 out.extend(arms.into_iter().flat_map(|(_, losses)| losses));
1016 out.push(SignalInfo::new(format!("{LOSS_PREFIX}hard_stops"), "group-joint", "quantity-damping-power", "W"));
1017 out.push(SignalInfo::new(format!("{LOSS_PREFIX}other"), "loss-other", "quantity-power-given-off", "W"));
1018 out.extend(ENERGY_PARTS.map(|part| {
1019 SignalInfo::new(format!("energy.{part}"), "group-energy", &format!("quantity-energy-{part}"), "J")
1020 }));
1021 for (e, x) in self.extras.iter().enumerate() {
1022 let (parts, losses) = Self::motor_infos(&self.motors[2 + e], self.axes[2 + e].key, x.joint.coupled);
1023 out.extend(parts);
1024 out.extend(losses);
1025 }
1026 for k in 0..2 {
1027 out.extend(RotaryJoint::friction_infos(JOINT_CONTACTS[k], ARMS[k]));
1028 }
1029 }
1030}
1031
1032const JOINT_CONTACTS: [&str; 2] = ["joint.1", "joint.2"];
1034const ARMS: [&str; 2] = ["arm-1", "arm-2"];
1035
1036impl Machine for ParallelScara {
1037 fn frame_momentum(&self, s: &[f64]) -> Option<sim_core::FrameMomentum> {
1041 use sim_components::base::{add_point, add_spin, add_turning};
1042 let mut f = sim_core::FrameMomentum { gravity: [0.0, 0.0, -self.g], ..Default::default() };
1043 let (t, w) = self.arms(s);
1044 let (p, j) = self.pose(t);
1045 let pv = mul(&j, w);
1046 let mut plate = self.m_nt();
1047 let rotor_speed = self.rotors(s).1;
1048 for (e, x) in self.extras.iter().enumerate() {
1049 let state = self.extra_state(s, e);
1050 let (q, v, spin) = (state[0], state[1], x.rotor(state).1);
1051 let rotor = x.joint.rotor_inertia;
1052 if x.screw.is_some() {
1053 let moved = x.mass(self.payload_attached);
1054 plate -= moved;
1055 add_point(&mut f, moved, [p[0], p[1], q], [pv[0], pv[1], v]);
1056 } else {
1057 add_spin(&mut f, [0.0, 0.0, 1.0], x.mass(self.payload_attached), v);
1058 }
1059 add_spin(&mut f, [0.0, 0.0, 1.0], rotor, spin);
1060 }
1061 let (la, m_fb) = (self.legs.la, self.m_forearms);
1065 let (at_elbow, at_plate) = ((self.forearm_share - 1.0 / 6.0) * m_fb, (5.0 / 6.0 - self.forearm_share) * m_fb);
1066 add_point(&mut f, plate - 2.0 * at_plate, [p[0], p[1], 0.0], [pv[0], pv[1], 0.0]);
1067 for k in 0..2 {
1068 let (side, (sin, cos)) = (SIDE[k], t[k].sin_cos());
1069 let (dir, ddir) = ([side * cos, -sin, 0.0], [-side * sin, -cos, 0.0]);
1070 let joint = [side * self.base_radius, 0.0, 0.0];
1071 let (inertia, moment) = (self.arm_inertia - la * la * at_elbow, self.arm_moment - la * at_elbow);
1072 add_turning(&mut f, joint, dir, ddir, w[k], inertia, moment);
1073 let end = [p[0] + side * self.platform_radius, p[1], 0.0];
1074 let middle: [f64; 3] = std::array::from_fn(|i| 0.5 * (joint[i] + la * dir[i] + end[i]));
1075 let speed: [f64; 3] = std::array::from_fn(|i| 0.5 * (la * w[k] * ddir[i] + [pv[0], pv[1], 0.0][i]));
1076 add_point(&mut f, 2.0 / 3.0 * m_fb, middle, speed);
1077 add_spin(&mut f, [0.0, 0.0, -side], self.joints[k].rotor_inertia, rotor_speed[k]);
1078 }
1079 Some(f)
1080 }
1081 fn axes(&self) -> &[AxisInfo] {
1082 &self.axes
1083 }
1084 fn motors(&self) -> &[MotorInfo] {
1085 &self.motors
1086 }
1087
1088 fn inverse(&self, tool: &[f64], motors: &mut [f64]) {
1090 let t = self.legs.inverse([tool[0], tool[1]]).unwrap_or([f64::NAN; 2]);
1091 for k in 0..2 {
1092 motors[k] = self.ratio() * t[k];
1093 }
1094 for (e, x) in self.extras.iter().enumerate() {
1095 motors[2 + e] = x.ratio() * tool[2 + e];
1096 }
1097 }
1098 fn forward(&self, motors: &[f64], tool: &mut [f64]) {
1099 let i = self.ratio();
1100 let p = self.legs.forward([motors[0] / i, motors[1] / i]).unwrap_or([f64::NAN; 2]);
1101 tool[..2].copy_from_slice(&p);
1102 for (e, x) in self.extras.iter().enumerate() {
1103 tool[2 + e] = motors[2 + e] / x.ratio();
1104 }
1105 }
1106
1107 fn state_len(&self) -> usize {
1108 self.planar_len() + self.extra_len() * self.extras.len()
1109 }
1110
1111 fn equilibrium(&self, tool: &[f64], state: &mut Vec<f64>, torque: &mut [f64]) {
1112 let t = self.legs.inverse([tool[0], tool[1]]).unwrap_or([f64::NAN; 2]);
1113 state.clear();
1114 state.extend(t);
1115 state.extend([0.0; 2]);
1116 for k in 0..2 {
1117 let joint = &self.joints[k];
1118 let out = -joint.output_torque(t[k], 0.0);
1120 let rotor = joint.ratio() * (t[k] + if self.elastic { joint.gearbox.static_twist(out) } else { 0.0 });
1121 if self.elastic {
1122 state.push(rotor);
1123 }
1124 torque[k] = joint.ripple.invert(out / joint.ratio(), rotor);
1125 }
1126 state.resize(self.planar_len(), 0.0);
1128 for (e, x) in self.extras.iter().enumerate() {
1129 let (q, i) = (tool[2 + e], x.ratio());
1131 let out = -x.weight(self.payload_attached) - x.joint.output_torque(q, 0.0);
1132 let rotor = i * (q + if self.elastic { x.joint.gearbox.static_twist_at(q, out) } else { 0.0 });
1134 let held = if self.elastic { x.joint.gearbox.held_at(q, out) } else { out };
1135 torque[2 + e] = x.joint.ripple.invert(held / i, rotor);
1136 state.extend([q, 0.0, 0.0]);
1137 if self.elastic {
1138 state.extend([rotor, 0.0]);
1139 }
1140 if self.extra_len() == 6 {
1141 state.push(x.joint.gearbox.arm_rest(rotor, q));
1142 }
1143 }
1144 }
1145
1146 fn adopt_state(&self, old: &dyn Machine, old_state: &[f64]) -> Vec<f64> {
1151 let (m, n) = (self.axes.len(), self.motors.len());
1152 let (mut pos, mut vel, mut before, mut after) = (vec![0.0; m], vec![0.0; m], vec![0.0; n], vec![0.0; n]);
1153 old.tool_state(old_state, &mut pos, &mut vel);
1154 old.inverse(&pos, &mut before);
1155 self.inverse(&pos, &mut after);
1156 if old_state.len() == self.state_len() && before == after {
1157 return old_state.to_vec();
1158 }
1159 let mut state = Vec::new();
1160 self.equilibrium(&pos, &mut state, &mut vec![0.0; n]);
1161 self.set_tool_velocity(&mut state, &vel);
1162 if self.elastic && old_state.len() == self.state_len() {
1163 let (mut rotor, mut speed) = (vec![0.0; n], vec![0.0; n]);
1164 old.motor_state(old_state, &mut rotor, &mut speed);
1165 for k in 0..2 {
1166 state[4 + k] = after[k] + rotor[k] - before[k];
1167 }
1168 for e in 0..self.extras.len() {
1170 let at = self.planar_len() + self.extra_len() * e + 3;
1171 state[at] = after[2 + e] + rotor[2 + e] - before[2 + e];
1172 if self.extras[e].relaxes() {
1174 let (g, q) = (&self.extras[e].joint.gearbox, state[at - 3]);
1175 let stretch = g.arm_rest(old_state[at], old_state[at - 3]) - old_state[at + 2];
1176 state[at + 2] = g.arm_rest(state[at], q) - stretch;
1177 }
1178 }
1179 }
1180 state
1181 }
1182
1183 fn derivatives(&self, s: &[f64], torque: &[f64], out: &mut [f64]) {
1184 for (e, x) in self.extras.iter().enumerate() {
1185 let (state, at) = (self.extra_state(s, e), self.planar_len() + self.extra_len() * e);
1186 out[at] = state[1];
1187 out[at + 1] = x.solve(state, torque[2 + e], self.brake_engaged, self.payload_attached).0;
1188 out[at + 2] = x.joint.brake.torque(self.brake_engaged, x.rotor(state).1, state[2]).1;
1189 if self.elastic {
1190 let (j, engaged) = (&x.joint, self.brake_engaged);
1191 let rotor_acc = j.rotor_under(torque[2 + e], state[3], state[4], x.gear(state), state[2], engaged).0;
1192 (out[at + 3], out[at + 4]) = (state[4], rotor_acc);
1193 if self.extra_len() == 6 {
1194 out[at + 5] = j.gearbox.arm(state[3], state[0], x.arm(state)).1;
1195 }
1196 }
1197 }
1198 if !self.elastic {
1199 let (acc, ..) = self.rigid_solve(s, torque);
1200 let (_, rotor_speed) = self.rotors(s);
1201 let brakes = self.brakes(s);
1202 out[..2].copy_from_slice(&s[2..4]);
1203 out[2..4].copy_from_slice(&acc);
1204 for k in 0..2 {
1205 out[4 + k] = self.joints[k].brake.torque(self.brake_engaged, rotor_speed[k], brakes[k]).1;
1206 }
1207 return;
1208 }
1209 let (t, w) = self.arms(s);
1210 let (mass, velocity) = self.load(t, w);
1211 let (mut rhs, push) = ([0.0; 2], self.pushed(s));
1212 for k in 0..2 {
1213 let joint = &self.joints[k];
1214 let (gear, rotor_acc, brake_rate) =
1215 joint.rotor(torque[k], s[4 + k], s[6 + k], t[k], w[k], s[8 + k], self.brake_engaged);
1216 rhs[k] = gear.output - velocity[k] + joint.output_torque(t[k], w[k]) + push[k];
1217 out[4 + k] = s[6 + k];
1218 out[6 + k] = rotor_acc;
1219 out[8 + k] = brake_rate;
1220 }
1221 let acc = inverse(&mass).map_or([f64::NAN; 2], |inv| mul(&inv, rhs));
1222 out[..2].copy_from_slice(&s[2..4]);
1223 out[2..4].copy_from_slice(&acc);
1224 }
1225
1226 fn tool_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
1227 let (t, w) = self.arms(s);
1228 let (p, j) = self.pose(t);
1229 pos[..2].copy_from_slice(&p);
1230 vel[..2].copy_from_slice(&mul(&j, w));
1231 for e in 0..self.extras.len() {
1232 (pos[2 + e], vel[2 + e]) = (self.extra_state(s, e)[0], self.extra_state(s, e)[1]);
1233 }
1234 }
1235 fn set_tool_velocity(&self, s: &mut [f64], vel: &[f64]) {
1236 let (t, _) = self.arms(s);
1237 let (_, j) = self.pose(t);
1238 let w = inverse(&j).map_or([f64::NAN; 2], |inv| mul(&inv, [vel[0], vel[1]]));
1239 s[2..4].copy_from_slice(&w);
1240 if self.elastic {
1241 for k in 0..2 {
1242 s[6 + k] = self.joints[k].ratio() * w[k];
1243 }
1244 }
1245 for (e, x) in self.extras.iter().enumerate() {
1246 let at = self.planar_len() + self.extra_len() * e;
1247 s[at + 1] = vel[2 + e];
1248 if self.elastic {
1249 s[at + 4] = x.ratio() * vel[2 + e];
1250 }
1251 }
1252 }
1253 fn motor_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
1254 let (rotor, speed) = self.rotors(s);
1255 pos[..2].copy_from_slice(&rotor);
1256 vel[..2].copy_from_slice(&speed);
1257 for (e, x) in self.extras.iter().enumerate() {
1258 (pos[2 + e], vel[2 + e]) = x.rotor(self.extra_state(s, e));
1259 }
1260 }
1261
1262 fn feedforward_torque(&self, pos: &[f64], acc: &[f64], out: &mut [f64]) {
1265 let t = self.legs.inverse([pos[0], pos[1]]).unwrap_or([f64::NAN; 2]);
1266 let (mass, _) = self.load(t, [0.0; 2]);
1267 let (_, j) = self.pose(t);
1268 let arm_acc = inverse(&j).map_or([f64::NAN; 2], |inv| mul(&inv, [acc[0], acc[1]]));
1269 let at_arm = mul(&mass, arm_acc);
1270 for k in 0..2 {
1271 let joint = &self.joints[k];
1272 out[k] = at_arm[k] / joint.ratio() + joint.rotor_inertia * joint.ratio() * arm_acc[k];
1273 }
1274 for (e, x) in self.extras.iter().enumerate() {
1275 out[2 + e] = x.feedforward(acc[2 + e], self.payload_attached);
1276 }
1277 }
1278
1279 fn feedforward_torque_moving(&self, pos: &[f64], vel: &[f64], acc: &[f64], out: &mut [f64]) {
1282 let p = [pos[0], pos[1]];
1283 let t = self.legs.inverse(p).unwrap_or([f64::NAN; 2]);
1284 let (_, j) = self.pose(t);
1285 let inv = inverse(&j).unwrap_or([[f64::NAN; 2]; 2]);
1286 let (pv, pa) = ([vel[0], vel[1]], [acc[0], acc[1]]);
1287 let w = mul(&inv, pv);
1288 let bend = self.legs.velocity_term(t, p, w, pv).unwrap_or([f64::NAN; 2]);
1289 let arm_acc = mul(&inv, [pa[0] - bend[0], pa[1] - bend[1]]);
1290 let force = transpose(&j).map(|column| self.m_nt() * dot(column, pa));
1291 for k in 0..2 {
1292 let joint = &self.joints[k];
1293 out[k] = (self.arm_inertia * arm_acc[k] + force[k]) / joint.ratio()
1294 + joint.rotor_inertia * joint.ratio() * arm_acc[k];
1295 }
1296 for (e, x) in self.extras.iter().enumerate() {
1298 out[2 + e] = x.feedforward(acc[2 + e], self.payload_attached);
1299 }
1300 }
1301
1302 fn steady_friction(&self, pos: &[f64], vel: &[f64], out: &mut [f64]) {
1306 let t = self.legs.inverse([pos[0], pos[1]]).unwrap_or([f64::NAN; 2]);
1307 let (_, j) = self.pose(t);
1308 let w = inverse(&j).map_or([f64::NAN; 2], |inv| mul(&inv, [vel[0], vel[1]]));
1309 let joints =
1310 self.joints.iter().zip(w).chain(self.extras.iter().map(|x| &x.joint).zip(vel[2..].iter().copied()));
1311 for (k, (joint, v)) in joints.enumerate() {
1312 let (i, friction) = (joint.ratio(), joint.friction.torque(v));
1313 out[k] = joint.shaft.torque(i * v) + friction / (i * joint.gearbox.loss_factor(friction, v));
1314 }
1315 }
1316
1317 fn energy(&self, s: &[f64]) -> f64 {
1318 self.energy_parts(s).iter().sum()
1319 }
1320
1321 fn set_payload_attached(&mut self, attached: bool) {
1322 self.payload_attached = attached;
1323 }
1324 fn set_brake_engaged(&mut self, engaged: bool) {
1325 self.brake_engaged = engaged;
1326 }
1327 fn substeps_wanted(&self, s: &[f64], _torque: &[f64], dt: f64, _substeps: u32) -> u32 {
1329 let (t, w) = self.arms(s);
1330 let extras = self.extras.iter().enumerate().map(|(e, x)| {
1331 let state = self.extra_state(s, e);
1332 x.joint.stop_substeps(state[0], state[1], dt)
1333 });
1334 (0..2).map(|k| self.joints[k].stop_substeps(t[k], w[k], dt)).chain(extras).max().unwrap_or(1)
1335 }
1336 fn set_tool_force(&mut self, force: &[f64]) -> bool {
1339 self.push = [force[0], force[1]];
1340 self.extras.iter_mut().zip(&force[2..]).for_each(|(x, f)| x.push = *f);
1341 true
1342 }
1343
1344 fn after_step(&mut self, s: &mut [f64], _dt: f64) {
1346 if self.elastic {
1347 for k in 0..2 {
1348 self.joints[k].gearbox.commit(s[4 + k], s[k]);
1349 }
1350 let (at, n) = (self.planar_len(), self.extra_len());
1351 for (e, x) in self.extras.iter_mut().enumerate() {
1352 x.joint.gearbox.commit(s[at + n * e + 3], s[at + n * e]);
1353 }
1354 }
1355 }
1356
1357 fn set_part_temperatures(&mut self, rises: &[f64]) {
1359 let Some(law) = &self.thermal else { return };
1360 let mut rises = rises.iter();
1361 if !self.joints[0].gearbox.is_coupling() {
1362 for (joint, rise) in self.joints.iter_mut().zip(rises.by_ref()) {
1363 joint.gearbox.efficiency = law.gearbox_efficiency(*rise);
1364 }
1365 }
1366 for x in self.extras.iter_mut().filter(|x| !x.joint.coupled) {
1367 if let (Some(law), Some(rise)) = (&x.thermal, rises.next()) {
1368 x.joint.gearbox.efficiency = law.gearbox_efficiency(*rise) * x.joint.extra_efficiency;
1369 }
1370 }
1371 }
1372
1373 fn modes(&self, tool_pose: &[f64]) -> Vec<sim_core::Mode> {
1375 self.modes_at(tool_pose, false)
1376 }
1377 fn modes_small_amplitude(&self, tool_pose: &[f64]) -> Vec<sim_core::Mode> {
1379 self.modes_at(tool_pose, true)
1380 }
1381 fn trains(&self, tool_pose: &[f64]) -> Vec<Option<sim_core::Train>> {
1384 if !self.elastic {
1385 return Vec::new();
1386 }
1387 let whole = sim_components::control::rigid_inertias(self, tool_pose);
1388 let mut out: Vec<_> = self.joints.iter().zip(whole).map(|(j, whole)| j.train(whole)).collect();
1389 out.resize(self.motors().len(), None);
1390 out
1391 }
1392
1393 fn resonance_hz(&self, tool_pose: &[f64]) -> Option<f64> {
1395 self.plane_modes(tool_pose, false).first().map(|m| m.hz)
1396 }
1397
1398 fn mode_shape(&self, tool_pose: &[f64]) -> Option<(f64, Vec<f64>)> {
1402 let hz = self.resonance_hz(tool_pose)?;
1403 let t = self.legs.inverse([tool_pose[0], tool_pose[1]])?;
1404 let (m, _) = self.load(t, [0.0; 2]);
1405 let k: V2 = std::array::from_fn(|i| spring(&self.joints[i].gearbox, false));
1406 let lambda = (std::f64::consts::TAU * hz).powi(2);
1407 let v = mode_vector(k, &m, lambda);
1408 let (_, j) = self.pose(t);
1409 let moved = mul(&j, v);
1410 let along = if moved[0].abs() > 1e-9 * norm(moved) { moved[0] } else { moved[1] };
1411 let mut shape = vec![0.0; self.state_len()];
1412 (shape[0], shape[1]) = (v[0] / along, v[1] / along);
1413 Some((hz, shape))
1414 }
1415
1416 fn setpoint_slack(&self) -> f64 {
1418 self.rest_slack
1419 }
1420
1421 fn unreachable(&self, tool: &[f64], slack: f64) -> Option<&'static str> {
1422 if tool.len() != self.axes.len() {
1423 return Some("error-target-out-of-range");
1424 }
1425 let p = [tool[0], tool[1]];
1426 if !self.in_envelope(&p, slack) {
1427 return Some("error-delta-outside-envelope");
1428 }
1429 let Some(t) = self.legs.inverse(p) else { return Some("error-delta-out-of-reach") };
1430 let (min, max) = self.joints[0].range;
1431 if t.iter().any(|a| *a < min || *a > max) {
1432 return Some("error-delta-joint-stop");
1433 }
1434 match self.legs.jacobian(t, p) {
1435 Some(j) if condition_number(&j) <= self.max_condition => None,
1436 _ => Some("error-delta-singularity"),
1437 }
1438 }
1439
1440 fn signal_infos(&self) -> Vec<SignalInfo> {
1441 let mut out = Vec::new();
1442 for (k, motor) in self.motors[..2].iter().enumerate() {
1443 let arm = ["arm-1", "arm-2"][k];
1444 out.push(SignalInfo::new(format!("arm.{}.angle", motor.id), arm, "quantity-arm-angle", "rad"));
1445 out.push(SignalInfo::new(
1446 format!("gearbox.{}.output_torque", motor.id),
1447 motor.key,
1448 "quantity-gearbox-torque",
1449 "N m",
1450 ));
1451 }
1452 out.push(SignalInfo::new("kinematics.condition", "group-kinematics", "quantity-condition-number", ""));
1453 for (e, x) in self.extras.iter().enumerate() {
1455 let (axis, motor) = (&self.axes[2 + e], &self.motors[2 + e]);
1456 match &x.screw {
1457 Some(screw) => {
1458 let force = format!("joint.{}.force", axis.id);
1459 out.push(SignalInfo::new(force, axis.key, "quantity-joint-force", "N"));
1460 out.extend(screw.signal_infos(axis.id, axis.key));
1461 }
1462 None => out.push(SignalInfo::new(
1463 format!("gearbox.{}.output_torque", motor.id),
1464 motor.key,
1465 "quantity-gearbox-torque",
1466 "N m",
1467 )),
1468 }
1469 }
1470 self.effect_infos(&mut out);
1471 out
1472 }
1473
1474 fn rating_checks(&self) -> Vec<RatingCheck> {
1476 let screws = self.extras.iter().enumerate().filter_map(|(e, x)| Some((e, x.screw.as_ref()?)));
1477 screws.flat_map(|(e, screw)| screw.rating_checks(self.axes[2 + e].id, 2 + e, self.required_life)).collect()
1478 }
1479
1480 fn base_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
1481 let (t, _) = self.arms(s);
1482 let gear = self.gear_output(s, torque);
1483 for k in 0..2 {
1484 out.extend([t[k], gear[k]]);
1485 }
1486 let (_, j) = self.pose(t);
1487 out.push(condition_number(&j));
1488 for (e, x) in self.extras.iter().enumerate() {
1489 let state = self.extra_state(s, e);
1490 let (.., force) = x.solve(state, torque[2 + e], self.brake_engaged, self.payload_attached);
1491 out.push(force);
1492 if let Some(screw) = &x.screw {
1493 screw.signals(state[1], force, out);
1494 }
1495 }
1496 }
1497 fn effect_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
1498 self.view_signals(s, torque, out);
1499 }
1500 fn loss_powers(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
1501 out.extend(self.losses(s, torque).powers);
1502 self.extra_losses(s, torque, out);
1503 }
1504
1505 fn friction_contacts(&self) -> Vec<sim_core::FrictionContact> {
1507 (0..2).map(|k| sim_core::FrictionContact { id: JOINT_CONTACTS[k], owner_key: ARMS[k] }).collect()
1508 }
1509 fn friction_rotary(&self, _i: usize) -> bool {
1510 true
1511 }
1512 fn friction_curve(&self, i: usize, speed: f64, _load_scale: f64) -> [f64; 3] {
1513 self.joints.get(i).filter(|_| i < 2).map_or([0.0; 3], |j| j.friction_split(speed))
1514 }
1515 fn friction_speed_limit(&self, i: usize, motor_speed: &[f64]) -> Option<f64> {
1517 if i < 2 { Some(motor_speed.get(i)? / self.joints[i].ratio()) } else { None }
1518 }
1519
1520 fn thermal_parts(&self) -> Vec<ThermalPart> {
1523 let planar = if self.joints[0].gearbox.is_coupling() {
1524 &[][..]
1525 } else {
1526 &[("gearbox_1", "motor-arm-1"), ("gearbox_2", "motor-arm-2")][..]
1527 };
1528 let extras = self.extras.iter().zip(&self.motors[2..]).filter(|(x, _)| !x.joint.coupled);
1529 let extras = extras.map(|(_, m)| (if m.id == "3" { "gearbox_3" } else { "gearbox_4" }, m.key));
1530 planar
1531 .iter()
1532 .copied()
1533 .zip(0..)
1534 .chain(extras.zip(2..))
1535 .map(|((id, owner_key), scene_index)| ThermalPart {
1536 id,
1537 kind: "gearbox",
1538 owner_key,
1539 scene_part: "gearbox",
1540 scene_index,
1541 })
1542 .collect()
1543 }
1544
1545 fn scene(&self, s: &[f64], out: &mut Scene) {
1550 let (t, _) = self.arms(s);
1551 let (rotor, rotor_speed) = self.rotors(s);
1552 let tool = self.tool_pose(s);
1553 let p = [tool[0], tool[1]];
1554 out.parts.clear();
1555 out.labels.clear();
1556 let grey = [0.62, 0.64, 0.68];
1557 out.parts.push(Part::new(
1558 "base",
1559 Shape::Box { size: [2.0 * self.base_radius + 0.2, 0.2, 0.04] },
1560 [0.0, 0.0, 0.1],
1561 grey,
1562 ));
1563 for k in 0..2 {
1564 let side = SIDE[k];
1565 let shoulder = [side * self.base_radius, 0.0, 0.0];
1566 let [elbow, ..] = self.legs.elbow(k, t[k]);
1568 let arm_end = [elbow[0] + side * self.platform_radius, elbow[1], 0.0];
1569 let at = |z: f64| [side * self.base_radius, 0.0, z];
1570 out.parts.push(Part::new(
1571 sim_core::scene::MOTOR_PART,
1572 Shape::Box { size: [0.09, 0.09, 0.12] },
1573 at(0.16),
1574 [0.9, 0.45, 0.1],
1575 ));
1576 out.parts.push(Part::new("gearbox", Shape::Box { size: [0.09, 0.09, 0.06] }, at(0.05), [0.25, 0.25, 0.28]));
1577 out.parts.push(
1578 Part::new("rotor-bar", Shape::Box { size: [0.07, 0.004, 0.012] }, at(0.225), [0.1, 0.1, 0.1])
1579 .turned(rotor[k]),
1580 );
1581 out.parts.push(Part::new("arm", Shape::Segment { to: arm_end, width: 0.04 }, shoulder, [0.2, 0.22, 0.26]));
1582 for half in [-0.5 * self.rod_spacing, 0.5 * self.rod_spacing] {
1583 let (from, to) = ([arm_end[0], arm_end[1], half], [p[0] + side * self.platform_radius, p[1], half]);
1584 out.parts.push(Part::new("forearm", Shape::Segment { to, width: 0.012 }, from, [0.15, 0.15, 0.15]));
1585 }
1586 out.labels.push(Label {
1587 pos: at(0.3),
1588 owner_key: self.motors[k].key,
1589 value: rotor_speed[k] * 60.0 / std::f64::consts::TAU,
1590 unit_key: "unit-rpm",
1591 decimals: 0,
1592 });
1593 }
1594 out.parts.extend(self.on_platform(&tool));
1595 let below = [p[0], p[1], self.flange_z(&tool) - 0.17];
1596 out.labels.push(Label {
1597 pos: below,
1598 owner_key: self.axes[1].key,
1599 value: p[1],
1600 unit_key: "unit-m",
1601 decimals: 3,
1602 });
1603 for (e, x) in self.extras.iter().enumerate() {
1606 let k = 2 + e;
1607 let state = self.extra_state(s, e);
1608 let at = |z: f64| [p[0], p[1] + if x.screw.is_some() { 0.08 } else { -0.08 }, z];
1609 out.parts.push(Part::new(
1610 sim_core::scene::MOTOR_PART,
1611 Shape::Box { size: [0.05, 0.05, 0.08] },
1612 at(0.13),
1613 [0.9, 0.45, 0.1],
1614 ));
1615 if !x.joint.coupled {
1616 out.parts.push(Part::new("gearbox", Shape::Box { size: [0.05, 0.05, 0.04] }, at(0.07), [0.25; 3]));
1617 }
1618 out.parts.push(
1619 Part::new("rotor-bar", Shape::Box { size: [0.04, 0.004, 0.01] }, at(0.18), [0.1; 3])
1620 .turned(x.rotor(state).0),
1621 );
1622 out.labels.push(Label {
1623 pos: at(0.23),
1624 owner_key: self.motors[k].key,
1625 value: x.rotor(state).1 * 60.0 / std::f64::consts::TAU,
1626 unit_key: "unit-rpm",
1627 decimals: 0,
1628 });
1629 if x.screw.is_none() {
1630 let (c, flange) = (state[0], self.flange_z(&tool) - 0.025);
1631 let (dx, dy) = (0.05 * c.cos(), 0.05 * c.sin());
1632 let to = [p[0] + dx, p[1] + dy, flange];
1633 out.parts.push(Part::new(
1634 "tool-bar",
1635 Shape::Segment { to, width: 0.01 },
1636 [p[0] - dx, p[1] - dy, flange],
1637 [0.9, 0.8, 0.1],
1638 ));
1639 }
1640 }
1641 }
1642
1643 fn scene_point(&self, tool_pose: &[f64]) -> Option<[f64; 3]> {
1645 Some([tool_pose[0], tool_pose[1], self.flange_z(tool_pose) - 0.02])
1646 }
1647
1648 fn collision_bodies(&self, s: &[f64]) -> Vec<sim_core::Aabb> {
1651 sim_core::scene::scene_boxes(&self.on_platform(&self.tool_pose(s)), &["platform", "quill", "tool", "payload"])
1652 }
1653}
1654
1655#[cfg(test)]
1656mod tests;