From 12e3b7d3633192ec9ad01bf46cc90a80f639b53c Mon Sep 17 00:00:00 2001 From: Wookie1 <6943491+Wookie1@users.noreply.github.com> Date: Wed, 18 Nov 2026 05:45:47 +0000 Subject: [PATCH 1/6] Run the independent leading-contact check on the adaptive pocket tests (#190) The sampled LeadingOracle from tests/roughing.rs (no planner, prover or stock code) now also checks AdaptivePocket's engagement_front runs: the L pocket, both link-feed runs, the square and circular wall-pass pockets, and the three ramp-entry runs. Every cutting and stay-down link stroke's leading contact must stay within acos(1 - stepover / r) plus the same 3 degree sampling slack the roughing test uses. A new test checks the oracle itself: a slot through fresh stock reads the full leading half-circle, and a pass beside a through-cut at 0.5, 1 and 1.5 mm reads acos(1 - w / r) to within its whole-degree count. Test-only: LeadingOracle and its methods become pub(crate) so adaptive.rs and ramp_entry_front.rs can use it; no existing assertion changes. --- tests/adaptive.rs | 93 ++++++++++++++++++++++++++++++++++++++- tests/ramp_entry_front.rs | 7 +++ tests/roughing.rs | 10 ++--- 3 files changed, 103 insertions(+), 7 deletions(-) diff --git a/tests/adaptive.rs b/tests/adaptive.rs index 6cd2b1bd..285b3054 100644 --- a/tests/adaptive.rs +++ b/tests/adaptive.rs @@ -1,6 +1,7 @@ use camlib::{ adaptive::*, motion::*, planar::*, pocket::Operation, stock::*, stream::StreamManifest, }; +use crate::roughing::LeadingOracle; use std::{ f64::consts::{PI, TAU}, sync::atomic::AtomicBool, @@ -14,6 +15,67 @@ fn operation() -> AdaptivePocketOperation { }; p } +/// What the sampled check may read above the proven limit: the oracle's +/// discs leave slivers step^2 / (8 r) deep between samples r / 20 apart, and +/// it counts whole degrees of the leading half-circle. Scale-free, as in the +/// roughing tests. +pub(crate) const LEADING_SLACK_DEG: f64 = 3.; + +/// #190: the independent, sampled leading-contact check from the roughing +/// tests (`LeadingOracle`), run over an adaptive pocket's motions. Per depth +/// level, flat feed moves clear their sweep; every cutting and stay-down link +/// stroke has its leading contact measured first. No planner, prover or stock +/// code: material is the stock footprint less what earlier centres swept. +/// Returns the worst contact, in degrees, over all levels. +pub(crate) fn leading_contact_deg(motions: &[Motion], r: f64, footprint: [[f64; 2]; 2]) -> f64 { + let mut worst = 0f64; + let mut leading = LeadingOracle::new(r, footprint); + let mut depth = f64::INFINITY; + for motion in motions { + let c = &motion.curve; + let flat = c.start()[2] == c.end()[2] && !matches!(c, Curve::Helix { .. }); + if !flat || !motion.kind.cuts() { + continue; + } + if c.start()[2] < depth - 1e-7 { + // A new level: nothing is cleared at this depth yet. + worst = worst.max(leading.worst_deg); + leading = LeadingOracle::new(r, footprint); + depth = c.start()[2]; + } + leading.feed(c, matches!(motion.kind, MoveKind::Cut | MoveKind::Link)); + } + worst.max(leading.worst_deg) +} +/// #190: the sampled check measures what it claims, so a pocket test that +/// passes it says something: a slot through fresh stock reads the full +/// leading half-circle, and a pass beside it at width w reads acos(1 - w / r) +/// (within the sampling slack above, and the whole-degree count below). +#[test] +fn leading_contact_check_reads_a_slot_and_a_side_step() { + let r = 2.; + let line = |y: f64, from: f64, to: f64| Curve::Line { + start: [from, y, 9.], + end: [to, y, 9.], + }; + let mut leading = LeadingOracle::new(r, [[0., 0.], [26., 26.]]); + leading.feed(&line(5., 2., 24.), true); + assert!(leading.worst_deg >= 175., "slot read {}", leading.worst_deg); + for w in [0.5, 1., 1.5] { + let mut leading = LeadingOracle::new(r, [[0., 0.], [26., 26.]]); + // The first pass runs right through the stock, so the second meets + // no end of it (where it would cut a wider arc, and the check says so). + leading.feed(&line(5., -3., 29.), false); + leading.feed(&line(5. + w, 2., 24.), true); + let exact = (1f64 - w / r).acos().to_degrees(); + assert!( + leading.worst_deg <= exact + LEADING_SLACK_DEG && leading.worst_deg >= exact - 2., + "w {w}: read {} against {exact}", + leading.worst_deg + ); + } +} + fn dist(a: [f64; 2], b: [f64; 2]) -> f64 { (a[0] - b[0]).hypot(a[1] - b[1]) } @@ -1748,6 +1810,13 @@ fn engagement_front_pocket_clears_the_region_once_within_its_engagement() { assert!(c["proven_max_engagement_deg"].as_f64().unwrap() <= limit); assert!(c["engagement_proved_strokes"].as_u64().unwrap() > 10); } + // Independent of that proof (#190): the sampled leading contact of every + // cutting and link stroke, against the 26 x 26 mm stock. + let worst = leading_contact_deg(&motions, 2., [[0., 0.], [26., 26.]]); + assert!( + worst <= limit + LEADING_SLACK_DEG, + "{worst} > {limit} + {LEADING_SLACK_DEG} degree sampling slack" + ); // Far less motion than the orbits for the same pocket. let cut = |list: &[Motion]| -> f64 { list.iter() @@ -1884,6 +1953,13 @@ fn engagement_front_pocket_links_feed_fast_only_clear_of_stock() { let plain = front_run(|_| ()).unwrap(); let fast = front_run(|op| op.link_feed_mm_min = Some(3000.)).unwrap(); let (r, cutting) = (2., 600.); + // #190: link and cutting strokes keep their sampled leading contact + // within acos(1 - 1.5 / 2), with and without the link feed. + let limit = (1f64 - 1.5 / r).acos().to_degrees(); + for run in [&plain, &fast] { + let worst = leading_contact_deg(&run.motions, r, [[0., 0.], [26., 26.]]); + assert!(worst <= limit + LEADING_SLACK_DEG, "{worst} > {limit}"); + } let (mut fast_mm, mut slow_mm) = (0f64, 0f64); for (i, motion) in fast.motions.iter().enumerate() { if motion.kind != MoveKind::Link { @@ -2168,6 +2244,7 @@ fn engagement_front_reports_the_material_its_wall_pass_left() { }; let r = m.tools[0].cutter.diameter_mm / 2.; let level = op.pocket.floor_z_mm; + let op_stepover = op.pocket.stepover_mm; let tool = m.tools[0].prepare().unwrap(); let mut stock = Stock::new(m.stock.height().unwrap().clone()).unwrap(); let mut plan = OperationPlan::prepare_with_stock( @@ -2179,7 +2256,7 @@ fn engagement_front_reports_the_material_its_wall_pass_left() { &|| false, ) .unwrap(); - let mut flat = vec![]; + let (mut flat, mut motions) = (vec![], vec![]); while let Some(motion) = plan.next_motion_with_stock(&stock, &|| false).unwrap() { if matches!(motion.kind, MoveKind::Cut | MoveKind::Lead | MoveKind::Link) && motion.curve.start()[2] == motion.curve.end()[2] @@ -2191,8 +2268,14 @@ fn engagement_front_reports_the_material_its_wall_pass_left() { .preview_sweep(&tool, &motion, 1., m.sweep, &|| false) .unwrap(); stock.apply_delta(&delta).unwrap(); + motions.push(motion); } plan.finish_report(&|| false).unwrap(); + // #190: the sampled leading contact of every cutting and link stroke, + // wall pass included, within acos(1 - stepover / r). + let limit = (1f64 - op_stepover / r).acos().to_degrees(); + let worst = leading_contact_deg(&motions, r, [[0., 0.], [26., 26.]]); + assert!(worst <= limit + LEADING_SLACK_DEG, "{worst} > {limit}"); let report = serde_json::to_value(plan.report()).unwrap(); let layers = report["layers"].as_array().unwrap(); assert_eq!(layers.len(), 1, "{report}"); @@ -2277,6 +2360,7 @@ fn engagement_front_reports_the_material_a_curved_wall_pass_left() { }; let r = m.tools[0].cutter.diameter_mm / 2.; let level = op.pocket.floor_z_mm; + let op_stepover = op.pocket.stepover_mm; let tool = m.tools[0].prepare().unwrap(); let mut stock = Stock::new(m.stock.height().unwrap().clone()).unwrap(); let mut plan = OperationPlan::prepare_with_stock( @@ -2288,7 +2372,7 @@ fn engagement_front_reports_the_material_a_curved_wall_pass_left() { &|| false, ) .unwrap(); - let mut flat = vec![]; + let (mut flat, mut motions) = (vec![], vec![]); while let Some(motion) = plan.next_motion_with_stock(&stock, &|| false).unwrap() { if matches!(motion.kind, MoveKind::Cut | MoveKind::Lead | MoveKind::Link) && motion.curve.start()[2] == motion.curve.end()[2] @@ -2300,8 +2384,13 @@ fn engagement_front_reports_the_material_a_curved_wall_pass_left() { .preview_sweep(&tool, &motion, 1., m.sweep, &|| false) .unwrap(); stock.apply_delta(&delta).unwrap(); + motions.push(motion); } plan.finish_report(&|| false).unwrap(); + // #190: the sampled leading contact, as for the square pocket. + let limit = (1f64 - op_stepover / r).acos().to_degrees(); + let worst = leading_contact_deg(&motions, r, [[0., 0.], [26., 26.]]); + assert!(worst <= limit + LEADING_SLACK_DEG, "{worst} > {limit}"); let report = serde_json::to_value(plan.report()).unwrap(); let clearing = &report["layers"][0]["clearing"]; assert_eq!(clearing["wall_passes"].as_u64().unwrap(), 1, "{clearing}"); diff --git a/tests/ramp_entry_front.rs b/tests/ramp_entry_front.rs index b558daaa..87b4ad26 100644 --- a/tests/ramp_entry_front.rs +++ b/tests/ramp_entry_front.rs @@ -271,6 +271,13 @@ fn check_entries(seen: &Seen, angle_deg: f64) { chord(limit) ); assert!(seen.lead_rate > 2. * RADIUS * 0.95, "{}", seen.lead_rate); + // #190: the sampled leading contact (the roughing tests' oracle) of every + // cutting and link stroke; the ramp's flat slot pass only clears. + let worst = crate::adaptive::leading_contact_deg(&seen.motions, RADIUS, [[0., 0.], [26., 26.]]); + assert!( + worst <= limit + crate::adaptive::LEADING_SLACK_DEG, + "{worst} > {limit}" + ); // Entry moves run at the entry feed, cutting moves at the cutting feed. for motion in &seen.motions { match motion.kind { diff --git a/tests/roughing.rs b/tests/roughing.rs index 0105109c..0ed1f7b1 100644 --- a/tests/roughing.rs +++ b/tests/roughing.rs @@ -805,15 +805,15 @@ fn exact_height_for(c: &Curve, p: [f64; 2], cutter_radius: f64, top: f64) -> f64 /// lies in the stock footprint and no earlier centre (of an earlier move, or /// earlier on this one) is within the cutter radius. Sampling can only miss /// thin slivers, so it is a refutation check with a stated slack, not a proof. -struct LeadingOracle { +pub(crate) struct LeadingOracle { r: f64, step: f64, footprint: [[f64; 2]; 2], cells: std::collections::HashMap<(i32, i32), Vec<[f64; 2]>>, - worst_deg: f64, + pub(crate) worst_deg: f64, } impl LeadingOracle { - fn new(r: f64, footprint: [[f64; 2]; 2]) -> Self { + pub(crate) fn new(r: f64, footprint: [[f64; 2]; 2]) -> Self { Self { r, step: r / 20., @@ -828,7 +828,7 @@ impl LeadingOracle { (p[1] / self.r).floor() as i32, ) } - fn cleared(&self, p: [f64; 2]) -> bool { + pub(crate) fn cleared(&self, p: [f64; 2]) -> bool { // Discs at samples `step` apart cover the swept strip but for // slivers step^2 / (8 r) deep. let reach = self.r + self.step * self.step / (8. * self.r) + 1e-9; @@ -861,7 +861,7 @@ impl LeadingOracle { } /// A flat feed move the cutter makes: clears its sweep; with `check`, /// its leading contact is measured first, pose by pose. - fn feed(&mut self, c: &Curve, check: bool) { + pub(crate) fn feed(&mut self, c: &Curve, check: bool) { for (i, (p, heading)) in self.poses(c).into_iter().enumerate() { if check && i > 0 { let mut hit = 0; From 599021da155fe19145bc0e3814614302b51c1487 Mon Sep 17 00:00:00 2001 From: Wookie1 <6943491+Wookie1@users.noreply.github.com> Date: Thu, 19 Nov 2026 04:44:08 +0000 Subject: [PATCH 2/6] Size the leading-contact check's sliver allowance by actual sample spacing (#190) The allowance for slivers between sampled discs used the largest sample step for every disc. A move shorter than that step then cleared its own leading edge from its start: a 0.1 mm straight cut in fresh stock read 179 degrees as one move and 0 as 200 moves. Each disc now carries the allowance of its own move's spacing. New test: the same slot and side step read the same split into one move or 200. --- tests/adaptive.rs | 46 ++++++++++++++++++++++++++++++++++++++++++++++ tests/roughing.rs | 31 +++++++++++++++++++------------ 2 files changed, 65 insertions(+), 12 deletions(-) diff --git a/tests/adaptive.rs b/tests/adaptive.rs index 285b3054..39abe7d0 100644 --- a/tests/adaptive.rs +++ b/tests/adaptive.rs @@ -76,6 +76,52 @@ fn leading_contact_check_reads_a_slot_and_a_side_step() { } } +/// #190 review: the reading does not depend on how a cut is split into +/// moves. The same straight cut through fresh stock, fed as one move or as +/// many moves shorter than the sampling step, reads the full leading +/// half-circle; so does a side step split the same way read its width. +#[test] +fn leading_contact_check_does_not_depend_on_move_length() { + let r = 2.; + let footprint = [[0., 0.], [26., 26.]]; + let split = |leading: &mut LeadingOracle, y: f64, from: f64, to: f64, n: usize| { + for i in 0..n { + let a = from + (to - from) * i as f64 / n as f64; + let b = from + (to - from) * (i + 1) as f64 / n as f64; + leading.feed( + &Curve::Line { + start: [a, y, 9.], + end: [b, y, 9.], + }, + true, + ); + } + }; + for n in [1, 200] { + let mut leading = LeadingOracle::new(r, footprint); + split(&mut leading, 5., 10., 10.1, n); + assert!(leading.worst_deg >= 175., "{n} moves: slot read {}", leading.worst_deg); + } + let w = 1.; + let exact = (1f64 - w / r).acos().to_degrees(); + for n in [1, 200] { + let mut leading = LeadingOracle::new(r, footprint); + leading.feed( + &Curve::Line { + start: [-3., 5., 9.], + end: [29., 5., 9.], + }, + false, + ); + split(&mut leading, 5. + w, 10., 10.1, n); + assert!( + leading.worst_deg <= exact + LEADING_SLACK_DEG && leading.worst_deg >= exact - 2., + "{n} moves: side step read {} against {exact}", + leading.worst_deg + ); + } +} + fn dist(a: [f64; 2], b: [f64; 2]) -> f64 { (a[0] - b[0]).hypot(a[1] - b[1]) } diff --git a/tests/roughing.rs b/tests/roughing.rs index 0ed1f7b1..b6991491 100644 --- a/tests/roughing.rs +++ b/tests/roughing.rs @@ -809,7 +809,8 @@ pub(crate) struct LeadingOracle { r: f64, step: f64, footprint: [[f64; 2]; 2], - cells: std::collections::HashMap<(i32, i32), Vec<[f64; 2]>>, + /// Sampled centres, each with the distance its disc is taken to clear. + cells: std::collections::HashMap<(i32, i32), Vec<([f64; 2], f64)>>, pub(crate) worst_deg: f64, } impl LeadingOracle { @@ -829,25 +830,24 @@ impl LeadingOracle { ) } pub(crate) fn cleared(&self, p: [f64; 2]) -> bool { - // Discs at samples `step` apart cover the swept strip but for - // slivers step^2 / (8 r) deep. - let reach = self.r + self.step * self.step / (8. * self.r) + 1e-9; let k = self.key(p); (k.0 - 1..=k.0 + 1).any(|x| { (k.1 - 1..=k.1 + 1).any(|y| { - self.cells - .get(&(x, y)) - .is_some_and(|v| v.iter().any(|q| (q[0] - p[0]).hypot(q[1] - p[1]) <= reach)) + self.cells.get(&(x, y)).is_some_and(|v| { + v.iter() + .any(|(q, reach)| (q[0] - p[0]).hypot(q[1] - p[1]) <= *reach) + }) }) }) } - fn poses(&self, c: &Curve) -> Vec<([f64; 2], f64)> { + /// Poses at most `step` apart along the move, and their actual spacing. + fn poses(&self, c: &Curve) -> (Vec<([f64; 2], f64)>, f64) { let len = match circle(c) { Some((o, s)) => (c.start()[0] - o[0]).hypot(c.start()[1] - o[1]) * s.abs(), None => (c.end()[0] - c.start()[0]).hypot(c.end()[1] - c.start()[1]), }; let n = (len / self.step).ceil().max(1.) as usize; - (0..=n) + let poses = (0..=n) .map(|i| { let t = i as f64 / n as f64; let p = position(c, t); @@ -857,12 +857,19 @@ impl LeadingOracle { }; ([p[0], p[1]], heading) }) - .collect() + .collect(); + (poses, len / n as f64) } /// A flat feed move the cutter makes: clears its sweep; with `check`, /// its leading contact is measured first, pose by pose. pub(crate) fn feed(&mut self, c: &Curve, check: bool) { - for (i, (p, heading)) in self.poses(c).into_iter().enumerate() { + let (poses, spacing) = self.poses(c); + // Discs at samples `spacing` apart cover the swept strip but for + // slivers spacing^2 / (8 r) deep. The allowance follows the actual + // spacing, not the largest one: a fixed `step` allowance would let a + // move shorter than it clear its own leading edge from its start. + let reach = self.r + spacing * spacing / (8. * self.r) + 1e-9; + for (i, (p, heading)) in poses.into_iter().enumerate() { if check && i > 0 { let mut hit = 0; for d in -89..=89 { @@ -877,7 +884,7 @@ impl LeadingOracle { self.worst_deg = self.worst_deg.max(hit as f64); } let k = self.key(p); - self.cells.entry(k).or_default().push(p); + self.cells.entry(k).or_default().push((p, reach)); } } } From f78ebc15c9c8afa3b554a2c565f6fe6a121cc53e Mon Sep 17 00:00:00 2001 From: Wookie1 <6943491+Wookie1@users.noreply.github.com> Date: Thu, 19 Nov 2026 06:44:58 +0000 Subject: [PATCH 3/6] Name the leading-contact disc type (clippy type_complexity) --- tests/roughing.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/roughing.rs b/tests/roughing.rs index 79ea26cc..ab8e5a41 100644 --- a/tests/roughing.rs +++ b/tests/roughing.rs @@ -805,12 +805,14 @@ fn exact_height_for(c: &Curve, p: [f64; 2], cutter_radius: f64, top: f64) -> f64 /// lies in the stock footprint and no earlier centre (of an earlier move, or /// earlier on this one) is within the cutter radius. Sampling can only miss /// thin slivers, so it is a refutation check with a stated slack, not a proof. +/// A sampled cutter centre and the distance its disc is taken to clear. +type Disc = ([f64; 2], f64); pub(crate) struct LeadingOracle { r: f64, step: f64, footprint: [[f64; 2]; 2], /// Sampled centres, each with the distance its disc is taken to clear. - cells: std::collections::HashMap<(i32, i32), Vec<([f64; 2], f64)>>, + cells: std::collections::HashMap<(i32, i32), Vec>, pub(crate) worst_deg: f64, } impl LeadingOracle { From fe0c5d98675c4ee52adaef1cd55418d99f579fe1 Mon Sep 17 00:00:00 2001 From: Wookie1 <6943491+Wookie1@users.noreply.github.com> Date: Fri, 20 Nov 2026 04:49:19 +0000 Subject: [PATCH 4/6] Measure the leading contact against the exact swept path (#190) The oracle cleared stock within an inflated radius of sampled centres, so an unchecked lead could clear stock ahead of its own end: a 0.0005 mm cut after a 1 mm lead read 0 degrees with the lead as one move and 179 with it split in 2,000. It now keeps each swept piece (line or arc) and clears exactly the points within the cutter radius of it, so the reading does not depend on how moves are split or sampled. New test for the lead case. --- tests/adaptive.rs | 26 ++++++++ tests/roughing.rs | 167 +++++++++++++++++++++++++++++++++++++++------- 2 files changed, 168 insertions(+), 25 deletions(-) diff --git a/tests/adaptive.rs b/tests/adaptive.rs index 39abe7d0..8bd248d5 100644 --- a/tests/adaptive.rs +++ b/tests/adaptive.rs @@ -122,6 +122,32 @@ fn leading_contact_check_does_not_depend_on_move_length() { } } +/// #190 review: an unchecked lead does not clear stock ahead of its end. A +/// short checked cut that continues a lead reads the full slot whether the +/// lead is one move or 2,000. +#[test] +fn leading_contact_check_reads_a_cut_after_a_lead_whatever_the_lead_split() { + let r = 2.; + let footprint = [[0., 0.], [26., 26.]]; + let line = |from: f64, to: f64| Curve::Line { + start: [from, 5., 9.], + end: [to, 5., 9.], + }; + for n in [1, 2000] { + let mut leading = LeadingOracle::new(r, footprint); + for i in 0..n { + let a = 9. + i as f64 / n as f64; + leading.feed(&line(a, a + 1. / n as f64), false); + } + leading.feed(&line(10., 10.0005), true); + assert!( + leading.worst_deg >= 175., + "lead in {n} moves: the cut read {}", + leading.worst_deg + ); + } +} + fn dist(a: [f64; 2], b: [f64; 2]) -> f64 { (a[0] - b[0]).hypot(a[1] - b[1]) } diff --git a/tests/roughing.rs b/tests/roughing.rs index ab8e5a41..da91adce 100644 --- a/tests/roughing.rs +++ b/tests/roughing.rs @@ -805,14 +805,95 @@ fn exact_height_for(c: &Curve, p: [f64; 2], cutter_radius: f64, top: f64) -> f64 /// lies in the stock footprint and no earlier centre (of an earlier move, or /// earlier on this one) is within the cutter radius. Sampling can only miss /// thin slivers, so it is a refutation check with a stated slack, not a proof. -/// A sampled cutter centre and the distance its disc is taken to clear. -type Disc = ([f64; 2], f64); +/// A piece of a cutter-centre path the oracle has swept: a straight segment, +/// or an arc about `centre` from angle `from` through `sweep` radians. The +/// cutter cleared exactly the points within its radius of it. +#[derive(Clone, Copy)] +enum Swept { + Line([f64; 2], [f64; 2]), + Arc { + centre: [f64; 2], + radius: f64, + from: f64, + sweep: f64, + }, +} +impl Swept { + /// A point every point of the piece is within `bound` of. + fn centre_bound(&self) -> ([f64; 2], f64) { + match *self { + Swept::Line(a, b) => ( + [(a[0] + b[0]) / 2., (a[1] + b[1]) / 2.], + (a[0] - b[0]).hypot(a[1] - b[1]) / 2., + ), + Swept::Arc { + centre, + radius, + from, + sweep, + } => { + let mid = from + sweep / 2.; + ( + [ + centre[0] + radius * mid.cos(), + centre[1] + radius * mid.sin(), + ], + radius * sweep.abs() / 2., + ) + } + } + } + fn distance(&self, q: [f64; 2]) -> f64 { + let d = |a: [f64; 2], b: [f64; 2]| (a[0] - b[0]).hypot(a[1] - b[1]); + match *self { + Swept::Line(a, b) => { + let v = [b[0] - a[0], b[1] - a[1]]; + let l = v[0] * v[0] + v[1] * v[1]; + let t = if l > 0. { + (((q[0] - a[0]) * v[0] + (q[1] - a[1]) * v[1]) / l).clamp(0., 1.) + } else { + 0. + }; + d([a[0] + t * v[0], a[1] + t * v[1]], q) + } + Swept::Arc { + centre, + radius, + from, + sweep, + } => { + let at = |angle: f64| { + [ + centre[0] + radius * angle.cos(), + centre[1] + radius * angle.sin(), + ] + }; + // Within the arc's angular span the nearest point is radial; + // outside it, one of the ends. + let angle = (q[1] - centre[1]).atan2(q[0] - centre[0]); + let along = if sweep >= 0. { + (angle - from).rem_euclid(std::f64::consts::TAU) + } else { + (from - angle).rem_euclid(std::f64::consts::TAU) + }; + if along <= sweep.abs() { + (d(centre, q) - radius).abs() + } else { + d(at(from), q).min(d(at(from + sweep), q)) + } + } + } + } +} pub(crate) struct LeadingOracle { r: f64, step: f64, footprint: [[f64; 2]; 2], - /// Sampled centres, each with the distance its disc is taken to clear. - cells: std::collections::HashMap<(i32, i32), Vec>, + /// The swept path pieces, listed under every grid cell their samples + /// pass through. + /// Each piece, with a centre and radius that bound it (a cheap reject). + swept: Vec<(Swept, [f64; 2], f64)>, + cells: std::collections::HashMap<(i32, i32), Vec>, pub(crate) worst_deg: f64, } impl LeadingOracle { @@ -820,36 +901,44 @@ impl LeadingOracle { Self { r, step: r / 20., + cell: r * 1.05, footprint, + swept: vec![], cells: Default::default(), worst_deg: 0., } } fn key(&self, p: [f64; 2]) -> (i32, i32) { ( - (p[0] / self.r).floor() as i32, - (p[1] / self.r).floor() as i32, + (p[0] / self.cell).floor() as i32, + (p[1] / self.cell).floor() as i32, ) } + /// Within the cutter radius of a swept path: exact distance to the path, + /// so the result does not depend on how the path was split into moves or + /// sampled. pub(crate) fn cleared(&self, p: [f64; 2]) -> bool { let k = self.key(p); (k.0 - 1..=k.0 + 1).any(|x| { (k.1 - 1..=k.1 + 1).any(|y| { self.cells.get(&(x, y)).is_some_and(|v| { - v.iter() - .any(|(q, reach)| (q[0] - p[0]).hypot(q[1] - p[1]) <= *reach) + v.iter().any(|&i| { + let (piece, c, bound) = &self.swept[i]; + (c[0] - p[0]).hypot(c[1] - p[1]) <= self.r + bound + 1e-9 + && piece.distance(p) <= self.r + 1e-9 + }) }) }) }) } - /// Poses at most `step` apart along the move, and their actual spacing. - fn poses(&self, c: &Curve) -> (Vec<([f64; 2], f64)>, f64) { + /// Poses at most `step` apart along the move, at parameters `t`. + fn poses(&self, c: &Curve) -> Vec<([f64; 2], f64, f64)> { let len = match circle(c) { Some((o, s)) => (c.start()[0] - o[0]).hypot(c.start()[1] - o[1]) * s.abs(), None => (c.end()[0] - c.start()[0]).hypot(c.end()[1] - c.start()[1]), }; let n = (len / self.step).ceil().max(1.) as usize; - let poses = (0..=n) + (0..=n) .map(|i| { let t = i as f64 / n as f64; let p = position(c, t); @@ -857,22 +946,50 @@ impl LeadingOracle { Some((o, s)) => (p[1] - o[1]).atan2(p[0] - o[0]) + s.signum() * PI / 2., None => (c.end()[1] - c.start()[1]).atan2(c.end()[0] - c.start()[0]), }; - ([p[0], p[1]], heading) + ([p[0], p[1]], heading, t) }) - .collect(); - (poses, len / n as f64) + .collect() + } + /// The piece of `c` between parameters `t0` and `t1`. + fn piece(c: &Curve, t0: f64, t1: f64) -> Swept { + let a = position(c, t0); + let b = position(c, t1); + match circle(c) { + Some((o, s)) => { + let start = c.start(); + Swept::Arc { + centre: [o[0], o[1]], + radius: (start[0] - o[0]).hypot(start[1] - o[1]), + from: (start[1] - o[1]).atan2(start[0] - o[0]) + s * t0, + sweep: s * (t1 - t0), + } + } + None => Swept::Line([a[0], a[1]], [b[0], b[1]]), + } + } + fn add(&mut self, piece: Swept, at: &[[f64; 2]]) { + let i = self.swept.len(); + let (c, bound) = piece.centre_bound(); + self.swept.push((piece, c, bound)); + let mut keys: Vec<_> = at.iter().map(|p| self.key(*p)).collect(); + keys.dedup(); + for k in keys { + let v = self.cells.entry(k).or_default(); + if v.last() != Some(&i) { + v.push(i); + } + } } /// A flat feed move the cutter makes: clears its sweep; with `check`, - /// its leading contact is measured first, pose by pose. + /// its leading contact is measured first, pose by pose, against what + /// was swept before that pose. pub(crate) fn feed(&mut self, c: &Curve, check: bool) { - let (poses, spacing) = self.poses(c); - // Discs at samples `spacing` apart cover the swept strip but for - // slivers spacing^2 / (8 r) deep. The allowance follows the actual - // spacing, not the largest one: a fixed `step` allowance would let a - // move shorter than it clear its own leading edge from its start. - let reach = self.r + spacing * spacing / (8. * self.r) + 1e-9; - for (i, (p, heading)) in poses.into_iter().enumerate() { - if check && i > 0 { + let poses = self.poses(c); + let start = poses[0].0; + self.add(Swept::Line(start, start), &[start]); + for i in 1..poses.len() { + let (p, heading, t) = poses[i]; + if check { let mut hit = 0; for d in -89..=89 { let a = heading + (d as f64).to_radians(); @@ -885,8 +1002,8 @@ impl LeadingOracle { } self.worst_deg = self.worst_deg.max(hit as f64); } - let k = self.key(p); - self.cells.entry(k).or_default().push((p, reach)); + let (previous, _, t0) = poses[i - 1]; + self.add(Self::piece(c, t0, t), &[previous, p]); } } } From e50d352f6df227f81c55fc1790b096f459e22f47 Mon Sep 17 00:00:00 2001 From: Wookie1 <6943491+Wookie1@users.noreply.github.com> Date: Fri, 20 Nov 2026 05:20:39 +0000 Subject: [PATCH 5/6] Declare the oracle's grid cell width --- tests/roughing.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/tests/roughing.rs b/tests/roughing.rs index da91adce..39846540 100644 --- a/tests/roughing.rs +++ b/tests/roughing.rs @@ -888,10 +888,12 @@ impl Swept { pub(crate) struct LeadingOracle { r: f64, step: f64, + /// Grid cell width: a point within r of a piece is within r + step / 2 + /// of one of its samples, so the 3 x 3 cells around it suffice. + cell: f64, footprint: [[f64; 2]; 2], - /// The swept path pieces, listed under every grid cell their samples - /// pass through. - /// Each piece, with a centre and radius that bound it (a cheap reject). + /// The swept path pieces, each with a centre and radius that bound it (a + /// cheap reject), listed under every grid cell their samples pass through. swept: Vec<(Swept, [f64; 2], f64)>, cells: std::collections::HashMap<(i32, i32), Vec>, pub(crate) worst_deg: f64, From e84c11277cce3fd0c05df53555e46662c17285d1 Mon Sep 17 00:00:00 2001 From: RobitOverlord <193709524+10-X-eng@users.noreply.github.com> Date: Sat, 21 Nov 2026 08:19:27 -0600 Subject: [PATCH 6/6] Measure pocket engagement against stock cleared at each depth --- tests/adaptive.rs | 76 +++++++++++++++++++++++++++++++++++------------ 1 file changed, 57 insertions(+), 19 deletions(-) diff --git a/tests/adaptive.rs b/tests/adaptive.rs index 8bd248d5..91e5d0c2 100644 --- a/tests/adaptive.rs +++ b/tests/adaptive.rs @@ -15,10 +15,8 @@ fn operation() -> AdaptivePocketOperation { }; p } -/// What the sampled check may read above the proven limit: the oracle's -/// discs leave slivers step^2 / (8 r) deep between samples r / 20 apart, and -/// it counts whole degrees of the leading half-circle. Scale-free, as in the -/// roughing tests. +/// Sampling allowance in degrees for the leading half-circle, as in the +/// roughing tests. Clearance uses distances to the swept lines and arcs. pub(crate) const LEADING_SLACK_DEG: f64 = 3.; /// #190: the independent, sampled leading-contact check from the roughing @@ -28,25 +26,65 @@ pub(crate) const LEADING_SLACK_DEG: f64 = 3.; /// code: material is the stock footprint less what earlier centres swept. /// Returns the worst contact, in degrees, over all levels. pub(crate) fn leading_contact_deg(motions: &[Motion], r: f64, footprint: [[f64; 2]; 2]) -> f64 { + let flat_feeds: Vec<_> = motions + .iter() + .filter(|m| { + let c = &m.curve; + m.kind.cuts() && c.start()[2] == c.end()[2] && !matches!(c, Curve::Helix { .. }) + }) + .collect(); + let checked = |m: &Motion| matches!(m.kind, MoveKind::Cut | MoveKind::Link); + let mut depths: Vec<_> = flat_feeds + .iter() + .filter(|m| checked(m)) + .map(|m| m.curve.start()[2]) + .collect(); + depths.sort_by(f64::total_cmp); + depths.dedup(); let mut worst = 0f64; - let mut leading = LeadingOracle::new(r, footprint); - let mut depth = f64::INFINITY; - for motion in motions { - let c = &motion.curve; - let flat = c.start()[2] == c.end()[2] && !matches!(c, Curve::Helix { .. }); - if !flat || !motion.kind.cuts() { - continue; - } - if c.start()[2] < depth - 1e-7 { - // A new level: nothing is cleared at this depth yet. - worst = worst.max(leading.worst_deg); - leading = LeadingOracle::new(r, footprint); - depth = c.start()[2]; + for z in depths { + let mut leading = LeadingOracle::new(r, footprint); + let last = flat_feeds + .iter() + .rposition(|m| checked(m) && m.curve.start()[2] == z) + .unwrap(); + for &m in &flat_feeds[..=last] { + let tip = m.curve.start()[2]; + // A deeper flat-end cut cleared this plane. A higher one did not. + if tip <= z { + leading.feed(&m.curve, tip == z && checked(m)); + } } - leading.feed(c, matches!(motion.kind, MoveKind::Cut | MoveKind::Link)); + worst = worst.max(leading.worst_deg); } - worst.max(leading.worst_deg) + worst } +#[test] +fn leading_contact_keeps_shallow_cuts_out_of_deeper_stock() { + let line = |id, kind, z| Motion { + id, + kind, + operation: "pocket".into(), + tool: "mill".into(), + feed_mm_min: Some(600.), + curve: Curve::Line { + start: [5., 5., z], + end: [15., 5., z], + }, + }; + let footprint = [[0., 0.], [26., 26.]]; + let upper = line(1, MoveKind::Lead, 8.); + let lower = line(2, MoveKind::Cut, 8. - 5e-8); + assert!(leading_contact_deg(&[upper.clone(), lower.clone()], 2., footprint) >= 175.); + let mut start = lower.clone(); + start.kind = MoveKind::Lead; + start.curve = Curve::Line { + start: [2., 2., 8. - 5e-8], + end: [3., 2., 8. - 5e-8], + }; + assert!(leading_contact_deg(&[start, upper, lower], 2., footprint) >= 175.); +} + /// #190: the sampled check measures what it claims, so a pocket test that /// passes it says something: a slot through fresh stock reads the full /// leading half-circle, and a pass beside it at width w reads acos(1 - w / r)