1use crate::{axis, gravity, machine, master, payload};
52use sim_components::cam::{Cam, Law, Segment};
53use sim_components::chain::Mechanism;
54use sim_components::joint::RotaryJoint;
55use sim_core::{CamMaster, Config, ConfigError, Label, Machine, Part, RatingCheck, Scene, Shape, SignalInfo};
56use std::f64::consts::TAU;
57
58pub struct DiscCam {
59 pub lift: Cam,
61 pub base_radius: f64,
62 pub roller_radius: f64,
63 pub offset: f64,
64 pub j_disc: f64,
65 pub m_follower: f64,
67 pub payload: f64,
68 pub attached: bool,
69 pub spring: f64,
70 pub preload: f64,
71 pub g: f64,
72 pub cam: Cam,
74 pub master: Option<CamMaster>,
75 pub lift_off: Option<LiftOff>,
77 limits: [f64; 2],
78}
79
80#[derive(Debug, Clone, Copy, PartialEq)]
82pub struct LiftOff {
83 pub width: f64,
85 pub zeta: f64,
87 pub friction: f64,
89}
90
91const GUIDE_SMOOTHING: f64 = 1e-3;
93
94const PALMGREN: f64 = 3.84e-8 / 251.188_643_150_958;
97
98impl LiftOff {
99 pub(crate) fn depth(&self, q: f64) -> f64 {
101 PALMGREN * q.max(0.0).powf(0.9) / self.width.powf(0.8)
102 }
103 pub(crate) fn load(&self, d: f64) -> [f64; 2] {
105 if d <= 0.0 {
106 return [0.0; 2];
107 }
108 let q = (d * self.width.powf(0.8) / PALMGREN).powf(1.0 / 0.9);
109 [q, q / (0.9 * d)]
110 }
111}
112
113pub fn build(cfg: &Config) -> Result<Box<dyn Machine>, ConfigError> {
114 let joint = RotaryJoint::from_config(cfg)?;
115 let disc = DiscCam::from_config(cfg)?;
116 let theta = axis(cfg, "disc", "axis-disc", "rad", joint.range)?;
117 machine(cfg, disc, (joint, None, "rad"), theta, true)
118}
119
120impl DiscCam {
121 pub fn from_config(cfg: &Config) -> Result<Self, ConfigError> {
122 let lift = Cam::from_config(cfg, "disc")?;
123 if (lift.period - TAU).abs() > 1e-6 || lift.advance.abs() > 1e-9 {
125 return Err(ConfigError::Invalid("disc.segment (one turn, 2 pi rad, rising by 0 in all)".into()));
126 }
127 let (base_radius, roller_radius) =
128 (cfg.positive("disc.base_radius_m")?, cfg.positive("follower.roller_radius_m")?);
129 let offset = cfg.f64("follower.offset_m")?;
130 if offset.abs() >= base_radius + roller_radius {
131 return Err(ConfigError::Invalid("follower.offset_m".into()));
132 }
133 let cam = Cam::from_segments(&[Segment { master: TAU, slave: TAU, law: Law::Linear }])
134 .expect("one turn at constant speed");
135 let master = master(cfg, TAU * cfg.positive("disc.turns_per_min")? / 60.0, cam.period)?;
136 Ok(DiscCam {
137 lift,
138 base_radius,
139 roller_radius,
140 offset,
141 j_disc: cfg.positive("disc.inertia_kgm2")?,
142 m_follower: cfg.positive("follower.mass_kg")?,
143 payload: payload(cfg)?,
144 attached: true,
145 spring: cfg.non_negative("follower.spring_n_m")?,
146 preload: cfg.non_negative("follower.spring_preload_n")?,
147 g: gravity(cfg)?,
148 cam,
149 master,
150 lift_off: if cfg.bool("effects.follower_lift_off")? {
151 Some(LiftOff {
152 width: cfg.positive("follower.roller_width_m")?,
153 zeta: cfg.non_negative("follower.contact_damping_ratio")?,
154 friction: cfg.non_negative("follower.guide_friction_n")?,
155 })
156 } else {
157 None
158 },
159 limits: [
160 cfg.f64("ratings.disc_max_contact_force_n").unwrap_or(f64::INFINITY),
161 cfg.f64("ratings.disc_max_pressure_angle_deg").map_or(f64::INFINITY, f64::to_radians),
162 ],
163 })
164 }
165
166 fn m(&self) -> f64 {
167 self.m_follower + if self.attached { self.payload } else { 0.0 }
168 }
169
170 pub fn s0(&self) -> f64 {
172 let pitch = self.base_radius + self.roller_radius;
173 (pitch * pitch - self.offset * self.offset).sqrt()
174 }
175
176 pub fn pressure_angle(&self, theta: f64) -> f64 {
178 let [s, s1, ..] = self.lift.at(theta);
179 ((s1 - self.offset) / (self.s0() + s)).atan()
180 }
181
182 fn held(&self, s: f64) -> f64 {
184 self.preload + self.spring * s + self.m() * self.g
185 }
186
187 pub fn loads(&self, theta: f64, speed: f64, acc: f64) -> [f64; 2] {
189 let [s, s1, s2, _] = self.lift.at(theta);
190 let phi = self.pressure_angle(theta);
191 let along = self.m() * (s2 * speed * speed + s1 * acc) + self.held(s);
192 let contact = along / phi.cos();
193 [contact, contact * phi.sin()]
194 }
195
196 pub fn contact_force(&self, g: f64, gd: f64) -> [f64; 2] {
199 let Some(lo) = self.lift_off else { return [0.0; 2] };
200 let [q, stiffness] = lo.load(-g);
201 let damper = 2.0 * lo.zeta * (stiffness * self.m()).sqrt() * -gd;
202 [(q + damper).max(0.0), q]
203 }
204
205 fn guide_friction(&self, v: f64) -> f64 {
207 self.lift_off.map_or(0.0, |lo| lo.friction * (v / GUIDE_SMOOTHING).tanh())
208 }
209
210 fn gap(q: &[f64], qd: &[f64], qdd: &[f64]) -> [f64; 3] {
213 let at = |x: &[f64]| x.get(1).copied().unwrap_or(0.0);
214 [at(q), at(qd), at(qdd)]
215 }
216}
217
218impl Mechanism for DiscCam {
219 fn frame_momentum(&self, q: &[f64], qd: &[f64], rotor_spin: &[f64]) -> Option<sim_core::FrameMomentum> {
222 let [s, s1, ..] = self.lift.at(q[0]);
223 let mut f = sim_core::FrameMomentum { gravity: [0.0, 0.0, -self.g], ..Default::default() };
224 let [g, gd, _] = Self::gap(q, qd, &[]);
225 let at = [self.offset, 0.0, self.s0() + s + g];
226 sim_components::base::add_point(&mut f, self.m(), at, [0.0, 0.0, s1 * qd[0] + gd]);
227 sim_components::base::add_spin(&mut f, [0.0, -1.0, 0.0], self.j_disc, qd[0]);
228 f.angular[1] -= rotor_spin[0];
229 Some(f)
230 }
231 fn dynamics(&self, q: &[f64], qd: &[f64], mass: &mut [f64], bias: &mut [f64]) {
232 let [s, s1, s2, _] = self.lift.at(q[0]);
233 let m = self.m();
234 mass[0] = self.j_disc + m * s1 * s1;
235 bias[0] = m * s1 * s2 * qd[0] * qd[0] + self.held(s) * s1;
236 if self.lift_off.is_some() {
237 let [g, gd, _] = Self::gap(q, qd, &[]);
239 let push = self.held(s + g) + self.guide_friction(s1 * qd[0] + gd);
240 (mass[1], mass[2], mass[3]) = (m * s1, m * s1, m);
241 bias[0] = m * s1 * s2 * qd[0] * qd[0] + push * s1;
242 bias[1] = m * s2 * qd[0] * qd[0] + push - self.contact_force(g, gd)[0];
243 }
244 }
245 fn potential(&self, q: &[f64]) -> f64 {
246 let g = q.get(1).copied().unwrap_or(0.0);
247 let s = self.lift.at(q[0])[0] + g;
248 let contact = self.lift_off.map_or(0.0, |lo| 9.0 / 19.0 * -g * lo.load(-g)[0]);
249 (self.preload + self.m() * self.g) * s + 0.5 * self.spring * s * s + contact
250 }
251 fn passive_joints(&self) -> Vec<(f64, f64)> {
252 self.lift_off.map(|_| (0.0, 0.0)).into_iter().collect()
253 }
254 fn passive_signals(&self) -> Vec<SignalInfo> {
255 let gap = SignalInfo::new("follower.gap", "group-follower", "quantity-follower-gap", "m");
256 self.lift_off.map(|_| gap).into_iter().collect()
257 }
258 fn passive_loss_row(&self) -> Option<(&'static str, &'static str)> {
260 None
261 }
262 fn passive_rest(&self, q: &[f64]) -> Vec<f64> {
265 let Some(lo) = self.lift_off else { return Vec::new() };
266 let s = self.lift.at(q[0])[0];
267 let mut d = 0.0;
268 for _ in 0..3 {
269 d = lo.depth(self.held(s - d));
270 }
271 vec![-d]
272 }
273 fn loss_row(&self) -> Option<(&'static str, &'static str)> {
275 self.lift_off.map(|_| ("follower_contact", "group-follower"))
276 }
277 fn loss_power(&self, q: &[f64], qd: &[f64]) -> f64 {
279 let [g, gd, _] = Self::gap(q, qd, &[]);
280 let [force, spring] = self.contact_force(g, gd);
281 let v = self.lift.at(q[0])[1] * qd[0] + gd;
282 -(force - spring) * gd + self.guide_friction(v) * v
283 }
284 fn forward(&self, q: &[f64], tool: &mut [f64]) {
285 tool[0] = q[0];
286 }
287 fn set_payload_attached(&mut self, attached: bool) {
288 self.attached = attached;
289 }
290 fn tool_is_joints(&self) -> bool {
292 false
293 }
294 fn cam(&self) -> Option<CamMaster> {
295 self.master
296 }
297 fn cam_at(&self, master: f64, out: &mut [[f64; 4]]) {
298 out[0] = self.cam.at(master);
299 }
300 fn cam_curve(&self) -> Option<sim_core::CamCurve> {
301 let cam = self.cam.clone();
302 Some(std::sync::Arc::new(move |master, out: &mut [[f64; 4]]| out[0] = cam.at(master)))
303 }
304
305 fn signal_infos(&self) -> Vec<SignalInfo> {
306 [
307 ("follower.lift", "group-follower", "quantity-position", "m"),
308 ("follower.speed", "group-follower", "quantity-speed", "m/s"),
309 ("follower.acceleration", "group-follower", "quantity-acceleration", "m/s²"),
310 ("follower.contact_force", "group-follower", "quantity-contact-force", "N"),
311 ("follower.pressure_angle", "group-follower", "quantity-pressure-angle", "rad"),
312 ("follower.guide_load", "group-follower", "quantity-guide-load", "N"),
313 ("disc.inertia", "group-disc", "quantity-disc-inertia", "kg m²"),
314 ]
315 .into_iter()
316 .chain(self.lift_off.map(|_| ("follower.off_disc", "group-follower", "quantity-follower-off-disc", "")))
317 .map(|(id, owner, quantity, unit)| SignalInfo::new(id, owner, quantity, unit))
318 .collect()
319 }
320 fn signals(&self, q: &[f64], qd: &[f64], qdd: &[f64], _force: &[f64], out: &mut Vec<f64>) {
321 let [s, s1, s2, _] = self.lift.at(q[0]);
322 let [g, gd, gdd] = Self::gap(q, qd, qdd);
323 let [mut contact, mut guide] = self.loads(q[0], qd[0], qdd[0]);
324 if self.lift_off.is_some() {
325 let (cos, sin) = (self.pressure_angle(q[0]).cos(), self.pressure_angle(q[0]).sin());
327 let along = if q.len() > 1 { self.contact_force(g, gd)[0] } else { (contact * cos).max(0.0) };
328 (contact, guide) = (along / cos, along / cos * sin);
329 }
330 out.extend([
331 s + g,
332 s1 * qd[0] + gd,
333 s2 * qd[0] * qd[0] + s1 * qdd[0] + gdd,
334 contact,
335 self.pressure_angle(q[0]),
336 guide,
337 self.j_disc + self.m() * s1 * s1,
338 ]);
339 if self.lift_off.is_some() {
340 out.push(f64::from(contact == 0.0));
342 }
343 }
344 fn rating_checks(&self) -> Vec<RatingCheck> {
345 [("disc-contact-force", "follower.contact_force"), ("disc-pressure-angle", "follower.pressure_angle")]
346 .into_iter()
347 .zip(self.limits)
348 .filter(|(_, limit)| limit.is_finite())
349 .map(|((check, signal), limit)| RatingCheck {
350 check,
351 signal: signal.into(),
352 motor: None,
353 limit,
354 life: false,
355 })
356 .collect()
357 }
358
359 fn collision_parts(&self) -> &'static [&'static str] {
360 &["follower", "payload"]
361 }
362
363 fn scene(&self, q: &[f64], rotors: &[f64], rotor_speeds: &[f64], out: &mut Scene) {
366 let (r, e) = (self.base_radius, self.offset);
367 let s = self.lift.at(q[0])[0] + q.get(1).copied().unwrap_or(0.0);
368 let roller = [e, 0.0, self.s0() + s];
369 out.parts.push(Part::new("disc", Shape::Cylinder { radius: r, length: 0.02 }, [0.0; 3], [0.45, 0.47, 0.5]));
370 out.parts.push(
371 Part::new("disc-mark", Shape::Box { size: [r, 0.004, 0.1 * r] }, [0.0, -0.012, 0.0], [0.1, 0.1, 0.1])
372 .turned(q[0]),
373 );
374 out.parts.push(Part::new(
375 "roller",
376 Shape::Cylinder { radius: self.roller_radius, length: 0.02 },
377 roller,
378 [0.2, 0.22, 0.26],
379 ));
380 let top = [e, 0.0, roller[2] + 0.15];
381 out.parts.push(Part::new(
383 "follower",
384 Shape::Box { size: [0.02, 0.02, 0.15] },
385 [e, 0.0, roller[2] + 0.075],
386 [0.75, 0.75, 0.78],
387 ));
388 if self.attached && self.payload > 0.0 {
389 out.parts.push(Part::new("payload", Shape::Box { size: [0.06, 0.06, 0.04] }, top, [0.2, 0.7, 0.3]));
390 }
391 out.parts.push(Part::new(
392 sim_core::scene::MOTOR_PART,
393 Shape::Cylinder { radius: 0.05, length: 0.12 },
394 [0.0, 0.12, 0.0],
395 [0.9, 0.45, 0.1],
396 ));
397 out.parts.push(Part::new(
398 "gearbox",
399 Shape::Box { size: [0.1, 0.06, 0.1] },
400 [0.0, 0.06, 0.0],
401 [0.25, 0.25, 0.28],
402 ));
403 out.parts.push(
404 Part::new("rotor-bar", Shape::Box { size: [0.07, 0.004, 0.012] }, [0.0, 0.19, 0.0], [0.1, 0.1, 0.1])
405 .turned(rotors[0]),
406 );
407 out.labels.push(Label {
408 pos: [0.0, 0.0, r + 0.08],
409 owner_key: "motor-joint-1",
410 value: rotor_speeds[0] * 60.0 / TAU,
411 unit_key: "unit-rpm",
412 decimals: 0,
413 });
414 out.labels.push(Label { pos: top, owner_key: "group-follower", value: s, unit_key: "unit-m", decimals: 4 });
415 }
416 fn scene_point(&self, tool: &[f64]) -> Option<[f64; 3]> {
417 Some([self.offset, 0.0, self.s0() + self.lift.at(tool[0])[0] + 0.15])
418 }
419}