1pub mod geometry;
9pub mod linkage;
10pub mod machine;
11pub mod netlist;
12pub mod scissor;
13pub mod spatial;
14pub mod worm;
15
16pub use machine::ConfigMachine;
17pub use netlist::{Netlist, VERSION, json_schema};
18
19use machine::intern;
20use sim_core::{Config, ConfigError, Machine, MachineEntry};
21use std::collections::HashMap;
22use std::fmt;
23use std::path::PathBuf;
24use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError};
25use toml::{Table, Value};
26
27pub fn build(cfg: &Config) -> Result<Box<dyn Machine>, ConfigError> {
29 let machine = build_without_cylinders(cfg)?;
30 let cylinders = netlist::cylinders(cfg)?;
31 if cylinders.is_empty() {
32 return Ok(machine);
33 }
34 let carrying: Vec<_> = (Netlist::parse(cfg)?.axes.iter().enumerate())
36 .map(|(i, a)| {
37 let (up, across) = a.incline_deg.to_radians().sin_cos();
38 (a.id.clone(), (!a.rotary).then_some(if i == 0 { [across, 0.0, up] } else { [0.0, across, up] }))
39 })
40 .collect();
41 sim_components::pneumatic::attach(cfg, &cylinders, &carrying, machine)
42}
43
44fn build_without_cylinders(cfg: &Config) -> Result<Box<dyn Machine>, ConfigError> {
45 let net = Netlist::parse(cfg)?;
46 if let Some(scissor) = &net.scissor {
47 return sim_components::base::mount(cfg, Box::new(scissor::ScissorMachine::from_node(cfg, &net, scissor)?));
48 }
49 match &net.linkage {
50 Some(linkage) if linkage.gearboxes.len() == 3 => {
51 sim_components::base::mount(cfg, Box::new(spatial::Delta::from_node(cfg, &net, linkage)?))
52 }
53 Some(linkage) => {
54 sim_components::base::mount(cfg, Box::new(linkage::LinkageMachine::from_node(cfg, &net, linkage)?))
55 }
56 None => sim_components::base::mount(cfg, Box::new(ConfigMachine::new(cfg, &net)?)),
57 }
58}
59
60fn no_suite_configs() -> Vec<Config> {
62 Vec::new()
63}
64
65#[derive(Debug, Clone, PartialEq)]
68pub struct FileError {
69 pub file: PathBuf,
70 pub line: Option<usize>,
71 pub error: ConfigError,
72}
73
74impl fmt::Display for FileError {
75 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
76 write!(f, "{}", self.file.display())?;
77 if let Some(line) = self.line {
78 write!(f, ":{line}")?;
79 }
80 write!(f, ": {}: {}", self.error.key(), self.error.detail())
81 }
82}
83
84impl std::error::Error for FileError {}
85
86pub fn from_text(
92 toml_text: &str,
93 lines: bool,
94 fallback_id: &str,
95 known: &[Config],
96) -> Result<&'static MachineEntry, (ConfigError, Option<usize>)> {
97 let key = (toml_text.to_string(), lines, fallback_id.to_string());
101 if let Some(&entry) = cache().get(&key) {
102 return Ok(entry);
103 }
104 let located = |e: ConfigError| {
105 let line = if lines { line_of(toml_text, e.detail()) } else { None };
106 (e, line)
107 };
108 let cfg = Config::parse(toml_text).map_err(|e| (e, None))?;
109 let net = Netlist::parse(&cfg).map_err(located)?;
110 cfg.check_keys(&schema(&cfg, &net, known), &sim_components::analysis::RATINGS_BEYOND_DEFAULT).map_err(located)?;
111 let text_of = |key: &str| cfg.get(key).ok().and_then(Value::as_str).map(str::to_string);
112 let id = text_of("machine.id").unwrap_or_else(|| fallback_id.to_string());
113 let name = text_of("machine.name").unwrap_or_else(|| id.clone());
114 let probe = MachineEntry { id: "", key: "", default_config: "", i18n: &[], build, suite_configs: no_suite_configs };
117 sim_components::Sim::new(&probe, &cfg).map_err(located)?;
118 let mut cache = cache();
119 let entry = *cache.entry(key).or_insert_with(|| {
121 Box::leak(Box::new(MachineEntry {
122 id: intern(&id),
123 key: intern(&name),
124 default_config: Box::leak(toml_text.to_string().into_boxed_str()),
125 ..probe
126 }))
127 });
128 Ok(entry)
129}
130
131type Cache = HashMap<(String, bool, String), &'static MachineEntry>;
132
133fn cache() -> MutexGuard<'static, Cache> {
136 static CACHE: OnceLock<Mutex<Cache>> = OnceLock::new();
137 CACHE.get_or_init(Default::default).lock().unwrap_or_else(PoisonError::into_inner)
138}
139
140#[doc(hidden)]
142pub fn kept_entries() -> usize {
143 cache().len()
144}
145
146fn schema(cfg: &Config, net: &Netlist, known: &[Config]) -> Config {
150 fn merge(into: &mut Table, from: &Table) {
151 for (key, value) in from {
152 match (into.get_mut(key), value) {
153 (Some(Value::Table(a)), Value::Table(b)) => merge(a, b),
154 (None, v) => {
155 into.insert(key.clone(), v.clone());
156 }
157 _ => {}
158 }
159 }
160 }
161 let mut all = Table::new();
162 for c in known {
163 if let Ok(text) = c.to_text() {
164 merge(&mut all, &text.parse().unwrap_or_default());
165 }
166 }
167 let axis = all.get("axis").and_then(|a| a.get("x")).cloned().unwrap_or_else(|| Value::Table(Table::new()));
168 let friction = all.get("friction_x").cloned().unwrap_or_else(|| Value::Table(Table::new()));
169 let turning = match &axis {
171 Value::Table(t) => Value::Table(t.iter().map(|(k, v)| (k.replace("_m_s", "_rad_s"), v.clone())).collect()),
172 other => other.clone(),
173 };
174 let mut axes = Table::new();
175 for a in &net.axes {
176 axes.insert(a.id.clone(), if a.rotary { turning.clone() } else { axis.clone() });
177 }
178 all.insert("axis".into(), Value::Table(axes));
179 for table in sim_components::catalog::PER_MOTOR_TABLES {
181 if let Some(Value::Table(shared)) = all.get(table).cloned() {
182 let plain: Table = shared.into_iter().filter(|(_, v)| !v.is_table()).collect();
183 if let Some(Value::Table(t)) = all.get_mut(table) {
184 for m in &net.motors {
185 t.insert(m.id.clone(), Value::Table(plain.clone()));
186 }
187 }
188 }
189 }
190 if let Some(Value::Table(process)) = all.get_mut("process") {
191 for a in &net.axes {
192 process.insert(format!("force_{}_n", a.id), Value::Float(0.0));
193 }
194 }
195 for g in &net.guides {
196 let nested = g
199 .friction
200 .rsplit('.')
201 .fold(friction.clone(), |inner, part| Value::Table(Table::from_iter([(part.to_string(), inner)])));
202 if let Value::Table(nested) = nested {
203 merge(&mut all, &nested);
204 }
205 }
206 for (layout, path) in &net.values {
208 let Some(known) = all.get(*layout).cloned() else { continue };
209 let nested =
210 path.rsplit('.').fold(known, |inner, part| Value::Table(Table::from_iter([(part.to_string(), inner)])));
211 if let Value::Table(nested) = nested {
212 merge(&mut all, &nested);
213 }
214 }
215 for path in &net.refs {
216 let nested = path
217 .rsplit('.')
218 .fold(Value::Float(0.0), |inner, part| Value::Table(Table::from_iter([(part.to_string(), inner)])));
219 if let Value::Table(nested) = nested {
220 merge(&mut all, &nested);
221 }
222 }
223 if net.gantry.as_ref().is_some_and(|g| g.drives.iter().flatten().count() >= 2) {
225 let sync = Table::from_iter([
226 ("sync".to_string(), Value::String("plain".into())),
227 ("sync_gain_1_s".to_string(), Value::Float(0.0)),
228 ]);
229 merge(&mut all, &Table::from_iter([("gantry".to_string(), Value::Table(sync))]));
230 }
231 for node in netlist::cylinders(cfg).unwrap_or_default() {
233 let table: Table = sim_components::pneumatic::TABLE.parse().unwrap_or_default();
234 let nested = node
235 .values
236 .rsplit('.')
237 .fold(Value::Table(table), |inner, part| Value::Table(Table::from_iter([(part.to_string(), inner)])));
238 let effects = sim_components::pneumatic::EFFECTS.map(|e| (e.to_string(), Value::Boolean(true)));
239 if let Value::Table(nested) = nested {
240 merge(&mut all, &nested);
241 }
242 merge(&mut all, &Table::from_iter([("effects".to_string(), Value::Table(Table::from_iter(effects)))]));
243 }
244 if let Ok(machine) = cfg.get("machine") {
245 all.insert("machine".into(), machine.clone());
246 }
247 all.insert("format_version".into(), Value::Integer(sim_core::config::FORMAT_VERSION));
248 Config::parse(&toml::to_string(&all).unwrap_or_default()).unwrap_or_else(|_| cfg.clone())
249}
250
251pub fn line_of(text: &str, detail: &str) -> Option<usize> {
255 let path = detail.split([' ', '(']).next().unwrap_or_default();
256 let lines: Vec<&str> = text.lines().collect();
257 let header = |line: &str| line.trim_start().starts_with('[');
258 let header_name =
259 |line: &str| line.split('#').next().unwrap_or_default().trim().trim_matches(['[', ']']).trim().to_string();
260 let key_of = |line: &str| line.split('=').next().unwrap_or_default().trim().trim_matches('"').to_string();
261 let key_below = |start: usize, key: &str| {
263 (start..lines.len()).take_while(|&i| i == start || !header(lines[i])).find(|&i| key_of(lines[i]) == key)
264 };
265
266 if let Some(rest) = path.strip_prefix("machine.").filter(|r| r.contains('[')) {
267 let (list, rest) = rest.split_once('[')?;
268 let (node, field) = rest.split_once(']')?;
269 let field = field.trim_start_matches('.').split('.').next().unwrap_or_default();
270 let start = if let Some(n) = node.strip_prefix('#') {
271 let n: usize = n.parse().ok()?;
272 lines
273 .iter()
274 .enumerate()
275 .filter(|(_, l)| header(l) && header_name(l) == format!("machine.{list}"))
276 .nth(n.checked_sub(1)?)?
277 .0
278 } else {
279 (0..lines.len()).find(|&i| {
283 let compact: String =
284 lines[i].split('#').next().unwrap_or_default().chars().filter(|c| !c.is_whitespace()).collect();
285 let under = (0..=i).rev().find(|&h| header(lines[h])).map(|h| header_name(lines[h]));
286 compact.contains(&format!("id=\"{node}\""))
287 && (under.as_deref() == Some(&format!("machine.{list}"))
288 || (under.as_deref() == Some("machine") && compact.contains('{')))
289 })?
290 };
291 let top = (0..=start).rev().find(|&i| header(lines[i])).unwrap_or(start);
293 let found = if field.is_empty() { None } else { key_below(top, field) };
295 return Some(found.unwrap_or(start) + 1);
296 }
297 let parts: Vec<&str> = path.split('.').collect();
299 for split in (0..=parts.len()).rev() {
300 let (table, key) = (parts[..split].join("."), parts[split..].join("."));
301 let top =
302 if table.is_empty() { Some(0) } else { lines.iter().position(|l| header(l) && header_name(l) == table) };
303 if let Some(top) = top {
304 return Some(if key.is_empty() { top } else { key_below(top, &key).unwrap_or(top) } + 1);
305 }
306 }
307 None
308}