1#[derive(Debug, Clone, PartialEq)]
5pub enum Shape {
6 Box { size: [f64; 3] },
8 Cylinder { radius: f64, length: f64 },
11 Segment { to: [f64; 3], width: f64 },
13}
14
15#[derive(Debug, Clone, PartialEq)]
16pub struct Part {
17 pub id: &'static str,
18 pub shape: Shape,
19 pub pos: [f64; 3],
20 pub angle: f64,
22 pub flat: bool,
25 pub color: [f32; 3],
26 pub highlight: f32,
28 pub heat: Option<f32>,
31}
32
33impl Part {
34 pub fn new(id: &'static str, shape: Shape, pos: [f64; 3], color: [f32; 3]) -> Self {
35 Self { id, shape, pos, angle: 0.0, flat: false, color, highlight: 0.0, heat: None }
36 }
37 pub fn turned(mut self, angle: f64) -> Self {
38 self.angle = angle;
39 self
40 }
41 pub fn highlighted(mut self, highlight: f32) -> Self {
42 self.highlight = highlight;
43 self
44 }
45 pub fn lay_flat(&mut self) {
50 let turn = |p: [f64; 3]| [p[0], p[2], -p[1]];
51 self.pos = turn(self.pos);
52 match &mut self.shape {
53 Shape::Segment { to, .. } => *to = turn(*to),
54 _ => self.flat = true,
55 }
56 }
57 pub fn oriented(&self, v: [f64; 3]) -> [f64; 3] {
59 if self.flat { [v[0], v[2], -v[1]] } else { v }
60 }
61}
62
63#[derive(Debug, Clone, PartialEq)]
66pub struct Label {
67 pub pos: [f64; 3],
68 pub owner_key: &'static str,
69 pub value: f64,
70 pub unit_key: &'static str,
71 pub decimals: usize,
72}
73
74#[derive(Debug, Clone, PartialEq)]
77pub struct Arrow {
78 pub pos: [f64; 3],
79 pub force: [f64; 3],
80 pub owner_key: &'static str,
81}
82
83#[derive(Debug, Clone, PartialEq)]
84pub struct Scene {
85 pub parts: Vec<Part>,
86 pub labels: Vec<Label>,
87 pub arrows: Vec<Arrow>,
89 pub tool: Option<[f64; 3]>,
92 pub planned: Option<[f64; 3]>,
94 pub exaggeration: f64,
97 pub obstacles: Vec<Obstacle>,
99 pub clearance: Option<([f64; 3], [f64; 3], f64)>,
102 pub first_contact: Option<f64>,
104}
105
106impl Default for Scene {
107 fn default() -> Self {
108 Self {
109 parts: Vec::new(),
110 labels: Vec::new(),
111 arrows: Vec::new(),
112 tool: None,
113 planned: None,
114 exaggeration: 1.0,
115 obstacles: Vec::new(),
116 clearance: None,
117 first_contact: None,
118 }
119 }
120}
121
122#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
125pub struct Aabb {
126 pub centre: [f64; 3],
127 pub size: [f64; 3],
128}
129
130impl Aabb {
131 pub fn extent(&self) -> ([f64; 3], [f64; 3]) {
133 (
134 std::array::from_fn(|i| self.centre[i] - self.size[i] / 2.0),
135 std::array::from_fn(|i| self.centre[i] + self.size[i] / 2.0),
136 )
137 }
138
139 pub fn gap(&self, other: &Aabb) -> ([f64; 3], [f64; 3], f64) {
145 let (mut p, mut q, mut apart, mut overlap) = ([0.0; 3], [0.0; 3], 0.0, f64::INFINITY);
146 for i in 0..3 {
147 let (lo, hi) = (self.centre[i] - self.size[i] / 2.0, self.centre[i] + self.size[i] / 2.0);
148 let (other_lo, other_hi) = (other.centre[i] - other.size[i] / 2.0, other.centre[i] + other.size[i] / 2.0);
149 (p[i], q[i]) = if hi < other_lo {
150 (hi, other_lo)
151 } else if other_hi < lo {
152 (lo, other_hi)
153 } else {
154 overlap = f64::min(overlap, f64::min(hi - other_lo, other_hi - lo));
155 let middle = (lo.max(other_lo) + hi.min(other_hi)) / 2.0;
156 (middle, middle)
157 };
158 apart += (q[i] - p[i]).powi(2);
159 }
160 (p, q, if apart > 0.0 { apart.sqrt() } else { -overlap })
161 }
162}
163
164#[derive(Debug, Clone, Copy, PartialEq)]
168pub struct Capsule {
169 pub from: [f64; 3],
170 pub to: [f64; 3],
171 pub radius: f64,
172}
173
174impl Capsule {
175 pub fn gap_capsule(&self, other: &Capsule) -> f64 {
180 let sub = |a: [f64; 3], b: [f64; 3]| -> [f64; 3] { std::array::from_fn(|i| a[i] - b[i]) };
181 let dot = |a: [f64; 3], b: [f64; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
182 let (d1, d2, r) = (sub(self.to, self.from), sub(other.to, other.from), sub(self.from, other.from));
183 let (a, e, f) = (dot(d1, d1), dot(d2, d2), dot(d2, r));
184 const TINY: f64 = 1e-18;
185 let (s, t) = if a <= TINY && e <= TINY {
186 (0.0, 0.0)
187 } else if a <= TINY {
188 (0.0, (f / e).clamp(0.0, 1.0))
189 } else {
190 let c = dot(d1, r);
191 if e <= TINY {
192 ((-c / a).clamp(0.0, 1.0), 0.0)
193 } else {
194 let b = dot(d1, d2);
195 let denom = a * e - b * b;
196 let s = if denom > TINY { ((b * f - c * e) / denom).clamp(0.0, 1.0) } else { 0.0 };
197 let t = (b * s + f) / e;
198 if t < 0.0 {
199 ((-c / a).clamp(0.0, 1.0), 0.0)
200 } else if t > 1.0 {
201 (((b - c) / a).clamp(0.0, 1.0), 1.0)
202 } else {
203 (s, t)
204 }
205 }
206 };
207 let apart: [f64; 3] = std::array::from_fn(|i| (self.from[i] + s * d1[i]) - (other.from[i] + t * d2[i]));
208 dot(apart, apart).sqrt() - self.radius - other.radius
209 }
210
211 pub fn extent(&self) -> ([f64; 3], [f64; 3]) {
213 (
214 std::array::from_fn(|i| self.from[i].min(self.to[i]) - self.radius),
215 std::array::from_fn(|i| self.from[i].max(self.to[i]) + self.radius),
216 )
217 }
218
219 pub fn gap(&self, other: &Aabb) -> ([f64; 3], [f64; 3], f64) {
225 let at = |t: f64| -> [f64; 3] { std::array::from_fn(|i| self.from[i] + t * (self.to[i] - self.from[i])) };
226 let signed = |t: f64| {
227 let q: [f64; 3] = std::array::from_fn(|i| (at(t)[i] - other.centre[i]).abs() - other.size[i] / 2.0);
228 q.iter().map(|v| v.max(0.0).powi(2)).sum::<f64>().sqrt() + q[0].max(q[1]).max(q[2]).min(0.0)
229 };
230 let golden = (5f64.sqrt() - 1.0) / 2.0;
231 let (mut a, mut b) = (0.0, 1.0);
232 let (mut c, mut d) = (b - golden * (b - a), a + golden * (b - a));
233 let (mut fc, mut fd) = (signed(c), signed(d));
234 for _ in 0..80 {
236 if fc < fd {
237 (b, d, fd) = (d, c, fc);
238 c = b - golden * (b - a);
239 fc = signed(c);
240 } else {
241 (a, c, fc) = (c, d, fd);
242 d = a + golden * (b - a);
243 fd = signed(d);
244 }
245 }
246 let t = [0.0, 1.0, 0.5 * (a + b)].into_iter().min_by(|x, y| signed(*x).total_cmp(&signed(*y))).unwrap_or(0.0);
247 let (p, distance) = (at(t), signed(t));
248 if distance <= 0.0 {
249 return (p, p, distance - self.radius);
250 }
251 let q: [f64; 3] = std::array::from_fn(|i| {
252 p[i].clamp(other.centre[i] - other.size[i] / 2.0, other.centre[i] + other.size[i] / 2.0)
253 });
254 let surface = std::array::from_fn(|i| p[i] + (q[i] - p[i]) * (self.radius / distance).min(1.0));
255 (surface, q, distance - self.radius)
256 }
257}
258
259#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
263pub struct Obstacle {
264 pub name: String,
265 pub aabb: Aabb,
266 pub contact: bool,
267 pub stiffness: f64,
268 pub damping: f64,
269}
270
271pub fn scene_boxes(parts: &[Part], ids: &[&str]) -> Vec<Aabb> {
275 parts
276 .iter()
277 .filter(|part| ids.contains(&part.id))
278 .filter_map(|part| match part.shape {
279 Shape::Box { size } => Some(Aabb { centre: part.pos, size: size.map(f64::abs) }),
280 _ => None,
281 })
282 .collect()
283}
284
285pub fn heat_color(heat: f32) -> [f32; 3] {
288 const SCALE: [[f32; 3]; 3] = [[0.15, 0.3, 0.75], [0.95, 0.8, 0.1], [0.95, 0.1, 0.05]];
289 if heat > 1.0 {
290 return [0.9, 0.2, 0.9];
291 }
292 let at = 2.0 * heat.max(0.0);
293 let (i, f) = if at < 1.0 { (0, at) } else { (1, at - 1.0) };
294 std::array::from_fn(|c| SCALE[i][c] + (SCALE[i + 1][c] - SCALE[i][c]) * f)
295}
296
297pub fn part_color(color: [f32; 3], highlight: f32, heat: Option<f32>) -> [f32; 3] {
301 if let Some(heat) = heat {
302 return heat_color(heat);
303 }
304 let h = highlight.clamp(-1.0, 1.0);
305 let (toward, amount) = if h >= 0.0 { ([1.0, 0.1, 0.1], h) } else { ([0.1, 0.3, 1.0], -h) };
306 std::array::from_fn(|c| color[c] + (toward[c] - color[c]) * amount)
307}
308
309pub fn on_circle(centre: [f64; 2], radius: f64, turn: f64) -> [f64; 2] {
311 [centre[0] + radius * turn.cos(), centre[1] + radius * turn.sin()]
312}
313
314pub const BELT_COLOR: [f32; 3] = [0.08, 0.08, 0.09];
316
317pub fn belt(
324 out: &mut Vec<Part>,
325 path: &[[f64; 2]],
326 y: f64,
327 width: f64,
328 tooth_spacing: f64,
329 shade: impl Fn(usize) -> f32,
330) {
331 let along: Vec<f64> = std::iter::once(0.0)
332 .chain(path.windows(2).scan(0.0, |sum, p| {
333 *sum += (p[1][0] - p[0][0]).hypot(p[1][1] - p[0][1]);
334 Some(*sum)
335 }))
336 .collect();
337 belt_along(out, path, &along, y, width, tooth_spacing, shade);
338}
339
340pub fn belt_along(
344 out: &mut Vec<Part>,
345 path: &[[f64; 2]],
346 along: &[f64],
347 y: f64,
348 width: f64,
349 tooth_spacing: f64,
350 shade: impl Fn(usize) -> f32,
351) {
352 let (strip, tooth) = (BELT_COLOR, [0.75, 0.75, 0.7]);
353 let mut next_tooth = tooth_spacing / 2.0;
354 for (i, pair) in path.windows(2).enumerate() {
355 let (a, b, (c0, c1)) = (pair[0], pair[1], (along[i], along[i + 1]));
356 let (dx, dz) = (b[0] - a[0], b[1] - a[1]);
357 if dx.hypot(dz) < 1e-9 || c1 - c0 < 1e-9 {
358 continue;
359 }
360 out.push(
361 Part::new("belt", Shape::Segment { to: [b[0], y, b[1]], width }, [a[0], y, a[1]], strip)
362 .highlighted(shade(i)),
363 );
364 while next_tooth < c1 {
365 let f = (next_tooth - c0) / (c1 - c0);
366 let pos = [a[0] + f * dx, y - 0.001, a[1] + f * dz];
367 out.push(
368 Part::new("belt-tooth", Shape::Box { size: [0.004, width, 0.007] }, pos, tooth).turned(dz.atan2(dx)),
369 );
370 next_tooth += tooth_spacing;
371 }
372 }
373}
374
375pub const MOTOR_PART: &str = "motor";
378
379pub fn drive_unit(
383 out: &mut Vec<Part>,
384 centre: [f64; 2],
385 y: f64,
386 radius: f64,
387 pulley_angle: f64,
388 rotor_angle: f64,
389 color: [f32; 3],
390) {
391 let at = |depth: f64| [centre[0], y + depth, centre[1]];
392 out.extend([
393 Part::new(MOTOR_PART, Shape::Box { size: [0.075, 0.13, 0.075] }, at(0.15), color),
394 Part::new("gearbox", Shape::Cylinder { radius: 0.035, length: 0.07 }, at(0.05), [0.25, 0.25, 0.28]),
395 Part::new("pulley", Shape::Cylinder { radius, length: 0.03 }, at(0.0), [0.55, 0.55, 0.6]),
396 Part::new(
397 "pulley-spoke",
398 Shape::Box { size: [1.8 * radius, 0.004, 0.22 * radius] },
399 at(-0.017),
400 [0.95, 0.95, 0.95],
401 )
402 .turned(pulley_angle),
403 Part::new(
404 "pulley-spoke",
405 Shape::Box { size: [0.22 * radius, 0.004, 1.8 * radius] },
406 at(-0.017),
407 [0.2, 0.2, 0.2],
408 )
409 .turned(pulley_angle),
410 Part::new("rotor-hub", Shape::Cylinder { radius: 0.5 * radius, length: 0.012 }, at(-0.024), [0.95, 0.75, 0.1]),
411 Part::new("rotor-bar", Shape::Box { size: [0.9 * radius, 0.004, 0.2 * radius] }, at(-0.032), [0.1, 0.1, 0.1])
412 .turned(rotor_angle),
413 ]);
414}
415
416pub fn idler(out: &mut Vec<Part>, centre: [f64; 2], y: f64, radius: f64, angle: f64) {
418 out.extend([
419 Part::new("idler", Shape::Cylinder { radius, length: 0.03 }, [centre[0], y, centre[1]], [0.5, 0.5, 0.55]),
420 Part::new(
421 "idler-bar",
422 Shape::Box { size: [1.7 * radius, 0.004, 0.25 * radius] },
423 [centre[0], y - 0.017, centre[1]],
424 [0.9, 0.9, 0.9],
425 )
426 .turned(angle),
427 ]);
428}
429
430#[cfg(test)]
431mod tests {
432 use super::*;
433
434 #[test]
440 fn a_box_inside_another_is_as_deep_as_its_way_out() {
441 let cube = Aabb { centre: [0.0; 3], size: [0.1; 3] };
442 let (_, _, d) = cube.gap(&Aabb { centre: [0.02, 0.0, 0.01], size: [0.0; 3] });
443 assert!((d + 0.03).abs() < 1e-12, "{d}");
444 let (_, _, d) = cube.gap(&Aabb { centre: [0.02, 0.0, 0.01], size: [0.02; 3] });
445 assert!((d + 0.04).abs() < 1e-12, "{d}");
446 }
447
448 #[test]
449 fn gap_between_boxes_by_hand() {
450 let big = Aabb { centre: [0.0; 3], size: [0.2; 3] };
451 let (p, q, d) = big.gap(&Aabb { centre: [0.4, 0.3, 0.0], size: [0.1; 3] });
452 assert!((d - (0.25f64.powi(2) + 0.15f64.powi(2)).sqrt()).abs() < 1e-12, "{d}");
453 let near = |a: [f64; 3], b: [f64; 3]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-12);
454 assert!(near(p, [0.1, 0.1, 0.0]) && near(q, [0.35, 0.25, 0.0]), "{p:?} {q:?}");
455 let (_, _, d) = big.gap(&Aabb { centre: [0.12, 0.0, 0.02], size: [0.1; 3] });
456 assert!((d + 0.03).abs() < 1e-12, "{d}");
457 }
458
459 #[test]
466 fn a_slanted_capsule_keeps_the_hand_calculated_clearance_to_a_box() {
467 let rod = Capsule { from: [0.0; 3], to: [0.3, 0.0, 0.3], radius: 0.006 };
468 let (p, q, d) = rod.gap(&Aabb { centre: [0.25, 0.0, 0.05], size: [0.1; 3] });
469 assert!((d - (0.1 / 2f64.sqrt() - 0.006)).abs() < 1e-12, "{d}");
470 let near = |a: [f64; 3], b: [f64; 3]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-9);
471 let s = 0.006 / 2f64.sqrt();
472 assert!(near(q, [0.2, 0.0, 0.1]) && near(p, [0.15 + s, 0.0, 0.15 - s]), "{p:?} {q:?}");
473 let boxed = Aabb { centre: [0.15, 0.0, 0.15], size: [0.312, 0.012, 0.312] };
474 assert!(boxed.gap(&Aabb { centre: [0.25, 0.0, 0.05], size: [0.1; 3] }).2 < 0.0);
475 let (_, _, d) = rod.gap(&Aabb { centre: [0.15, 0.0, 0.1], size: [0.1; 3] });
476 assert!((d + 0.031).abs() < 1e-12, "{d}");
477 }
478
479 #[test]
480 fn belt_teeth_keep_their_place_on_the_belt_when_the_path_changes() {
481 let teeth = |path: &[[f64; 2]]| {
482 let mut parts = Vec::new();
483 belt(&mut parts, path, 0.0, 0.02, 0.1, |_| 0.0);
484 parts.into_iter().filter(|p| p.id == "belt-tooth").map(|p| p.pos).collect::<Vec<_>>()
485 };
486 let before = teeth(&[[0.0, 0.0], [0.6, 0.0], [0.6, 0.4]]);
488 assert_eq!(before.len(), 10);
489 assert!((before[0][0] - 0.05).abs() < 1e-12 && (before[9][2] - 0.35).abs() < 1e-12);
490 let after = teeth(&[[0.0, 0.0], [0.5, 0.0], [0.5, 0.5]]);
492 assert_eq!(after.len(), 10);
493 assert_eq!(before.iter().filter(|p| p[2] > 0.0).count() + 1, after.iter().filter(|p| p[2] > 0.0).count());
494 }
495
496 #[test]
497 fn belt_strips_carry_the_shade_of_their_section() {
498 let mut parts = Vec::new();
499 belt(&mut parts, &[[0.0, 0.0], [1.0, 0.0], [1.0, 1.0]], 0.0, 0.02, 10.0, |i| i as f32 * 0.5);
500 let shades: Vec<f32> = parts.iter().filter(|p| p.id == "belt").map(|p| p.highlight).collect();
501 assert_eq!(shades, vec![0.0, 0.5]);
502 }
503}