Skip to main content

sim_core/
scene.rs

1//! What a machine looks like, as data. A machine never renders; a front end draws these parts.
2//! Coordinates in metres: x to the right, y into the depth, z up.
3
4#[derive(Debug, Clone, PartialEq)]
5pub enum Shape {
6    /// Box centred on `pos`.
7    Box { size: [f64; 3] },
8    /// Cylinder centred on `pos`, axis along y (pulleys and motors seen from the front), or along z where the part is
9    /// laid flat (`Part::flat`).
10    Cylinder { radius: f64, length: f64 },
11    /// Straight strip from `pos` to `to` (a belt span).
12    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    /// Rotation about the depth axis in radians, from +x towards +z: what turns a pulley's spoke.
21    pub angle: f64,
22    /// Laid flat (`lay_flat`): the box or cylinder, after `angle`, turned a quarter turn about x, its y axis to -z and its
23    /// z axis to +y. A segment is never flat: its ends give its direction.
24    pub flat: bool,
25    pub color: [f32; 3],
26    /// -1..1, drawn as a colour shift: belt tension below or above pretension.
27    pub highlight: f32,
28    /// Temperature rise as a share of the part's rated limit, where it is computed: drawn from cold to hot in place
29    /// of the part's colour. Set by the simulation, not by the machine.
30    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    /// Turns the part, drawn upright, a quarter turn about the x axis through the origin: (x, y, z) to (x, z, -y). Seen
46    /// from above it then looks as it looked from the front, a wheel facing up, its `angle` turning from +x towards +y.
47    /// For a wheel of a belt in the x-y plane (an H-bot's): draw it upright at (x, y) in the x-z plane at depth -z, then
48    /// lay it flat.
49    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    /// The direction a vector of the upright part points in the scene: as it is, or turned as `lay_flat` turns it.
58    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/// A live value shown in the 3D view next to the part it belongs to, e.g. a motor's speed.
64/// Both keys are translation keys; the front end formats "owner value unit".
65#[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/// A force that acts at a place in the machine, drawn as an arrow: on what (`owner_key`, a translation key)
75/// and how much, in newtons, along the scene's axes.
76#[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    /// Forces worth seeing, e.g. the belt's pull on the carriage. Filled in by the machine.
88    pub arrows: Vec<Arrow>,
89    /// Where the tool is in the scene right now (`Machine::scene_point` of its pose), for drawing the path
90    /// it travels. Filled in by whoever steps the machine, not by the machine; `None` where there is no mapping.
91    pub tool: Option<[f64; 3]>,
92    /// Where the plan has the tool now (`Machine::scene_point` of the planned pose), filled in like `tool`.
93    pub planned: Option<[f64; 3]>,
94    /// Asked of the machine, not filled in by it: how many times larger to draw the parts' deflections (frame
95    /// sway, the Z axis leaning), which are micrometres. 1 draws them as they are.
96    pub exaggeration: f64,
97    /// The obstacles of the config, each marked while a part of the machine touches it. Filled in like `tool`.
98    pub obstacles: Vec<Obstacle>,
99    /// Where there are obstacles: the nearest points of the machine's parts and of an obstacle (`Aabb::gap`), and the
100    /// clearance between them, m. Filled in like `tool`.
101    pub clearance: Option<([f64; 3], [f64; 3], f64)>,
102    /// The simulated time of the first contact with an obstacle so far, s. Filled in like `tool`.
103    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/// A box with its edges along the scene's axes: an obstacle, or a part of the machine that can hit one
123/// (`Machine::collision_bodies`). Metres, in scene coordinates.
124#[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    /// The least and greatest corner.
132    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    /// The nearest points of the two boxes, one on each, and the clearance between them: the distance of the two
140    /// points; where the boxes overlap, the depth of the overlap, negative: how far one box would have to move to part
141    /// from the other, along the axis where that is least (both points then lie in the middle of the overlap). A box
142    /// inside the other along an axis has to leave by the nearer face; the intersection's width (the depth until 14
143    /// November) is the depth only where neither box holds the other, and was 0 for a point inside a box.
144    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/// A capsule: every point within `radius` of the segment from `from` to `to`. A slanted rod, arm or shaft as a part
165/// that can hit an obstacle (`Machine::collision_capsules`), where a box along the scene's axes around it would be up to
166/// its length wider than it. Metres, in scene coordinates.
167#[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    /// The clearance between two capsules (the planning check of the machine's own parts, `Machine::connected_bodies`):
176    /// the distance of the two segments (closest points as Ericson, Real-Time Collision Detection 5.1.9) less both
177    /// radii. Negative in an overlap, then up to the radii's sum where the segments cross (a measure of how deep, not
178    /// the exact depth).
179    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    /// The least and greatest corner of the box along the scene's axes around the capsule.
212    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    /// The nearest points of the capsule and the box, one on each, and the clearance between them, as `Aabb::gap` has
220    /// them: the least signed distance of the segment's points to the box, less the radius. Negative in an overlap,
221    /// where it is the depth to the box face nearest to the segment's deepest point (both points then on the
222    /// segment). The signed distance of a point to a box is convex along a line, so its least along the segment is
223    /// found by a golden-section search, to the last bit of the segment's parameter: exact, as is the box's.
224    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        // 0.618^80 is 2e-17: the interval is down to the last bit of the parameter.
235        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/// An obstacle of the config (`[[obstacles]]`), and whether a part of the machine touches it now. With effects.crash
260/// it pushes back on a part that goes into it with `stiffness` (N/m) times the depth and `damping` (N s/m) times the
261/// speed into it.
262#[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
271/// The boxes among `parts` (as a machine draws them in its scene) whose id is one of `ids`, turned or not: what
272/// `Machine::collision_bodies` takes for the parts that move with the tool. A machine passes only the parts it needs:
273/// drawing the whole scene every base step made the live check about three times as slow as the run without it.
274pub 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
285/// The colour of the heat scale at a temperature rise of `heat` times the rated one: cold blue, yellow at half, red at
286/// the rated rise, and magenta beyond it.
287pub 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
297/// The colour a 3D view draws a part in: where its warmth is computed (`Part::heat`) the heat scale in its place;
298/// otherwise its own colour, shifted towards red by belt tension above pretension (`highlight` up to 1, at twice the
299/// pretension) and towards blue below it (-1 at no tension).
300pub 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
309/// A point on a circle, for laying a belt path around a pulley. `turn` is in radians from +x.
310pub 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
314/// The colour of a belt strip at pretension; its highlight shifts it.
315pub const BELT_COLOR: [f32; 3] = [0.08, 0.08, 0.09];
316
317/// Draws a belt along a path in the x-z plane at depth `y`: one strip per path segment, and teeth
318/// at a fixed spacing of belt length counted from the start of the path.
319///
320/// Start the path where the belt is clamped. Then the teeth sit at fixed places on the belt, and
321/// when the path changes with the pose they travel along it and around the pulleys by themselves.
322/// `shade(i)` is the highlight of the strip from point i to point i + 1.
323pub 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
340/// `belt` with the belt length of each path point given (`along`, rising) rather than taken from the drawn path:
341/// for a drawn path that is not the belt's length, e.g. a span drawn sagging larger than it is. Each tooth keeps its
342/// place in belt length and sits on the drawn segment whose ends' belt lengths hold it, at the same share between them.
343pub 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
375/// The id of a motor's housing in the scene (`drive_unit`): the k-th such part is motor k's, and the simulation
376/// colours it by the warmth of that motor's winding.
377pub const MOTOR_PART: &str = "motor";
378
379/// Draws a motor with gearbox and belt pulley at `centre` (x, z), the pulley in the belt plane
380/// at depth `y` and the motor behind it. A cross on the pulley turns with the pulley, a bar on
381/// the hub turns with the motor shaft, so both speeds can be seen.
382pub 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
416/// Draws a free-running pulley with a bar that shows its rotation.
417pub 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    /// By hand: a 0.2 m cube at the origin and a 0.1 m cube at (0.4, 0.3, 0): 0.25 m apart in x (0.4 - 0.1 - 0.05),
435    /// 0.15 m in y, overlapping in z, so 0.29155 m apart. Moved to (0.12, 0, 0.02) they overlap by 0.03 m in x, the
436    /// least of 0.03, 0.1 and 0.1.
437    /// By hand: a point at (0.02, 0, 0.01) inside a 0.1 m cube at the origin leaves it by the nearest face, x = 0.05,
438    /// 0.03 m away (z = 0.05 is 0.04 away). A 0.02 m cube there leaves by 0.03 + 0.01 = 0.04 m.
439    #[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    /// By hand: a rod of radius 6 mm slanted at 45 degrees in the x-z plane, from (0, 0, 0) to (0.3, 0, 0.3), and a
460    /// 0.1 m cube centred at (0.25, 0, 0.05). The cube's top edge nearest to the rod runs along y through
461    /// (0.2, y, 0.1); the rod's line x = z is (0.2 - 0.1) / sqrt(2) = 70.711 mm from it, its nearest point (0.15, 0,
462    /// 0.15) within the segment, so the clearance is 70.711 - 6 = 64.711 mm. The old box around the rod (0.312 m wide)
463    /// overlapped the cube. Shifted to centre (0.15, 0, 0.1), the cube holds the rod's point (0.125, 0, 0.125), 25 mm
464    /// inside its top face and its left face: the overlap is 25 + 6 = 31 mm deep.
465    #[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        // An L-shaped path of 1 m: 0.6 m right, then 0.4 m up. Ten teeth, 0.1 m apart.
487        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        // The corner moves 0.1 m to the left: the same belt, one tooth more on the vertical part.
491        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}