1use crate::machine::intern;
36use crate::netlist::{AxisNode, Kind, MotorNode, NODES, Netlist, Node, Transmission, number};
37use sim_components::catalog::motor_config;
38use sim_components::joint::RotaryJoint;
39use sim_components::mech::{HardStop, ShaftFriction, ThermalFeedback};
40use sim_core::{
41 AxisInfo, Config, ConfigError, ENERGY_PARTS, LOSS_PREFIX, Label, Machine, MotorInfo, Part, Scene, Shape,
42 SignalInfo, TORQUE_PARTS, ThermalPart,
43};
44use toml::Value;
45
46const G: f64 = 9.80665;
47
48pub struct ScissorNode {
51 pub id: String,
52 pub gearbox: String,
53 values: Vec<(&'static str, f64)>,
54}
55
56impl ScissorNode {
57 pub fn value(&self, name: &str) -> f64 {
58 self.values.iter().find(|(n, _)| *n == name).map_or(0.0, |(_, v)| *v)
59 }
60}
61
62pub(crate) fn read(
65 cfg: &Config,
66 axes: &[Node],
67 motors: &[Node],
68 gearboxes: &[Node],
69 scissors: &[Node],
70 others: &[&[Node]],
71) -> Result<Netlist, ConfigError> {
72 let node = match scissors {
73 [node] => node,
74 _ => return Err(ConfigError::Invalid(format!("{} (one scissor per file)", scissors[1].path))),
75 };
76 if let Some(other) = others.iter().find_map(|nodes| nodes.first()) {
77 return Err(ConfigError::Invalid(format!(
78 "{} (a file with a scissor lift has an axis, a motor, a gearbox and the scissor only)",
79 other.path
80 )));
81 }
82 let effects = cfg.get("effects").ok().and_then(Value::as_table);
83 for (effect, on) in effects.into_iter().flatten() {
84 if effect.starts_with("belt_") && on.as_bool() == Some(true) {
85 return Err(ConfigError::Invalid(format!("effects.{effect} (a scissor lift has no belt: switch it off)")));
86 }
87 }
88 let id_of = |n: &Node| n.table["id"].as_str().unwrap_or_default().to_string();
89 let one = |nodes: &[Node], field: &str, list: &str| -> Result<usize, ConfigError> {
90 let id = node.text(field)?.unwrap_or_default();
91 match nodes.iter().position(|n| n.table["id"].as_str() == Some(id)) {
92 Some(i) if nodes.len() == 1 => Ok(i),
93 Some(_) => Err(ConfigError::Invalid(format!("{} (one machine.{list} node)", node.at(field)))),
94 None => Err(ConfigError::Invalid(format!("{} = \"{id}\"", node.at(field)))),
95 }
96 };
97
98 let fields = NODES.iter().find(|(list, ..)| *list == "scissor").map_or(&[][..], |(_, _, f)| *f);
99 let (mut refs, mut values) = (Vec::new(), Vec::new());
100 for f in fields.iter().filter(|f| f.kind == Kind::Number) {
101 let v = node.get(f.name).map(|v| number(cfg, v, &node.at(f.name), &mut refs)).transpose()?;
102 let v = v.unwrap_or(if f.name == "screw_efficiency" { 1.0 } else { 0.0 });
103 let positive = !["payload_kg", "screw_inertia_kgm2", "arms_kg"].contains(&f.name);
104 if if positive { !(v > 0.0) } else { !(v >= 0.0) } {
105 return Err(ConfigError::Invalid(node.at(f.name)));
106 }
107 values.push((f.name, v));
108 }
109 let value = |name: &str| values.iter().find(|(n, _)| *n == name).map_or(0.0, |(_, v)| *v);
110 let stages = value("stages");
111 for (field, bad, why) in [
112 ("stages", stages.fract() != 0.0, "a whole number"),
113 ("screw_efficiency", value("screw_efficiency") > 1.0, "at most 1"),
114 ("max_height_m", value("max_height_m") <= value("min_height_m"), "above min_height_m"),
115 ("max_height_m", value("max_height_m") >= stages * value("arm_m"), "below stages times arm_m"),
116 ] {
117 if bad {
118 return Err(ConfigError::Invalid(format!("{} ({why})", node.at(field))));
119 }
120 }
121
122 let axis = &axes[one(axes, "axis", "axis")?];
123 for field in ["stroke_m", "stroke_rad", "incline_deg", "cable_chain"] {
124 if axis.get(field).is_some() {
125 return Err(ConfigError::Invalid(format!(
126 "{} (a scissor lift's axis takes its range from min_height_m and max_height_m)",
127 axis.at(field)
128 )));
129 }
130 }
131 let axis_id = id_of(axis);
132 let axis_key = axis.text("key")?.map_or_else(|| format!("axis-{axis_id}"), str::to_string);
133 let gearbox = &gearboxes[one(gearboxes, "gearbox", "gearbox")?];
134 let motor_id = gearbox.text("motor")?.unwrap_or_default();
135 let motor = match motors.iter().position(|n| n.table["id"].as_str() == Some(motor_id)) {
136 Some(m) if motors.len() == 1 => &motors[m],
137 _ => return Err(ConfigError::Invalid(format!("{} = \"{motor_id}\" (the one motor)", gearbox.at("motor")))),
138 };
139 let key = motor.text("key")?.map_or_else(|| format!("motor-{motor_id}"), str::to_string);
140 Ok(Netlist {
141 axes: vec![AxisNode {
142 id: axis_id,
143 key: axis_key,
144 stroke: value("max_height_m") - value("min_height_m"),
145 incline_deg: 90.0,
146 cable_chain: false,
147 rotary: false,
148 }],
149 motors: vec![MotorNode {
151 id: motor_id.to_string(),
152 key,
153 radius: 1.0,
154 inertia: 0.0,
155 pulley: String::new(),
156 at: None,
157 body: None,
158 clockwise: false,
159 transmission: Transmission::Belt,
160 axis: None,
161 worm: None,
162 }],
163 sections: Vec::new(),
164 bodies: Vec::new(),
165 guides: Vec::new(),
166 idlers: Vec::new(),
167 frame: None,
168 spans: Vec::new(),
169 lean: None,
170 refs,
171 values: Vec::new(),
172 linkage: None,
173 scissor: Some(ScissorNode { id: id_of(node), gearbox: id_of(gearbox), values }),
174 gantry: None,
175 tcp: None,
176 })
177}
178
179pub const LOSSY_EFFECTS: [&str; 4] = ["motor_friction", "gearbox_efficiency", "torque_ripple", "holding_brake"];
181
182const N_ELASTIC: usize = 5;
184const N_RIGID: usize = 3;
185
186#[derive(Debug, Clone, Copy)]
189pub struct Stages {
190 pub stages: f64,
191 pub arm: f64,
192 pub lever: f64,
193 pub span_low: f64,
194}
195
196impl Stages {
197 pub fn height(&self, theta: f64) -> [f64; 3] {
199 let (n, c, l) = (self.stages, self.lever, self.arm);
200 let u = self.span_low - c * theta;
201 let s = (l * l - u * u).max(0.0).sqrt();
202 [n * s, n * c * u / s, -n * c * c * l * l / s.powi(3)]
203 }
204
205 pub fn arm_motion(&self, theta: f64, arms: f64) -> (f64, f64) {
208 let (c, l) = (self.lever, self.arm);
209 let u = self.span_low - c * theta;
210 let s = (self.height(theta)[0] / self.stages).max(1e-9);
211 (arms * c * c * (0.25 + l * l / (12.0 * s * s)), -arms * c.powi(3) * l * l * u / (12.0 * s.powi(4)))
212 }
213
214 pub fn angle(&self, h: f64) -> f64 {
216 let s = h / self.stages;
217 let u = (self.arm * self.arm - s * s).sqrt();
218 if h > 0.0 && u.is_finite() { (self.span_low - u) / self.lever } else { f64::NAN }
219 }
220
221 pub fn actuator_force(&self, w: f64, h: f64) -> f64 {
223 let s = h / self.stages;
224 w * self.stages * (self.arm * self.arm - s * s).sqrt() / s
225 }
226}
227
228pub struct ScissorMachine {
229 geometry: Stages,
230 min_height: f64,
231 max_height: f64,
232 screw_inertia: f64,
234 m_moving: f64,
235 arms: f64,
237 m_weight: f64,
238 m_payload: f64,
239 payload_attached: bool,
240 brake_engaged: bool,
241 tool_push: f64,
243 screw_efficiency: f64,
245 joint: RotaryJoint,
246 thermal: Option<ThermalFeedback>,
247 elastic: bool,
248 g: f64,
249 axes: [AxisInfo; 1],
250 motors: [MotorInfo; 1],
251 gearbox_id: &'static str,
252 id: &'static str,
253 rest_slack: f64,
254}
255
256impl ScissorMachine {
257 pub fn from_node(cfg: &Config, net: &Netlist, node: &ScissorNode) -> Result<Self, ConfigError> {
258 let v = |name: &str| node.value(name);
259 let (stages, arm, lever) = (v("stages"), v("arm_m"), v("lead_m") / std::f64::consts::TAU);
260 let (min_height, max_height) = (v("min_height_m"), v("max_height_m"));
261 let span_low = (arm * arm - (min_height / stages).powi(2)).sqrt();
262 let own = motor_config(cfg, &net.motors[0].id)?;
263 let theta_max = (span_low - (arm * arm - (max_height / stages).powi(2)).sqrt()) / lever;
264 let free = ShaftFriction::NONE;
265 let mut joint = RotaryJoint::with(&own, free, HardStop { stiffness: 0.0, damping: 0.0 }, (0.0, theta_max))?;
266 let counts = cfg.bool("effects.gearbox_efficiency")?;
267 let screw_efficiency = if counts { v("screw_efficiency") } else { 1.0 };
268 joint.gearbox.efficiency *= screw_efficiency;
269 let axis = &net.axes[0];
270 let arms = v("arms_kg");
271 let mut machine = Self {
272 geometry: Stages { stages, arm, lever, span_low },
273 min_height,
274 max_height,
275 screw_inertia: v("screw_inertia_kgm2"),
276 m_moving: v("platform_kg") + arms * (4.0 * stages * stages - 1.0) / (12.0 * stages * stages),
277 arms,
278 m_weight: v("platform_kg") + 0.5 * arms,
279 m_payload: if cfg.bool("effects.payload")? { v("payload_kg") } else { 0.0 },
280 payload_attached: true,
281 brake_engaged: false,
282 tool_push: 0.0,
283 screw_efficiency,
284 joint,
285 thermal: ThermalFeedback::from_config(cfg)?,
286 elastic: cfg.bool("effects.joint_elasticity")?,
287 g: if cfg.bool("effects.gravity")? { G } else { 0.0 },
288 axes: [AxisInfo {
289 id: intern(&axis.id),
290 key: intern(&axis.key),
291 unit: "m",
292 min: min_height,
293 max: max_height,
294 max_vel: cfg.positive(&format!("axis.{}.max_velocity_m_s", axis.id))?,
295 max_acc: cfg.positive(&format!("axis.{}.max_acceleration_m_s2", axis.id))?,
296 max_jerk: cfg.positive(&format!("axis.{}.max_jerk_m_s3", axis.id))?,
297 }],
298 motors: [MotorInfo { id: intern(&net.motors[0].id), key: intern(&net.motors[0].key) }],
299 gearbox_id: intern(&format!("gearbox_{}", net.motors[0].id)),
301 id: intern(&node.id),
302 rest_slack: 0.0,
303 };
304 machine.rest_slack = machine.rest_sag();
305 Ok(machine)
306 }
307
308 fn height(&self, theta: f64) -> [f64; 3] {
309 self.geometry.height(theta)
310 }
311 fn angle(&self, h: f64) -> f64 {
312 self.geometry.angle(h)
313 }
314
315 fn m_nt(&self) -> f64 {
316 self.m_moving + if self.payload_attached { self.m_payload } else { 0.0 }
317 }
318 fn m_g(&self) -> f64 {
319 self.m_weight + if self.payload_attached { self.m_payload } else { 0.0 }
320 }
321
322 fn load(&self, theta: f64, w: f64) -> (f64, f64, f64) {
324 let [_, d1, d2] = self.height(theta);
325 let (turn, turn_rate) = self.geometry.arm_motion(theta, self.arms);
326 (
327 self.screw_inertia + self.m_nt() * d1 * d1 + turn,
328 (self.m_nt() * d1 * d2 + turn_rate) * w * w,
329 -self.g * self.m_g() * d1,
330 )
331 }
332
333 fn push(&self, theta: f64) -> f64 {
336 self.tool_push * self.height(theta)[1]
337 }
338
339 fn rotor(&self, s: &[f64]) -> (f64, f64) {
340 if self.elastic { (s[2], s[3]) } else { (self.joint.ratio() * s[0], self.joint.ratio() * s[1]) }
341 }
342 fn brake(&self, s: &[f64]) -> f64 {
343 s[if self.elastic { 4 } else { 2 }]
344 }
345
346 fn rigid_solve(&self, s: &[f64], torque: f64) -> (f64, f64, f64) {
348 let (theta, w) = (s[0], s[1]);
349 let (rotor, rotor_speed) = self.rotor(s);
350 let (mass, velocity, gravity) = self.load(theta, w);
351 let j = &self.joint;
352 let drive = j.rigid_drive(torque, rotor, rotor_speed, self.brake(s), self.brake_engaged).0;
353 let rest = gravity + self.push(theta) - velocity + j.output_torque(theta, w);
354 let first = (drive + rest) / (mass + j.reflected_inertia());
355 let loss = j.gearbox.loss_factor(drive - j.reflected_inertia() * first, w);
356 let acc = (loss * drive + rest) / (mass + loss * j.reflected_inertia());
357 let into = drive - j.reflected_inertia() * acc;
358 (acc, into, loss * into)
359 }
360
361 fn acceleration(&self, s: &[f64], torque: f64) -> f64 {
362 let mut d = [0.0; N_ELASTIC];
363 self.derivatives(s, &[torque], &mut d);
364 d[1]
365 }
366
367 fn gear(&self, s: &[f64], torque: f64) -> f64 {
368 if self.elastic {
369 self.joint.gearbox.torque(s[2], s[3], s[0], s[1]).output
370 } else {
371 self.rigid_solve(s, torque).2
372 }
373 }
374
375 fn losses(&self, s: &[f64], torque: f64) -> ([f64; 3], f64) {
378 let (theta, w) = (s[0], s[1]);
379 let (rotor, rotor_speed) = self.rotor(s);
380 let j = &self.joint;
381 let [_, _, shaft, drag] = j.losses(theta, w, rotor_speed, self.brake(s), self.brake_engaged);
382 let (gear, at_rotor) = if self.elastic {
383 let g = j.gearbox.torque(s[2], s[3], theta, w);
384 (j.gearbox.loss_power(s[2], s[3], theta, w), g.rotor - g.output / j.ratio())
385 } else {
386 let (_, into, out) = self.rigid_solve(s, torque);
387 ((into - out) * w, (into - out) / j.ratio())
388 };
389 ([shaft, gear + drag, (torque - j.ripple.apply(torque, rotor)) * rotor_speed], at_rotor)
390 }
391
392 fn energy_parts(&self, s: &[f64]) -> [f64; 3] {
393 let (theta, w) = (s[0], s[1]);
394 let (mass, ..) = self.load(theta, w);
395 let mut kinetic = 0.5 * mass * w * w;
396 let potential = self.g * self.m_g() * self.height(theta)[0];
397 let mut elastic = 0.0;
398 if self.elastic {
399 kinetic += 0.5 * self.joint.rotor_inertia * s[3] * s[3];
400 elastic += self.joint.gearbox.energy(s[2], s[0]);
401 } else {
402 kinetic += 0.5 * self.joint.reflected_inertia() * w * w;
403 }
404 [kinetic, potential, elastic]
405 }
406
407 fn rest_sag(&self) -> f64 {
411 if !self.elastic {
412 return 1e-4;
413 }
414 let gear = &self.joint.gearbox;
415 let most = (0..=20)
416 .map(|k| self.min_height + (self.max_height - self.min_height) * k as f64 / 20.0)
417 .map(|h| {
418 let [_, d1, _] = self.height(self.angle(h));
419 let held = self.g * (self.m_weight + self.m_payload) * d1;
420 d1 * (held / gear.stiffness + gear.half_backlash)
421 })
422 .fold(0.0, f64::max);
423 (1.1 * most).max(1e-4)
424 }
425}
426
427impl Machine for ScissorMachine {
428 fn axes(&self) -> &[AxisInfo] {
429 &self.axes
430 }
431 fn motors(&self) -> &[MotorInfo] {
432 &self.motors
433 }
434 fn inverse(&self, tool: &[f64], motors: &mut [f64]) {
435 motors[0] = self.joint.ratio() * self.angle(tool[0]);
436 }
437 fn forward(&self, motors: &[f64], tool: &mut [f64]) {
438 tool[0] = self.height(motors[0] / self.joint.ratio())[0];
439 }
440 fn state_len(&self) -> usize {
441 if self.elastic { N_ELASTIC } else { N_RIGID }
442 }
443
444 fn equilibrium(&self, tool: &[f64], state: &mut Vec<f64>, torque: &mut [f64]) {
445 let theta = self.angle(tool[0]);
446 let (_, _, gravity) = self.load(theta, 0.0);
447 let j = &self.joint;
448 let out = -gravity - j.output_torque(theta, 0.0);
449 let rotor = j.ratio() * (theta + if self.elastic { j.gearbox.static_twist(out) } else { 0.0 });
450 state.clear();
451 state.extend([theta, 0.0]);
452 if self.elastic {
453 state.extend([rotor, 0.0]);
454 }
455 state.push(0.0);
456 torque[0] = j.ripple.invert(out / j.ratio(), rotor);
457 }
458
459 fn derivatives(&self, s: &[f64], torque: &[f64], out: &mut [f64]) {
460 let j = &self.joint;
461 if !self.elastic {
462 let (acc, ..) = self.rigid_solve(s, torque[0]);
463 let rotor_speed = self.rotor(s).1;
464 out[..3].copy_from_slice(&[s[1], acc, j.brake.torque(self.brake_engaged, rotor_speed, s[2]).1]);
465 return;
466 }
467 let (theta, w) = (s[0], s[1]);
468 let (mass, velocity, gravity) = self.load(theta, w);
469 let (gear, rotor_acc, brake_rate) = j.rotor(torque[0], s[2], s[3], theta, w, s[4], self.brake_engaged);
470 let acc = (gear.output + gravity + self.push(theta) - velocity + j.output_torque(theta, w)) / mass;
471 out[..5].copy_from_slice(&[w, acc, s[3], rotor_acc, brake_rate]);
472 }
473
474 fn tool_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
475 let [h, d1, _] = self.height(s[0]);
476 (pos[0], vel[0]) = (h, d1 * s[1]);
477 }
478 fn set_tool_velocity(&self, s: &mut [f64], vel: &[f64]) {
479 s[1] = vel[0] / self.height(s[0])[1];
480 if self.elastic {
481 s[3] = self.joint.ratio() * s[1];
482 }
483 }
484 fn motor_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
485 (pos[0], vel[0]) = self.rotor(s);
486 }
487
488 fn feedforward_torque(&self, pos: &[f64], acc: &[f64], out: &mut [f64]) {
490 let theta = self.angle(pos[0]);
491 let (mass, _, gravity) = self.load(theta, 0.0);
492 let acc = acc[0] / self.height(theta)[1];
493 let j = &self.joint;
494 out[0] = (mass * acc - gravity) / j.ratio() + j.rotor_inertia * j.ratio() * acc;
495 }
496
497 fn feedforward_torque_moving(&self, pos: &[f64], vel: &[f64], acc: &[f64], out: &mut [f64]) {
500 let theta = self.angle(pos[0]);
501 let [_, d1, d2] = self.height(theta);
502 let (_, _, gravity) = self.load(theta, 0.0);
503 let w = vel[0] / d1;
504 let theta_acc = (acc[0] - d2 * w * w) / d1;
505 let (turn, turn_rate) = self.geometry.arm_motion(theta, self.arms);
506 let j = &self.joint;
507 out[0] = (self.screw_inertia * theta_acc + self.m_nt() * d1 * acc[0] + turn * theta_acc + turn_rate * w * w
508 - gravity)
509 / j.ratio()
510 + j.rotor_inertia * j.ratio() * theta_acc;
511 }
512
513 fn energy(&self, s: &[f64]) -> f64 {
514 self.energy_parts(s).iter().sum()
515 }
516 fn frame_momentum(&self, s: &[f64]) -> Option<sim_core::FrameMomentum> {
523 use sim_components::base::{add_point, add_spin};
524 let mut f = sim_core::FrameMomentum { gravity: [0.0, 0.0, -self.g], ..Default::default() };
525 let Stages { stages, lever, span_low, .. } = self.geometry;
526 let (theta, w) = (s[0], s[1]);
527 let [h, d1, _] = self.height(theta);
528 let (u, du) = (span_low - lever * theta, -lever * w);
529 let (stage, rise) = (h / stages, d1 * w / stages);
530 let platform = self.m_weight - 0.5 * self.arms + if self.payload_attached { self.m_payload } else { 0.0 };
531 add_point(&mut f, platform, [0.0, 0.0, h], [0.0, 0.0, d1 * w]);
532 let pair = self.arms / stages;
533 for k in 0..stages as usize {
534 let up = k as f64 + 0.5;
535 add_point(&mut f, pair, [-0.5 * span_low + 0.5 * u, 0.0, up * stage], [0.5 * du, 0.0, up * rise]);
536 }
537 add_spin(&mut f, [1.0, 0.0, 0.0], self.screw_inertia, w);
538 add_spin(&mut f, [1.0, 0.0, 0.0], self.joint.rotor_inertia, self.rotor(s).1);
539 Some(f)
540 }
541 fn set_payload_attached(&mut self, attached: bool) {
542 self.payload_attached = attached;
543 }
544 fn set_tool_force(&mut self, force: &[f64]) -> bool {
547 self.tool_push = force[0];
548 true
549 }
550 fn set_brake_engaged(&mut self, engaged: bool) {
551 self.brake_engaged = engaged;
552 }
553 fn substeps_wanted(&self, s: &[f64], torque: &[f64], dt: f64, substeps: u32) -> u32 {
556 let h = dt / f64::from(substeps);
557 let gear = &self.joint.gearbox;
558 let output = if self.elastic {
559 gear.torque(s[2], s[3], s[0], s[1]).rotor * gear.ratio
560 } else {
561 self.rigid_solve(s, torque[0]).2
562 };
563 let damping = gear.fade_damping(output, s[1]);
564 if damping == 0.0 {
565 return 1;
566 }
567 sim_components::mech::fade_substeps(damping, h, self.load(s[0], s[1]).0)
568 }
569 fn after_step(&mut self, s: &mut [f64], _dt: f64) {
571 if self.elastic {
572 self.joint.gearbox.commit(s[2], s[0]);
573 }
574 }
575 fn memory(&self) -> Vec<f64> {
576 self.joint.gearbox.anchor.to_vec()
577 }
578 fn set_memory(&mut self, memory: &[f64]) {
579 sim_components::mech::Gearbox::set_anchors([&mut self.joint.gearbox], memory)
580 }
581
582 fn set_part_temperatures(&mut self, rises: &[f64]) {
583 if let (Some(law), Some(rise), false) = (&self.thermal, rises.first(), self.joint.gearbox.is_coupling()) {
584 self.joint.gearbox.efficiency = law.gearbox_efficiency(*rise) * self.screw_efficiency;
585 }
586 }
587 fn setpoint_slack(&self) -> f64 {
588 self.rest_slack
589 }
590 fn unreachable(&self, tool: &[f64], slack: f64) -> Option<&'static str> {
591 let inside = tool.len() == 1 && tool[0] >= self.min_height - slack && tool[0] <= self.max_height + slack;
592 (!inside).then_some("error-target-out-of-range")
593 }
594
595 fn signal_infos(&self) -> Vec<SignalInfo> {
596 let (motor, axis) = (&self.motors[0], &self.axes[0]);
597 let mut out = vec![
598 SignalInfo::new(format!("gearbox.{}.output_torque", motor.id), motor.key, "quantity-gearbox-torque", "N m"),
599 SignalInfo::new(format!("scissor.{}.actuator_force", self.id), axis.key, "quantity-joint-force", "N"),
600 ];
601 out.extend(TORQUE_PARTS.map(|part| {
602 SignalInfo::new(
603 format!("motor.{}.torque_{part}", motor.id),
604 motor.key,
605 &format!("quantity-torque-{part}"),
606 "N m",
607 )
608 }));
609 let gear = if self.joint.gearbox.is_coupling() {
610 "quantity-coupling-loss-power"
611 } else {
612 "quantity-gearbox-loss-power"
613 };
614 out.extend([
615 SignalInfo::new(
616 format!("{LOSS_PREFIX}shaft_{}", motor.id),
617 motor.key,
618 "quantity-shaft-friction-power",
619 "W",
620 ),
621 SignalInfo::new(format!("{LOSS_PREFIX}gearbox_{}", motor.id), motor.key, gear, "W"),
622 SignalInfo::new(format!("{LOSS_PREFIX}other"), "loss-other", "quantity-power-given-off", "W"),
623 ]);
624 out.extend(ENERGY_PARTS.map(|part| {
625 SignalInfo::new(format!("energy.{part}"), "group-energy", &format!("quantity-energy-{part}"), "J")
626 }));
627 out
628 }
629
630 fn base_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
635 let gear = self.gear(s, torque[0]);
636 let shaft = shaft_torque(gear, s[1], self.screw_efficiency);
637 out.extend([shaft, gear / self.geometry.lever]);
638 }
639 fn effect_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
640 let (theta, w) = (s[0], s[1]);
641 let j = &self.joint;
642 let (mass, velocity, gravity) = self.load(theta, w);
643 let acc = self.acceleration(s, torque[0]);
644 let (powers, gear_at_rotor) = self.losses(s, torque[0]);
645 let rotor_speed = self.rotor(s).1;
646 let held = j.brake.torque(self.brake_engaged, rotor_speed, self.brake(s)).0;
647 let parts = [
648 (mass * acc + velocity + j.reflected_inertia() * acc) / j.ratio(),
649 -gravity / j.ratio(),
650 j.shaft.torque(rotor_speed) + held + gear_at_rotor,
651 ];
652 out.extend(parts);
653 out.push(torque[0] - parts.iter().sum::<f64>());
654 out.extend(powers);
655 out.extend(self.energy_parts(s));
656 }
657 fn loss_powers(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
658 out.extend(self.losses(s, torque[0]).0);
659 }
660
661 fn thermal_parts(&self) -> Vec<ThermalPart> {
662 if self.joint.gearbox.is_coupling() {
663 return Vec::new();
664 }
665 vec![ThermalPart {
666 id: self.gearbox_id,
667 kind: "gearbox",
668 owner_key: self.motors[0].key,
669 scene_part: "gearbox",
670 scene_index: 0,
671 }]
672 }
673
674 fn scene(&self, s: &[f64], out: &mut Scene) {
677 let h = self.height(s[0])[0];
678 let (rotor, rotor_speed) = self.rotor(s);
679 let Stages { stages, arm, .. } = self.geometry;
680 let (n, u) = (stages as usize, (arm * arm - (h / stages).powi(2)).max(0.0).sqrt());
681 let grey = [0.62, 0.64, 0.68];
682 out.parts.clear();
683 out.labels.clear();
684 let width = arm.max(0.2);
685 out.parts.push(Part::new("base", Shape::Box { size: [width + 0.2, 0.4, 0.04] }, [0.0, 0.0, -0.02], grey));
686 let foot = [-0.5 * u, 0.0, 0.0];
687 out.parts.push(Part::new(
688 sim_core::scene::MOTOR_PART,
689 Shape::Box { size: [0.12, 0.09, 0.09] },
690 [-0.5 * width - 0.2, 0.0, 0.06],
691 [0.9, 0.45, 0.1],
692 ));
693 out.parts.push(Part::new(
694 "gearbox",
695 Shape::Box { size: [0.06, 0.09, 0.09] },
696 [-0.5 * width - 0.11, 0.0, 0.06],
697 [0.25, 0.25, 0.28],
698 ));
699 out.parts.push(
700 Part::new(
701 "rotor-bar",
702 Shape::Box { size: [0.004, 0.07, 0.012] },
703 [-0.5 * width - 0.27, 0.0, 0.06],
704 [0.1, 0.1, 0.1],
705 )
706 .turned(rotor),
707 );
708 out.parts.push(Part::new(
709 "screw",
710 Shape::Segment { to: [0.5 * u, 0.0, 0.06], width: 0.016 },
711 [-0.5 * width - 0.08, 0.0, 0.06],
712 [0.5, 0.5, 0.55],
713 ));
714 let stage = h / stages;
715 for k in 0..n {
716 let (low, high) = (k as f64 * stage, (k + 1) as f64 * stage);
717 for (from, to) in [(foot[0], 0.5 * u), (0.5 * u, foot[0])] {
718 out.parts.push(Part::new(
719 "arm",
720 Shape::Segment { to: [to, 0.0, high], width: 0.03 },
721 [from, 0.0, low],
722 [0.2, 0.22, 0.26],
723 ));
724 }
725 }
726 out.parts.push(Part::new(
727 "platform",
728 Shape::Box { size: [width, 0.4, 0.03] },
729 [0.0, 0.0, h + 0.015],
730 [0.55, 0.55, 0.6],
731 ));
732 if self.payload_attached && self.m_payload > 0.0 {
733 out.parts.push(Part::new(
734 "payload",
735 Shape::Box { size: [0.2, 0.2, 0.15] },
736 [0.0, 0.0, h + 0.105],
737 [0.2, 0.7, 0.3],
738 ));
739 }
740 out.labels.push(Label {
741 pos: [-0.5 * width - 0.2, 0.0, 0.16],
742 owner_key: self.motors[0].key,
743 value: rotor_speed * 60.0 / std::f64::consts::TAU,
744 unit_key: "unit-rpm",
745 decimals: 0,
746 });
747 out.labels.push(Label {
748 pos: [0.5 * width + 0.1, 0.0, h],
749 owner_key: self.axes[0].key,
750 value: h,
751 unit_key: "unit-m",
752 decimals: 3,
753 });
754 }
755
756 fn scene_point(&self, tool_pose: &[f64]) -> Option<[f64; 3]> {
757 Some([0.0, 0.0, tool_pose[0] + 0.03])
758 }
759}
760
761fn shaft_torque(after_screw: f64, speed: f64, screw_efficiency: f64) -> f64 {
763 after_screw * if after_screw * speed >= 0.0 { 1.0 / screw_efficiency } else { screw_efficiency }
764}
765
766#[cfg(test)]
767mod tests {
768 use super::*;
769
770 #[test]
776 fn the_scissor_force_ratio_is_n_cot_alpha_at_two_heights() {
777 let lift = Stages { stages: 2.0, arm: 1.0, lever: 0.01 / std::f64::consts::TAU, span_low: 0.99f64.sqrt() };
778 for (h, by_hand, cot) in [(0.6, 6359.59, 3.179_797), (1.6, 1500.0, 0.75)] {
779 let force = lift.actuator_force(1000.0, h);
780 assert!((force - by_hand).abs() < 0.01, "h = {h}: {force} N against {by_hand}");
781 assert!((force - 1000.0 * 2.0 * cot).abs() < 0.001, "h = {h}: n cot alpha");
782 let theta = lift.angle(h);
783 let [height, d1, _] = lift.height(theta);
784 assert!((height - h).abs() < 1e-12, "{height}");
785 assert!((1000.0 * d1 / lift.lever - force).abs() < 1e-6, "virtual work at h = {h}");
786 }
787 let ratio = lift.actuator_force(1000.0, 0.6) / lift.actuator_force(1000.0, 1.6);
788 assert!((ratio - 4.239_73).abs() < 1e-5, "{ratio}");
789 let theta = lift.angle(1.0);
791 let step = 1e-3;
792 let numeric = (lift.height(theta + step)[1] - lift.height(theta - step)[1]) / (2.0 * step);
793 assert!((lift.height(theta)[2] - numeric).abs() < 1e-9 * numeric.abs().max(1e-9), "{numeric}");
794 }
795 #[test]
801 fn the_arms_turning_and_sideways_motion_add_their_inertia() {
802 let lift = Stages { stages: 2.0, arm: 1.0, lever: 0.01, span_low: 0.99f64.sqrt() };
803 let theta = lift.angle(1.0);
804 let (m, rate) = lift.arm_motion(theta, 40.0);
805 assert!((m - 2.333_333e-3).abs() < 1e-8, "{m}");
806 let step = 1e-4;
807 let slope = (lift.arm_motion(theta + step, 40.0).0 - lift.arm_motion(theta - step, 40.0).0) / (2.0 * step);
808 assert!((rate - 0.5 * slope).abs() < 1e-6 * rate.abs(), "{rate} against {}", 0.5 * slope);
809 }
810 #[test]
814 fn the_gearbox_shaft_carries_the_screws_loss() {
815 assert!((shaft_torque(27.780, 0.05, 0.9) - 30.867).abs() < 1e-3);
816 assert!((shaft_torque(27.780, -0.05, 0.9) - 25.002).abs() < 1e-3);
817 }
818}