Skip to main content

sim_components/
conveyor.rs

1//! Picking from a moving belt conveyor: parts ride on a belt through a pick window; the tool meets each part with the
2//! belt's speed, moves with it while the gripper closes, lifts off and places it at a fixed place or onto a second
3//! moving belt. Works on any machine whose tool axes are Cartesian positions (a delta, a gantry), through the tool
4//! pose alone; all vectors are tool poses or tool velocities, one value per axis (0 on a rotation axis).
5//!
6//! Every move of a pass is a superposition: a jerk-limited straight move (`profile::Move`) from where the phase starts
7//! to a point Q, plus a belt term whose velocity blends from the start velocity `va` to the end velocity `vb` as
8//! `va + (vb - va) h(u)`, `h(u) = 3u^2 - 2u^3`, u = t / T: zero acceleration at both ends, so the phases join without a
9//! jump in acceleration. The belt term covers `T (va + vb) / 2`; a target that moves with `vb` is met at T when
10//! `Q = target(0) + T (vb - va) / 2`. The move is planned with each axis's limits less what the belt term takes
11//! (`max(|va|, |vb|)` of the speed, `1.5 |vb - va| / T` of the acceleration, `6 |vb - va| / T^2` of the jerk), and
12//! T is the shortest time in which the move to that Q fits (`intercept`).
13//!
14//! While the belt is still on its ramp the part speeds up: the intercept then meets it where it is at T with its speed
15//! at T (`intercept_moving`), and the grip follows the belt's own motion (`Track`). The acceleration of the setpoint
16//! steps by the belt's (speed / ramp) where the grip begins and ends.
17//!
18//! With input shaping the setpoint is the plan's weighted copies (`Controller::shape`): a plan at the belt's speed
19//! arrives the mean of the shaper's delays behind, and on the part only once the whole shaper has passed. So a pass
20//! plans for the part that far ahead on each axis, and its grip and release are longer by the shaper's span; the grip
21//! as `Pass::holds` and `Conveyor::gripping` count it begins once the shaped setpoint is on the part.
22
23use crate::profile::Move;
24use sim_core::{AxisInfo, Config, ConfigError};
25
26type Result<T> = std::result::Result<T, ConfigError>;
27
28/// The conveyor of `[conveyor]` and how far it has got: the parts picked and missed so far.
29#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
30pub struct Conveyor {
31    /// Unit vector along the belt in tool coordinates, and the belt's speed, m/s, which it reaches `ramp` seconds after
32    /// the start at a constant acceleration.
33    pub direction: Vec<f64>,
34    pub speed: f64,
35    pub ramp: f64,
36    /// The tool pose that grips a part where it enters the belt (belt position 0), and the belt's length from there.
37    pub origin: Vec<f64>,
38    pub length: f64,
39    /// Parts pass the origin at `n pitch + arrivals[j]`, n = 0, 1, ...
40    pub pitch: f64,
41    pub arrivals: Vec<f64>,
42    /// The stretch of the belt, from the origin, in which the gripper may close: from its start to its end.
43    pub window: [f64; 2],
44    /// Added to a grip or place pose for the pose above it, which the tool comes from and lifts to.
45    pub lift: Vec<f64>,
46    /// Seconds the tool moves with the part while the gripper closes, and with the place while it opens.
47    pub grip: f64,
48    pub release: f64,
49    /// The place pose, and the velocity of the belt it lies on (zero for a fixed place).
50    pub place: Vec<f64>,
51    pub place_velocity: Vec<f64>,
52    /// The verdict `pick-tracking`: the most the tool may be from the part along the belt during a grip, m.
53    pub tolerance: f64,
54    /// The next part not yet picked or missed, counted from 0.
55    next: u64,
56    pub picked: u64,
57    pub missed: u64,
58}
59
60/// One move of a pass, from `start` seconds after the pass began, for `duration`: the move `mv` plus the belt term from
61/// `va` to `vb` (see the module).
62#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
63struct Phase {
64    start: f64,
65    duration: f64,
66    mv: Move,
67    va: Vec<f64>,
68    vb: Vec<f64>,
69    /// A grip: the tool moves with the belt as it runs, in place of the belt term.
70    track: Option<Track>,
71}
72
73/// The belt's own motion along `direction` from the absolute times `from` (one per axis, as the part is planned for),
74/// at `speed` after a ramp of `ramp` seconds.
75#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
76struct Track {
77    direction: Vec<f64>,
78    from: Vec<f64>,
79    speed: f64,
80    ramp: f64,
81}
82
83/// How far a belt has run `t` seconds after its start, at `speed` after a ramp of `ramp` at a constant acceleration,
84/// and its speed and acceleration then.
85fn belt_motion(speed: f64, ramp: f64, t: f64) -> [f64; 3] {
86    let t = t.max(0.0);
87    if t < ramp {
88        [speed * t * t / (2.0 * ramp), speed * t / ramp, speed / ramp]
89    } else {
90        [speed * (t - ramp / 2.0), speed, 0.0]
91    }
92}
93
94impl Phase {
95    fn at(&self, t: f64, pos: &mut [f64], vel: &mut [f64], acc: &mut [f64]) {
96        let tt = self.duration;
97        let t = t.clamp(0.0, tt);
98        self.mv.at(t, pos, vel, acc);
99        if let Some(track) = &self.track {
100            for i in 0..pos.len() {
101                let (d, from) = (track.direction[i], track.from[i]);
102                let [s, v, a] = belt_motion(track.speed, track.ramp, from + t);
103                pos[i] += d * (s - belt_motion(track.speed, track.ramp, from)[0]);
104                vel[i] += d * v;
105                acc[i] += d * a;
106            }
107            return;
108        }
109        let u = if tt > 0.0 { t / tt } else { 1.0 };
110        let (g, h, dh) = (u * u * u - u * u * u * u / 2.0, 3.0 * u * u - 2.0 * u * u * u, 6.0 * u - 6.0 * u * u);
111        for i in 0..pos.len() {
112            let dv = self.vb[i] - self.va[i];
113            pos[i] += self.va[i] * t + dv * tt * g;
114            vel[i] += self.va[i] + dv * h;
115            acc[i] += if tt > 0.0 { dv * dh / tt } else { 0.0 };
116        }
117    }
118}
119
120/// One pick and place, from rest to rest, beginning at the absolute time `start`.
121#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
122pub struct Pass {
123    pub start: f64,
124    phases: Vec<Phase>,
125    /// The grip, from its start to its end, seconds after the pass began, and the part it grips.
126    grip: (f64, f64),
127    part: u64,
128    /// When the gripper lets go, seconds after the pass began.
129    release_end: f64,
130}
131
132impl Pass {
133    pub fn duration(&self) -> f64 {
134        self.phases.last().map_or(0.0, |p| p.start + p.duration)
135    }
136
137    /// Tool pose, velocity and acceleration `t` seconds after the pass began.
138    pub fn at(&self, t: f64, pos: &mut [f64], vel: &mut [f64], acc: &mut [f64]) {
139        let i = self.phases.partition_point(|p| p.start <= t).saturating_sub(1);
140        let phase = &self.phases[i];
141        phase.at(t - phase.start, pos, vel, acc);
142    }
143
144    /// Whether the part is in the gripper `t` seconds after the pass began: from the end of the grip to the end of the
145    /// release.
146    pub fn holds(&self, t: f64) -> bool {
147        t >= self.grip.1 && t < self.release_end
148    }
149}
150
151fn number(v: &toml::Value) -> Option<f64> {
152    v.as_float().or_else(|| v.as_integer().map(|i| i as f64))
153}
154
155impl Conveyor {
156    /// The conveyor of the config's `[conveyor]` table, for a tool of `axes` axes; `None` without the table or with
157    /// `conveyor.enabled = false`.
158    pub fn from_config(cfg: &Config, axes: usize) -> Result<Option<Self>> {
159        if cfg.get("conveyor").is_err() || !cfg.bool("conveyor.enabled")? {
160            return Ok(None);
161        }
162        let pose = |key: &str| -> Result<Vec<f64>> {
163            let path = format!("conveyor.{key}");
164            let v = cfg.f64s(&path)?;
165            if v.len() == axes && v.iter().all(|x| x.is_finite()) { Ok(v) } else { Err(ConfigError::Invalid(path)) }
166        };
167        let unit = |key: &str| -> Result<Vec<f64>> {
168            let v = pose(key)?;
169            let norm = v.iter().map(|x| x * x).sum::<f64>().sqrt();
170            if norm > 0.0 {
171                Ok(v.iter().map(|x| x / norm).collect())
172            } else {
173                Err(ConfigError::Invalid(format!("conveyor.{key}")))
174            }
175        };
176        let direction = unit("direction")?;
177        let place_direction = unit("place_direction")?;
178        let place_speed = cfg.non_negative("conveyor.place_speed_m_s")?;
179        let window = cfg.f64s("conveyor.window_m")?;
180        let length = cfg.positive("conveyor.length_m")?;
181        if window.len() != 2 || !(0.0 <= window[0] && window[0] <= window[1] && window[1] <= length) {
182            return Err(ConfigError::Invalid("conveyor.window_m".into()));
183        }
184        let pitch = cfg.positive("conveyor.pitch_s")?;
185        let bad = || ConfigError::Invalid("conveyor.arrivals_s".into());
186        let mut arrivals: Vec<f64> =
187            cfg.array("conveyor.arrivals_s")?.iter().map(number).collect::<Option<_>>().ok_or_else(bad)?;
188        arrivals.sort_by(f64::total_cmp);
189        if arrivals.is_empty() || arrivals[0] < 0.0 || arrivals[arrivals.len() - 1] >= pitch {
190            return Err(bad());
191        }
192        Ok(Some(Self {
193            direction,
194            speed: cfg.non_negative("conveyor.speed_m_s")?,
195            ramp: cfg.non_negative("conveyor.ramp_s")?,
196            origin: pose("origin")?,
197            length,
198            pitch,
199            arrivals,
200            window: [window[0], window[1]],
201            lift: pose("lift")?,
202            grip: cfg.non_negative("conveyor.grip_s")?,
203            release: cfg.non_negative("conveyor.release_s")?,
204            place: pose("place")?,
205            place_velocity: place_direction.iter().map(|d| d * place_speed).collect(),
206            tolerance: cfg.positive("conveyor.tracking_tolerance_m")?,
207            next: 0,
208            picked: 0,
209            missed: 0,
210        }))
211    }
212
213    /// Goes on where `old` was: its next part, and the parts it picked and missed.
214    pub fn carry_on(&mut self, old: &Self) {
215        (self.next, self.picked, self.missed) = (old.next, old.picked, old.missed);
216    }
217
218    /// How far the belt has run since the start at time `t`.
219    pub fn belt(&self, t: f64) -> f64 {
220        belt_motion(self.speed, self.ramp, t)[0]
221    }
222
223    /// The time at which the belt has run `s`; infinite on a belt that stands.
224    fn belt_time(&self, s: f64) -> f64 {
225        if self.speed <= 0.0 {
226            return f64::INFINITY;
227        }
228        if s < self.speed * self.ramp / 2.0 {
229            (2.0 * self.ramp * s / self.speed).sqrt()
230        } else {
231            s / self.speed + self.ramp / 2.0
232        }
233    }
234
235    /// When part `k` passes the origin.
236    pub fn arrival(&self, k: u64) -> f64 {
237        let n = self.arrivals.len() as u64;
238        (k / n) as f64 * self.pitch + self.arrivals[(k % n) as usize]
239    }
240
241    /// Parts a minute the belt brings.
242    pub fn offered_per_minute(&self) -> f64 {
243        60.0 * self.arrivals.len() as f64 / self.pitch
244    }
245
246    /// Where part `k` is along the belt at time `t`, from the origin (negative before it gets there).
247    pub fn position(&self, k: u64, t: f64) -> f64 {
248        self.belt(t) - self.belt(self.arrival(k))
249    }
250
251    /// The pose that grips part `k` at time `t`.
252    pub fn part_pose(&self, k: u64, t: f64) -> Vec<f64> {
253        let s = self.position(k, t);
254        self.origin.iter().zip(&self.direction).map(|(o, d)| o + d * s).collect()
255    }
256
257    /// The parts on the belt at time `t` that are not in the gripper, with their positions along it: those not yet
258    /// planned for, and the one of `pass` until its grip ends. What the scene draws.
259    pub fn parts_on_belt(&self, t: f64, pass: Option<&Pass>) -> Vec<(u64, f64)> {
260        let waiting = pass.filter(|p| t < p.start + p.grip.1).map(|p| p.part);
261        waiting
262            .into_iter()
263            .chain((self.next..).take_while(|k| self.arrival(*k) <= t).take(64))
264            .map(|k| (k, self.position(k, t)))
265            .filter(|(_, s)| (0.0..=self.length).contains(s))
266            .collect()
267    }
268
269    /// The next pass from `from` at rest at time `now`: for the first part that can be gripped inside the window, the
270    /// parts before it counted as missed. A part the tool would grip before the window waits for it (the pass starts
271    /// later); one it would grip beyond the window, or whose pass leaves `reachable`, is missed. `None` where a
272    /// thousand parts in a row are missed: no part can be picked. Also while the belt is on its ramp.
273    ///
274    /// `shaping`, from the input shaper (`Controller::shaper_delays`): per axis how far its setpoint lags a plan at a
275    /// constant speed, s, and how long after the plan it arrives, s; zeros without shaping. The pass is planned for the
276    /// part that far ahead on each axis, so that the shaped setpoint meets it, and grip and release are longer by the
277    /// span, so that the shaped setpoint is on the part for the whole grip.
278    pub fn plan(
279        &mut self,
280        axes: &[AxisInfo],
281        now: f64,
282        from: &[f64],
283        reachable: &dyn Fn(&[f64]) -> bool,
284        shaping: &(Vec<f64>, f64),
285    ) -> Option<Pass> {
286        let earliest = now;
287        for _ in 0..1000 {
288            let k = self.next;
289            self.next += 1;
290            let Some(pass) = self.pass_for(axes, k, earliest, from, shaping) else {
291                self.missed += 1;
292                continue;
293            };
294            let gripped = self.position(k, pass.start + pass.grip.1);
295            let samples = (pass.duration() / 0.005).ceil() as usize;
296            let n = from.len();
297            let (mut pos, mut vel, mut acc) = (vec![0.0; n], vec![0.0; n], vec![0.0; n]);
298            let inside = (0..=samples).all(|i| {
299                pass.at(pass.duration() * i as f64 / samples.max(1) as f64, &mut pos, &mut vel, &mut acc);
300                reachable(&pos)
301            });
302            if gripped > self.window[1] + 1e-9 || !inside {
303                self.missed += 1;
304                continue;
305            }
306            self.picked += 1;
307            return Some(pass);
308        }
309        None
310    }
311
312    /// The pass for part `k`, starting no earlier than `earliest`, and later where the grip would begin before the
313    /// window or before the part has arrived.
314    fn pass_for(
315        &self,
316        axes: &[AxisInfo],
317        k: u64,
318        earliest: f64,
319        from: &[f64],
320        shaping: &(Vec<f64>, f64),
321    ) -> Option<Pass> {
322        let build = |t0: f64| self.build(axes, k, t0, from, shaping);
323        let mut pass = build(earliest)?;
324        let grip_at = |p: &Pass| p.start + p.grip.0;
325        if self.position(k, grip_at(&pass)) < self.window[0] {
326            if self.speed <= 0.0 {
327                return None;
328            }
329            // Wait: by the time the part reaches the window's start, a pass started then grips it inside.
330            let (mut lo, mut hi) = (earliest, self.belt_time(self.window[0] + self.belt(self.arrival(k))));
331            let mut found = build(hi)?;
332            for _ in 0..50 {
333                let mid = 0.5 * (lo + hi);
334                match build(mid) {
335                    Some(p) if self.position(k, grip_at(&p)) >= self.window[0] => (hi, found) = (mid, p),
336                    _ => lo = mid,
337                }
338            }
339            pass = found;
340        }
341        // On a belt that stands the part is gripped once it is there.
342        let early = self.arrival(k) - grip_at(&pass);
343        if early > 0.0 {
344            pass = build(pass.start + early)?;
345        }
346        Some(pass)
347    }
348
349    /// The phases of a pass for part `k` starting at `t0` from `from` at rest: to above the part, down onto it, the
350    /// grip, up, to above the place, down, the release, up, and, onto a moving place, to rest above the place. With
351    /// `shaping` (see `plan`) the part is planned for that far ahead on each axis, grip and release are longer by the
352    /// span, and the grip counts from the span on.
353    fn build(&self, axes: &[AxisInfo], k: u64, t0: f64, from: &[f64], shaping: &(Vec<f64>, f64)) -> Option<Pass> {
354        let n = from.len();
355        let (lead, settle) = (&shaping.0, shaping.1);
356        let (zero, placed) = (vec![0.0; n], self.place_velocity.clone());
357        let plus = |a: &[f64], b: &[f64]| -> Vec<f64> { a.iter().zip(b).map(|(x, y)| x + y).collect() };
358        let minus = |a: &[f64], b: &[f64]| -> Vec<f64> { a.iter().zip(b).map(|(x, y)| x - y).collect() };
359        let times = |s: f64| -> Vec<f64> { (0..n).map(|i| t0 + s + lead.get(i).copied().unwrap_or(0.0)).collect() };
360        // The part's pose and velocity `s` seconds into the pass, each axis its lead ahead.
361        let part = |s: f64| -> (Vec<f64>, Vec<f64>) {
362            let at = times(s);
363            let pos = (0..n).map(|i| self.origin[i] + self.direction[i] * self.position(k, at[i])).collect();
364            let vel = (0..n).map(|i| self.direction[i] * belt_motion(self.speed, self.ramp, at[i])[1]).collect();
365            (pos, vel)
366        };
367        let part = &part;
368        // Whether the belt still speeds up `s` seconds into the pass on some axis.
369        let ramping = |s: f64| self.speed > 0.0 && times(s).iter().any(|t| *t < self.ramp);
370        let mut phases: Vec<Phase> = Vec::new();
371        let mut at = from.to_vec();
372        let mut t = 0.0;
373        // A phase from where the last ended, with `va`, to a target that is at `target(T)` with the velocity there after
374        // T seconds; `dwell` for a phase of a fixed time that stays with `va`, or with `track` along the belt.
375        let mut add = |at: &mut Vec<f64>,
376                       t: &mut f64,
377                       va: &[f64],
378                       target: &dyn Fn(f64) -> (Vec<f64>, Vec<f64>),
379                       dwell: Option<(f64, Option<Track>)>|
380         -> Option<Vec<f64>> {
381            let (duration, mv, vb, track) = match dwell {
382                Some((d, track)) => {
383                    // The velocity it ends with: the belt's then along a track, else `va` as it is.
384                    let vb = match &track {
385                        Some(track) => (0..n)
386                            .map(|i| track.direction[i] * belt_motion(track.speed, track.ramp, track.from[i] + d)[1])
387                            .collect(),
388                        None => va.to_vec(),
389                    };
390                    (d, Move::new(at, at, axes), vb, track)
391                }
392                None => {
393                    let (duration, mv, vb) = intercept_moving(axes, at, va, target)?;
394                    (duration, mv, vb, None)
395                }
396            };
397            let phase = Phase { start: *t, duration, mv, va: va.to_vec(), vb: vb.clone(), track };
398            let (mut pos, mut vel, mut acc) = (vec![0.0; n], vec![0.0; n], vec![0.0; n]);
399            phase.at(duration, &mut pos, &mut vel, &mut acc);
400            *at = pos;
401            *t += duration;
402            phases.push(phase);
403            // The velocity as given, not as the phase sums it up: a rounding off it would take the next phase off the
404            // intercept's closed form for a tool already moving with its target.
405            Some(vb)
406        };
407        // A target at `pose` now moving with `v`.
408        let steady = |pose: Vec<f64>, v: Vec<f64>| {
409            move |tt: f64| -> (Vec<f64>, Vec<f64>) {
410                let p = pose.iter().zip(&v).map(|(p, v)| p + v * tt).collect();
411                (p, v.clone())
412            }
413        };
414        let lift = self.lift.clone();
415        // Onto the part: where it is after T while the belt speeds up, else at its speed (the intercept in closed form,
416        // as `intercept` has it).
417        let now = t;
418        let above = move |tt: f64| {
419            let (p, v) = part(now + tt);
420            (plus(&p, &lift), v)
421        };
422        let va = if ramping(t) {
423            add(&mut at, &mut t, &zero, &above, None)?
424        } else {
425            let (p, v) = above(0.0);
426            add(&mut at, &mut t, &zero, &steady(p, v), None)?
427        };
428        // Down from where the tool met the part, as at the place: the part's pose to rounding. Its pose computed anew
429        // differs from there by rounding, which a move of no lift made a move of microseconds (the S-curve of a
430        // 1e-16 m step takes (1e-16 / 2 j)^(1/3) * 4 = 2 us), shifting the grip by that.
431        let on_part = minus(&at, &self.lift);
432        let va = if ramping(t) {
433            let (base, start) = (on_part.clone(), part(t).0);
434            let now = t;
435            let down = move |tt: f64| {
436                let (p, v) = part(now + tt);
437                (base.iter().zip(&p).zip(&start).map(|((b, p), s)| b + p - s).collect(), v)
438            };
439            add(&mut at, &mut t, &va, &down, None)?
440        } else {
441            add(&mut at, &mut t, &va, &steady(on_part, va.clone()), None)?
442        };
443        let grip_start = t;
444        // Along the belt as it runs while it speeds up; after, at its speed as the belt term has it.
445        let track = ramping(t).then(|| Track {
446            direction: self.direction.clone(),
447            from: times(t),
448            speed: self.speed,
449            ramp: self.ramp,
450        });
451        let va = add(&mut at, &mut t, &va, &steady(vec![], vec![]), Some((self.grip + settle, track)))?;
452        let grip_end = t;
453        let up = plus(&at, &self.lift);
454        let va = add(&mut at, &mut t, &va, &steady(up, va.clone()), None)?;
455        let va = add(&mut at, &mut t, &va, &steady(plus(&self.place, &self.lift), placed.clone()), None)?;
456        let down = minus(&at, &self.lift);
457        let va = add(&mut at, &mut t, &va, &steady(down, placed.clone()), None)?;
458        let va = add(&mut at, &mut t, &va, &steady(vec![], vec![]), Some((self.release + settle, None)))?;
459        let release_end = t;
460        let up = plus(&at, &self.lift);
461        let va = add(&mut at, &mut t, &va, &steady(up, placed.clone()), None)?;
462        if placed.iter().any(|v| *v != 0.0) {
463            add(&mut at, &mut t, &va, &steady(plus(&self.place, &self.lift), zero.clone()), None)?;
464        }
465        Some(Pass { start: t0, phases, grip: (grip_start + settle, grip_end), part: k, release_end })
466    }
467
468    /// The part in the gripper's grip at time `t` of `pass` (from the grip's start to its end): its pose.
469    pub fn gripping(&self, pass: &Pass, t: f64) -> Option<Vec<f64>> {
470        // In absolute time: `t - start` of a time `start + grip.0` can round to below `grip.0`.
471        (t >= pass.start + pass.grip.0 && t <= pass.start + pass.grip.1).then(|| self.part_pose(pass.part, t))
472    }
473}
474
475/// The shortest time T in which the tool, at `from` with velocity `va`, meets a target that is at `target` now and
476/// moves with `vb`, arriving with its velocity: T, and the move to Q = target + T (vb - va) / 2 that the belt term goes
477/// on top of (see the module). Searched by bisection on T, since the move's limits depend on T; at once where
478/// `va == vb`. `None` where no T up to 1000 s fits, or the belt term alone breaks an axis's limits.
479pub fn intercept(axes: &[AxisInfo], from: &[f64], va: &[f64], target: &[f64], vb: &[f64]) -> Option<(f64, Move)> {
480    intercept_with(axes, from, va, &|_| (target.to_vec(), vb.to_vec())).map(|(t, mv, _)| (t, mv))
481}
482
483/// `intercept` for a target that is at `target(T)` with the velocity there after T seconds (a part on a belt that still
484/// speeds up): T, the move, and the target's velocity at T. The move goes to Q = target(T) - T (va + vb(T)) / 2.
485pub fn intercept_moving(
486    axes: &[AxisInfo],
487    from: &[f64],
488    va: &[f64],
489    target: &dyn Fn(f64) -> (Vec<f64>, Vec<f64>),
490) -> Option<(f64, Move, Vec<f64>)> {
491    // `intercept_with` goes to X + T (vb - va) / 2; for Q = target(T) - T (va + vb) / 2 that is X = target(T) - T vb.
492    let shifted = |t: f64| {
493        let (pos, vb) = target(t);
494        (pos.iter().zip(&vb).map(|(p, b)| p - t * b).collect(), vb)
495    };
496    if target(0.0).1 == va && target(1.0).1 == va {
497        // Moving with the tool already: the plain intercept.
498        let (pos, vb) = target(0.0);
499        return intercept(axes, from, va, &pos, &vb).map(|(t, mv)| (t, mv, vb));
500    }
501    intercept_with(axes, from, va, &shifted)
502}
503
504/// The search of `intercept`: for T, `target(T)` gives X and vb, and the move goes to Q = X + T (vb - va) / 2 (for a
505/// steady target X is where it is now; with `va == vb`, T is infinite).
506fn intercept_with(
507    axes: &[AxisInfo],
508    from: &[f64],
509    va: &[f64],
510    target: &dyn Fn(f64) -> (Vec<f64>, Vec<f64>),
511) -> Option<(f64, Move, Vec<f64>)> {
512    let fits = |t: f64| -> Option<Move> {
513        let (target, vb) = target(t);
514        let reduced: Vec<AxisInfo> = axes
515            .iter()
516            .enumerate()
517            .map(|(i, a)| {
518                let dv = (vb[i] - va[i]).abs();
519                let blend = |limit: f64| if dv > 0.0 { limit } else { 0.0 };
520                AxisInfo {
521                    max_vel: a.max_vel - va[i].abs().max(vb[i].abs()),
522                    max_acc: a.max_acc - blend(1.5 * dv / t),
523                    max_jerk: a.max_jerk - blend(6.0 * dv / (t * t)),
524                    ..a.clone()
525                }
526            })
527            .collect();
528        if reduced.iter().any(|a| a.max_vel <= 0.0 || a.max_acc <= 0.0 || a.max_jerk <= 0.0) {
529            return None;
530        }
531        // Where the velocities agree the shift is none, also for the T = infinity of `va == vb`.
532        let q: Vec<f64> =
533            (0..from.len()).map(|i| target[i] + if vb[i] == va[i] { 0.0 } else { t * (vb[i] - va[i]) / 2.0 }).collect();
534        let mv = Move::new(from, &q, &reduced);
535        (mv.duration() <= t).then_some(mv)
536    };
537    let vb = |t: f64| target(t).1;
538    if va == vb(f64::INFINITY) && va == vb(0.0) {
539        // The belt term moves at a constant velocity: the move takes its own time, which then is T.
540        let mv = fits(f64::INFINITY)?;
541        return Some((mv.duration(), mv, va.to_vec()));
542    }
543    let mut hi = 1e-3;
544    while fits(hi).is_none() {
545        hi *= 2.0;
546        if hi > 1000.0 {
547            return None;
548        }
549    }
550    let mut lo = hi / 2.0;
551    for _ in 0..60 {
552        let mid = 0.5 * (lo + hi);
553        if fits(mid).is_some() { hi = mid } else { lo = mid }
554    }
555    Some((hi, fits(hi)?, vb(hi)))
556}
557
558#[cfg(test)]
559mod tests {
560    use super::*;
561
562    fn axis(max_vel: f64, max_acc: f64, max_jerk: f64) -> AxisInfo {
563        AxisInfo { id: "x", key: "", unit: "m", min: -10.0, max: 10.0, max_vel, max_acc, max_jerk }
564    }
565
566    /// A belt along the one axis at 0.5 m/s, a part every 2 s, the window from 0.5 to 1.0 m, the place at -0.5 m.
567    fn conveyor() -> Conveyor {
568        let cfg = Config::parse(
569            "format_version = 1\n[conveyor]\nenabled = true\ndirection = [1.0]\nspeed_m_s = 0.5\nramp_s = 0.0\n\
570             origin = [0.0]\n\
571             length_m = 2.0\npitch_s = 2.0\narrivals_s = [0.0]\nwindow_m = [0.5, 1.0]\nlift = [0.0]\ngrip_s = 0.1\n\
572             release_s = 0.1\nplace = [-0.5]\nplace_direction = [1.0]\nplace_speed_m_s = 0.0\n\
573             tracking_tolerance_m = 0.001\n",
574        )
575        .unwrap();
576        Conveyor::from_config(&cfg, 1).unwrap().unwrap()
577    }
578
579    /// No input shaping.
580    fn none() -> (Vec<f64>, f64) {
581        (vec![0.0], 0.0)
582    }
583
584    /// The intercept against the closed form of a trapezoidal move (jerk so high that the S-curve is one). The tool at
585    /// 0 at rest meets a part at D0 = 1 m moving at v = 0.5 m/s, with v_max = 2 m/s and a = 20 m/s^2. The move goes to
586    /// D = D0 + v T / 2 with v' = v_max - v = 1.5 m/s and a' = a - 1.5 v / T, so with cruise T = D / v' + v' / a', which
587    /// is the quadratic a alpha T^2 - (alpha c + a beta + v') T + beta c = 0, alpha = 1 - v / (2 v'), beta = D0 / v',
588    /// c = 1.5 v: T = 0.89395 s.
589    #[test]
590    fn the_intercept_of_a_trapezoidal_move_is_the_closed_form() {
591        let (vm, a, v, d0): (f64, f64, f64, f64) = (2.0, 20.0, 0.5, 1.0);
592        let vp = vm - v;
593        let (alpha, beta, c) = (1.0 - v / (2.0 * vp), d0 / vp, 1.5 * v);
594        let (qa, qb, qc) = (a * alpha, alpha * c + a * beta + vp, beta * c);
595        let expected = (qb + (qb * qb - 4.0 * qa * qc).sqrt()) / (2.0 * qa);
596        assert!((expected - 0.89395).abs() < 1e-4, "{expected}");
597        let (t, mv) = intercept(&[axis(vm, a, 1e9)], &[0.0], &[0.0], &[d0], &[v]).unwrap();
598        assert!((t - expected).abs() < 1e-5, "{t} against {expected}");
599        // The move ends where the part is less what the belt term covers, v T / 2.
600        let (mut p, mut vel, mut acc) = ([0.0], [0.0], [0.0]);
601        mv.at(f64::INFINITY, &mut p, &mut vel, &mut acc);
602        assert!((p[0] - (d0 + v * t / 2.0)).abs() < 1e-12);
603    }
604
605    /// The tool meets the part where it is, with its speed, and stays within the axis's limits on the way.
606    #[test]
607    fn the_tool_arrives_on_the_part_with_the_belts_speed_within_its_limits() {
608        let ax = [axis(2.0, 20.0, 400.0)];
609        let (t, mv) = intercept(&ax, &[0.0], &[0.0], &[0.3], &[0.5]).unwrap();
610        let phase = Phase { start: 0.0, duration: t, mv, va: vec![0.0], vb: vec![0.5], track: None };
611        let (mut p, mut v, mut a) = ([0.0], [0.0], [0.0]);
612        for i in 0..=1000 {
613            phase.at(t * i as f64 / 1000.0, &mut p, &mut v, &mut a);
614            assert!(v[0].abs() <= 2.0 + 1e-9 && a[0].abs() <= 20.0 + 1e-9, "{v:?} {a:?}");
615        }
616        phase.at(t, &mut p, &mut v, &mut a);
617        assert!((p[0] - (0.3 + 0.5 * t)).abs() < 1e-9 && (v[0] - 0.5).abs() < 1e-12 && a[0].abs() < 1e-12);
618    }
619
620    /// During the grip the plan moves with the belt: its speed along the belt is the belt's, 0.5 m/s, and it is on the
621    /// part.
622    #[test]
623    fn during_the_grip_the_plan_moves_with_the_part() {
624        let mut c = conveyor();
625        let pass = c.plan(&[axis(2.0, 20.0, 400.0)], 0.0, &[-0.5], &|_| true, &none()).unwrap();
626        let (mut p, mut v, mut a) = ([0.0], [0.0], [0.0]);
627        for i in 0..=10 {
628            let t = pass.grip.0 + (pass.grip.1 - pass.grip.0) * i as f64 / 10.0;
629            pass.at(t, &mut p, &mut v, &mut a);
630            assert!((v[0] - 0.5).abs() < 1e-9, "{v:?}");
631            let part = c.gripping(&pass, pass.start + t).unwrap();
632            assert!((p[0] - part[0]).abs() < 1e-9, "{} against {}", p[0], part[0]);
633        }
634        // Part 0 passes the origin at 0 and is gripped as it reaches the window's start, 0.5 m on: 1 s in.
635        assert!((pass.start + pass.grip.0 - 1.0).abs() < 1e-6, "{}", pass.start + pass.grip.0);
636        assert_eq!((c.picked, c.missed), (1, 0));
637    }
638
639    /// A part the tool cannot grip before it leaves the window is missed. Parts pass the origin at 0, 2, 4 and 6 s; at
640    /// 5 s, where the tool starts from -0.5 m, they are 2.5, 1.5, 0.5 and -0.5 m along the belt. The window ends at
641    /// 1.0 m: parts 0 and 1 are missed. Part 2 is met after T = D / v' + v' / a' + a' / j' with D = 1 + 0.25 T,
642    /// v' = 1.5 m/s, a' = 20 - 0.75 / T, j' = 400 - 3 / T^2: T = 0.9518 s, so the grip ends 1.0518 s on, with the part
643    /// at 0.5 + 0.5 * 1.0518 = 1.026 m, beyond the window: missed too (without the jerk limit, T = 0.894 s would grip it
644    /// at 0.997 m). Part 3 is waited for at the window's start and picked inside it.
645    #[test]
646    fn a_part_beyond_the_window_counts_as_missed() {
647        let mut c = conveyor();
648        let pass = c.plan(&[axis(2.0, 20.0, 400.0)], 5.0, &[-0.5], &|_| true, &none()).unwrap();
649        assert_eq!((pass.part, c.missed, c.picked), (3, 3, 1));
650        let s = c.position(pass.part, pass.start + pass.grip.1);
651        assert!((0.5..=1.0).contains(&s), "{s}");
652        assert!((c.position(pass.part, pass.start + pass.grip.0) - 0.5).abs() < 1e-6);
653    }
654
655    /// A pass whose path leaves what the machine reaches is not run: its part counts as missed too.
656    #[test]
657    fn a_part_out_of_reach_counts_as_missed() {
658        let mut c = conveyor();
659        // Nothing at or behind -0.4 m is reachable, and the place at -0.5 m lies there: no part can be placed. Every
660        // part is missed, and after a thousand in a row the planner gives up.
661        assert!(c.plan(&[axis(2.0, 20.0, 400.0)], 0.0, &[-0.5], &|p: &[f64]| p[0] > -0.4, &none()).is_none());
662        assert_eq!((c.picked, c.missed), (0, 1000));
663    }
664
665    /// A pick while the belt still speeds up: a ramp of 4 s to 0.5 m/s, so the belt has run 0.5 t^2 / 8 m after t s.
666    /// Part 0 enters at 0 and reaches the window's start, 0.5 m, at t = sqrt 8 = 2.828 s, inside the ramp; the pass
667    /// waits for it there. Through the grip the plan is on the part with its speed then, 0.5 t / 4 m/s (0.354 m/s at the
668    /// grip's start), within the axis's limits on the whole pass.
669    #[test]
670    fn a_pick_during_the_belts_ramp_meets_the_part() {
671        let mut c = conveyor();
672        c.ramp = 4.0;
673        let ax = [axis(2.0, 20.0, 400.0)];
674        let pass = c.plan(&ax, 0.0, &[-0.5], &|_| true, &none()).unwrap();
675        let grip = pass.start + pass.grip.0;
676        assert!((grip - 8f64.sqrt()).abs() < 1e-6 && pass.start + pass.grip.1 < c.ramp, "{grip}");
677        let (mut p, mut v, mut a) = ([0.0], [0.0], [0.0]);
678        for i in 0..=20 {
679            let t = pass.grip.0 + (pass.grip.1 - pass.grip.0) * i as f64 / 20.0;
680            pass.at(t, &mut p, &mut v, &mut a);
681            let now = pass.start + t;
682            assert!((p[0] - c.part_pose(pass.part, now)[0]).abs() < 1e-9, "{} against the part at {now} s", p[0]);
683            // The belt's acceleration, 0.5 / 4 m/s^2, until the grip's end, where the lift begins without it.
684            assert!((v[0] - 0.5 * now / 4.0).abs() < 1e-9 && ((a[0] - 0.125).abs() < 1e-9 || i == 20), "{v:?} {a:?}");
685        }
686        for i in 0..=4000 {
687            pass.at(pass.duration() * i as f64 / 4000.0, &mut p, &mut v, &mut a);
688            assert!(v[0].abs() <= 2.0 + 1e-9 && a[0].abs() <= 20.0 + 1e-9, "{v:?} {a:?}");
689        }
690        assert_eq!((c.picked, c.missed), (1, 0));
691    }
692
693    /// The gripper on the shaped time. A ZVD shaper of a 25 Hz mode puts the setpoint at a quarter, a half and a quarter
694    /// of the plan now, 20 ms and 40 ms ago: at a constant speed it lags by the mean, 20 ms, and it has left the plan
695    /// before only 40 ms on. Planned without it, the shaped tool trails the part through the grip by 0.5 m/s * 20 ms =
696    /// 10 mm. Planned for it (the part 20 ms ahead, grip and release 40 ms longer), the shaped setpoint is on the part
697    /// for the whole grip of 0.1 s, and the gripper holds the part from its end.
698    #[test]
699    fn the_gripper_closes_on_the_shaped_time() {
700        let zvd = [(0.0, 0.25), (0.02, 0.5), (0.04, 0.25)];
701        let shaped = |pass: &Pass, t: f64| {
702            let (mut p, mut v, mut a) = ([0.0], [0.0], [0.0]);
703            zvd.iter()
704                .map(|(delay, w)| {
705                    pass.at(t - delay, &mut p, &mut v, &mut a);
706                    w * p[0]
707                })
708                .sum::<f64>()
709        };
710        let ax = [axis(2.0, 20.0, 400.0)];
711        let mut plain = conveyor();
712        let pass = plain.plan(&ax, 0.0, &[-0.5], &|_| true, &none()).unwrap();
713        let t = pass.grip.1 - 0.01;
714        let behind = plain.part_pose(pass.part, pass.start + t)[0] - shaped(&pass, t);
715        assert!((behind - 0.01).abs() < 1e-9, "{behind}");
716
717        let mut c = conveyor();
718        let pass = c.plan(&ax, 0.0, &[-0.5], &|_| true, &(vec![0.02], 0.04)).unwrap();
719        assert!((pass.grip.1 - pass.grip.0 - 0.1).abs() < 1e-12, "{:?}", pass.grip);
720        for i in 0..=20 {
721            let t = pass.grip.0 + (pass.grip.1 - pass.grip.0) * i as f64 / 20.0;
722            let off = shaped(&pass, t) - c.part_pose(pass.part, pass.start + t)[0];
723            assert!(off.abs() < 1e-9, "{off} at {t} s");
724            assert!(c.gripping(&pass, pass.start + t).is_some() && !pass.holds(t - 1e-9) || i == 20);
725        }
726        assert!(pass.holds(pass.grip.1) && !pass.holds(pass.grip.0));
727    }
728}