1use crate::{axis, machine, master, payload};
70use sim_components::cam::{Cam, Law, Segment};
71use sim_components::chain::Mechanism;
72use sim_components::joint::RotaryJoint;
73use sim_core::{CamMaster, Config, ConfigError, Label, Machine, Part, RatingCheck, Scene, Shape, SignalInfo};
74use std::f64::consts::{PI, TAU};
75
76pub fn modified_sine(u: f64) -> [f64; 3] {
80 let k = 1.0 / (4.0 + PI);
81 let ends = |base: f64| {
82 let a = 4.0 * PI * u;
83 [k * (base + PI * u - 0.25 * a.sin()), k * (PI - PI * a.cos()), k * 4.0 * PI * PI * a.sin()]
84 };
85 if u <= 0.125 {
86 ends(0.0)
87 } else if u >= 0.875 {
88 ends(4.0)
89 } else {
90 let a = PI / 3.0 + 4.0 * PI * u / 3.0;
91 [k * (2.0 + PI * u - 2.25 * a.sin()), k * (PI - 3.0 * PI * a.cos()), k * 4.0 * PI * PI * a.sin()]
92 }
93}
94
95#[derive(Debug, Clone, Copy, PartialEq)]
97pub enum Drive {
98 Geneva { lambda: f64, crank_radius: f64 },
100 Cam { pitch_radius: f64, cam_radius: Option<f64> },
102}
103
104pub struct Indexer {
105 pub drive: Drive,
106 pub stations: usize,
107 pub half: f64,
109 pub j_driver: f64,
110 pub j_wheel_table: f64,
112 pub payload: f64,
113 pub station_radius: f64,
114 pub attached: bool,
115 pub play: f64,
116 pub mode: (f64, f64),
118 pub j_wheel: f64,
120 pub twist: Option<(f64, f64)>,
122 pub tolerance: f64,
124 pub cam: Cam,
125 pub master: Option<CamMaster>,
126 limits: [f64; 3],
127}
128
129pub fn build_geneva(cfg: &Config) -> Result<Box<dyn Machine>, ConfigError> {
130 build(cfg, false)
131}
132
133pub fn build_cam(cfg: &Config) -> Result<Box<dyn Machine>, ConfigError> {
134 build(cfg, true)
135}
136
137fn build(cfg: &Config, cam: bool) -> Result<Box<dyn Machine>, ConfigError> {
138 let joint = RotaryJoint::from_config(cfg)?;
139 let indexer = Indexer::from_config(cfg, cam)?;
140 let theta = axis(cfg, "driver", "axis-driver", "rad", joint.range)?;
141 machine(cfg, indexer, (joint, None, "rad"), theta, true)
142}
143
144impl Indexer {
145 pub fn from_config(cfg: &Config, cam: bool) -> Result<Self, ConfigError> {
146 let stations = cfg.positive("indexer.stations")?;
147 let least = if cam { 2.0 } else { 3.0 };
148 if stations.fract() != 0.0 || stations < least {
149 return Err(ConfigError::Invalid("indexer.stations".into()));
150 }
151 let n = stations as usize;
152 let (drive, half) = if cam {
153 let angle = cfg.positive("indexer.index_angle_deg")?;
154 if angle >= 360.0 {
155 return Err(ConfigError::Invalid("indexer.index_angle_deg".into()));
156 }
157 let cam_radius = if cfg.get("indexer.cam_radius_m").is_ok() {
158 Some(cfg.positive("indexer.cam_radius_m")?)
159 } else {
160 None
161 };
162 let pitch_radius = cfg.positive("indexer.roller_pitch_radius_m")?;
163 (Drive::Cam { pitch_radius, cam_radius }, 0.5 * angle.to_radians())
164 } else {
165 let lambda = (PI / n as f64).sin();
166 (Drive::Geneva { lambda, crank_radius: cfg.positive("indexer.crank_radius_m")? }, 0.5 * PI - PI / n as f64)
167 };
168 let station_radius = cfg.positive("table.station_radius_m")?;
169 let j_wheel = cfg.positive("indexer.wheel_inertia_kgm2")?;
170 let j_wheel_table = j_wheel + cfg.positive("table.inertia_kgm2")?;
171 let payload = payload(cfg)?;
172 let j_all = j_wheel_table + payload * station_radius * station_radius;
173 let stiffness = cfg.positive("table.stiffness_nm_rad")?;
174 let j_side = j_all - j_wheel;
176 let w_n = (stiffness / j_side).sqrt();
177 let zeta = cfg.positive("table.damping_ratio")?;
178 let twist = cfg.bool("effects.table_twist")?.then(|| (stiffness, 2.0 * zeta * (stiffness * j_side).sqrt()));
179 let one_turn = Cam::from_segments(&[Segment { master: TAU, slave: TAU, law: Law::Linear }])
180 .expect("one turn at constant speed");
181 let master = master(cfg, TAU * cfg.positive("indexer.turns_per_min")? / 60.0, one_turn.period)?;
182 Ok(Indexer {
183 drive,
184 stations: n,
185 half,
186 j_driver: cfg.positive("indexer.driver_inertia_kgm2")?,
187 j_wheel_table,
188 payload,
189 station_radius,
190 attached: true,
191 play: cfg.non_negative("indexer.locking_play_rad")?,
192 mode: (w_n, zeta),
193 j_wheel,
194 twist,
195 tolerance: cfg.positive("ratings.index_settling_tolerance_m")? / station_radius,
196 cam: one_turn,
197 master,
198 limits: [
199 cfg.f64("ratings.indexer_max_contact_force_n").unwrap_or(f64::INFINITY),
200 cfg.f64("ratings.index_max_error_m").unwrap_or(f64::INFINITY),
201 cfg.f64("ratings.index_max_settling_s").unwrap_or(f64::INFINITY),
202 ],
203 })
204 }
205
206 pub fn j_table(&self) -> f64 {
208 let r = self.station_radius;
209 self.j_wheel_table + if self.attached { self.payload * r * r } else { 0.0 }
210 }
211
212 fn j_side(&self) -> f64 {
214 self.j_table() - self.j_wheel
215 }
216
217 pub fn pressure_angle(&self, theta: f64) -> f64 {
220 match self.drive {
221 Drive::Cam { pitch_radius, cam_radius: Some(r) } => (pitch_radius * self.motion(theta)[1] / r).atan(),
222 _ => 0.0,
223 }
224 }
225
226 fn step(&self) -> f64 {
228 TAU / self.stations as f64
229 }
230
231 fn phase(&self, theta: f64) -> (Option<f64>, f64) {
233 let h = self.half;
234 let k = ((theta + h) / TAU).floor();
235 let w = theta + h - TAU * k;
236 ((w < 2.0 * h).then_some(w - h), k)
237 }
238
239 pub fn motion(&self, theta: f64) -> [f64; 3] {
241 let (x, k) = self.phase(theta);
242 let step = self.step();
243 let Some(x) = x else { return [(k + 1.0) * step, 0.0, 0.0] };
244 match self.drive {
245 Drive::Geneva { lambda: l, .. } => {
246 let d = 1.0 - 2.0 * l * x.cos() + l * l;
247 let local = (l * x.sin()).atan2(1.0 - l * x.cos());
248 [k * step + 0.5 * step + local, l * (x.cos() - l) / d, -l * (1.0 - l * l) * x.sin() / (d * d)]
249 }
250 Drive::Cam { .. } => {
251 let span = 2.0 * self.half;
252 let [s, s1, s2] = modified_sine((x + self.half) / span);
253 [k * step + step * s, step * s1 / span, step * s2 / (span * span)]
254 }
255 }
256 }
257
258 pub fn lever(&self, theta: f64) -> Option<f64> {
260 let x = self.phase(theta).0?;
261 Some(match self.drive {
262 Drive::Geneva { lambda: l, crank_radius } => crank_radius / l * (1.0 - 2.0 * l * x.cos() + l * l).sqrt(),
263 Drive::Cam { pitch_radius, .. } => pitch_radius,
264 })
265 }
266
267 pub fn loads(&self, theta: f64, speed: f64, acc: f64) -> [f64; 2] {
270 self.loads_twisted(theta, speed, acc, None)
271 }
272
273 fn loads_twisted(&self, theta: f64, speed: f64, acc: f64, held: Option<f64>) -> [f64; 2] {
277 let [_, p1, p2] = self.motion(theta);
278 let a_w = p2 * speed * speed + p1 * acc;
279 let torque = match held {
280 Some(held) => self.j_wheel * a_w - held,
281 None => self.j_table() * a_w,
282 };
283 [torque, self.lever(theta).map_or(0.0, |r| torque / r / self.pressure_angle(theta).cos())]
284 }
285
286 pub fn residual(&self, speed: f64) -> f64 {
290 let (w, zeta) = self.mode;
291 if speed.abs() < 1e-9 {
292 return 0.0;
293 }
294 const STEPS: usize = 2000;
295 let (sigma, wd) = (zeta * w, w * (1.0 - zeta * zeta).sqrt());
296 let dt = 2.0 * self.half / speed.abs() / STEPS as f64;
297 let (c, s, e) = ((wd * dt).cos(), (wd * dt).sin(), (-sigma * dt).exp());
298 let phi = [[e * (c + sigma / wd * s), e * s / wd], [-e * w * w / wd * s, e * (c - sigma / wd * s)]];
299 let (mut x, mut v) = (0.0, 0.0);
300 for i in 0..STEPS {
301 let theta = -self.half + (i as f64 + 0.5) * 2.0 * self.half / STEPS as f64;
302 let rest = -self.motion(theta)[2] * speed * speed / (w * w);
303 let y = x - rest;
304 (x, v) = (rest + phi[0][0] * y + phi[0][1] * v, phi[1][0] * y + phi[1][1] * v);
305 }
306 x.hypot((v + sigma * x) / wd)
307 }
308
309 pub fn settling_time(&self, speed: f64) -> f64 {
311 let a = self.residual(speed);
312 if a <= self.tolerance { 0.0 } else { (a / self.tolerance).ln() / (self.mode.0 * self.mode.1) }
313 }
314}
315
316impl Mechanism for Indexer {
317 fn frame_momentum(&self, q: &[f64], qd: &[f64], rotor_spin: &[f64]) -> Option<sim_core::FrameMomentum> {
323 use sim_components::base::{add_point, add_spin};
324 let [phi, p1, _] = self.motion(q[0]);
325 let (x, xd) = (q.get(1).copied().unwrap_or(0.0), qd.get(1).copied().unwrap_or(0.0));
326 let (wheel, table) = (p1 * qd[0], p1 * qd[0] + xd);
327 let mut f = sim_core::FrameMomentum::default();
328 add_spin(&mut f, [0.0, 1.0, 0.0], self.j_wheel, wheel);
329 add_spin(&mut f, [0.0, 1.0, 0.0], self.j_wheel_table - self.j_wheel, table);
330 let (parts, r) = (if self.attached { self.payload } else { 0.0 }, self.station_radius);
331 for i in 0..self.stations {
332 let a = self.step() * i as f64 - phi - x;
334 let (s, c) = a.sin_cos();
335 add_point(&mut f, parts / self.stations as f64, [r * c, 0.0, r * s], [r * s * table, 0.0, -r * c * table]);
336 }
337 let shaft = match self.drive {
338 Drive::Geneva { .. } => [0.0, -1.0, 0.0],
339 Drive::Cam { .. } => [0.0, 0.0, 1.0],
340 };
341 add_spin(&mut f, shaft, self.j_driver, qd[0]);
342 add_spin(&mut f, shaft, 1.0, rotor_spin[0]);
343 Some(f)
344 }
345 fn dynamics(&self, q: &[f64], qd: &[f64], mass: &mut [f64], bias: &mut [f64]) {
346 let [_, p1, p2] = self.motion(q[0]);
347 mass[0] = self.j_driver + self.j_table() * p1 * p1;
348 bias[0] = self.j_table() * p1 * p2 * qd[0] * qd[0];
349 if self.twist.is_some() {
350 let js = self.j_side();
352 (mass[1], mass[2], mass[3]) = (js * p1, js * p1, js);
353 bias[1] = js * p2 * qd[0] * qd[0];
354 }
355 }
356 fn passive_joints(&self) -> Vec<(f64, f64)> {
357 self.twist.into_iter().collect()
358 }
359 fn passive_signals(&self) -> Vec<SignalInfo> {
360 self.twist
361 .map(|_| SignalInfo::new("table.twist", "group-table", "quantity-table-twist", "rad"))
362 .into_iter()
363 .collect()
364 }
365 fn passive_loss_row(&self) -> Option<(&'static str, &'static str)> {
366 Some(("table_twist", "group-table"))
367 }
368 fn forward(&self, q: &[f64], tool: &mut [f64]) {
369 tool[0] = q[0];
370 }
371 fn potential(&self, _q: &[f64]) -> f64 {
372 0.0
373 }
374 fn set_payload_attached(&mut self, attached: bool) {
375 self.attached = attached;
376 }
377 fn tool_is_joints(&self) -> bool {
379 false
380 }
381 fn cam(&self) -> Option<CamMaster> {
382 self.master
383 }
384 fn cam_at(&self, master: f64, out: &mut [[f64; 4]]) {
385 out[0] = self.cam.at(master);
386 }
387 fn cam_curve(&self) -> Option<sim_core::CamCurve> {
388 let cam = self.cam.clone();
389 Some(std::sync::Arc::new(move |master, out: &mut [[f64; 4]]| out[0] = cam.at(master)))
390 }
391
392 fn signal_infos(&self) -> Vec<SignalInfo> {
393 [
394 ("table.angle", "group-table", "quantity-position", "rad"),
395 ("table.speed", "group-table", "quantity-speed", "rad/s"),
396 ("table.acceleration", "group-table", "quantity-acceleration", "rad/s²"),
397 ("table.drive_torque", "group-table", "quantity-table-torque", "N m"),
398 ("indexer.contact_force", "group-indexer", "quantity-contact-force", "N"),
399 ("table.index_error", "group-table", "quantity-index-error", "m"),
400 ("table.settling_time", "group-table", "quantity-settling-time", "s"),
401 ("indexer.inertia", "group-indexer", "quantity-driver-inertia", "kg m²"),
402 ]
403 .into_iter()
404 .chain(matches!(self.drive, Drive::Cam { cam_radius: Some(_), .. }).then_some((
405 "indexer.pressure_angle",
406 "group-indexer",
407 "quantity-pressure-angle",
408 "rad",
409 )))
410 .map(|(id, owner, quantity, unit)| SignalInfo::new(id, owner, quantity, unit))
411 .collect()
412 }
413 fn signals(&self, q: &[f64], qd: &[f64], qdd: &[f64], _force: &[f64], out: &mut Vec<f64>) {
414 let [phi, p1, p2] = self.motion(q[0]);
415 let at = |v: &[f64]| v.get(1).copied().unwrap_or(0.0);
417 let (x, xd, xdd) = (at(q), at(qd), at(qdd));
418 let held = self.twist.filter(|_| q.len() > 1).map(|(k, c)| k * x + c * xd);
419 let [torque, contact] = self.loads_twisted(q[0], qd[0], qdd[0], held);
420 let moving = self.phase(q[0]).0.is_some();
421 out.extend([
423 phi + x,
424 p1 * qd[0] + xd,
425 p2 * qd[0] * qd[0] + p1 * qdd[0] + xdd,
426 torque,
427 contact,
428 if moving { 0.0 } else { (0.5 * self.play + x.abs()) * self.station_radius },
430 if moving { self.settling_time(qd[0]) } else { 0.0 },
431 self.j_driver + self.j_table() * p1 * p1,
432 ]);
433 if matches!(self.drive, Drive::Cam { cam_radius: Some(_), .. }) {
434 out.push(self.pressure_angle(q[0]));
435 }
436 }
437 fn rating_checks(&self) -> Vec<RatingCheck> {
438 [
439 ("indexer-contact-force", "indexer.contact_force"),
440 ("index-accuracy", "table.index_error"),
441 ("index-settling", "table.settling_time"),
442 ]
443 .into_iter()
444 .zip(self.limits)
445 .filter(|(_, limit)| limit.is_finite())
446 .map(|((check, signal), limit)| RatingCheck { check, signal: signal.into(), motor: None, limit, life: false })
447 .collect()
448 }
449
450 fn collision_parts(&self) -> &'static [&'static str] {
453 &["station", "payload"]
454 }
455
456 fn scene(&self, q: &[f64], rotors: &[f64], rotor_speeds: &[f64], out: &mut Scene) {
459 let r = self.station_radius;
460 let phi = self.motion(q[0])[0] + q.get(1).copied().unwrap_or(0.0);
462 let driver = [-(r + 0.12), 0.0, 0.0];
463 out.parts.push(Part::new("table", Shape::Cylinder { radius: r, length: 0.03 }, [0.0; 3], [0.45, 0.47, 0.5]));
464 for i in 0..self.stations {
465 out.parts.push(
466 Part::new("table-mark", Shape::Box { size: [r, 0.004, 0.02] }, [0.0, -0.017, 0.0], [0.1, 0.1, 0.1])
467 .turned(-phi + self.step() * i as f64),
468 );
469 let a = -phi + self.step() * i as f64;
470 let at = |y: f64| [0.85 * r * a.cos(), y, 0.85 * r * a.sin()];
471 let fixture = Part::new("station", Shape::Box { size: [0.05, 0.01, 0.05] }, at(-0.02), [0.6, 0.62, 0.66]);
472 out.parts.push(fixture.turned(a));
473 if self.attached && self.payload > 0.0 {
474 let part = Part::new("payload", Shape::Box { size: [0.04, 0.03, 0.04] }, at(-0.04), [0.2, 0.7, 0.3]);
475 out.parts.push(part.turned(a));
476 }
477 }
478 out.parts.push(Part::new("driver", Shape::Cylinder { radius: 0.08, length: 0.03 }, driver, [0.3, 0.32, 0.36]));
479 out.parts.push(
480 Part::new("driver-mark", Shape::Box { size: [0.08, 0.004, 0.015] }, driver, [0.9, 0.8, 0.2]).turned(q[0]),
481 );
482 let motor = [driver[0], 0.12, 0.0];
483 out.parts.push(Part::new(
484 sim_core::scene::MOTOR_PART,
485 Shape::Cylinder { radius: 0.05, length: 0.12 },
486 motor,
487 [0.9, 0.45, 0.1],
488 ));
489 out.parts.push(Part::new(
491 "gearbox",
492 Shape::Box { size: [0.1, 0.06, 0.1] },
493 [driver[0], 0.06, 0.0],
494 [0.25, 0.25, 0.28],
495 ));
496 out.parts.push(
497 Part::new("rotor-bar", Shape::Box { size: [0.07, 0.004, 0.012] }, [motor[0], 0.19, 0.0], [0.1, 0.1, 0.1])
498 .turned(rotors[0]),
499 );
500 out.labels.push(Label {
501 pos: [driver[0], 0.0, 0.16],
502 owner_key: "motor-joint-1",
503 value: rotor_speeds[0] * 60.0 / TAU,
504 unit_key: "unit-rpm",
505 decimals: 0,
506 });
507 out.labels.push(Label {
508 pos: [0.0, 0.0, r + 0.05],
509 owner_key: "group-table",
510 value: phi.to_degrees(),
511 unit_key: "unit-deg",
512 decimals: 1,
513 });
514 }
515}