1mod crank;
25mod disc;
26mod indexer;
27mod knife;
28mod saw;
29mod toggle;
30
31use sim_components::chain::{JOINT_KEYS, JointMachine, JointSpec, MOTOR_IDS, MOTOR_KEYS, Mechanism};
32use sim_components::joint::RotaryJoint;
33use sim_components::mech::ThermalFeedback;
34use sim_core::{AxisInfo, Config, ConfigError, Machine, MachineEntry, MotorInfo};
35
36pub use crank::SliderCrank;
37pub use disc::DiscCam;
38pub use indexer::{Drive, Indexer, modified_sine};
39pub use knife::RotaryKnife;
40pub use saw::FlyingSaw;
41pub use toggle::TogglePress;
42
43const I18N: &[(&str, &str)] = &[("en", include_str!("../i18n/en.ftl")), ("de", include_str!("../i18n/de.ftl"))];
44
45const NO_TWIST_LIFT_OFF_OR_LINKS: &[&str] =
48 &["table_twist", "follower_lift_off", "link_bending", "link_bending_reaction"];
49
50macro_rules! entry {
51 ($name:ident, $id:literal, $file:literal, $build:expr, $unmodelled:expr) => {
52 pub static $name: MachineEntry = MachineEntry {
53 id: $id,
54 key: concat!("machine-", $id),
55 default_config: concat!(
56 include_str!("../config/common.toml"),
57 "\n",
58 include_str!(concat!("../config/", $file))
59 ),
60 i18n: I18N,
61 build: |cfg| {
62 sim_components::refuse_unmodelled(cfg, $unmodelled)?;
63 $build(cfg)
64 },
65 suite_configs: || suite_configs(&$name),
66 };
67 };
68}
69
70entry!(SLIDER_CRANK, "slider-crank", "slider-crank.toml", crank::build, NO_TWIST_LIFT_OFF_OR_LINKS);
71entry!(ROTARY_KNIFE, "rotary-knife", "rotary-knife.toml", knife::build, NO_TWIST_LIFT_OFF_OR_LINKS);
72entry!(FLYING_SAW, "flying-saw", "flying-saw.toml", saw::build, NO_TWIST_LIFT_OFF_OR_LINKS);
73entry!(DISC_CAM, "disc-cam", "disc-cam.toml", disc::build, &["table_twist", "link_bending", "link_bending_reaction"]);
74entry!(TOGGLE_PRESS, "toggle-press", "toggle-press.toml", toggle::build, NO_TWIST_LIFT_OFF_OR_LINKS);
75const INDEXER: &[&str] = &["follower_lift_off", "link_bending", "link_bending_reaction"];
76entry!(GENEVA_DRIVE, "geneva-drive", "geneva-drive.toml", indexer::build_geneva, INDEXER);
77entry!(CAM_INDEXER, "cam-indexer", "cam-indexer.toml", indexer::build_cam, INDEXER);
78
79const G: f64 = 9.80665;
80
81pub const LOSSY_EFFECTS: [&str; 6] =
83 ["joint_friction", "motor_friction", "gearbox_efficiency", "torque_ripple", "holding_brake", "process_force"];
84
85pub fn lossless_config(entry: &MachineEntry) -> Config {
87 let mut cfg = entry.config();
88 for effect in LOSSY_EFFECTS {
89 cfg.set_text(&format!("effects.{effect} = false")).unwrap();
90 }
91 cfg.set_text("gearbox.damping_nm_s_rad = 0.0").unwrap();
92 let stops = if cfg.get("slide.stop_damping_n_s_m").is_ok() {
93 "slide.stop_damping_n_s_m"
94 } else {
95 "joint.stop_damping_nm_s_rad"
96 };
97 cfg.set_text(&format!("{stops} = 0.0")).unwrap();
98 cfg
99}
100
101fn suite_configs(entry: &MachineEntry) -> Vec<Config> {
103 [(false, true), (false, false), (true, true), (true, false)]
104 .into_iter()
105 .map(|(elastic, payload)| {
106 let mut cfg = lossless_config(entry);
107 cfg.set_text(&format!("effects.joint_elasticity = {elastic}")).unwrap();
108 cfg.set_text(&format!("effects.payload = {payload}")).unwrap();
109 if entry.id == SLIDER_CRANK.id {
113 cfg.set_text("effects.gravity = false").unwrap();
114 }
115 cfg
116 })
117 .collect()
118}
119
120fn gravity(cfg: &Config) -> Result<f64, ConfigError> {
121 Ok(if cfg.bool("effects.gravity")? { G } else { 0.0 })
122}
123
124fn payload(cfg: &Config) -> Result<f64, ConfigError> {
125 Ok(if cfg.bool("effects.payload")? { cfg.non_negative("mass.payload_kg")? } else { 0.0 })
126}
127
128fn master(cfg: &Config, speed: f64, period: f64) -> Result<Option<sim_core::CamMaster>, ConfigError> {
130 if !cfg.bool("cam.run")? {
131 return Ok(None);
132 }
133 Ok(Some(sim_core::CamMaster { speed, period, ramp_s: cfg.positive("cam.ramp_s")? }))
134}
135
136fn axis(
139 cfg: &Config,
140 id: &'static str,
141 key: &'static str,
142 unit: &'static str,
143 (min, max): (f64, f64),
144) -> Result<AxisInfo, ConfigError> {
145 let get = |what: &str, rate: &str| cfg.positive(&format!("axis.{id}.max_{what}_{unit}_{rate}"));
146 Ok(AxisInfo {
147 id,
148 key,
149 unit,
150 min,
151 max,
152 max_vel: get("velocity", "s")?,
153 max_acc: get("acceleration", "s2")?,
154 max_jerk: get("jerk", "s3")?,
155 })
156}
157
158fn machine<M: Mechanism + 'static>(
165 cfg: &Config,
166 mechanism: M,
167 (mut drive, gear_lever, unit): (RotaryJoint, Option<f64>, &'static str),
168 axis: AxisInfo,
169 turns_on: bool,
170) -> Result<Box<dyn Machine>, ConfigError> {
171 if turns_on {
172 let stop = |key: &str, none: f64| -> Result<f64, ConfigError> {
173 if cfg.get(key).is_ok() { cfg.f64(key).map(f64::to_radians) } else { Ok(none) }
174 };
175 drive.range = (stop("joint.stop_min_deg", -1e12)?, stop("joint.stop_max_deg", 1e12)?);
176 if drive.range.0 >= drive.range.1 {
177 return Err(ConfigError::Invalid("joint.stop_min_deg".into()));
178 }
179 }
180 let spec = JointSpec { drive, id: MOTOR_IDS[0], key: JOINT_KEYS[0], gear_lever, unit };
181 sim_components::base::mount(
182 cfg,
183 Box::new(JointMachine::new(
184 mechanism,
185 vec![spec],
186 cfg.bool("effects.joint_elasticity")?,
187 ThermalFeedback::from_config(cfg)?,
188 vec![axis],
189 vec![MotorInfo { id: MOTOR_IDS[0], key: MOTOR_KEYS[0] }],
190 )),
191 )
192}
193
194#[derive(Debug, Clone, Default)]
197struct Table {
198 at: Vec<f64>,
199 value: Vec<f64>,
200}
201
202impl Table {
203 fn from_config(cfg: &Config, at: &str, value: &str) -> Result<Self, ConfigError> {
204 let read = |key: &str| -> Result<Vec<f64>, ConfigError> {
205 cfg.array(key)?
206 .iter()
207 .map(|v| v.as_float().or_else(|| v.as_integer().map(|i| i as f64)))
208 .map(|f| f.filter(|f| sim_core::config::number(*f, key).is_ok()))
209 .collect::<Option<Vec<_>>>()
210 .ok_or_else(|| ConfigError::Type(key.into()))
211 };
212 let (a, v) = (read(at)?, read(value)?);
213 if a.is_empty() || a.len() != v.len() || a.windows(2).any(|w| w[1] <= w[0]) {
214 return Err(ConfigError::Invalid(at.into()));
215 }
216 Ok(Self { at: a, value: v })
217 }
218
219 fn at(&self, x: f64) -> f64 {
220 let (a, v) = (&self.at, &self.value);
221 if a.is_empty() || x < a[0] || x > a[a.len() - 1] {
222 return 0.0;
223 }
224 let i = a.partition_point(|p| *p <= x).clamp(1, a.len().max(2) - 1);
225 if a.len() == 1 {
226 return v[0];
227 }
228 let u = (x - a[i - 1]) / (a[i] - a[i - 1]);
229 v[i - 1] + u * (v[i] - v[i - 1])
230 }
231}
232
233fn forwards(v: f64, smoothing: f64) -> f64 {
237 (v / smoothing - 1.0).clamp(0.0, 1.0)
238}
239
240#[cfg(test)]
241mod disc_tests;
242#[cfg(test)]
243mod indexer_tests;
244#[cfg(test)]
245mod tests;
246#[cfg(test)]
247mod toggle_tests;