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 01/17] 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 afb22e6c6e0b9e53c9964480a66048204ddcb0f7 Mon Sep 17 00:00:00 2001 From: Wookie1 <6943491+Wookie1@users.noreply.github.com> Date: Wed, 18 Nov 2026 09:31:58 +0000 Subject: [PATCH 02/17] Remove the disk_front and stock_front adaptive planners (#190) engagement_front is now the only adaptive planner for AdaptivePocket and Roughing's AdaptiveClearing. The orbit planners, their options (orbit_radius_mm, min_orbit_radius_mm, local_orbit_tolerance_mm, boundary_tolerance_mm, AdaptivePocket's clockwise), their proofs and their tests are removed. Their names and fields are refused when a program is read. Tests that ran on them are converted to the engagement front where they test more than the old planner. Regeneration now treats every adaptive operation as reading committed clearance. --- docs/operations.md | 61 +- fixtures/operations/adaptive-connected.json | 5 +- fixtures/operations/adaptive-pocket.json | 2 - fixtures/operations/adaptive-tapered.json | 189 - fixtures/operations/helical-adaptive.json | 7 +- fixtures/operations/roughing-adaptive.json | 6 +- fixtures/operations/roughing-open-block.json | 6 +- .../stock-front-straight-transition.json | 1640 ------ ...ont.json => adaptive-roughing-layers.json} | 8 +- fixtures/regressions/disconnected-pocket.json | 4 +- fixtures/regressions/retained-body.json | 6 +- python/camlib/operations.py | 62 +- python/tests/support/adaptive_connected.py | 70 - .../{stock_front_rest.py => adaptive_rest.py} | 1 - python/tests/support/adaptive_tapered.py | 71 - python/tests/support/helical_pocket.py | 12 - python/tests/support/roughing.py | 24 +- python/tests/test_adaptive.py | 102 +- python/tests/test_adaptive_connected.py | 116 - python/tests/test_adaptive_tapered.py | 124 - python/tests/test_closed_orbit_posting.py | 6 +- python/tests/test_dynamics.py | 10 +- python/tests/test_helical_entry.py | 29 +- python/tests/test_no_entry.py | 13 +- python/tests/test_ramp_entry.py | 4 - python/tests/test_rapid_retracts.py | 11 +- python/tests/test_roughing.py | 32 +- python/tests/test_stream_policy.py | 2 +- src/adaptive.rs | 1659 +----- src/adaptive_front.rs | 4428 ----------------- src/adaptive_front/channel.rs | 610 --- src/adaptive_front/convex.rs | 1366 ----- src/adaptive_front/enclosed.rs | 1267 ----- src/adaptive_front/linear_channel.rs | 449 -- src/adaptive_front/peeling.rs | 914 ---- src/engagement.rs | 990 +--- src/entry.rs | 21 +- src/lib.rs | 1 - src/navigation.rs | 69 +- src/operation.rs | 48 +- src/pocket.rs | 337 +- src/pocket/admission_tests.rs | 70 - src/pocket_front.rs | 9 +- src/regeneration.rs | 36 +- src/roughing.rs | 219 +- src/stock.rs | 7 +- tests/adaptive.rs | 1601 +----- tests/adaptive_connected.rs | 692 --- tests/adaptive_front_complete.rs | 90 +- tests/helical_entry.rs | 212 +- tests/main.rs | 1 - tests/no_entry.rs | 115 +- tests/pocket_top.rs | 42 +- tests/ramp_entry.rs | 24 +- tests/ramp_entry_front.rs | 24 +- tests/roughing.rs | 612 +-- 56 files changed, 580 insertions(+), 17956 deletions(-) delete mode 100644 fixtures/operations/adaptive-tapered.json delete mode 100644 fixtures/operations/stock-front-straight-transition.json rename fixtures/regressions/{stock-front.json => adaptive-roughing-layers.json} (98%) delete mode 100644 python/tests/support/adaptive_connected.py rename python/tests/support/{stock_front_rest.py => adaptive_rest.py} (97%) delete mode 100644 python/tests/support/adaptive_tapered.py delete mode 100644 python/tests/test_adaptive_connected.py delete mode 100644 python/tests/test_adaptive_tapered.py delete mode 100644 src/adaptive_front.rs delete mode 100644 src/adaptive_front/channel.rs delete mode 100644 src/adaptive_front/convex.rs delete mode 100644 src/adaptive_front/enclosed.rs delete mode 100644 src/adaptive_front/linear_channel.rs delete mode 100644 src/adaptive_front/peeling.rs delete mode 100644 tests/adaptive_connected.rs diff --git a/docs/operations.md b/docs/operations.md index 9b7dd4fa..3e0c9ec9 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -25,7 +25,7 @@ machine, so they have no defaults: pass them as keyword arguments. | `work_offset` | 1 | 1..9 → G54..G59.x | | `retract_z_mm` | `clearance_z_mm` | Rapid travel height between passes (Pocket, RestPocket, AdaptivePocket, Roughing, Contour, Chamfer, Facing, TrochoidalSlot, Bore, Parallel, Spiral, Radial, Project, Waterline, Trace) | | `feed_z_mm` | `retract_z_mm` | Rapid descent stops here and plunge feed begins; leaving a pass, feed changes to rapid here | -| `boundary_tolerance_mm` | 0.01 | Allowed construction error of offset boundaries (Contour, Chamfer, Bore, TrochoidalSlot, adaptive clearing) | +| `boundary_tolerance_mm` | 0.01 | Allowed construction error of offset boundaries (Contour, Chamfer, Bore, TrochoidalSlot) | | `reverse` | off | Run the passes the other way: Facing and Parallel start each pass from the opposite end, Waterline cuts its contours the other way, Contour/Chamfer (`None` = from `cutting_sense`) reverse the loop direction | | `one_way` | off | Parallel: cut every row in the same direction instead of alternating (see [Parallel finishing](#parallel-finishing-parallel)); Facing has `mode="one_way"` | @@ -155,17 +155,16 @@ without a word: `AdaptivePocket` no place in that connected area of tool centres is clear of material to enter from and no helix the entry allows fits (a helix the policy forbids, `StockEdgeEntry(helix=None)`, is no way in), or the area is - tighter than the planner resolves (below); for `disk_front` and - `stock_front` no orbit fits. The message names the operation, a tool-centre - position in the area, the area's extent, what was tried (the helix or orbit + tighter than the planner resolves (below). The message names the operation, a tool-centre + position in the area, the area's extent, what was tried (the helix radii and what the area leaves) and the options: another entry (`RampEntry`, a plunge, a smaller helix), a smaller cutter, an earlier operation that opens a start there, or a region without that area. - **A region the cutter fits nowhere in refuses the operation**, since it can do nothing it was asked to. (This used to be an empty plan with a `CamWarning`.) -- `Pocket`, `RestPocket`, `disk_front` and `stock_front` refuse before any - motion. `AdaptivePocket`'s default strategy plans from the stock, so it +- `Pocket` and `RestPocket` refuse before any + motion. `AdaptivePocket` plans from the stock, so it refuses when a level starts, before that level's first motion: for the first level that is before any motion of the operation. - **Not refused:** a pocket with nothing left to cut, and the parts of a @@ -360,8 +359,6 @@ Decisions (#219), with the reason: place, and it would ramp through the air beside the stock and through the air the layers above have cut (a layer's pocket starts at the stock top while the flutes span it). Use `AdaptiveClearing` for a ramp. -- **`path_strategy="disk_front"` and `"stock_front"` refuse it**: they start - every pass from a fitted seed circle, which a helix opens. - **A `Contour` ramp with holding tabs stays refused.** A tab is a lift whose far side comes back down into the uncut loop at the tab's own slope (45 degrees for a triangle, straight down for a rectangle). A tool that needs a @@ -383,8 +380,8 @@ Refused, before any motion: - `RampEntry` on a `Contour` with holding tabs, or with limits that block part of a loop: the tool comes back down from a tab or a lift steeper than the ramp angle. A `Contour` accepts no other entry type. -- `RampEntry` on `Roughing` with offset or raster clearing, and with the - `disk_front` and `stock_front` strategies (see the decisions above). +- `RampEntry` on `Roughing` with offset or raster clearing (see the + decisions above). Refused while running (the run stops and no program is written): @@ -404,7 +401,9 @@ Same region and depths as `Pocket`, cleared with a bounded radial engagement: no full-width slotting, for hard materials and high-speed toolpaths. `retract_z_mm`/`feed_z_mm` work as for `Pocket`. -- **It follows the stock** (`path_strategy="engagement_front"`, the default): +- **It follows the stock** (`path_strategy="engagement_front"`, the only + planner; the orbit planners `disk_front` and `stock_front` were removed in + #190 and their names are refused): one depth level at a time, each pass runs along the boundary between cut and uncut stock inside the region, so nothing is cut twice. The region's boundary is a wall. @@ -498,27 +497,10 @@ no full-width slotting, for hard materials and high-speed toolpaths. - `ramp_clearance_mm`: each helix starts this far above the material it meets, never above `feed_z_mm`. The wall pass is reached like any other pass (a stay-down link, or a - descent with these options) and enters on its lead-in arc at `feed_mm_min`. `path_strategy="disk_front"` and `"stock_front"` - refuse all four by name. -- Orbit options, `max_stay_down_mm` and `rest_tolerance_mm` do not apply and - are refused. Corners the cutter cannot reach are left and reported as the - level's residual area. -- `path_strategy="disk_front"` is the earlier planner: it covers the region - with orbits of `orbit_radius_mm` (default half the tool radius) whatever - the stock holds. Its orbits overlap, so it cuts many times longer (33.7 m - against 1.1 m on a 50 x 30 x 8 mm pocket with a 10 mm cutter). With it, - `clockwise` sets the orbit direction, `max_engagement_deg` (default 90) - bounds the total contact, and `min_orbit_radius_mm` with - `local_orbit_tolerance_mm` sizes each orbit from the clearance around it. - An orbit sweeps a disk of the cutter radius plus the orbit radius. An - area of the region the cutter fits in (a component of its tool-centre - region) that is nowhere that wide is an area no entry reaches: the pocket - is refused before any motion with the sweep's size and the options (#250; - it used to be left). The narrower parts of an area an orbit does fit in - are left and reported in the plan's residual region, as before. The same - holds for `stock_front`. -- `path_strategy="stock_front"` is a development strategy; it stops with an - error where its coverage is unresolved. + descent with these options) and enters on its lead-in arc at `feed_mm_min`. +- `max_stay_down_mm` and `rest_tolerance_mm` do not apply and are refused. + Corners the cutter cannot reach are left and reported as the level's + residual area. ## Surface mesh inputs @@ -581,7 +563,7 @@ refused with its location: export the mesh with shared edge vertices passes, with that much overlap reserved for the coverage proof, - `AdaptiveClearing(max_radial_engagement_mm)`: engagement-limited clearing that follows the boundary between cut and uncut stock - (`path_strategy="engagement_front"`, the default). Passes start from air + (`path_strategy="engagement_front"`, the only planner, #190). Passes start from air beside the stock or from stock already cleared (proven clear by the committed cuts) and helix only into enclosed material; each pass starts at the upstream end of the material it cuts; short moves between passes stay @@ -643,7 +625,7 @@ refused with its location: export the mesh with shared edge vertices `wall_passes_skipped`. - Every cutting and link move is also checked exactly against the layer region before it is emitted, and the run fails rather than emit one that - does not fit. Orbit options and `omit_empty_cuts` do not apply, the entry + does not fit. `omit_empty_cuts` does not apply, the entry must be `StockEdgeEntry` or `RampEntry`, and the direction is `cutting_sense` (`"climb"` by default, `"conventional"`); `clockwise` does not apply. @@ -659,8 +641,8 @@ refused with its location: export the mesh with shared edge vertices material and no way in (as defined for [`AdaptivePocket`](#adaptive-pocket-adaptivepocket)) is put in the layer's report, `layers[].clearing.unentered_areas`: `reason` - (`no_helix_fits`, `no_helix_allowed`, `tighter_than_planner_resolves`, - or `no_orbit_fits` with `stock_front`), `at_mm`, the extent of its tool + (`no_helix_fits`, `no_helix_allowed` or + `tighter_than_planner_resolves`), `at_mm`, the extent of its tool centres (`min_mm`, `max_mm`), `level_z_mm`, `cutter_radius_mm`, `radii_tried_mm`, `needed_mm` and `available_mm`. Its stock is in the layer's residual area, which counts all the stock left in the layer's @@ -683,13 +665,6 @@ refused with its location: export the mesh with shared edge vertices an area has none (for example with `StockEdgeEntry(helix=None)` and an enclosed area), naming the area, what was tried and the options. They leave no area without an entry, so they list none. - - `path_strategy="disk_front"` is refused in `Roughing`. It covers a region - it takes to be solid with small orbits and never reads the stock; - `Roughing`'s region is the stock grown by a margin, so it orbited through - the air beside the stock (#167: 75 m of a 137 m path on a 130 x 90 mm - stock). It remains `AdaptivePocket`'s strategy, where the region's - boundary is a wall. `path_strategy="stock_front"` is a development - strategy with the same options as `AdaptivePocket`. With `rapid_descent_clearance_mm` (opt-in, on `Roughing`), a descent into a column that the committed cuts prove clear for the whole tool assembly is rapid down to that far above diff --git a/fixtures/operations/adaptive-connected.json b/fixtures/operations/adaptive-connected.json index efe764ca..bbc60923 100644 --- a/fixtures/operations/adaptive-connected.json +++ b/fixtures/operations/adaptive-connected.json @@ -178,10 +178,7 @@ "length_register": 1, "coolant": "flood", "kind": "adaptive_pocket", - "max_engagement_deg": 90, - "boundary_tolerance_mm": 0.01, - "clockwise": true, - "min_orbit_radius_mm": 0.25 + "max_engagement_deg": 90 } ] } diff --git a/fixtures/operations/adaptive-pocket.json b/fixtures/operations/adaptive-pocket.json index 5b1840fb..6c970dc7 100644 --- a/fixtures/operations/adaptive-pocket.json +++ b/fixtures/operations/adaptive-pocket.json @@ -68,8 +68,6 @@ { "kind": "adaptive_pocket", "max_engagement_deg": 90, - "boundary_tolerance_mm": 0.01, - "clockwise": true, "id": "adaptive", "tool": "t1", "region": { diff --git a/fixtures/operations/adaptive-tapered.json b/fixtures/operations/adaptive-tapered.json deleted file mode 100644 index 418b0f35..00000000 --- a/fixtures/operations/adaptive-tapered.json +++ /dev/null @@ -1,189 +0,0 @@ -{ - "version": 1, - "run": { - "id": "adaptive-tapered", - "revision": "tapered-1" - }, - "stock": { - "version": 1, - "units": "mm", - "min_mm": [ - 0, - 0, - 0 - ], - "max_mm": [ - 34, - 20, - 10 - ], - "cell_size_mm": 0.4, - "max_cells": 1048576 - }, - "tools": [ - { - "id": "t1", - "cutter": { - "id": "em4", - "name": "em4", - "shape": { - "kind": "flat" - }, - "diameter_mm": 4, - "cutting_length_mm": 20, - "overall_length_mm": 50, - "shank_diameter_mm": 4, - "flutes": 3, - "center_cutting": true, - "material": "carbide", - "neck": null - }, - "stickout_mm": 30, - "gauge_length_mm": 60, - "holders": [ - { - "z_min_mm": 30, - "z_max_mm": 60, - "radius_min_mm": 4, - "radius_max_mm": 4 - } - ] - } - ], - "operations": [ - { - "id": "tapered", - "tool": "t1", - "region": { - "version": 1, - "units": "mm", - "name": "tapered-rooms", - "boundary_error_mm": 1.0000000000000002e-07, - "components": [ - { - "outer": { - "vertices": [ - [ - 13.0, - 3.0, - 0.0 - ], - [ - 3.0, - 3.0, - 0.0 - ], - [ - 3.0, - 17.0, - 0.0 - ], - [ - 13.0, - 17.0, - 0.0 - ], - [ - 13.0, - 12.5, - 0.0 - ], - [ - 21.0, - 13.5, - 0.0 - ], - [ - 21.0, - 17.0, - 0.0 - ], - [ - 31.0, - 17.0, - 0.0 - ], - [ - 31.0, - 3.0, - 0.0 - ], - [ - 21.0, - 3.0, - 0.0 - ], - [ - 21.0, - 6.5, - 0.0 - ], - [ - 13.0, - 7.5, - 0.0 - ] - ] - }, - "holes": [] - } - ], - "source": { - "model": "CadQuery tapered neck", - "revision": "tapered-1", - "cadquery_version": "2.9.0.dev0", - "ocp_version": "8.0.1.1", - "python_version": "3.12.13", - "floor_z_mm": 9.0, - "adapter": "analytic_horizontal_lines_circles_v1", - "curve_counts": { - "line": 12 - }, - "adapter_sha256": "c51a74031f07eb9a17590173051c73cbf2360a94b30cae2cc40e4c038e25dfb6", - "error_components_mm": { - "chord": 0.0, - "joining": 0.0, - "cad_topology": 1.0000000000000002e-07 - }, - "extraction_ms": 4.97550901491195 - } - }, - "top_z_mm": 10, - "floor_z_mm": 9, - "stepdown_mm": 1, - "stepover_mm": 1.5, - "clearance_z_mm": 12, - "feed_mm_min": 600, - "plunge_mm_min": 150, - "radial_allowance_mm": 0, - "bottom_allowance_mm": 0, - "tolerance_mm": 1e-05, - "spindle_rpm": 12000, - "work_offset": 1, - "tool_number": 1, - "length_register": 1, - "coolant": "flood", - "kind": "adaptive_pocket", - "max_engagement_deg": 90, - "boundary_tolerance_mm": 0.01, - "clockwise": true, - "orbit_radius_mm": 1, - "min_orbit_radius_mm": 0.25, - "local_orbit_tolerance_mm": 0.05 - } - ], - "initial_position_mm": [ - 0, - 0, - 12 - ], - "sweep": { - "tolerance_mm": 1e-05, - "chord_error_mm": 0.002, - "max_tip_step_mm": 0.1, - "max_segments": 100000, - "max_scratch_cells": 1048576, - "max_changed_cells": 1048576, - "max_cell_visits": 100000000 - } -} diff --git a/fixtures/operations/helical-adaptive.json b/fixtures/operations/helical-adaptive.json index 00414ca8..82c801d1 100644 --- a/fixtures/operations/helical-adaptive.json +++ b/fixtures/operations/helical-adaptive.json @@ -144,12 +144,7 @@ "angle_rad": 0.05235987755982989 }, "kind": "adaptive_pocket", - "max_engagement_deg": 90, - "boundary_tolerance_mm": 0.01, - "clockwise": true, - "orbit_radius_mm": 1, - "min_orbit_radius_mm": 0.25, - "local_orbit_tolerance_mm": 0.05 + "max_engagement_deg": 90 } ], "initial_position_mm": [ diff --git a/fixtures/operations/roughing-adaptive.json b/fixtures/operations/roughing-adaptive.json index 66534bc4..fd69973a 100644 --- a/fixtures/operations/roughing-adaptive.json +++ b/fixtures/operations/roughing-adaptive.json @@ -841,11 +841,7 @@ "clearing": { "kind": "adaptive", "path_strategy": "engagement_front", - "max_radial_engagement_mm": 0.25, - "orbit_radius_mm": null, - "min_orbit_radius_mm": null, - "local_orbit_tolerance_mm": null, - "boundary_tolerance_mm": 0.01 + "max_radial_engagement_mm": 0.25 }, "feed_mm_min": 600, "plunge_mm_min": 150, diff --git a/fixtures/operations/roughing-open-block.json b/fixtures/operations/roughing-open-block.json index 5d0c66be..35a33fcb 100644 --- a/fixtures/operations/roughing-open-block.json +++ b/fixtures/operations/roughing-open-block.json @@ -292,11 +292,7 @@ "clearing": { "kind": "adaptive", "path_strategy": "engagement_front", - "max_radial_engagement_mm": 3.0, - "orbit_radius_mm": null, - "min_orbit_radius_mm": null, - "local_orbit_tolerance_mm": null, - "boundary_tolerance_mm": 0.01 + "max_radial_engagement_mm": 3.0 }, "top_z_mm": 21.0, "floor_z_mm": 14.0, diff --git a/fixtures/operations/stock-front-straight-transition.json b/fixtures/operations/stock-front-straight-transition.json deleted file mode 100644 index 2cf540d8..00000000 --- a/fixtures/operations/stock-front-straight-transition.json +++ /dev/null @@ -1,1640 +0,0 @@ -{ - "provenance": { - "source": "docs/checkpoints/development/stock-front-frustum/ranked-actual-lead-failure-trace.json", - "source_sha256": "19ed4ad02192ddcfbc5ced2b8d01b5e71ae29ecadab73bc2a9be6a83a7179031", - "scope": "Actual first28 committed motions before straight-stock-edge steering oscillation; native source benchmark unchanged, not complete operation acceptance" - }, - "manifest": { - "initial_position_mm": [ - 0.0, - 0.0, - 12.0 - ], - "operations": [ - { - "bottom_allowance_mm": 0.2, - "clearance_z_mm": 12.0, - "clearing": { - "boundary_tolerance_mm": 0.01, - "kind": "adaptive", - "local_orbit_tolerance_mm": 0.05, - "max_radial_engagement_mm": 0.25, - "min_orbit_radius_mm": 0.2, - "orbit_radius_mm": 0.5, - "path_strategy": "stock_front" - }, - "clockwise": true, - "coolant": "flood", - "entry": { - "angle_rad": 0.05235987755982989, - "kind": "stock_edge_or_helix" - }, - "feed_mm_min": 600.0, - "floor_z_mm": 2.0, - "id": "rough", - "kind": "roughing", - "length_register": 1, - "omit_empty_cuts": true, - "plunge_mm_min": 150.0, - "radial_allowance_mm": 0.1, - "spindle_rpm": 12000.0, - "stepdown_mm": 2.0, - "target": { - "source": { - "adapter": "planar_cad_solid_facets_v1", - "cadquery_version": "2.9.0.dev0", - "error_basis": "planar faces, straight trim edges, twice CAD topology tolerance plus numerical guard", - "extraction_ms": 16.828104970045388, - "faces": 16, - "model": "CadQuery retained frustum and enclosed opening", - "ocp_version": "8.0.1.1", - "revision": "roughing-1", - "triangle_count": 44 - }, - "surface_error_mm": 2.0100000000000004e-07, - "triangles": [ - [ - [ - 4.0, - 24.0, - 2.0 - ], - [ - 4.0, - 24.0, - 0.0 - ], - [ - 4.0, - 4.0, - 2.0 - ] - ], - [ - [ - 4.0, - 4.0, - 2.0 - ], - [ - 4.0, - 24.0, - 0.0 - ], - [ - 4.0, - 4.0, - 0.0 - ] - ], - [ - [ - 4.0, - 4.0, - 0.0 - ], - [ - 28.0, - 4.0, - 0.0 - ], - [ - 4.0, - 4.0, - 2.0 - ] - ], - [ - [ - 28.0, - 4.0, - 0.0 - ], - [ - 28.0, - 4.0, - 2.0 - ], - [ - 4.0, - 4.0, - 2.0 - ] - ], - [ - [ - 8.0, - 20.0, - 2.0 - ], - [ - 4.0, - 24.0, - 2.0 - ], - [ - 8.0, - 8.0, - 2.0 - ] - ], - [ - [ - 28.0, - 24.0, - 2.0 - ], - [ - 4.0, - 24.0, - 2.0 - ], - [ - 24.0, - 20.0, - 2.0 - ] - ], - [ - [ - 24.0, - 8.0, - 2.0 - ], - [ - 28.0, - 24.0, - 2.0 - ], - [ - 24.0, - 20.0, - 2.0 - ] - ], - [ - [ - 24.0, - 8.0, - 2.0 - ], - [ - 28.0, - 4.0, - 2.0 - ], - [ - 28.0, - 24.0, - 2.0 - ] - ], - [ - [ - 4.0, - 24.0, - 2.0 - ], - [ - 4.0, - 4.0, - 2.0 - ], - [ - 8.0, - 8.0, - 2.0 - ] - ], - [ - [ - 24.0, - 8.0, - 2.0 - ], - [ - 4.0, - 4.0, - 2.0 - ], - [ - 28.0, - 4.0, - 2.0 - ] - ], - [ - [ - 24.0, - 20.0, - 2.0 - ], - [ - 4.0, - 24.0, - 2.0 - ], - [ - 8.0, - 20.0, - 2.0 - ] - ], - [ - [ - 8.0, - 8.0, - 2.0 - ], - [ - 4.0, - 4.0, - 2.0 - ], - [ - 24.0, - 8.0, - 2.0 - ] - ], - [ - [ - 4.0, - 24.0, - 0.0 - ], - [ - 4.0, - 24.0, - 2.0 - ], - [ - 28.0, - 24.0, - 0.0 - ] - ], - [ - [ - 28.0, - 24.0, - 0.0 - ], - [ - 4.0, - 24.0, - 2.0 - ], - [ - 28.0, - 24.0, - 2.0 - ] - ], - [ - [ - 28.0, - 24.0, - 0.0 - ], - [ - 28.0, - 4.0, - 0.0 - ], - [ - 4.0, - 24.0, - 0.0 - ] - ], - [ - [ - 4.0, - 24.0, - 0.0 - ], - [ - 28.0, - 4.0, - 0.0 - ], - [ - 4.0, - 4.0, - 0.0 - ] - ], - [ - [ - 28.0, - 24.0, - 2.0 - ], - [ - 28.0, - 4.0, - 2.0 - ], - [ - 28.0, - 24.0, - 0.0 - ] - ], - [ - [ - 28.0, - 4.0, - 2.0 - ], - [ - 28.0, - 4.0, - 0.0 - ], - [ - 28.0, - 24.0, - 0.0 - ] - ], - [ - [ - 11.0, - 18.0, - 10.0 - ], - [ - 8.0, - 20.0, - 2.0 - ], - [ - 8.0, - 8.0, - 2.0 - ] - ], - [ - [ - 11.0, - 18.0, - 10.0 - ], - [ - 8.0, - 8.0, - 2.0 - ], - [ - 11.0, - 10.0, - 10.0 - ] - ], - [ - [ - 8.0, - 8.0, - 2.0 - ], - [ - 24.0, - 8.0, - 2.0 - ], - [ - 11.0, - 10.0, - 10.0 - ] - ], - [ - [ - 11.0, - 10.0, - 10.0 - ], - [ - 24.0, - 8.0, - 2.0 - ], - [ - 21.0, - 10.0, - 10.0 - ] - ], - [ - [ - 24.0, - 8.0, - 2.0 - ], - [ - 24.0, - 20.0, - 2.0 - ], - [ - 21.0, - 18.0, - 10.0 - ] - ], - [ - [ - 21.0, - 10.0, - 10.0 - ], - [ - 24.0, - 8.0, - 2.0 - ], - [ - 21.0, - 18.0, - 10.0 - ] - ], - [ - [ - 11.0, - 18.0, - 10.0 - ], - [ - 24.0, - 20.0, - 2.0 - ], - [ - 8.0, - 20.0, - 2.0 - ] - ], - [ - [ - 21.0, - 18.0, - 10.0 - ], - [ - 24.0, - 20.0, - 2.0 - ], - [ - 11.0, - 18.0, - 10.0 - ] - ], - [ - [ - 18.0, - 16.0, - 10.0 - ], - [ - 11.0, - 18.0, - 10.0 - ], - [ - 14.0, - 16.0, - 10.0 - ] - ], - [ - [ - 14.0, - 16.0, - 10.0 - ], - [ - 11.0, - 18.0, - 10.0 - ], - [ - 14.0, - 12.0, - 10.0 - ] - ], - [ - [ - 11.0, - 18.0, - 10.0 - ], - [ - 11.0, - 10.0, - 10.0 - ], - [ - 14.0, - 12.0, - 10.0 - ] - ], - [ - [ - 18.0, - 16.0, - 10.0 - ], - [ - 21.0, - 18.0, - 10.0 - ], - [ - 11.0, - 18.0, - 10.0 - ] - ], - [ - [ - 18.0, - 12.0, - 10.0 - ], - [ - 21.0, - 18.0, - 10.0 - ], - [ - 18.0, - 16.0, - 10.0 - ] - ], - [ - [ - 14.0, - 12.0, - 10.0 - ], - [ - 11.0, - 10.0, - 10.0 - ], - [ - 18.0, - 12.0, - 10.0 - ] - ], - [ - [ - 11.0, - 10.0, - 10.0 - ], - [ - 21.0, - 10.0, - 10.0 - ], - [ - 18.0, - 12.0, - 10.0 - ] - ], - [ - [ - 18.0, - 12.0, - 10.0 - ], - [ - 21.0, - 10.0, - 10.0 - ], - [ - 21.0, - 18.0, - 10.0 - ] - ], - [ - [ - 14.0, - 12.0, - 10.0 - ], - [ - 14.0, - 12.0, - 2.0 - ], - [ - 14.0, - 16.0, - 10.0 - ] - ], - [ - [ - 14.0, - 12.0, - 2.0 - ], - [ - 14.0, - 16.0, - 2.0 - ], - [ - 14.0, - 16.0, - 10.0 - ] - ], - [ - [ - 18.0, - 12.0, - 10.0 - ], - [ - 18.0, - 12.0, - 2.0 - ], - [ - 14.0, - 12.0, - 10.0 - ] - ], - [ - [ - 18.0, - 12.0, - 2.0 - ], - [ - 14.0, - 12.0, - 2.0 - ], - [ - 14.0, - 12.0, - 10.0 - ] - ], - [ - [ - 18.0, - 12.0, - 10.0 - ], - [ - 18.0, - 16.0, - 10.0 - ], - [ - 18.0, - 12.0, - 2.0 - ] - ], - [ - [ - 18.0, - 12.0, - 2.0 - ], - [ - 18.0, - 16.0, - 10.0 - ], - [ - 18.0, - 16.0, - 2.0 - ] - ], - [ - [ - 18.0, - 16.0, - 10.0 - ], - [ - 14.0, - 16.0, - 10.0 - ], - [ - 18.0, - 16.0, - 2.0 - ] - ], - [ - [ - 18.0, - 16.0, - 2.0 - ], - [ - 14.0, - 16.0, - 10.0 - ], - [ - 14.0, - 16.0, - 2.0 - ] - ], - [ - [ - 18.0, - 16.0, - 2.0 - ], - [ - 14.0, - 16.0, - 2.0 - ], - [ - 18.0, - 12.0, - 2.0 - ] - ], - [ - [ - 14.0, - 16.0, - 2.0 - ], - [ - 14.0, - 12.0, - 2.0 - ], - [ - 18.0, - 12.0, - 2.0 - ] - ] - ], - "units": "mm", - "version": 1 - }, - "tolerance_mm": 1e-05, - "tool": "t1", - "tool_number": 1, - "top_z_mm": 10.0, - "work_offset": 1 - } - ], - "run": { - "id": "roughing-adaptive", - "revision": "roughing-1" - }, - "stock": { - "cell_size_mm": 0.4, - "max_cells": 1048576, - "max_mm": [ - 32.0, - 28.0, - 10.0 - ], - "min_mm": [ - 0.0, - 0.0, - 0.0 - ], - "units": "mm", - "version": 1 - }, - "sweep": { - "chord_error_mm": 0.002, - "max_cell_visits": 100000000, - "max_changed_cells": 1048576, - "max_scratch_cells": 1048576, - "max_segments": 100000, - "max_tip_step_mm": 0.1, - "tolerance_mm": 1e-05 - }, - "tools": [ - { - "cutter": { - "center_cutting": true, - "cutting_length_mm": 20.0, - "diameter_mm": 2.0, - "flutes": 3, - "id": "em2", - "material": "carbide", - "name": "em2", - "neck": null, - "overall_length_mm": 50.0, - "shank_diameter_mm": 2.0, - "shape": { - "kind": "flat" - } - }, - "gauge_length_mm": 60.0, - "holders": [ - { - "radius_max_mm": 4.0, - "radius_min_mm": 4.0, - "z_max_mm": 60.0, - "z_min_mm": 30.0 - } - ], - "id": "t1", - "stickout_mm": 30.0 - } - ], - "version": 1 - }, - "history": [ - { - "curve": { - "end": [ - -6.799677641281743, - -6.299677641281747, - 12.0 - ], - "kind": "line", - "start": [ - 0.0, - 0.0, - 12.0 - ] - }, - "feed_mm_min": null, - "id": 1, - "kind": "rapid", - "operation": "rough", - "tool": "t1" - }, - { - "curve": { - "end": [ - -6.799677641281743, - -6.299677641281747, - 8.0 - ], - "kind": "line", - "start": [ - -6.799677641281743, - -6.299677641281747, - 12.0 - ] - }, - "feed_mm_min": 150.0, - "id": 2, - "kind": "plunge", - "operation": "rough", - "tool": "t1" - }, - { - "curve": { - "center": [ - -6.799677641281743, - -6.799677641281747, - 8.0 - ], - "end": [ - -6.799677641281743, - -6.299677641281747, - 8.0 - ], - "kind": "arc", - "plane": "xy", - "start": [ - -6.799677641281743, - -6.299677641281747, - 8.0 - ], - "sweep_rad": 6.283185307179586 - }, - "feed_mm_min": 150.0, - "id": 3, - "kind": "cut", - "operation": "rough", - "tool": "t1" - }, - { - "curve": { - "center": [ - -6.799677641281743, - -6.499677641281747, - 8.0 - ], - "end": [ - -6.999677641281743, - -6.499677641281747, - 8.0 - ], - "kind": "arc", - "plane": "xy", - "start": [ - -6.799677641281743, - -6.299677641281747, - 8.0 - ], - "sweep_rad": 1.5707963267948966 - }, - "feed_mm_min": 600.0, - "id": 4, - "kind": "link", - "operation": "rough", - "tool": "t1" - }, - { - "curve": { - "center": [ - -6.78915132549227, - -6.499677641281747, - 8.0 - ], - "end": [ - -6.78915132549227, - -6.71020395707122, - 8.0 - ], - "kind": "arc", - "plane": "xy", - "start": [ - -6.999677641281743, - -6.499677641281747, - 8.0 - ], - "sweep_rad": 1.5707963267948966 - }, - "feed_mm_min": 600.0, - "id": 5, - "kind": "link", - "operation": "rough", - "tool": "t1" - }, - { - "curve": { - "center": [ - -6.789151325492269, - -2.7102039570712204, - 8.0 - ], - "end": [ - -3.4232673862606835, - -4.8714131805437795, - 8.0 - ], - "kind": "arc", - "plane": "xy", - "start": [ - -6.78915132549227, - -6.71020395707122, - 8.0 - ], - "sweep_rad": 1.0 - }, - "feed_mm_min": 600.0, - "id": 6, - "kind": "link", - "operation": "rough", - "tool": "t1" - }, - { - "curve": { - "end": [ - -1.262058162788124, - -1.505529241312194, - 8.0 - ], - "kind": "line", - "start": [ - -3.4232673862606835, - -4.8714131805437795, - 8.0 - ] - }, - "feed_mm_min": 600.0, - "id": 7, - "kind": "link", - "operation": "rough", - "tool": "t1" - }, - { - "curve": { - "center": [ - -0.4205871779802276, - -2.0458315471803337, - 8.0 - ], - "end": [ - -0.42058717798022754, - -1.0458315471803337, - 8.0 - ], - "kind": "arc", - "plane": "xy", - "start": [ - -1.262058162788124, - -1.505529241312194, - 8.0 - ], - "sweep_rad": -1.0 - }, - "feed_mm_min": 600.0, - "id": 8, - "kind": "link", - "operation": "rough", - "tool": "t1" - }, - { - "curve": { - "center": [ - -0.42058717798022754, - 2.9541684528196663, - 8.0 - ], - "end": [ - 0.07811175556068345, - -1.0146222160976497, - 8.0 - ], - "kind": "arc", - "plane": "xy", - "start": [ - -0.42058717798022754, - -1.0458315471803337, - 8.0 - ], - "sweep_rad": 0.125 - }, - "feed_mm_min": 600.0, - "id": 9, - "kind": "link", - "operation": "rough", - "tool": "t1" - }, - { - "curve": { - "center": [ - 0.5768106891015943, - -4.983412885014966, - 8.0 - ], - "end": [ - 0.20235976415954293, - -1.0009781391829589, - 8.0 - ], - "kind": "arc", - "plane": "xy", - "start": [ - 0.07811175556068345, - -1.0146222160976497, - 8.0 - ], - "sweep_rad": -0.03125 - }, - "feed_mm_min": 600.0, - "id": 10, - "kind": "link", - "operation": "rough", - "tool": "t1" - }, - { - "curve": { - "center": [ - 0.2210823104066455, - -1.2000998764745592, - 8.0 - ], - "end": [ - 0.23357417397512156, - -1.0004903743345395, - 8.0 - ], - "kind": "arc", - "plane": "xy", - "start": [ - 0.20235976415954293, - -1.0009781391829589, - 8.0 - ], - "sweep_rad": -0.15625 - }, - "feed_mm_min": 600.0, - "id": 11, - "kind": "link", - "operation": "rough", - "tool": "t1" - }, - { - "curve": { - "center": [ - 0.26480383289631165, - -0.5014666189844899, - 8.0 - ], - "end": [ - 0.29603349181750177, - -1.0004903743345395, - 8.0 - ], - "kind": "arc", - "plane": "xy", - "start": [ - 0.23357417397512156, - -1.0004903743345395, - 8.0 - ], - "sweep_rad": 0.125 - }, - "feed_mm_min": 600.0, - "id": 12, - "kind": "link", - "operation": "rough", - "tool": "t1" - }, - { - "curve": { - "center": [ - 0.3085253553859778, - -1.2000998764745594, - 8.0 - ], - "end": [ - 0.5081348575259976, - -1.1876080129060833, - 8.0 - ], - "kind": "arc", - "plane": "xy", - "start": [ - 0.29603349181750177, - -1.0004903743345395, - 8.0 - ], - "sweep_rad": -1.5707963267948966 - }, - "feed_mm_min": 600.0, - "id": 13, - "kind": "link", - "operation": "rough", - "tool": "t1" - }, - { - "curve": { - "center": [ - 0.7077443596660175, - -1.1751161493376072, - 8.0 - ], - "end": [ - 0.7202362232344935, - -1.3747256514776272, - 8.0 - ], - "kind": "arc", - "plane": "xy", - "start": [ - 0.5081348575259976, - -1.1876080129060833, - 8.0 - ], - "sweep_rad": 1.5707963267948966 - }, - "feed_mm_min": 600.0, - "id": 14, - "kind": "link", - "operation": "rough", - "tool": "t1" - }, - { - "curve": { - "center": [ - 0.7070868931624135, - -1.16461038606708, - 8.0 - ], - "end": [ - 0.9172021585729606, - -1.1514610559949998, - 8.0 - ], - "kind": "arc", - "plane": "xy", - "start": [ - 0.7202362232344935, - -1.3747256514776272, - 8.0 - ], - "sweep_rad": 1.5707963267948966 - }, - "feed_mm_min": 600.0, - "id": 15, - "kind": "link", - "operation": "rough", - "tool": "t1" - }, - { - "curve": { - "center": [ - 0.2518371514395612, - -1.1931006012232535, - 8.0 - ], - "end": [ - 0.8557129403901853, - -0.9106497630872946, - 8.0 - ], - "kind": "arc", - "plane": "xy", - "start": [ - 0.9172021585729606, - -1.1514610559949998, - 8.0 - ], - "sweep_rad": 0.375 - }, - "feed_mm_min": 600.0, - "id": 16, - "kind": "cut", - "operation": "rough", - "tool": "t1" - }, - { - "curve": { - "center": [ - 0.6745502037049981, - -0.9953850145280823, - 8.0 - ], - "end": [ - 0.5898149522642104, - -0.814222277842895, - 8.0 - ], - "kind": "arc", - "plane": "xy", - "start": [ - 0.8557129403901853, - -0.9106497630872946, - 8.0 - ], - "sweep_rad": 1.5707963267948966 - }, - "feed_mm_min": 600.0, - "id": 17, - "kind": "cut", - "operation": "rough", - "tool": "t1" - }, - { - "curve": { - "center": [ - 0.5050797008234228, - -0.6330595411577078, - 8.0 - ], - "end": [ - 0.3598779697712803, - -0.7705966536018087, - 8.0 - ], - "kind": "arc", - "plane": "xy", - "start": [ - 0.5898149522642104, - -0.814222277842895, - 8.0 - ], - "sweep_rad": -1.25 - }, - "feed_mm_min": 600.0, - "id": 18, - "kind": "cut", - "operation": "rough", - "tool": "t1" - }, - { - "curve": { - "center": [ - -0.6081335705763363, - -1.687510736562482, - 8.0 - ], - "end": [ - -0.043231894304419205, - -0.4797591586612333, - 8.0 - ], - "kind": "arc", - "plane": "xy", - "start": [ - 0.3598779697712803, - -0.7705966536018087, - 8.0 - ], - "sweep_rad": 0.375 - }, - "feed_mm_min": 600.0, - "id": 19, - "kind": "cut", - "operation": "rough", - "tool": "t1" - }, - { - "curve": { - "center": [ - -0.8905844087122955, - -2.291386525513106, - 8.0 - ], - "end": [ - -0.5177778151877557, - -0.32643989931059547, - 8.0 - ], - "kind": "arc", - "plane": "xy", - "start": [ - -0.043231894304419205, - -0.4797591586612333, - 8.0 - ], - "sweep_rad": 0.25 - }, - "feed_mm_min": 600.0, - "id": 20, - "kind": "cut", - "operation": "rough", - "tool": "t1" - }, - { - "curve": { - "center": [ - -0.5550584745402096, - -0.5229345619308465, - 8.0 - ], - "end": [ - -0.7515531371604607, - -0.4856539025783925, - 8.0 - ], - "kind": "arc", - "plane": "xy", - "start": [ - -0.5177778151877557, - -0.32643989931059547, - 8.0 - ], - "sweep_rad": 1.5707963267948966 - }, - "feed_mm_min": 600.0, - "id": 21, - "kind": "link", - "operation": "rough", - "tool": "t1" - }, - { - "curve": { - "center": [ - -0.5550584745402096, - -0.5229345619308465, - 8.0 - ], - "end": [ - -0.5923391338926637, - -0.7194292245510976, - 8.0 - ], - "kind": "arc", - "plane": "xy", - "start": [ - -0.7515531371604607, - -0.4856539025783925, - 8.0 - ], - "sweep_rad": 1.5707963267948966 - }, - "feed_mm_min": 600.0, - "id": 22, - "kind": "link", - "operation": "rough", - "tool": "t1" - }, - { - "curve": { - "center": [ - -0.553096334574291, - -0.5125927375824123, - 8.0 - ], - "end": [ - -0.3462598476056057, - -0.551835536900785, - 8.0 - ], - "kind": "arc", - "plane": "xy", - "start": [ - -0.5923391338926637, - -0.7194292245510976, - 8.0 - ], - "sweep_rad": 1.5707963267948966 - }, - "feed_mm_min": 600.0, - "id": 23, - "kind": "link", - "operation": "rough", - "tool": "t1" - }, - { - "curve": { - "center": [ - -2.3112064738081157, - -0.1790289433762438, - 8.0 - ], - "end": [ - -0.935835349367105, - 1.2729883671451803, - 8.0 - ], - "kind": "arc", - "plane": "xy", - "start": [ - -0.3462598476056057, - -0.551835536900785, - 8.0 - ], - "sweep_rad": 1.0 - }, - "feed_mm_min": 600.0, - "id": 24, - "kind": "cut", - "operation": "rough", - "tool": "t1" - }, - { - "curve": { - "center": [ - -1.0733724618112062, - 1.127786636093038, - 8.0 - ], - "end": [ - -1.2185741928633484, - 1.2653237485371391, - 8.0 - ], - "kind": "arc", - "plane": "xy", - "start": [ - -0.935835349367105, - 1.2729883671451803, - 8.0 - ], - "sweep_rad": 1.5707963267948966 - }, - "feed_mm_min": 600.0, - "id": 25, - "kind": "link", - "operation": "rough", - "tool": "t1" - }, - { - "curve": { - "center": [ - -1.0733724618112062, - 1.127786636093038, - 8.0 - ], - "end": [ - -1.2109095742553073, - 0.9825849050408957, - 8.0 - ], - "kind": "arc", - "plane": "xy", - "start": [ - -1.2185741928633484, - 1.2653237485371391, - 8.0 - ], - "sweep_rad": 1.5707963267948966 - }, - "feed_mm_min": 600.0, - "id": 26, - "kind": "link", - "operation": "rough", - "tool": "t1" - }, - { - "curve": { - "center": [ - -1.0661336664194112, - 1.1354288324642032, - 8.0 - ], - "end": [ - -0.9132897389961037, - 0.9906529246283071, - 8.0 - ], - "kind": "arc", - "plane": "xy", - "start": [ - -1.2109095742553073, - 0.9825849050408957, - 8.0 - ], - "sweep_rad": 1.5707963267948966 - }, - "feed_mm_min": 600.0, - "id": 27, - "kind": "link", - "operation": "rough", - "tool": "t1" - }, - { - "curve": { - "center": [ - -1.6392983942568145, - 1.6783384868488138, - 8.0 - ], - "end": [ - -0.6683667964593634, - 1.9176956099901328, - 8.0 - ], - "kind": "arc", - "plane": "xy", - "start": [ - -0.9132897389961037, - 0.9906529246283071, - 8.0 - ], - "sweep_rad": 1.0 - }, - "feed_mm_min": 600.0, - "id": 28, - "kind": "cut", - "operation": "rough", - "tool": "t1" - } - ], - "old_next": { - "curve": { - "center": [ - 1.273496399135539, - 2.3964098562727707, - 8.0 - ], - "end": [ - -0.6601567142568199, - 2.9072773900503996, - 8.0 - ], - "kind": "arc", - "plane": "xy", - "start": [ - -0.6683667964593634, - 1.9176956099901328, - 8.0 - ], - "sweep_rad": -0.5 - }, - "feed_mm_min": 600.0, - "id": 29, - "kind": "cut", - "operation": "rough", - "tool": "t1" - } -} diff --git a/fixtures/regressions/stock-front.json b/fixtures/regressions/adaptive-roughing-layers.json similarity index 98% rename from fixtures/regressions/stock-front.json rename to fixtures/regressions/adaptive-roughing-layers.json index 7c60f038..51fec0f2 100644 --- a/fixtures/regressions/stock-front.json +++ b/fixtures/regressions/adaptive-roughing-layers.json @@ -9,13 +9,9 @@ "bottom_allowance_mm": 0.2, "clearance_z_mm": 12.0, "clearing": { - "boundary_tolerance_mm": 0.01, "kind": "adaptive", - "local_orbit_tolerance_mm": 0.05, "max_radial_engagement_mm": 0.25, - "min_orbit_radius_mm": 0.2, - "orbit_radius_mm": 0.5, - "path_strategy": "stock_front" + "path_strategy": "engagement_front" }, "clockwise": true, "coolant": "flood", @@ -28,7 +24,7 @@ "id": "rough", "kind": "roughing", "length_register": 1, - "omit_empty_cuts": true, + "omit_empty_cuts": false, "plunge_mm_min": 150.0, "radial_allowance_mm": 0.1, "spindle_rpm": 12000.0, diff --git a/fixtures/regressions/disconnected-pocket.json b/fixtures/regressions/disconnected-pocket.json index be584ed2..af66019e 100644 --- a/fixtures/regressions/disconnected-pocket.json +++ b/fixtures/regressions/disconnected-pocket.json @@ -69,9 +69,7 @@ { "kind": "adaptive_pocket", "bottom_allowance_mm": 0.0, - "boundary_tolerance_mm": 0.01, "clearance_z_mm": 12.0, - "clockwise": true, "coolant": "flood", "entry": { "angle_rad": 0.05235987755982989, @@ -82,7 +80,7 @@ "id": "adaptive", "length_register": 1, "max_engagement_deg": 90.0, - "path_strategy": "stock_front", + "path_strategy": "engagement_front", "plunge_mm_min": 150.0, "radial_allowance_mm": 0.0, "region": { diff --git a/fixtures/regressions/retained-body.json b/fixtures/regressions/retained-body.json index 0bae9a87..eaa7ff87 100644 --- a/fixtures/regressions/retained-body.json +++ b/fixtures/regressions/retained-body.json @@ -14,12 +14,8 @@ "bottom_allowance_mm": 0.2, "clearance_z_mm": 12.0, "clearing": { - "boundary_tolerance_mm": 0.01, "kind": "adaptive", - "local_orbit_tolerance_mm": 0.05, - "max_radial_engagement_mm": 0.25, - "min_orbit_radius_mm": 0.2, - "orbit_radius_mm": 0.5 + "max_radial_engagement_mm": 0.25 }, "clockwise": true, "coolant": "flood", diff --git a/python/camlib/operations.py b/python/camlib/operations.py index 769dfa76..231c09fa 100644 --- a/python/camlib/operations.py +++ b/python/camlib/operations.py @@ -1473,8 +1473,7 @@ class RampEntry: proves, then one flat pass along it. The ramp and that pass are entry moves at the entry feed, a full-width slot like a helix's bore, and are not bounded by the engagement limit; every cutting pass after them is. - Roughing with offset or raster clearing, and the disk_front and - stock_front strategies, refuse a ramp entry. + Roughing with offset or raster clearing refuses a ramp entry. """ angle_deg: float @@ -1537,27 +1536,16 @@ class AdaptiveClearing: """Engagement-limited roughing: the cutter never takes more than max_radial_engagement_mm of radial width. - The default path_strategy='engagement_front' follows the boundary - between cut and uncut stock, entering from air or proven-cleared stock - and helixing only into enclosed material. Every cutting and stay-down - link stroke is proven exactly within the contact angle of that width, - acos(1 - w/r) (the layer report's proven_max_engagement_deg). Orbit - options do not apply to it. - - path_strategy='stock_front' is a development strategy: it can stream a - productive prefix but raises if coverage/steering is unresolved. Its - cutting_sense is 'climb' (default) or 'conventional' with the CW spindle. - - path_strategy='disk_front' (orbits over a whole region) is refused by - Roughing: it does not read the stock, so around a part it orbits through - the air beside the stock (#167). It remains AdaptivePocket's strategy. + path_strategy='engagement_front', the only planner (#190), follows the + boundary between cut and uncut stock, entering from air or + proven-cleared stock and helixing only into enclosed material. Every + cutting and stay-down link stroke is proven exactly within the contact + angle of that width, acos(1 - w/r) (the layer report's + proven_max_engagement_deg). cutting_sense is 'climb' (default) or + 'conventional' with the CW spindle. """ max_radial_engagement_mm: float - orbit_radius_mm: float | None = None - min_orbit_radius_mm: float | None = None - local_orbit_tolerance_mm: float | None = None - boundary_tolerance_mm: float = 0.01 path_strategy: str = "engagement_front" cutting_sense: str | None = None @@ -1762,8 +1750,9 @@ class RestPocket(Pocket): class AdaptivePocket(Pocket): """A pocket cleared with a bounded radial engagement. - The default path_strategy='engagement_front' follows the boundary between - cut and uncut stock inside the region, one depth level at a time (#190). + path_strategy='engagement_front', the only planner (#190), follows the + boundary between cut and uncut stock inside the region, one depth level + at a time. stepover_mm is the radial width of each pass (at most the cutter radius); max_engagement_deg below acos(1 - stepover/r) narrows it further. Each level enters by a helix into uncut material (entry's helix, or @@ -1781,10 +1770,10 @@ class AdaptivePocket(Pocket): (about 0.19 mm a side with a 4 mm cutter; use a Pocket there), and a region the cutter fits nowhere in. Each level's report counts all the stock left in the region as its residual area. - Orbit options, max_stay_down_mm and rest_tolerance_mm do not apply; the + max_stay_down_mm and rest_tolerance_mm do not apply; the direction is cutting_sense ('climb' by default, or 'conventional'). - engagement_front's entry and link options are the ones Roughing's + The entry and link options are the ones Roughing's adaptive clearing has. All are unset by default. The link options change feeds only; the entry options change descents, never a cutting pass: @@ -1803,28 +1792,13 @@ class AdaptivePocket(Pocket): depth. None: rapid descent stops at feed_z_mm. - ramp_clearance_mm: each helical entry starts this far above the material its bore meets (never above feed_z_mm). None: at that material. - - path_strategy='disk_front' is the earlier planner: it covers the region - with orbits of orbit_radius_mm (None: half the cutter radius) whatever the - stock holds, so its orbits overlap and it cuts far longer. With it, - clockwise sets the orbit direction; set min_orbit_radius_mm below - orbit_radius_mm and local_orbit_tolerance_mm (for example .05 mm) to size - orbits from whole-guide clearance. path_strategy='stock_front' is a - development strategy that raises on unresolved steering/coverage. Both - refuse the four options above, and an area of the region the cutter - fits in that no orbit does (cutter radius plus orbit radius). """ - orbit_radius_mm: float | None = None max_engagement_deg: float = 90 - boundary_tolerance_mm: float = 0.01 - clockwise: bool = True - min_orbit_radius_mm: float | None = None - local_orbit_tolerance_mm: float | None = None path_strategy: str = "engagement_front" cutting_sense: str | None = None - # engagement_front only (see the class docstring); as on Roughing. + # See the class docstring; as on Roughing. rapid_descent_clearance_mm: float | None = None ramp_clearance_mm: float | None = None link_feed_mm_min: float | None = None @@ -1848,19 +1822,11 @@ def to_dict(self): pocket, kind="adaptive_pocket", max_engagement_deg=self.max_engagement_deg, - boundary_tolerance_mm=self.boundary_tolerance_mm, - clockwise=self.clockwise, ) # The strategy is always written: a saved program states which planner made it. result["path_strategy"] = self.path_strategy if self.cutting_sense is not None: result["cutting_sense"] = self.cutting_sense - if self.orbit_radius_mm is not None: - result["orbit_radius_mm"] = self.orbit_radius_mm - if self.min_orbit_radius_mm is not None: - result["min_orbit_radius_mm"] = self.min_orbit_radius_mm - if self.local_orbit_tolerance_mm is not None: - result["local_orbit_tolerance_mm"] = self.local_orbit_tolerance_mm # Written only when set: a job without them is the job it was. for key in ("rapid_descent_clearance_mm", "ramp_clearance_mm", "link_feed_mm_min"): if getattr(self, key) is not None: diff --git a/python/tests/support/adaptive_connected.py b/python/tests/support/adaptive_connected.py deleted file mode 100644 index 2a2037e3..00000000 --- a/python/tests/support/adaptive_connected.py +++ /dev/null @@ -1,70 +0,0 @@ -"""Synthetic CAM regression input.""" - -from camlib.cadquery import export_floor_region -from camlib.operations import AdaptivePocket -from camlib.simulation import StockSpec -from camlib.tools import EndMill, HolderSection, ToolAssembly - - -POINTS = ( - (3, 3), - (13, 3), - (13, 7.5), - (21, 7.5), - (21, 3), - (31, 3), - (31, 17), - (21, 17), - (21, 12.5), - (13, 12.5), - (13, 17), - (3, 17), -) - - -def cavity(): - import cadquery as cq - - return cq.Workplane("XY").polyline(POINTS).close().extrude(1).translate((0, 0, 9)) - - -def target(): - import cadquery as cq - - return cq.Workplane("XY").box(34, 20, 10, centered=(False, False, False)).cut(cavity()) - - -def connected_job(): - region = export_floor_region( - cavity().faces(" 0.001: - first = True - self.assertFalse(sim.state.finished) - self.assertFalse(sim.state.finished) # streamed: before the run's end - self.assertTrue(first and sim.state.finished) - self.assertEqual(plunges, 1) - self.assertEqual(report["navigation_components"], 1) - self.assertEqual(report["seed_orbits"], 1) - self.assertAlmostEqual(report["min_cutting_orbit_radius_mm"], 0.25) - self.assertLessEqual(report["max_bounded_engagement_deg"], 90.0) - self.assertGreater(report["committed_tube_advances"], 0) - self.assertGreater(report["omitted_endpoint_orbits"], 0) - self.assertGreater(sim.state.volume()["removed_lower_mm3"], 250.0) - self.assertLessEqual(sim.state.volume()["removed_lower_mm3"], 6800.0 - shape.Volume() + 1e-7) - for y in range(sim.state.ny): - for x in range(sim.state.nx): - px = (x + 0.5) * sim.state.dx - py = (y + 0.5) * sim.state.dy - if 14 <= px <= 20 and 9.7 <= py <= 10.3: - self.assertLess(sim.state.heights[2 * (y * sim.state.nx + x) + 1], 9.01) - count = sim.state.completed - program = dict( - version=1, - id="connected-program", - revision="1", - units="mm", - tolerance_mm=1e-5, - frame=dict(origin_mm=(0, 0, 0), x=(1, 0, 0), y=(0, 1, 0), z=(0, 0, 1)), - initial_position_mm=(0, 0, 12), - tools=[t.to_dict() for t in c["tools"]], - events=events, - ) - with Engine() as engine: - self.assertEqual( - engine._request("validate_program", program=program, capabilities=None)["summary"]["motions"], count - ) - - def test_partial_radius_change_replay_and_bad_minimum_before_motion(self): - c = config() - with RecordedRun(**{'rapid_mm_min': 6000, **c}, checkpoint_every=32) as run: - player = Player(run) - player.pause() - run.wait(timeout=60) - count = run.status()["available"] - partial = None - for i in range(min(count, 400)): - player.seek(Cursor(i, 0.5)) - motion = player.motion - curve = motion["curve"] - if ( - motion["kind"] == "link" - and motion["feed_mm_min"] == 150 - and curve["start"][2] == curve["end"][2] == 9 - ): - partial = Cursor(i, 0.5) - break - self.assertIsNotNone(partial) - saved = player.state.heights.tobytes() - position = player.state.position - player.seek(Cursor(count)) - self.assertTrue(player.state.finished) - player.seek(Cursor()) - player.seek(partial) - self.assertEqual(player.state.position, position) - self.assertEqual(player.state.heights.tobytes(), saved) - self.assertLessEqual(run.status()["largest_frame_bytes"], 8 * 1024 * 1024) - self.assertEqual(player.state.manifest["run"]["revision"], c["revision"]) - for minimum in [0, -1, 2]: - bad = dict(c, operations=(replace(c["operations"][0], min_orbit_radius_mm=minimum),)) - with Simulation(**bad) as sim: - with self.assertRaises(SimulationError): - list(sim.run_operations()) - self.assertEqual(sim.state.completed, 0) diff --git a/python/tests/test_adaptive_tapered.py b/python/tests/test_adaptive_tapered.py deleted file mode 100644 index fb674fd3..00000000 --- a/python/tests/test_adaptive_tapered.py +++ /dev/null @@ -1,124 +0,0 @@ -"""Exercise local orbit selection through the public Python/stream interface.""" - -from dataclasses import replace -from functools import lru_cache -import importlib.util -import math -from pathlib import Path -import unittest - -from camlib import Engine -from camlib.playback import Cursor, Player, RecordedRun -from camlib.simulation import OperationUpdate, Simulation, SimulationError - - -@lru_cache(None) -def example(): - path = Path(__file__).resolve().parents[2] / 'python/tests/support/adaptive_tapered.py' - spec = importlib.util.spec_from_file_location('tapered_example', path) - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - return module - - -@lru_cache(None) -def config(): - return example().tapered_job() - - -class TaperedAdaptiveTest(unittest.TestCase): - def test_real_cad_local_targets_cut_material_and_validate_as_typed_program(self): - c = config() - shape = example().target().val() - self.assertTrue(shape.isValid()) - self.assertAlmostEqual(shape.Volume(), 6472.0) - events, radii = [], [] - first = False - report = None - with Simulation(**c) as sim: - for update in sim.run_operations(): - if isinstance(update, OperationUpdate): - events.extend(update.events) - if update.stage == 'end': - report = update.report - continue - motion = update.motion - events.append(dict(kind='motion', motion=motion)) - curve = motion['curve'] - if motion['kind'] == 'cut' and curve['kind'] == 'arc': - radii.append( - math.hypot(curve['start'][0] - curve['center'][0], curve['start'][1] - curve['center'][1]) - ) - if not first and sim.state.volume()['removed_lower_mm3'] > 0.001: - first = True - self.assertFalse(sim.state.finished) - self.assertFalse(sim.state.finished) # streamed: before the run's end - self.assertTrue(first and sim.state.finished) - self.assertEqual(report['navigation_components'], 1) - self.assertEqual(report['seed_orbits'], 1) - self.assertGreater(report['local_radius_splits'], 0) - self.assertGreater(report['locally_sized_guides'], 0) - self.assertGreater(report['distinct_guide_radii'], 2) - self.assertLessEqual(report['max_bounded_engagement_deg'], 90.0) - self.assertTrue( - any( - 0.30 < target < 0.95 and any(abs(actual - target) < 1e-8 for actual in radii) - for target in report['guide_orbit_radii_mm'] - ) - ) - self.assertGreater(sim.state.volume()['removed_lower_mm3'], 250.0) - self.assertLessEqual(sim.state.volume()['removed_lower_mm3'], 328.0 + 1e-7) - count = sim.state.completed - program = dict( - version=1, - id='tapered-program', - revision='1', - units='mm', - tolerance_mm=1e-5, - frame=dict(origin_mm=(0, 0, 0), x=(1, 0, 0), y=(0, 1, 0), z=(0, 0, 1)), - initial_position_mm=(0, 0, 12), - tools=[t.to_dict() for t in c['tools']], - events=events, - ) - with Engine() as engine: - self.assertEqual( - engine._request('validate_program', program=program, capabilities=None)['summary']['motions'], count - ) - - def test_partial_local_radius_replay_and_resolution_admission(self): - c = config() - with RecordedRun(**{'rapid_mm_min': 6000, **c}, checkpoint_every=32) as run: - player = Player(run) - player.pause() - run.wait(timeout=60) - count = run.status()['available'] - partial = None - for i in range(min(count, 600)): - player.seek(Cursor(i, 0.5)) - motion = player.motion - curve = motion['curve'] - if ( - motion['kind'] == 'link' - and motion['feed_mm_min'] == 150 - and curve['start'][2] == curve['end'][2] == 9 - ): - partial = Cursor(i, 0.5) - break - self.assertIsNotNone(partial) - saved, position = player.state.heights.tobytes(), player.state.position - player.seek(Cursor(count)) - self.assertTrue(player.state.finished) - player.seek(Cursor()) - player.seek(partial) - self.assertEqual(player.state.position, position) - self.assertEqual(player.state.heights.tobytes(), saved) - self.assertLessEqual(run.status()['largest_frame_bytes'], 8 * 1024 * 1024) - self.assertEqual(player.state.manifest['run']['revision'], c['revision']) - operation = c['operations'][0] - self.assertNotIn('local_orbit_tolerance_mm', replace(operation, local_orbit_tolerance_mm=None).to_dict()) - for tolerance in (0, -0.05, 0.0001, 2): - bad = dict(c, operations=(replace(operation, local_orbit_tolerance_mm=tolerance),)) - with Simulation(**bad) as sim: - with self.assertRaises(SimulationError): - list(sim.run_operations()) - self.assertEqual(sim.state.completed, 0) diff --git a/python/tests/test_closed_orbit_posting.py b/python/tests/test_closed_orbit_posting.py index d606d5d0..be0f0707 100644 --- a/python/tests/test_closed_orbit_posting.py +++ b/python/tests/test_closed_orbit_posting.py @@ -75,13 +75,13 @@ def test_lowered_full_circle_closes_at_the_decoded_start(self): self.assertEqual(chords[-1].end[:2], moved) def test_adaptive_orbits_post_at_three_decimals(self): - """The workload that found #58: every orbit stays one native block.""" + """The adaptive pocket that found #58 (then cleared with orbits): every arc stays one native block.""" from camlib.jobs import Job, Setup from camlib.post import Machine, ToolSetting from camlib.postprocessor import GCodeDialect from support.adaptive_pocket import adaptive_job - c = adaptive_job(path_strategy="disk_front") + c = adaptive_job() tool = c["tools"][0] setup = Setup("top", c["stock"], c["tools"], c["operations"], c["initial_position_mm"]) job = Job("adaptive-orbits", c["revision"], (setup,)) @@ -114,7 +114,7 @@ def test_adaptive_orbits_post_at_three_decimals(self): lowering=LoweringOptions(native_arcs=True), accept={"unchecked_machine"}, ).text - # Same blocks as at 6 decimals: no orbit had to be lowered to chords. + # Same blocks as at 6 decimals: no arc had to be lowered to chords. self.assertEqual(len(coarse.splitlines()), len(fine.splitlines())) diff --git a/python/tests/test_dynamics.py b/python/tests/test_dynamics.py index 66c4e581..5801c852 100644 --- a/python/tests/test_dynamics.py +++ b/python/tests/test_dynamics.py @@ -283,7 +283,6 @@ def test_complete_connected_cad_passage_schedule_stock_and_checked_post(self): manifest = json.loads( (Path(__file__).resolve().parents[2] / 'fixtures/operations/adaptive-connected.json').read_text() ) - manifest['operations'][0]['path_strategy'] = 'stock_front' tools = tuple(ToolAssembly.from_dict(t) for t in manifest['tools']) pose = tuple(manifest['initial_position_mm']) header = Program('connected-schedule', 'r1', tools, pose, (), tolerance_mm=manifest['sweep']['tolerance_mm']) @@ -325,9 +324,10 @@ def test_complete_connected_cad_passage_schedule_stock_and_checked_post(self): source_motion_count = sim.state.completed self.assertTrue(sim.state.finished) # Check preservation against the independently consumed stock stream. - # A fixed planner count (3205 on Linux, 3195 on Windows) tests the host's - # adaptive subdivision, not whether scheduling preserves every motion. - self.assertGreater(source_motion_count, 3000) + # A fixed planner count tests the host's adaptive subdivision, not + # whether scheduling preserves every motion. (The removed orbit planner + # made about 3,200 motions here; the engagement front about 220, #190.) + self.assertGreater(source_motion_count, 100) self.assertEqual(len(scheduled.report['segments']), source_motion_count) self.assertGreater(scheduled.report['feed_limited_motions'], 0) with Simulation( @@ -345,4 +345,4 @@ def test_complete_connected_cad_passage_schedule_stock_and_checked_post(self): self.assertEqual(replay.state.heights.tobytes(), saved) chunks = list(post_program(scheduled.program, machine)) self.assertIn('M2', chunks[-1].text) - self.assertGreater(sum(len(c.motions) for c in chunks), 3000) + self.assertGreater(sum(len(c.motions) for c in chunks), 100) diff --git a/python/tests/test_helical_entry.py b/python/tests/test_helical_entry.py index 737a8acd..d3534bb9 100644 --- a/python/tests/test_helical_entry.py +++ b/python/tests/test_helical_entry.py @@ -72,19 +72,28 @@ def test_real_cad_both_native_strategies_stream_entries_and_validate_typed_motio descents[-1].append(m) else: descents.append([m]) - self.assertEqual(len(descents), 2) self.assertTrue(all(abs(abs(m['curve']['sweep_rad']) - math.tau) < 1e-9 for m in helices)) - self.assertEqual(report['helical_entries'], 2) - self.assertEqual(report['entry_turns'], 20 if adaptive else 14) - self.assertEqual( - report['entry_turns'], sum(round(abs(m['curve']['sweep_rad']) / math.tau) for m in helices) - ) - self.assertEqual(report.get('cleared_entry_descents', 0), 0 if adaptive else 1) - self.assertEqual(report['entry_radii_mm'], [1.0]) - self.assertGreater(report['entry_geometry_work'], 0) + self.assertEqual(report['helical_entries'], len(descents)) + if adaptive: + # The engagement front (#190) enters this ring around an island four times over its two levels; + # each helix starts on the material it meets. + self.assertEqual(len(descents), 4) + else: + self.assertEqual(len(descents), 2) + self.assertEqual(report['entry_turns'], 14) + self.assertEqual( + report['entry_turns'], sum(round(abs(m['curve']['sweep_rad']) / math.tau) for m in helices) + ) + self.assertEqual(report.get('cleared_entry_descents', 0), 1) + self.assertEqual(report['entry_radii_mm'], [1.0]) + self.assertGreater(report['entry_geometry_work'], 0) for i, descent in enumerate(descents): curve = descent[0]['curve'] - if adaptive or i == 0: + if adaptive: + # On the stock top, or on the floor the first level cut (within the stock's height guard). + z = curve['start'][2] + self.assertTrue(z == 10 or 8 <= z <= 8.011, z) + elif i == 0: self.assertEqual(curve['start'][2], 10) else: previous_floor = descents[i - 1][-1]['curve']['end'][2] diff --git a/python/tests/test_no_entry.py b/python/tests/test_no_entry.py index 2f04a518..40e4dd1b 100644 --- a/python/tests/test_no_entry.py +++ b/python/tests/test_no_entry.py @@ -57,19 +57,14 @@ def test_adaptive_pocket_refuses_a_slot_no_helix_fits(self): 'an earlier operation that opens a start there', ): self.assertIn(part, error) - # The orbit strategies sweep a disk of radius 3 mm: none fits. - for strategy in ('disk_front', 'stock_front'): - error = refused(self, adaptive_job(None, path_strategy=strategy)) - self.assertIn('adaptive pocket slot: no orbit fits the area at (', error) - self.assertIn('though the cutter fits it', error) - self.assertIn('path_strategy engagement_front', error) def test_a_region_the_cutter_fits_nowhere_in_is_refused(self): # 26 x 3 mm for the 4 mm cutter: no operation can do anything there. narrow = ((3.0, 10.5), (29.0, 13.5)) - jobs = [(slot_job(None, region=narrow), 'pocket slot')] - for strategy in ('engagement_front', 'disk_front', 'stock_front'): - jobs.append((adaptive_job(None, region=narrow, path_strategy=strategy), 'adaptive pocket slot')) + jobs = [ + (slot_job(None, region=narrow), 'pocket slot'), + (adaptive_job(None, region=narrow), 'adaptive pocket slot'), + ] for job, name in jobs: error = refused(self, job) self.assertIn(f'{name}: the cutter fits nowhere in the region', error) diff --git a/python/tests/test_ramp_entry.py b/python/tests/test_ramp_entry.py index 3328eb22..3bcacfe4 100644 --- a/python/tests/test_ramp_entry.py +++ b/python/tests/test_ramp_entry.py @@ -552,10 +552,6 @@ def test_adaptive_pocket_ramps_into_a_slot_no_helix_fits(self): def test_adaptive_and_roughing_refusals_name_the_reason(self): cases = ( (adaptive_job(RampEntry(4)), ('no ramp entry into the enclosed material', 'min_length_mm is not set')), - ( - adaptive_job(RampEntry(4, min_length_mm=2), path_strategy='disk_front'), - ('RampEntry is not supported here', 'engagement_front ramps into enclosed material'), - ), ) for job, parts in cases: with Simulation(**job) as sim: diff --git a/python/tests/test_rapid_retracts.py b/python/tests/test_rapid_retracts.py index ef02911c..935f2031 100644 --- a/python/tests/test_rapid_retracts.py +++ b/python/tests/test_rapid_retracts.py @@ -107,8 +107,6 @@ def test_adaptive_links_at_the_retract_height(self): 20, retract_z_mm=13, feed_z_mm=11, - # This test is of the orbit planner's links. - path_strategy="disk_front", feed_mm_min=600, plunge_mm_min=150, spindle_rpm=12000, @@ -127,8 +125,13 @@ def test_adaptive_links_at_the_retract_height(self): moves, statuses = run(camlib.Job("adaptive", "1", (setup,))) self.assertEqual(set(statuses), {"clear"}, statuses) inner = moves[1:-1] - # Only the first and last moves reach clearance; travel is at Z13. - self.assertTrue(all(max(m["curve"]["start"][2], m["curve"]["end"][2]) <= 13 + 1e-9 for m in inner[1:])) + # Travel within a level is at Z13. The engagement front plans each level on its own and goes to the + # clearance height between them (the one trip up, across and down at Z20 below); the removed orbit planner + # stayed at Z13 there too (#190). + travel = inner[1:] + high = [i for i, m in enumerate(travel) if max(m["curve"]["start"][2], m["curve"]["end"][2]) > 13 + 1e-9] + self.assertEqual(high, [high[0], high[0] + 1, high[0] + 2], high) + self.assertTrue(all(travel[i]["kind"] == "rapid" for i in high)) # Rapid descents stop at the feed height; below it the tool feeds. for m in moves: a, b = m["curve"]["start"], m["curve"]["end"] diff --git a/python/tests/test_roughing.py b/python/tests/test_roughing.py index bfd44886..4c491cbd 100644 --- a/python/tests/test_roughing.py +++ b/python/tests/test_roughing.py @@ -73,33 +73,6 @@ def stream(adaptive=False): class RoughingTest(unittest.TestCase): - def test_stock_front_four_layer_cad_rough_streams_bulk_removal_and_completes(self): - c = example().roughing_job(stock_front=True, omit_empty_cuts=True) - self.assertEqual(c['operations'][0].clearing.path_strategy, 'stock_front') - first_removal = False - report = None - with Simulation(**c) as sim: - for update in sim.run_operations(): - if isinstance(update, OperationUpdate): - if update.stage == 'end': - report = update.report - elif not first_removal and sim.state.volume()['removed_lower_mm3'] > 1: - self.assertFalse(sim.state.finished) - first_removal = True - self.assertTrue(first_removal and sim.state.finished) - self.assertIsNotNone(report) - self.assertEqual(report['completed_layers'], 4) - self.assertEqual(report['motions'], sim.state.completed) - self.assertLessEqual(sim.state.completed, 10000) - self.assertGreater(sim.state.volume()['removed_lower_mm3'], 5500) - self.assertLess(sim.state.volume()['removed_upper_mm3'], 32 * 28 * 10 - 1888) - for layer in report['layers']: - front = layer['clearing']['front'] - self.assertTrue(front['coverage_complete']) - self.assertEqual(front['completed_components'], 2) - self.assertGreater(front['bulk_contours'], 0) - self.assertLessEqual(front['max_bounded_engagement_deg'], report['max_engagement_deg']) - def test_step_up_layers_follow_each_stepdown_and_remove_the_wall_stair(self): base = example().roughing_job(offset=True) operation = base['operations'][0] @@ -129,7 +102,7 @@ def run(c): run(dict(base, operations=(replace(operation, stepup_mm=2.0),))) def test_engagement_front_clears_every_layer_and_reports_its_estimate(self): - c = example().roughing_job(engagement_front=True) + c = example().roughing_job(adaptive=True) clearing = c['operations'][0].clearing self.assertEqual(clearing.to_dict()['path_strategy'], 'engagement_front') report = None @@ -223,7 +196,8 @@ def run(entry, clearing=AdaptiveClearing(3)): self.assertNotIn('confined_strokes', front) paths.append(kinds) self.assertEqual(paths[0], paths[1]) - with self.assertRaisesRegex(SimulationError, 'does not clear with path_strategy disk_front'): + # The orbit planner was removed (#190): its name is refused. + with self.assertRaisesRegex(SimulationError, 'unknown variant'): run(StockEdgeEntry(), AdaptiveClearing(3, path_strategy='disk_front')) def test_empty_cut_policy_is_an_explicit_strict_python_boolean(self): diff --git a/python/tests/test_stream_policy.py b/python/tests/test_stream_policy.py index b41c14b8..9a02f09f 100644 --- a/python/tests/test_stream_policy.py +++ b/python/tests/test_stream_policy.py @@ -250,7 +250,7 @@ def test_complete_connected_passage_streamed_policy_preserves_posted_stock(self) tool = ToolAssembly.from_dict(m['tools'][0]) definition = dict(m['operations'][0]) definition.pop('kind') - definition.update(tool=tool, path_strategy='stock_front') + definition.update(tool=tool) stock = StockSpec(**{k: v for k, v in m['stock'].items() if k not in ('version', 'units')}) setup = Setup( 'top', diff --git a/src/adaptive.rs b/src/adaptive.rs index ad6bb372..d4ce24d9 100644 --- a/src/adaptive.rs +++ b/src/adaptive.rs @@ -1,37 +1,19 @@ -//! Region-based, stock-aware disk-front clearing. See docs/adaptive-pocket.md. -use crate::{ - Point, - adaptive_front::FrontDriver, - entry::{EntryFitOptions, EntryLocation, fit_entries}, - motion::{Curve, Event, Motion, MoveKind, Plane, Vec3}, - navigation::{GraphOptions, Guide, graph}, - planar::{ConstructionOptions, PlanarRegion}, - pocket::{PocketOperation, PocketPlan, ResidualStatus, Stroke}, - stock::{CancelSignal, Stock, StockSpec}, - tool::ToolAssembly, -}; +//! The adaptive pocket operation: its options and wire format. It is planned +//! by the engagement front (`crate::pocket_front`), the planner Roughing's +//! adaptive clearing uses (`crate::roughing::EngagementFrontPlan`). +use crate::pocket::PocketOperation; use serde::{Deserialize, Serialize}; -use std::{ - collections::HashMap, - f64::consts::{PI, TAU}, -}; - -pub use crate::adaptive_front::FrontReport; +/// The adaptive clearing planner. One remains: the engagement front, which +/// follows the boundary between cut and uncut stock and proves every cutting +/// stroke within its contact angle. A saved program states it (#190: the +/// orbit planners `disk_front` and `stock_front` were removed). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum AdaptivePathStrategy { #[default] - DiskFront, - StockFront, - /// Roughing only: grid-steered constant-engagement front following. EngagementFront, } -impl AdaptivePathStrategy { - pub(crate) fn is_default(&self) -> bool { - *self == Self::DiskFront - } -} #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] @@ -46,24 +28,20 @@ pub struct AdaptivePocketOperation { pub pocket: PocketOperation, pub path_strategy: AdaptivePathStrategy, pub cutting_sense: Option, - pub orbit_radius_mm: Option, - pub min_orbit_radius_mm: Option, - pub local_orbit_tolerance_mm: Option, + /// An upper limit on the contact angle: below the stepover's own angle, + /// acos(1 - stepover / r), it narrows the radial width. pub max_engagement_deg: f64, - pub boundary_tolerance_mm: f64, - pub clockwise: bool, - /// engagement_front only: see `RoughingOperation::rapid_descent_clearance_mm`. + /// See `RoughingOperation::rapid_descent_clearance_mm`. /// The proof is per depth level: a descent into a level below one /// already cut is rapid down to this far above what the committed sweeps /// prove clear for the whole tool. None: rapid descent stops at `feed_z_mm`. pub rapid_descent_clearance_mm: Option, - /// engagement_front only: see `RoughingOperation::ramp_clearance_mm`. + /// See `RoughingOperation::ramp_clearance_mm`. pub ramp_clearance_mm: Option, - /// engagement_front only: see `RoughingOperation::link_feed_mm_min`. + /// See `RoughingOperation::link_feed_mm_min`. /// None: every stay-down link feeds at `feed_mm_min`. pub link_feed_mm_min: Option, - /// engagement_front only, with `link_feed_mm_min`: see - /// `RoughingOperation::link_chip_thinning`. + /// With `link_feed_mm_min`: see `RoughingOperation::link_chip_thinning`. pub link_chip_thinning: bool, } // Keep the public operation wire flat, like Pocket. Explicitly consume strategy @@ -81,54 +59,7 @@ impl AdaptivePocketOperation { link_chip_thinning: self.link_chip_thinning, } } - /// The orbit planners' parameters (disk_front, stock_front). - pub(crate) fn validate_parameters(&self, r: f64) -> Result<(f64, f64, f64), String> { - if self.path_strategy != AdaptivePathStrategy::EngagementFront { - self.front_motion_options().validate( - "adaptive pocket", - Some("; leave it unset or use path_strategy engagement_front (disk_front and stock_front relink by lifted re-entries)"), - )?; - } - if self.pocket.max_stay_down_mm.is_some() { - return Err("max_stay_down_mm applies to pocket and rest pocket links; adaptive clearing relinks through its own proven-clear re-entries".into()); - } - if self.path_strategy == AdaptivePathStrategy::DiskFront && self.cutting_sense.is_some() { - return Err("cutting_sense requires stock_front; disk_front defines only the orbit direction (clockwise)".into()); - } - let guard = 16. * self.pocket.tolerance_mm; - let radius = self.orbit_radius_mm.unwrap_or(r / 2.); - let a = r + radius; - let min_radius = self.min_orbit_radius_mm.unwrap_or(radius); - if let Some(t) = self.local_orbit_tolerance_mm - && (!t.is_finite() || t <= 8. * guard || t > radius || min_radius >= radius) - { - return Err("local orbit tolerance requires variable radii and finite resolution above numerical guard and within max radius".into()); - } - if !min_radius.is_finite() - || min_radius <= 4. * guard - || min_radius > radius - || !radius.is_finite() - || radius <= 4. * guard - || radius > r - || !self.max_engagement_deg.is_finite() - || !(1. ..=170.).contains(&self.max_engagement_deg) - || !self.boundary_tolerance_mm.is_finite() - || self.boundary_tolerance_mm <= 2. * guard - || self.boundary_tolerance_mm > r / 4. - || self.pocket.rest_tolerance_mm.is_some() - { - return Err("invalid adaptive orbit/engagement/boundary budget; rest height tolerance is not an engagement proof".into()); - } - let half = self.max_engagement_deg.to_radians() / 2.; - let bound = - (a * a - r * r * half.sin().powi(2)).sqrt() - r * half.cos() - radius - 2. * guard; - if bound <= guard { - return Err("adaptive advance below numerical resolution".into()); - } - Ok((radius, min_radius, bound)) - } } - impl TryFrom for AdaptivePocketOperation { type Error = String; fn try_from(value: serde_json::Value) -> Result { @@ -138,48 +69,21 @@ impl TryFrom for AdaptivePocketOperation { let path_strategy = serde_json::from_value( fields .remove("path_strategy") - .unwrap_or(serde_json::json!("disk_front")), + .unwrap_or(serde_json::json!("engagement_front")), ) - .map_err(|e| e.to_string())?; + .map_err(|e| format!("path_strategy: {e}"))?; let cutting_sense = serde_json::from_value( fields .remove("cutting_sense") .unwrap_or(serde_json::Value::Null), ) .map_err(|e| e.to_string())?; - let orbit_radius_mm = serde_json::from_value( - fields - .remove("orbit_radius_mm") - .unwrap_or(serde_json::Value::Null), - ) - .map_err(|e| e.to_string())?; - let min_orbit_radius_mm = serde_json::from_value( - fields - .remove("min_orbit_radius_mm") - .unwrap_or(serde_json::Value::Null), - ) - .map_err(|e| e.to_string())?; let max_engagement_deg = serde_json::from_value( fields .remove("max_engagement_deg") .ok_or("missing max_engagement_deg")?, ) .map_err(|e| e.to_string())?; - let local_orbit_tolerance_mm = serde_json::from_value( - fields - .remove("local_orbit_tolerance_mm") - .unwrap_or(serde_json::Value::Null), - ) - .map_err(|e| e.to_string())?; - let boundary_tolerance_mm = serde_json::from_value( - fields - .remove("boundary_tolerance_mm") - .ok_or("missing boundary_tolerance_mm")?, - ) - .map_err(|e| e.to_string())?; - let clockwise = - serde_json::from_value(fields.remove("clockwise").ok_or("missing clockwise")?) - .map_err(|e| e.to_string())?; let mut optional = |name: &str| -> Result, String> { serde_json::from_value(fields.remove(name).unwrap_or(serde_json::Value::Null)) .map_err(|e| format!("{name}: {e}")) @@ -199,12 +103,7 @@ impl TryFrom for AdaptivePocketOperation { pocket, path_strategy, cutting_sense, - orbit_radius_mm, - min_orbit_radius_mm, - local_orbit_tolerance_mm, max_engagement_deg, - boundary_tolerance_mm, - clockwise, rapid_descent_clearance_mm, ramp_clearance_mm, link_feed_mm_min, @@ -216,30 +115,15 @@ impl From for serde_json::Value { fn from(op: AdaptivePocketOperation) -> Self { let mut value = serde_json::to_value(op.pocket).expect("Pocket serialization"); let fields = value.as_object_mut().expect("Pocket object"); - if !op.path_strategy.is_default() { - fields.insert( - "path_strategy".into(), - serde_json::to_value(op.path_strategy).unwrap(), - ); - } + // Always written: a saved program states which planner made it. + fields.insert( + "path_strategy".into(), + serde_json::to_value(op.path_strategy).unwrap(), + ); if let Some(sense) = op.cutting_sense { fields.insert("cutting_sense".into(), serde_json::to_value(sense).unwrap()); } - if let Some(r) = op.orbit_radius_mm { - fields.insert("orbit_radius_mm".into(), r.into()); - } - if let Some(r) = op.min_orbit_radius_mm { - fields.insert("min_orbit_radius_mm".into(), r.into()); - } - if let Some(t) = op.local_orbit_tolerance_mm { - fields.insert("local_orbit_tolerance_mm".into(), t.into()); - } fields.insert("max_engagement_deg".into(), op.max_engagement_deg.into()); - fields.insert( - "boundary_tolerance_mm".into(), - op.boundary_tolerance_mm.into(), - ); - fields.insert("clockwise".into(), op.clockwise.into()); // Absent when unset: an operation without them serializes as before. for (name, value) in [ ("rapid_descent_clearance_mm", op.rapid_descent_clearance_mm), @@ -256,1504 +140,3 @@ impl From for serde_json::Value { value } } -#[derive(Serialize)] -pub struct AdaptiveReport { - #[serde(skip_serializing_if = "Option::is_none")] - pub stock_top: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub front: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub empty_cuts: Option, - pub stock_edge_entries: usize, - pub helical_entries: usize, - pub entry_turns: usize, - pub entry_geometry_work: usize, - pub entry_navigation_links: usize, - pub entry_radii_mm: Vec, - pub max_entry_turns_per_descent: usize, - pub strategy: &'static str, - /// Areas the cutter fits in that no orbit does - /// (`crate::entry::UnenteredArea`): an `AdaptivePocket` is refused with - /// the first; a roughing layer lists them here. Their material is in - /// the residual region below. - #[serde(skip_serializing_if = "Vec::is_empty")] - pub unentered_areas: Vec, - pub geometric_residual_status: ResidualStatus, - pub geometric_residual: Option, - pub geometric_residual_area_mm2: Option, - pub target_z_mm: f64, - pub depth_passes: usize, - pub center_components: usize, - pub navigation_components: usize, - pub guide_strokes: usize, - pub navigation_links: usize, - pub navigation_work: usize, - pub orbit_radius_mm: f64, - pub swept_disk_radius_mm: f64, - pub min_orbit_radius_mm: f64, - pub min_active_radius_mm: f64, - pub min_cutting_orbit_radius_mm: Option, - pub radius_changes: usize, - pub radius_growth_orbits: usize, - pub fine_guide_strokes: usize, - pub local_radius_splits: usize, - pub local_radius_work: usize, - pub locally_sized_guides: usize, - pub uncertain_local_guides: usize, - pub distinct_guide_radii: usize, - pub guide_orbit_radii_mm: Vec, - pub guide_orbit_radii_truncated: bool, - pub omitted_endpoint_orbits: usize, - pub omitted_seed_orbits: usize, - pub stock_clear_radius_changes: usize, - pub committed_tube_advances: usize, - pub max_engagement_deg: f64, - pub max_bounded_engagement_deg: f64, - pub bounded_advance_mm: f64, - pub boundary_underclearance_budget_mm: f64, - pub seed_entry_policy: &'static str, - pub seed_orbits: usize, - pub controlled_orbits: usize, - pub bounded_advances: usize, - pub stock_clear_advances: usize, - pub turn_arcs: usize, - pub chord_fallbacks: usize, - pub stock_query_work: usize, - pub stock_query_work_exhausted: bool, - pub motions: usize, - pub diagnostics: Vec, -} -fn distance(a: Point, b: Point) -> f64 { - (a[0] - b[0]).hypot(a[1] - b[1]) -} -fn point(s: Stroke, f: f64) -> Point { - if f == 0. { - return s.a; - } - if f == 1. { - return s.b; - } - if let Some((c, sweep)) = s.arc { - let a = (s.a[1] - c[1]).atan2(s.a[0] - c[0]) + f * sweep; - let r = distance(s.a, c); - [c[0] + r * a.cos(), c[1] + r * a.sin()] - } else { - [ - s.a[0] + f * (s.b[0] - s.a[0]), - s.a[1] + f * (s.b[1] - s.a[1]), - ] - } -} -fn tangent(s: Stroke, f: f64) -> Point { - if let Some((c, sweep)) = s.arc { - let p = point(s, f); - let r = distance(p, c); - let sign = sweep.signum(); - [-(p[1] - c[1]) * sign / r, (p[0] - c[0]) * sign / r] - } else { - s.tangent(false) - } -} -fn length(s: Stroke) -> f64 { - s.arc - .map_or_else(|| distance(s.a, s.b), |(c, a)| distance(s.a, c) * a.abs()) -} -#[derive(Default)] -struct LocalSizing { - originals: Vec<(Stroke, f64, f64)>, - splits: usize, - work: usize, - resized: usize, - uncertain: usize, -} -fn size_guides( - guides: &PocketPlan, - originals: Vec<(Stroke, f64, f64)>, - cutter: f64, - maximum: f64, - tolerance: f64, - cancel: &impl CancelSignal, -) -> Result { - let mut out = LocalSizing::default(); - let mut stack: Vec<_> = originals.into_iter().rev().map(|g| (g, 0usize)).collect(); - while let Some(((s, base, coverage), depth)) = stack.pop() { - if cancel.is_cancelled() { - return Err("adaptive local sizing cancelled".into()); - } - out.work += guides.link_work_per_query(); - let Some((lower, upper)) = guides.guide_radius_bounds(s) else { - out.originals.push((s, base, coverage)); - out.uncertain += 1; - continue; - }; - let radius = (lower - cutter).min(maximum).max(base); - let upper = (upper - cutter).min(maximum).max(radius); - if upper - radius > tolerance { - if depth >= 32 || length(s) <= tolerance / 64. { - return Err("adaptive local sizing subdivision limit exceeded".into()); - } - let mid = point(s, 0.5); - let arc = s.arc.map(|(c, a)| (c, a / 2.)); - stack.push(( - ( - Stroke { - a: mid, - b: s.b, - arc, - }, - base, - coverage, - ), - depth + 1, - )); - stack.push(( - ( - Stroke { - a: s.a, - b: mid, - arc, - }, - base, - coverage, - ), - depth + 1, - )); - out.splits += 1; - } else { - out.resized += usize::from(radius > base + tolerance / 64.); - out.originals.push((s, radius, coverage)); - } - } - Ok(out) -} -struct Advance { - curve: Curve, - fraction: f64, - center: Point, - normal: Point, - clear: bool, - committed_tube: bool, - angle: f64, - chord: bool, -} -#[derive(Clone, Copy, PartialEq)] -enum Phase { - Up, - Across, - Plunge, - EntryTop, - EntryHelix, - Seed, - Turn, - Advance, - Orbit, - RadiusOrbit, - Front, - Retract, - /// Rapid from the feed height to the retract height (clearance at the end). - Rise, - /// Rapid from the travel height down to the feed height above an entry. - Descend, - Done, -} -pub struct AdaptivePlan { - heights: crate::heights::Heights, - /// The entry phase after the descent to the feed height. - entry: Phase, - stock_top: Option, - front: Option, - op: AdaptivePocketOperation, - guides: PocketPlan, - tours: Vec>, - helical: Option>, - spec: StockSpec, - position: Vec3, - center: Point, - normal: Point, - r: f64, - guard: f64, - active_radius: f64, - disk_radius: f64, - /// (emitted, total) one-turn helices of the current helical entry. - entry_turn: Option<(usize, usize)>, - cleared_edges: HashMap, - pass: usize, - component: usize, - guide: usize, - fraction: f64, - phase: Phase, - advance: Option, - next_id: u64, - generation: Option, - report: AdaptiveReport, - /// Whether the cutter fits anywhere in the region (its own centre - /// region, not the orbits'). - cutter_fits: bool, -} -impl AdaptivePlan { - pub fn prepare_with_stock( - op: AdaptivePocketOperation, - tool: &ToolAssembly, - stock: &Stock, - initial: Vec3, - first_id: u64, - cancel: &impl CancelSignal, - ) -> Result { - let scope = crate::pocket::ReachScope { - operation: &op.pocket.id, - tool, - region: &op.pocket.region, - lowest_tip_z: op.pocket.floor_z_mm + op.pocket.bottom_allowance_mm, - clearance_z: op.pocket.clearance_z_mm, - // Adaptive paths may approach the boundary within this tolerance. - boundary_slack_mm: op.boundary_tolerance_mm, - }; - let (envelope, bound) = crate::pocket::StockTop::prepare( - stock, - op.pocket.top_z_mm, - op.pocket.tolerance_mm, - &scope, - cancel, - )?; - let mut plan = Self::prepare(op, tool, &envelope, initial, first_id, cancel)?; - if let Some(bound) = bound { - plan.activate_layer(initial, first_id, stock.spec())?; - plan.report.stock_top = Some(bound.report.clone()); - plan.stock_top = Some(bound); - plan.generation = Some(stock.generation()); - } - Ok(plan) - } - pub(crate) fn enable_empty_cuts(&mut self) { - self.report.empty_cuts = Some(Default::default()); - self.report.diagnostics.push("Omitted non-seed full orbits require a whole empty support disk; no unexecuted in-stock disk is considered cleared".into()); - } - pub(crate) fn construction_error_mm(&self) -> f64 { - self.guides.construction_error_mm() - } - pub(crate) fn activate_layer( - &mut self, - initial: Vec3, - first_id: u64, - stock: &StockSpec, - ) -> Result<(), String> { - let mut envelope = stock.clone(); - envelope.max_mm[2] = self.spec.max_mm[2]; - if self.report.motions != 0 - || self.generation.is_some() - || self.phase != Phase::Up - || first_id == 0 - || initial.iter().any(|x| !x.is_finite() || x.abs() > 1e6) - || initial[2] < self.op.pocket.clearance_z_mm - || envelope != self.spec - || stock.max_mm[2] < self.spec.max_mm[2] - { - return Err("cannot activate a used adaptive layer or invalid start".into()); - } - self.guides.activate_layer(initial, first_id, stock)?; - self.position = initial; - self.next_id = first_id; - self.spec = stock.clone(); - Ok(()) - } - pub fn prepare( - op: AdaptivePocketOperation, - tool: &ToolAssembly, - spec: &StockSpec, - initial: Vec3, - first_id: u64, - cancel: &impl CancelSignal, - ) -> Result { - if op.path_strategy == AdaptivePathStrategy::EngagementFront { - return Err("an engagement_front adaptive pocket is planned by PocketFrontPlan (OperationPlan::prepare)".into()); - } - if let Some(entry) = &op.pocket.entry { - // disk_front and stock_front plan every pass from a fitted seed - // circle, which a helix opens; a ramp has no seed circle. The - // engagement front ramps into enclosed material (#219). - entry.refuse_ramp( - &format!("adaptive pocket {}", op.pocket.id), - "the disk_front and stock_front strategies start every pass from a fitted seed circle that a helix opens; path_strategy engagement_front ramps into enclosed material", - )?; - } - let prepared = tool.prepare()?; - if tool.cutter.shape.indexable().is_some() { - return Err("AdaptivePocket does not support indexable insert engagement; use Pocket or raster/offset Roughing".into()); - } - let r = prepared.cutter().definition().diameter_mm / 2.; - let (radius, min_radius, bound) = op.validate_parameters(r)?; - let guard = 16. * op.pocket.tolerance_mm; - let a = r + radius; - let coarse = PocketPlan::prepare_guides( - op.pocket.clone(), - tool, - spec, - initial, - first_id, - Some(a), - cancel, - )?; - let variable = min_radius < radius; - let coarse_coverage = if variable { - op.boundary_tolerance_mm / 2. - } else { - op.boundary_tolerance_mm - }; - let mut originals: Vec<_> = coarse - .guide_strokes() - .iter() - .map(|s| (*s, radius, coarse_coverage)) - .collect(); - let (guides, fine_count) = if variable { - let fine = PocketPlan::prepare_guides( - op.pocket.clone(), - tool, - spec, - initial, - first_id, - Some(r + min_radius), - cancel, - )?; - let cover = coarse.guide_cover_region( - radius - min_radius + op.boundary_tolerance_mm - coarse_coverage - 2. * guard, - )?; - let options = ConstructionOptions { - tolerance_mm: op.pocket.tolerance_mm, - }; - let cover = cover - .prepare(options)? - .offset(cover.boundary_error_mm + 4. * op.pocket.tolerance_mm)? - .region; - let retained = fine.guides_outside(&cover, cancel)?; - let count = retained.len(); - originals.extend( - retained - .into_iter() - .map(|s| (s, min_radius, op.boundary_tolerance_mm)), - ); - (fine, count) - } else { - (coarse, 0) - }; - let sizing = if let Some(t) = op.local_orbit_tolerance_mm { - size_guides(&guides, originals, r, radius, t, cancel)? - } else { - LocalSizing { - originals, - ..LocalSizing::default() - } - }; - let guide_count = sizing.originals.len(); - let mut graph = graph( - &guides, - sizing.originals, - GraphOptions { - bridge_radius: min_radius, - cutter_radius: r, - coverage: op.boundary_tolerance_mm, - local_sizing: op.local_orbit_tolerance_mm.is_some(), - starting_work: 0, - }, - cancel, - )?; - let mut helical = None; - let mut entry_work = 0; - let mut entry_links = 0; - if let Some(entry) = &op.pocket.entry { - let fit = fit_entries( - &guides, - &graph.tours, - entry.helix().ok_or("missing helical entry")?, - EntryFitOptions { - cutter_radius: r, - minimum_orbit: min_radius, - preferred_cap: radius, - max_depth: op.pocket.top_z_mm - guides.report().target_z_mm, - starting_work: graph.work, - policy: entry.policy(), - }, - cancel, - )?; - entry_work = fit.work - graph.work; - let mut edge = graph - .tours - .iter() - .flatten() - .map(|g| g.edge) - .max() - .unwrap_or(0) - + 1; - for (tour, location) in graph.tours.iter_mut().zip(&fit.locations) { - tour.rotate_left(location.attachment); - let target = tour[0].stroke.a; - if location.center != target { - tour.insert( - 0, - Guide { - stroke: Stroke::line(location.center, target), - radius: min_radius, - coverage: op.boundary_tolerance_mm, - edge, - }, - ); - edge += 1; - entry_links += 1; - } - } - helical = Some(fit.locations); - } - let mut targets: Vec<_> = graph.tours.iter().flatten().map(|g| g.radius).collect(); - targets.sort_by(f64::total_cmp); - targets.dedup(); - let distinct_guide_radii = targets.len(); - let guide_orbit_radii_truncated = targets.len() > 64; - let guide_orbit_radii_mm = if guide_orbit_radii_truncated { - (0..64) - .map(|i| targets[i * (targets.len() - 1) / 63]) - .collect() - } else { - targets - }; - // Areas the cutter fits in that no orbit does (#250): components of - // the cutter's own centre region (as `PocketPlan` constructs it) - // that hold no guide of any tour. - let options = ConstructionOptions { - tolerance_mm: op.pocket.tolerance_mm, - }; - let cutter = guides - .source_region() - .cutter_region(r, op.pocket.radial_allowance_mm + guard)? - .region; - let cutter_fits = !cutter.components.is_empty(); - let mut unentered_areas = vec![]; - for component in &cutter.components { - if cancel.is_cancelled() { - return Err("adaptive pocket planning cancelled".into()); - } - let mut one = cutter.clone(); - one.components = vec![component.clone()]; - let one = one.prepare(options)?; - let mut entered = false; - for tour in &graph.tours { - // A tour is connected: one of its points decides. - let Some(first) = tour.first() else { continue }; - if one - .query(first.stroke.a)? - .signed_clearance_mm - .is_some_and(|d| d >= 0.) - { - entered = true; - break; - } - } - if entered { - continue; - } - let Some(at) = component.outer.vertices.first() else { - continue; - }; - let (mut low, mut high) = ([at[0], at[1]], [at[0], at[1]]); - for v in &component.outer.vertices { - low = [low[0].min(v[0]), low[1].min(v[1])]; - high = [high[0].max(v[0]), high[1].max(v[1])]; - } - unentered_areas.push(crate::entry::UnenteredArea { - reason: "no_orbit_fits", - at_mm: [at[0], at[1]], - min_mm: low, - max_mm: high, - level_z_mm: guides.report().target_z_mm, - cutter_radius_mm: r, - radii_tried_mm: if min_radius < radius { - vec![radius, min_radius] - } else { - vec![radius] - }, - needed_mm: min_radius, - available_mm: None, - }); - } - let mut report=AdaptiveReport { - unentered_areas, - stock_top:None, - front:None, - stock_edge_entries:0,helical_entries:0,entry_turns:0,entry_geometry_work:entry_work,entry_navigation_links:entry_links, - entry_radii_mm:helical.as_ref().map_or_else(Vec::new,|locations|locations.iter().map(|e|e.radius).collect()), - max_entry_turns_per_descent:helical.as_ref().and_then(|locations|locations.iter().map(|e|e.max_turns).max()).unwrap_or(0), - strategy:"adaptive_pocket",geometric_residual_status:ResidualStatus::Pending, - geometric_residual:None,geometric_residual_area_mm2:None, - target_z_mm:guides.report().target_z_mm,depth_passes:guides.report().depth_passes, - center_components:guides.report().center_components,navigation_components:graph.tours.len(), - guide_strokes:guide_count,navigation_links:graph.links+entry_links,navigation_work:graph.work, - orbit_radius_mm:radius,swept_disk_radius_mm:a,max_engagement_deg:op.max_engagement_deg, - min_orbit_radius_mm:min_radius,min_active_radius_mm:radius,min_cutting_orbit_radius_mm:None, - radius_changes:0,radius_growth_orbits:0,fine_guide_strokes:fine_count,omitted_endpoint_orbits:0,omitted_seed_orbits:0,stock_clear_radius_changes:0,committed_tube_advances:0, - local_radius_splits:sizing.splits,local_radius_work:sizing.work,locally_sized_guides:sizing.resized,uncertain_local_guides:sizing.uncertain, - distinct_guide_radii,guide_orbit_radii_mm,guide_orbit_radii_truncated, - max_bounded_engagement_deg:0.,bounded_advance_mm:bound, - boundary_underclearance_budget_mm:op.boundary_tolerance_mm, - seed_entry_policy:if op.pocket.entry.as_ref().is_some_and(|e|e.policy()!=crate::entry::EntryPolicy::Helix) {"whole-source admitted seed disks completely outside original stock permit air descent; any enclosed helix and full floor seed are explicit startup exceptions; subsequent approach/growth/clearing retains bounded engagement"} else if op.pocket.entry.is_some() {"descending helix and first full floor orbit are explicit startup exceptions; all subsequent approach/growth/clearing retains bounded engagement"} else {"plunge and first full orbit per connected guide component/depth are explicit engagement exceptions at plunge feed"}, - seed_orbits:0,controlled_orbits:0,bounded_advances:0,stock_clear_advances:0,turn_arcs:0,chord_fallbacks:0, - stock_query_work:0,stock_query_work_exhausted:false,motions:0,empty_cuts:None, - diagnostics:vec!["Orbit sweep radius exceeds actual tool radius; narrow features and corner rest remain explicit nominal residual, actual remaining stock is separately verified".into()], - }; - let phase = if graph.tours.is_empty() { - Phase::Done - } else { - Phase::Up - }; - let front = - (op.path_strategy == AdaptivePathStrategy::StockFront).then(|| FrontDriver::new(tool)); - if let Some(front) = &front { - report.front = Some(front.report.clone()); - report.diagnostics.push("Development stock_front: committed-sweep coverage and proven-clear re-entry; broad geometry, full dynamics and performance qualification remain open; unresolved steering/coverage stops with an error".into()); - } - let heights = crate::heights::Heights::resolve( - op.pocket.clearance_z_mm, - op.pocket.retract_z_mm, - op.pocket.feed_z_mm, - spec.max_mm[2].max(op.pocket.top_z_mm), - guard, - )?; - Ok(Self { - heights, - entry: Phase::Plunge, - stock_top: None, - front, - op, - guides, - tours: graph.tours, - helical, - spec: spec.clone(), - position: initial, - center: [0., 0.], - normal: [0., 0.], - r, - guard, - active_radius: radius, - disk_radius: 0., - entry_turn: None, - cleared_edges: HashMap::new(), - pass: 0, - component: 0, - guide: 0, - fraction: 0., - phase, - advance: None, - next_id: first_id, - generation: None, - report, - cutter_fits, - }) - } - pub fn report(&self) -> &AdaptiveReport { - &self.report - } - /// The rule of `crate::entry::UnenteredArea` for an `AdaptivePocket` - /// planned with orbits (#250): the orbit that opens each area is this - /// strategy's entry, so an area the cutter fits in and no orbit does - /// refuses the pocket, as does a region the cutter fits nowhere in. - /// (A roughing layer lists such areas in its report instead.) Parts of - /// an area an orbit does fit in that are too narrow for one are that - /// area's reported residual, as before. - pub(crate) fn refuse_unentered(&self) -> Result<(), String> { - let pocket = &self.op.pocket; - let name = format!("adaptive pocket {}", pocket.id); - if !self.cutter_fits { - return Err(crate::pocket::cutter_fits_nowhere( - &name, - self.r, - pocket.radial_allowance_mm, - )); - } - match self.report.unentered_areas.first() { - Some(area) => Err(area.message(&name)), - None => Ok(()), - } - } - /// For roughing: why this layer, having made no motion, left material - /// it was asked to cut (its first area no orbit fits in). - pub(crate) fn refusal(&self) -> Option { - if self.report.motions > 0 { - return None; - } - Some( - self.report - .unentered_areas - .first()? - .message(&self.op.pocket.id), - ) - } - /// Planning progress (#198): depth passes done of those planned. - pub fn progress(&self) -> crate::progress::Planned { - crate::progress::Planned::Layers { - done: self.pass, - total: self.report.depth_passes, - } - } - pub fn prefix_events(&self) -> Vec { - self.guides.prefix_events() - } - pub fn suffix_events(&self) -> Vec { - self.guides.suffix_events() - } - pub fn finish_report(&mut self, cancel: &impl CancelSignal) -> Result<(), String> { - #[cfg(feature = "profile-planning")] - let _profile = crate::planning_profile::span("adaptive.finish"); - if cancel.is_cancelled() { - return Err("adaptive report cancelled".into()); - } - if self.phase != Phase::Done { - return Err("drain adaptive motions before report".into()); - } - if self.report.geometric_residual_status != ResidualStatus::Pending { - return Ok(()); - } - let residual = self.guides.guide_residual( - self.r + self.report.min_orbit_radius_mm - self.op.boundary_tolerance_mm, - ); - if cancel.is_cancelled() { - return Err("adaptive report cancelled".into()); - } - match residual { - Ok(residual) => { - let (residual, prepared) = residual.into_parts(); - self.report.geometric_residual_area_mm2 = Some(prepared.summary().area_mm2); - self.report.geometric_residual = Some(residual.region); - self.report.geometric_residual_status = ResidualStatus::Estimated; - } - Err(e) => { - self.report.geometric_residual_status = ResidualStatus::Unknown; - self.report.diagnostics.push(e); - } - } - Ok(()) - } - fn sign(&self) -> f64 { - if self.op.clockwise { -1. } else { 1. } - } - fn normal_for(&self, d: Point) -> Point { - [self.sign() * d[1], -self.sign() * d[0]] - } - fn z(&self) -> f64 { - (self.op.pocket.top_z_mm - (self.pass + 1) as f64 * self.op.pocket.stepdown_mm) - .max(self.report.target_z_mm) - } - fn tip(&self, p: Point, n: Point, z: f64) -> Vec3 { - [ - p[0] + self.active_radius * n[0], - p[1] + self.active_radius * n[1], - z, - ] - } - fn emit( - &mut self, - curve: Curve, - kind: MoveKind, - entry: bool, - stock: &Stock, - ) -> Result, String> { - curve.prepare(self.op.pocket.tolerance_mm)?; - let motion = Motion { - id: self.next_id, - operation: self.op.pocket.id.clone(), - tool: self.op.pocket.tool.clone(), - kind, - curve, - feed_mm_min: if kind == MoveKind::Rapid { - None - } else { - Some(if entry { - self.op - .pocket - .entry - .as_ref() - .and_then(|e| e.feed_mm_min()) - .unwrap_or(self.op.pocket.plunge_mm_min) - } else { - self.op.pocket.feed_mm_min - }) - }, - }; - if let Some(front) = &mut self.front { - front.emitted(stock, &motion); - } - self.position = motion.curve.end(); - self.next_id += 1; - self.report.motions += 1; - self.generation = Some(stock.generation() + 1); - Ok(Some(motion)) - } - fn stock_clears_disk( - &mut self, - radius: f64, - stock: &Stock, - cancel: &impl CancelSignal, - ) -> Result { - let mut work = usize::MAX; - if work == 0 { - return Ok(false); - } - let start = [ - self.center[0] + radius * self.normal[0], - self.center[1] + radius * self.normal[1], - self.z(), - ]; - let query = Motion { - id: self.next_id, - operation: self.op.pocket.id.clone(), - tool: self.op.pocket.tool.clone(), - kind: MoveKind::Link, - curve: Curve::Arc { - start, - end: start, - center: [self.center[0], self.center[1], self.z()], - plane: Plane::Xy, - sweep_rad: self.sign() * TAU, - }, - feed_mm_min: Some(self.op.pocket.feed_mm_min), - }; - let before = work; - let clear = !stock.may_remove_material( - &query, - self.r, - 0., - self.op.pocket.tolerance_mm, - &mut work, - cancel, - )?; - self.report.stock_query_work += before - work; - self.report.stock_query_work_exhausted |= work == 0; - Ok(clear) - } - fn adjust_radius( - &mut self, - stock: &Stock, - cancel: &impl CancelSignal, - ) -> Result, String> { - let guide = self.tours[self.component][self.guide]; - let mut target = guide.radius; - if let Some(covered) = self.cleared_edges.get(&guide.edge) { - let smaller = covered - self.r - 2. * self.guard; - let parallel = guide.stroke.arc.is_none_or(|(c, sweep)| { - distance(guide.stroke.a, c) + smaller * self.sign() * sweep.signum() > self.guard - }); - if smaller > 4. * self.guard && parallel { - // A cleared return never needs a larger offset or a new orbit. - target = target.min(smaller).min(self.active_radius); - } - } - if (target - self.active_radius).abs() <= self.op.pocket.tolerance_mm { - return Ok(None); - } - let stock_clear = target > self.active_radius - && target + self.r > self.disk_radius - && self.stock_clears_disk(target, stock, cancel)?; - let next = - if target < self.active_radius || target + self.r <= self.disk_radius || stock_clear { - target - } else { - let half = self.op.max_engagement_deg.to_radians() / 2.; - let allowed = (self.disk_radius * self.disk_radius - - self.r * self.r * half.sin().powi(2)) - .max(0.) - .sqrt() - - self.r * half.cos() - - 2. * self.guard; - if allowed <= self.active_radius + self.guard { - return Err("adaptive radius growth below resolution".into()); - } - target.min(allowed) - }; - let grow = next + self.r > self.disk_radius && !stock_clear; - let delta = next - self.active_radius; - let end = [ - self.position[0] + delta * self.normal[0], - self.position[1] + delta * self.normal[1], - self.z(), - ]; - let result = self.emit( - Curve::Line { - start: self.position, - end, - }, - MoveKind::Link, - true, - stock, - )?; - self.active_radius = next; - if stock_clear { - self.disk_radius = self.r + next; - self.report.stock_clear_radius_changes += 1; - } - self.report.radius_changes += 1; - self.report.min_active_radius_mm = self.report.min_active_radius_mm.min(next); - if grow { - let q = next + self.guard; - let angle = 2. - * ((self.disk_radius * self.disk_radius - q * q - self.r * self.r) - / (2. * q * self.r)) - .clamp(-1., 1.) - .acos() - .to_degrees(); - self.report.max_bounded_engagement_deg = - self.report.max_bounded_engagement_deg.max(angle); - self.phase = Phase::RadiusOrbit; - } - Ok(result) - } - fn make_advance( - &mut self, - stock: &Stock, - cancel: &impl CancelSignal, - ) -> Result { - let guide = self.tours[self.component][self.guide]; - let s = guide.stroke; - let total = length(s); - let remaining = (1. - self.fraction) * total; - let half_budget = (guide.coverage - self.guard) / 2.; - let a = self.r + self.active_radius; - let half = self.op.max_engagement_deg.to_radians() / 2.; - let bound = (self.disk_radius * self.disk_radius - self.r * self.r * half.sin().powi(2)) - .max(0.) - .sqrt() - - self.r * half.cos() - - self.active_radius - - 2. * self.guard; - let mut step = bound.min(2. * (2. * a * half_budget - half_budget * half_budget).sqrt()); - if let Some((c, _)) = s.arc { - let rho = distance(s.a, c); - step = step - .min(2. * rho * (1. - (half_budget / rho).min(1.)).acos()) - .min(PI * rho); - } - let mut committed_tube = self - .cleared_edges - .get(&guide.edge) - .is_some_and(|radius| *radius >= a + self.guard); - let mut clear = committed_tube; - let mut query_work = usize::MAX; - // Local clearance subdivision creates guides shorter than a bounded - // cutting advance. They still need an air query, otherwise precleared - // stock acquires redundant cutting orbits at every short piece. - let query_short = self.op.local_orbit_tolerance_mm.is_some(); - if !clear && (remaining > step || query_short) && query_work > 0 { - let query = Motion { - id: self.next_id, - operation: self.op.pocket.id.clone(), - tool: self.op.pocket.tool.clone(), - kind: MoveKind::Link, - curve: match s.arc { - Some((c, sweep)) => Curve::Arc { - start: [self.center[0], self.center[1], self.z()], - end: [s.b[0], s.b[1], self.z()], - center: [c[0], c[1], self.z()], - plane: Plane::Xy, - sweep_rad: sweep * (1. - self.fraction), - }, - None => Curve::Line { - start: [self.center[0], self.center[1], self.z()], - end: [s.b[0], s.b[1], self.z()], - }, - }, - feed_mm_min: Some(self.op.pocket.feed_mm_min), - }; - let before = query_work; - clear = !stock.may_remove_material( - &query, - a, - 0., - self.op.pocket.tolerance_mm, - &mut query_work, - cancel, - )?; - self.report.stock_query_work += before - query_work; - self.report.stock_query_work_exhausted |= query_work == 0; - } - let bounded_step = step.min(remaining); - step = if clear { remaining } else { bounded_step }; - loop { - if step <= self.guard && step < remaining { - return Err("adaptive advance below resolution".into()); - } - let f = if step >= remaining { - 1. - } else { - self.fraction + step / total - }; - let center = point(s, f); - let mut n0 = self.normal_for(tangent(s, self.fraction)); - let mut n1 = self.normal_for(tangent(s, f)); - let mut chord = false; - let curve = if let Some((c, sweep)) = s.arc { - let rho = distance(s.a, c); - let offset = rho + self.active_radius * self.sign() * sweep.signum(); - if offset > self.guard { - Curve::Arc { - start: self.tip(self.center, n0, self.z()), - end: self.tip(center, n1, self.z()), - center: [c[0], c[1], self.z()], - plane: Plane::Xy, - sweep_rad: sweep * (f - self.fraction), - } - } else { - if !self - .guides - .link_geometry_fits_radius(self.center, center, a) - { - // The clear certificate covers the original guide tube, - // not this shortened chord. Restore both limits as well - // as revoking clear before retrying. - step = (step / 2.).min(bounded_step); - clear = false; - committed_tube = false; - continue; - } - if clear { - // An arc-tube certificate does not certify its chord tube. - clear = false; - committed_tube = false; - step = step.min(bounded_step); - continue; - } - let d = [ - (center[0] - self.center[0]) / distance(self.center, center), - (center[1] - self.center[1]) / distance(self.center, center), - ]; - n0 = self.normal_for(d); - n1 = n0; - chord = true; - Curve::Line { - start: self.tip(self.center, n0, self.z()), - end: self.tip(center, n1, self.z()), - } - } - } else { - Curve::Line { - start: self.tip(self.center, n0, self.z()), - end: self.tip(center, n1, self.z()), - } - }; - let q = self.active_radius + step + self.guard; - let angle = 2. - * ((self.disk_radius * self.disk_radius - q * q - self.r * self.r) - / (2. * q * self.r)) - .clamp(-1., 1.) - .acos() - .to_degrees(); - return Ok(Advance { - curve, - fraction: f, - center, - normal: n1, - clear, - committed_tube, - angle, - chord, - }); - } - } - pub fn next_motion_with_stock( - &mut self, - stock: &Stock, - cancel: &impl CancelSignal, - ) -> Result, String> { - let result = self.next_planned(stock, cancel)?; - if let (Some(bound), Some(motion)) = (&self.stock_top, &result) { - bound.admit(motion)?; - } - Ok(result) - } - fn next_planned( - &mut self, - stock: &Stock, - cancel: &impl CancelSignal, - ) -> Result, String> { - if let Some(bound) = &mut self.stock_top { - bound.validate(stock, cancel)?; - } - if stock.spec() != &self.spec - || stock.generation() == u64::MAX - || self.generation.is_some_and(|g| g != stock.generation()) - { - return Err( - "commit preceding adaptive motion to matching stock before planning".into(), - ); - } - if let Some(front) = &mut self.front { - front.synchronize(stock, self.r, self.op.pocket.tolerance_mm, cancel)?; - self.report.max_bounded_engagement_deg = self - .report - .max_bounded_engagement_deg - .max(front.report.max_bounded_engagement_deg); - self.report.front = Some(front.report.clone()); - } - loop { - if cancel.is_cancelled() { - return Err("adaptive planning cancelled".into()); - } - match self.phase { - Phase::Front => { - let prototype = Motion { - id: self.next_id, - operation: self.op.pocket.id.clone(), - tool: self.op.pocket.tool.clone(), - kind: MoveKind::Cut, - curve: Curve::Line { - start: self.position, - end: [ - self.position[0] + self.r, - self.position[1], - self.position[2], - ], - }, - feed_mm_min: Some(self.op.pocket.feed_mm_min), - }; - let floor = self.z(); - let front = self.front.as_mut().ok_or("missing stock-front driver")?; - front.begin_component( - &self.guides, - self.center, - (self.pass, self.component), - floor, - self.r, - self.report.min_orbit_radius_mm, - self.r + self.report.min_orbit_radius_mm - self.op.boundary_tolerance_mm, - self.op.pocket.tolerance_mm, - self.op.boundary_tolerance_mm, - )?; - let result = front.next( - &self.guides, - stock, - self.position, - self.r, - self.report.min_orbit_radius_mm, - self.op.max_engagement_deg, - self.op.cutting_sense.unwrap_or(CuttingSense::Climb) == CuttingSense::Climb, - prototype, - self.op.pocket.tolerance_mm, - crate::adaptive_front::LinkHeights { - retract: self.heights.retract, - feed: self.heights.feed, - }, - self.op.pocket.plunge_mm_min, - cancel, - ); - self.report.max_bounded_engagement_deg = self - .report - .max_bounded_engagement_deg - .max(front.report.max_bounded_engagement_deg); - self.report.front = Some(front.report.clone()); - let Some(motion) = result? else { - self.phase = Phase::Retract; - continue; - }; - return self.emit( - motion.curve, - motion.kind, - motion.kind == MoveKind::Plunge, - stock, - ); - } - Phase::Done => return Ok(None), - Phase::Up => { - let end = [ - self.position[0], - self.position[1], - self.op.pocket.clearance_z_mm, - ]; - self.phase = Phase::Across; - if end != self.position { - return self.emit( - Curve::Line { - start: self.position, - end, - }, - MoveKind::Rapid, - false, - stock, - ); - } - } - Phase::Across => { - let first = self.tours[self.component][0]; - let s = first.stroke; - self.active_radius = self - .helical - .as_ref() - .map_or(first.radius, |locations| locations[self.component].radius); - self.disk_radius = 0.; - self.report.min_active_radius_mm = - self.report.min_active_radius_mm.min(self.active_radius); - self.center = s.a; - self.normal = self.normal_for(tangent(s, 0.)); - // Travel at the current height: clearance first, then - // the retract height between regions. - let end = self.tip(self.center, self.normal, self.position[2]); - self.phase = Phase::Descend; - self.entry = if self - .helical - .as_ref() - .is_some_and(|locations| !locations[self.component].stock_edge) - { - Phase::EntryTop - } else { - Phase::Plunge - }; - if end != self.position { - return self.emit( - Curve::Line { - start: self.position, - end, - }, - MoveKind::Rapid, - false, - stock, - ); - } - } - Phase::Descend => { - self.phase = self.entry; - let end = self.tip(self.center, self.normal, self.heights.feed); - if end[2] < self.position[2] { - return self.emit( - Curve::Line { - start: self.position, - end, - }, - MoveKind::Rapid, - false, - stock, - ); - } - } - Phase::Plunge => { - let end = self.tip(self.center, self.normal, self.z()); - self.phase = Phase::Seed; - let result = self.emit( - Curve::Line { - start: self.position, - end, - }, - MoveKind::Plunge, - true, - stock, - )?; - if self - .helical - .as_ref() - .is_some_and(|locations| locations[self.component].stock_edge) - { - self.report.stock_edge_entries += 1; - } - return Ok(result); - } - Phase::EntryTop => { - let end = self.tip(self.center, self.normal, self.op.pocket.top_z_mm); - self.phase = Phase::EntryHelix; - return self.emit( - Curve::Line { - start: self.position, - end, - }, - MoveKind::Plunge, - true, - stock, - ); - } - Phase::EntryHelix => { - let h = self - .op - .pocket - .entry - .as_ref() - .and_then(|e| e.helix()) - .ok_or("missing helical entry")?; - let turns = h.turns(self.active_radius, self.op.pocket.top_z_mm - self.z())?; - let default_clockwise = if self.front.is_some() { - self.op.cutting_sense.unwrap_or(CuttingSense::Climb) - == CuttingSense::Conventional - } else { - self.op.clockwise - }; - let sweep = if h.clockwise.unwrap_or(default_clockwise) { - -TAU - } else { - TAU - }; - // One motion per full turn: every controller can represent - // a <=one-turn helix as a single G2/G3 block. - let (done, total) = self.entry_turn.unwrap_or((0, turns)); - let top = self.op.pocket.top_z_mm; - let bottom = self.z(); - let end_z = if done + 1 == total { - bottom - } else { - top - (top - bottom) * (done + 1) as f64 / total as f64 - }; - let curve = Curve::Helix { - start: self.position, - end: self.tip(self.center, self.normal, end_z), - center: [self.center[0], self.center[1], self.position[2]], - plane: Plane::Xy, - sweep_rad: sweep, - }; - let result = self.emit(curve, MoveKind::Lead, true, stock)?; - if done + 1 < total { - self.entry_turn = Some((done + 1, total)); - return Ok(result); - } - self.entry_turn = None; - self.report.helical_entries += 1; - self.report.entry_turns += total; - self.phase = Phase::Seed; - return Ok(result); - } - Phase::Seed | Phase::Orbit | Phase::RadiusOrbit => { - let seed = self.phase == Phase::Seed; - if seed - && self.front.is_none() - && self.stock_clears_disk(self.active_radius, stock, cancel)? - { - self.disk_radius = self.r + self.active_radius; - self.report.omitted_seed_orbits += 1; - self.phase = Phase::Turn; - continue; - } - let growth = self.phase == Phase::RadiusOrbit; - let z = self.z(); - let sign = self.sign(); - if !seed && let Some(proof) = &mut self.report.empty_cuts { - // radius<=r is enforced at admission: the full circle - // swept by the cutter covers the entire support disk. - // Query canonical active radius, not a sampled annulus. - let start = [ - self.center[0] + self.active_radius * self.normal[0], - self.center[1] + self.active_radius * self.normal[1], - z, - ]; - let support = Motion { - id: self.next_id, - operation: self.op.pocket.id.clone(), - tool: self.op.pocket.tool.clone(), - kind: MoveKind::Cut, - curve: Curve::Arc { - start, - end: start, - center: [self.center[0], self.center[1], z], - plane: Plane::Xy, - sweep_rad: sign * TAU, - }, - feed_mm_min: Some(self.op.pocket.feed_mm_min), - }; - if proof.may_omit( - stock, - &support, - self.r, - self.op.pocket.tolerance_mm, - cancel, - )? { - self.disk_radius = self.r + self.active_radius; - self.phase = Phase::Turn; - // Closed orbit ends at its start: actual pose/IDs/ - // generation do not advance for the omitted move. - continue; - } - } - let curve = Curve::Arc { - start: self.position, - end: self.position, - center: [self.center[0], self.center[1], self.z()], - plane: Plane::Xy, - sweep_rad: if seed && self.front.is_some() { - if self.op.cutting_sense.unwrap_or(CuttingSense::Climb) - == CuttingSense::Climb - { - TAU - } else { - -TAU - } - } else if seed { - self.op - .pocket - .entry - .as_ref() - .and_then(|e| e.helix()?.clockwise) - .map_or(self.sign(), |clockwise| if clockwise { -1. } else { 1. }) - * TAU - } else { - self.sign() * TAU - }, - }; - let result = self.emit(curve, MoveKind::Cut, seed, stock)?; - if seed { - self.report.seed_orbits += 1; - } else { - self.report.controlled_orbits += 1; - } - self.disk_radius = self.r + self.active_radius; - self.report.min_cutting_orbit_radius_mm = Some( - self.report - .min_cutting_orbit_radius_mm - .map_or(self.active_radius, |old| old.min(self.active_radius)), - ); - if growth { - self.report.radius_growth_orbits += 1; - } - self.phase = if seed && self.front.is_some() { - Phase::Front - } else { - Phase::Turn - }; - return Ok(result); - } - Phase::Turn => { - while self.fraction == 1. { - if self.report.min_orbit_radius_mm < self.report.orbit_radius_mm { - let guide = self.tours[self.component][self.guide]; - let radius = self.r + self.active_radius - guide.coverage - self.guard; - self.cleared_edges - .entry(guide.edge) - .and_modify(|old| *old = old.max(radius)) - .or_insert(radius); - } - self.guide += 1; - self.fraction = 0.; - } - if self.guide == self.tours[self.component].len() { - self.phase = Phase::Retract; - continue; - } - if self.advance.is_none() { - if let Some(motion) = self.adjust_radius(stock, cancel)? { - return Ok(Some(motion)); - } - self.advance = Some(self.make_advance(stock, cancel)?); - } - let end = self.advance.as_ref().unwrap().curve.start(); - self.phase = Phase::Advance; - if distance([self.position[0], self.position[1]], [end[0], end[1]]) - > self.op.pocket.tolerance_mm - { - let old = [ - self.position[0] - self.center[0], - self.position[1] - self.center[1], - ]; - let next = [end[0] - self.center[0], end[1] - self.center[1]]; - let angle = (old[0] * next[1] - old[1] * next[0]) - .atan2(old[0] * next[0] + old[1] * next[1]); - let sweep = if self.sign() > 0. { - angle.rem_euclid(TAU) - } else { - -(-angle).rem_euclid(TAU) - }; - let result = self.emit( - Curve::Arc { - start: self.position, - end, - center: [self.center[0], self.center[1], self.z()], - plane: Plane::Xy, - sweep_rad: sweep, - }, - MoveKind::Link, - false, - stock, - )?; - self.report.turn_arcs += 1; - return Ok(result); - } - } - Phase::Advance => { - let next = self.advance.take().unwrap(); - let mut curve = next.curve; - match &mut curve { - Curve::Line { start, .. } | Curve::Arc { start, .. } => { - *start = self.position - } - _ => unreachable!(), - } - let result = self.emit(curve, MoveKind::Link, false, stock)?; - if next.clear { - if next.committed_tube { - self.report.committed_tube_advances += 1; - } else { - self.report.stock_clear_advances += 1; - } - self.report.omitted_endpoint_orbits += 1; - } else { - self.report.bounded_advances += 1; - self.report.max_bounded_engagement_deg = - self.report.max_bounded_engagement_deg.max(next.angle); - } - self.report.chord_fallbacks += usize::from(next.chord); - self.fraction = next.fraction; - self.center = next.center; - self.normal = next.normal; - self.phase = if next.clear { - Phase::Turn - } else { - Phase::Orbit - }; - if next.clear { - // A complete committed guide also proved both endpoint - // disks before its tube was contracted for scallops. - // Retain that larger endpoint witness on a cached return. - self.disk_radius = if next.committed_tube { - let guide = self.tours[self.component][self.guide]; - self.cleared_edges[&guide.edge] + guide.coverage + self.guard - } else { - self.r + self.active_radius - }; - } - return Ok(result); - } - Phase::Retract => { - // Leave the cut at feed up to the feed height. - let end = [self.position[0], self.position[1], self.heights.feed]; - self.component += 1; - if self.component == self.tours.len() { - self.component = 0; - self.pass += 1; - self.cleared_edges.clear(); - } - self.guide = 0; - self.fraction = 0.; - self.phase = Phase::Rise; - if end[2] > self.position[2] { - return self.emit( - Curve::Line { - start: self.position, - end, - }, - MoveKind::Retract, - false, - stock, - ); - } - } - Phase::Rise => { - // Rapid to the retract height, or clearance at the end. - let done = self.pass == self.report.depth_passes; - let z = if done { - self.heights.clearance - } else { - self.heights.retract - }; - let end = [self.position[0], self.position[1], z.max(self.position[2])]; - self.phase = if done { Phase::Done } else { Phase::Across }; - if end != self.position { - return self.emit( - Curve::Line { - start: self.position, - end, - }, - MoveKind::Rapid, - false, - stock, - ); - } - } - } - } - } -} diff --git a/src/adaptive_front.rs b/src/adaptive_front.rs deleted file mode 100644 index f09fa69f..00000000 --- a/src/adaptive_front.rs +++ /dev/null @@ -1,4428 +0,0 @@ -//! Native stock-front steering under development. Admission is continuous; -//! sampled potential-contact ranking is deliberately only a heuristic. -use crate::{ - Point, - engagement::{ClearedSweep, EngagementOptions, EngagementScene, EngagementStatus}, - geometry::Bounds, - motion::{Curve, Motion, MoveKind, Plane, Vec3}, - planar::PreparedRegion, - pocket::{GuideTubeApproval, PocketPlan, Stroke}, - stock::{CancelSignal, Stock}, - tool::ToolAssembly, -}; -use serde::Serialize; -use std::{ - collections::{HashSet, VecDeque}, - f64::consts::{PI, TAU}, -}; -mod peeling; -use peeling::PeelContour; -mod convex; -use convex::{ConvexContour, ConvexFront, ConvexMaterial}; -mod channel; -use channel::{ChannelFront, ChannelRecipe}; -mod linear_channel; -use linear_channel::{LinearChannel, LinearRecipe}; -mod enclosed; -use enclosed::{EnclosedContour, EnclosedFront}; - -enum BulkContour { - Linear(LinearRecipe), - Channel(ChannelRecipe), - Rectangle(PeelContour), - Convex(ConvexContour), - Enclosed(EnclosedContour), -} -impl BulkContour { - fn expects(&self, motion: &Motion, radius: f64, tolerance: f64) -> Result { - match self { - Self::Linear(r) => r.expects(motion, radius, tolerance), - Self::Channel(r) => r.expects(motion, radius, tolerance), - Self::Rectangle(r) => r.expects(motion, radius, tolerance), - Self::Convex(r) => r.expects(motion, radius, tolerance), - Self::Enclosed(r) => r.expects(motion, radius, tolerance), - } - } - fn certified_angle(&self, motion: &Motion) -> Option { - match self { - Self::Linear(r) => r.certified_angle(motion), - Self::Channel(r) => r.certified_angle(motion), - Self::Convex(r) => r.certified_angle(motion), - Self::Enclosed(r) => r.certified_angle(motion), - Self::Rectangle(r) => r.certified_angle(motion), - } - } -} - -#[derive(Clone, Debug, Default, Serialize)] -pub struct FrontReport { - pub committed_supports: usize, - pub front_moves: usize, - /// Positive sampled potential among locally ranked candidates, not a - /// certificate of actual material removal. - pub productive_candidates: usize, - pub navigation_moves: usize, - /// Cut/lead moves in fixed contour recipes. They are not ranked and make - /// no claim about positive removal or known-air travel. - pub unranked_contour_moves: usize, - pub candidate_tests: usize, - pub source_rejections: usize, - pub recovery_rejections: usize, - /// Ranked admission uses the joint contact/side proof: its refusals. - pub joint_rejections: usize, - pub max_bounded_engagement_deg: f64, - pub coverage_complete: bool, - pub completed_components: usize, - pub coverage_goals: usize, - pub coverage_tiles: usize, - pub coverage_cache_hits: usize, - pub coverage_reused_branches: usize, - pub coverage_envelopes: usize, - pub reentries: usize, - pub reentry_moves: usize, - pub reentry_budget_stops: usize, - pub cleared_reentry_links: usize, - pub cleared_link_work: u64, - pub cleared_link_budget_stops: usize, - pub steering_budget_stops: usize, - pub bulk_contours: usize, - pub bulk_committed_moves: usize, - pub bulk_abandoned: usize, - pub bulk_material_bounds_mm: Option<[Point; 2]>, - pub bulk_material_floor_mm: Option, - pub convex_contours: usize, - pub convex_resets: usize, - pub enclosed_contours: usize, - pub channel_contours: usize, - pub channel_committed_moves: usize, - pub channel_resets: usize, - pub linear_contours: usize, - pub linear_committed_moves: usize, - pub linear_resets: usize, - pub enclosed_resets: usize, - pub enclosed_committed_moves: usize, - pub status: &'static str, -} - -type RankedFrontMove = (f64, Motion, f64, bool, u8); - -// Coarse generator: 2 initial +17 grid +8 local +2 radius limits +3 goal hints, -// each at8 lengths. These are proposals, never emitted/cleared motion history. -const MAX_FRONT_PROPOSALS: usize = 32 * 8; - -struct FrontProposal { - score: f64, - motion: Motion, - novelty: bool, - tier: u8, -} - -struct RefinedAdvance { - best: Option, - budget_stopped: bool, -} - -pub(crate) struct FrontDriver { - scene: Option, - tool: ToolAssembly, - pending: Option<(u64, Motion)>, - identity: Option, - heading: Option, - curvature: f64, - navigation_steps: usize, - progress_epoch: usize, - pending_novelty: bool, - coverage: Option, - initial_coverage_checked: bool, - goal: Option, - transfer: VecDeque, - bulk_enabled: bool, - bulk_used_in_component: bool, - bulk: Option, - source_approvals: Vec, - convex_front: Option, - enclosed_front: Option, - channel_front: Option, - linear_front: Option, - linear_rails: Option>, - last_floor_circle: Option, - pending_heading: Option<(u64, f64)>, - visited: HashSet<(u64, u64, u8, usize)>, - pub report: FrontReport, -} -impl FrontDriver { - pub fn new(tool: &ToolAssembly) -> Self { - Self { - scene: None, - tool: tool.clone(), - pending: None, - identity: None, - heading: None, - curvature: 0., - navigation_steps: 0, - progress_epoch: 0, - pending_novelty: false, - coverage: None, - initial_coverage_checked: false, - goal: None, - transfer: VecDeque::new(), - bulk_enabled: true, - bulk_used_in_component: false, - bulk: None, - source_approvals: Vec::new(), - convex_front: None, - enclosed_front: None, - channel_front: None, - linear_front: None, - linear_rails: None, - last_floor_circle: None, - pending_heading: None, - visited: HashSet::new(), - report: FrontReport { - status: "startup", - ..Default::default() - }, - } - } - /// Called before any planner mutation. Matching generation alone is not - /// enough: an unrelated/partial/snapshot-restored transaction cannot clear - /// the pending geometric sweep. A failed synchronization retains pending. - pub fn synchronize( - &mut self, - stock: &Stock, - radius: f64, - tolerance: f64, - cancel: &impl CancelSignal, - ) -> Result<(), String> { - #[cfg(feature = "profile-planning")] - let _profile = crate::planning_profile::span("front.synchronize"); - if cancel.is_cancelled() { - return Err("stock-front planning cancelled".into()); - } - stock.request_sweep_receipts(); - if let Some((base, pending)) = &self.pending { - let receipt = stock.last_sweep_receipt().ok_or("stock-front needs the native committed preceding sweep; snapshot/wire/undo is not sweep authority")?; - if receipt.base_identity != *base - || !receipt.motion.commits(pending) - || receipt.tool != self.tool - || receipt.fraction != 1. - || receipt.tolerance_mm > tolerance - { - return Err( - "stock-front preceding motion/tool/fraction/stock identity mismatch".into(), - ); - } - let bulk_commit = self - .bulk - .as_ref() - .map(|b| b.expects(pending, radius, receipt.tolerance_mm)) - .transpose()? - .unwrap_or(false); - self.last_floor_circle = match &pending.curve { - Curve::Arc { - start, - end, - plane: Plane::Xy, - sweep_rad, - .. - } if pending.kind == MoveKind::Cut && start == end && sweep_rad.abs() == TAU => { - Some(pending.clone()) - } - _ => None, - }; - if pending.kind != MoveKind::Rapid - && pending.curve.start()[2] == pending.curve.end()[2] - && matches!( - pending.curve, - Curve::Line { .. } - | Curve::Arc { - plane: Plane::Xy, - .. - } - ) - { - let support = ClearedSweep::from_motion(pending, radius, tolerance)?; - self.scene - .as_mut() - .ok_or("stock-front missing scene")? - .append(support)?; - self.report.committed_supports += 1; - self.heading = Some(tangent(&pending.curve, 1.)); - self.curvature = match pending.curve { - Curve::Arc { - start, - center, - sweep_rad, - .. - } => sweep_rad.signum() / (start[0] - center[0]).hypot(start[1] - center[1]), - _ => 0., - }; - } - if bulk_commit { - if matches!(self.bulk, Some(BulkContour::Linear(_))) { - self.report.linear_committed_moves += 1; - } else if matches!(self.bulk, Some(BulkContour::Channel(_))) { - self.report.channel_committed_moves += 1; - } else if matches!(self.bulk, Some(BulkContour::Enclosed(_))) { - self.report.enclosed_committed_moves += 1; - } else { - self.report.bulk_committed_moves += 1; - } - let completed = match self.bulk.as_mut().unwrap() { - BulkContour::Linear(recipe) => { - if recipe.advance() { - self.linear_front - .as_mut() - .ok_or("linear channel lost owner")? - .committed(recipe)?; - self.report.linear_contours += 1; - self.bulk = None; - } - None - } - BulkContour::Channel(recipe) => { - if recipe.advance() { - self.channel_front - .as_mut() - .ok_or("channel lost its owner")? - .committed(recipe)?; - self.report.channel_contours += 1; - self.bulk_used_in_component = true; - self.bulk = None; - } - None - } - BulkContour::Enclosed(recipe) => { - if recipe.advance() { - let owner = self - .enclosed_front - .as_mut() - .ok_or("enclosed contour lost owner")?; - owner.committed(recipe)?; - let coverage = self - .coverage - .as_mut() - .ok_or("enclosed contour has no coverage domain")?; - coverage.enclosed_complete = owner.covers_offset( - coverage.inflation, - coverage.domain.definition().boundary_error_mm - + coverage.centres.definition().boundary_error_mm, - coverage.floor, - radius, - tolerance, - ); - self.report.enclosed_contours += 1; - self.bulk = None; - } - None - } - BulkContour::Rectangle(recipe) => recipe.committed(), - BulkContour::Convex(recipe) => { - if recipe.advance() { - let owner = self - .convex_front - .as_mut() - .ok_or("convex contour lost its envelope owner")?; - owner.committed(recipe)?; - self.coverage - .as_mut() - .ok_or("convex contour has no coverage domain")? - .material = owner.material_envelope(); - self.report.convex_contours += 1; - Some(recipe.envelope()) - } else { - None - } - } - }; - if let Some((mut bounds, floor)) = completed { - let old = self.scene.as_ref().unwrap().material_bounds(floor); - for k in 0..2 { - bounds[0][k] = bounds[0][k].max(old[0][k]); - bounds[1][k] = bounds[1][k].min(old[1][k]); - } - self.scene - .as_mut() - .unwrap() - .append_rectangular_shell(bounds, floor)?; - self.bulk = None; - self.report.bulk_contours += 1; - self.bulk_used_in_component = true; - self.report.bulk_material_bounds_mm = Some(bounds); - self.report.bulk_material_floor_mm = Some(floor); - } - if self.bulk.is_none() { - self.source_approvals.clear(); - // A fully committed envelope starts a fresh local search - // if contour generation later stops. Sampled novelty on - // individual recipe curves does not control this state. - self.navigation_steps = 0; - self.progress_epoch += 1; - self.visited.clear(); - } - } - if let Some((id, heading)) = self.pending_heading { - if pending.id != id { - return Err("stock-front re-entry commit ID mismatch".into()); - } - self.heading = Some(heading); - self.curvature = 0.; - self.navigation_steps = 0; - self.pending_heading = None; - } - if self.pending_novelty { - self.progress_epoch += 1; - self.visited.clear(); - self.pending_novelty = false; - } - self.pending = None; - } else if self.identity.is_some_and(|id| id != stock.identity()) { - return Err("stock-front stock changed without the pending motion".into()); - } - if self.scene.is_none() { - // Only actual native full flat sweeps carry across operations. - // Snapshot cells and a matching nominal generation are not sweeps. - self.scene = Some(EngagementScene::new_with_cancel( - stock.spec().clone(), - stock.committed_clearance(tolerance, cancel)?, - cancel, - )?); - } - self.identity = Some(stock.identity()); - Ok(()) - } - pub fn emitted(&mut self, stock: &Stock, motion: &Motion) { - self.pending = Some((stock.identity(), motion.clone())); - } - #[allow(clippy::too_many_arguments)] - pub fn begin_component( - &mut self, - source: &PocketPlan, - seed: Point, - key: (usize, usize), - floor: f64, - cutter_radius: f64, - minimum_radius: f64, - inflation: f64, - tolerance: f64, - boundary_budget: f64, - ) -> Result<(), String> { - if self.coverage.as_ref().is_some_and(|c| c.key == key) { - return Ok(()); - } - if !self.transfer.is_empty() || self.pending.is_some() { - return Err("stock-front component change has pending motion".into()); - } - let (centres, domain) = source.front_component_region(seed, inflation)?; - self.enclosed_front = self.last_floor_circle.as_ref().and_then(|motion| { - EnclosedFront::new( - centres.definition(), - motion, - cutter_radius, - minimum_radius, - tolerance, - ) - }); - self.channel_front = self.last_floor_circle.as_ref().and_then(|motion| { - let channel = ChannelFront::new( - centres.definition(), - motion, - cutter_radius, - minimum_radius, - tolerance, - )?; - let (rail, radius) = channel.rail_tube(); - source.guide_tube_fits(rail, radius).then_some(channel) - }); - self.coverage = Some(FrontCoverage::new( - domain, - seed, - key, - floor, - tolerance, - boundary_budget, - self.curvature.recip().abs(), - centres, - inflation, - )?); - self.goal = None; - self.initial_coverage_checked = false; - self.linear_front = None; - self.linear_rails = None; - self.visited.clear(); - self.navigation_steps = 0; - self.report.coverage_complete = false; - self.bulk_enabled = true; - self.bulk_used_in_component = false; - self.bulk = None; - self.source_approvals.clear(); - let material = self - .scene - .as_ref() - .ok_or("stock-front component has no committed scene")? - .material_bounds(floor); - self.convex_front = ConvexFront::new( - source.front_obstacles(seed)?, - material, - floor, - source.cutter_axis_clearance(cutter_radius) + 32. * tolerance, - tolerance, - ); - Ok(()) - } - #[allow(clippy::too_many_arguments)] - fn prepare_convex( - &mut self, - source: &PocketPlan, - position: Vec3, - radius: f64, - minimum_radius: f64, - max_angle: f64, - boundary_budget: f64, - tolerance: f64, - right: bool, - prototype: &Motion, - clearance: LinkHeights, - plunge_feed: f64, - cancel: &impl CancelSignal, - ) -> Result { - let Some(front) = self.convex_front.as_ref() else { - return Ok(false); - }; - let had_commit = front.has_commit(); - let recipe = front.prepare( - position, - radius, - minimum_radius, - max_angle, - boundary_budget, - tolerance, - right, - cancel, - )?; - let Some(recipe) = recipe else { - self.convex_front = None; - if had_commit { - self.bulk_enabled = false; - return Ok(true); - } - return Ok(false); - }; - let mut approvals = Vec::new(); - for curve in recipe.leads.iter().chain(&recipe.contour) { - if cancel.is_cancelled() { - return Err("convex source admission cancelled".into()); - } - self.report.candidate_tests += 1; - let Some(approval) = source.approve_guide_tube(curve, radius) else { - self.report.source_rejections += 1; - self.convex_front = None; - if had_commit { - self.bulk_enabled = false; - return Ok(true); - } - return Ok(false); - }; - approvals.push(approval); - } - let mut queue = VecDeque::new(); - if recipe.reset { - let p = [recipe.start[0], recipe.start[1]]; - // The reset disk's whole-empty premise is proved by the current - // convex envelope; its entire source tube is still independently fit. - if !source.link_geometry_fits_radius(p, p, radius + 64. * tolerance) { - self.convex_front = None; - return Ok(false); - } - push_relink( - &mut queue, - position, - recipe.start, - clearance, - prototype.feed_mm_min, - plunge_feed, - Some(recipe.heading), - ); - self.report.convex_resets += 1; - self.report.reentries += 1; - } else if recipe.start != position { - return Err("convex continuing seam mismatch".into()); - } - for curve in &recipe.leads { - queue.push_back(Transfer { - curve: curve.clone(), - kind: MoveKind::Lead, - feed: prototype.feed_mm_min, - heading: None, - }); - } - for curve in &recipe.contour { - queue.push_back(Transfer { - curve: curve.clone(), - kind: MoveKind::Cut, - feed: prototype.feed_mm_min, - heading: None, - }); - } - self.bulk = Some(BulkContour::Convex(recipe)); - self.transfer = queue; - self.source_approvals = approvals; - self.report.status = "convex_contour"; - Ok(true) - } - #[allow(clippy::too_many_arguments)] - fn prepare_enclosed( - &mut self, - source: &PocketPlan, - position: Vec3, - radius: f64, - max_angle: f64, - tolerance: f64, - right: bool, - prototype: &Motion, - clearance: LinkHeights, - plunge_feed: f64, - cancel: &impl CancelSignal, - ) -> Result<(), String> { - let recipe = self - .enclosed_front - .as_ref() - .unwrap() - .prepare(position, max_angle, tolerance, right, cancel)?; - let Some(recipe) = recipe else { - self.enclosed_front = None; - self.bulk_enabled = false; - return Ok(()); - }; - let mut approvals = Vec::new(); - for curve in recipe.leads.iter().chain(&recipe.contour) { - if cancel.is_cancelled() { - return Err("enclosed source admission cancelled".into()); - } - self.report.candidate_tests += 1; - let Some(approval) = source.approve_guide_tube(curve, radius) else { - self.report.source_rejections += 1; - self.enclosed_front = None; - self.bulk_enabled = false; - return Ok(()); - }; - approvals.push(approval); - } - let mut queue = VecDeque::new(); - if recipe.reset { - let p = [recipe.start[0], recipe.start[1]]; - let pad = 64. * tolerance; - if !source.link_geometry_fits_radius(p, p, radius + pad) - || !self - .scene - .as_ref() - .ok_or("enclosed entry has no scene")? - .clear_disk( - p, - radius + pad, - position[2], - tolerance, - &mut 2_000_000, - cancel, - )? - { - self.enclosed_front = None; - self.bulk_enabled = false; - return Ok(()); - } - push_relink( - &mut queue, - position, - recipe.start, - clearance, - prototype.feed_mm_min, - plunge_feed, - Some(recipe.heading), - ); - self.report.enclosed_resets += 1; - self.report.reentries += 1; - } - for curve in &recipe.leads { - queue.push_back(Transfer { - curve: curve.clone(), - kind: MoveKind::Lead, - feed: prototype.feed_mm_min, - heading: None, - }); - } - for curve in &recipe.contour { - queue.push_back(Transfer { - curve: curve.clone(), - kind: MoveKind::Cut, - feed: prototype.feed_mm_min, - heading: None, - }); - } - if cancel.is_cancelled() { - return Err("enclosed contour cancelled".into()); - } - self.bulk = Some(BulkContour::Enclosed(recipe)); - self.transfer = queue; - self.source_approvals = approvals; - self.report.status = "enclosed_contour"; - Ok(()) - } - #[allow(clippy::too_many_arguments)] - fn prepare_bulk( - &mut self, - source: &PocketPlan, - _stock: &Stock, - position: Vec3, - radius: f64, - minimum_radius: f64, - max_angle: f64, - right: bool, - prototype: &Motion, - tolerance: f64, - clearance: LinkHeights, - plunge_feed: f64, - cancel: &impl CancelSignal, - ) -> Result<(), String> { - #[cfg(feature = "profile-planning")] - let _profile = crate::planning_profile::span("front.bulk"); - if self.bulk.is_some() { - return Err("stock-front contour needs its preceding full commit".into()); - } - self.source_approvals.clear(); - if cancel.is_cancelled() { - return Err("stock-front contour preparation cancelled".into()); - } - let boundary_budget = self - .coverage - .as_ref() - .ok_or("stock-front contour has no coverage domain")? - .goal_pad - * 4.; - if let Some(channel) = &self.channel_front { - let recipe = match channel.prepare(position, max_angle, tolerance, right, cancel)? { - Some(recipe) => Some(recipe), - None => channel.prepare_inner( - max_angle, - tolerance, - right, - |stroke| source.guide_tube_fits(stroke, radius), - cancel, - )?, - }; - if let Some(recipe) = recipe { - let mut approvals = Vec::new(); - for curve in &recipe.curves { - if cancel.is_cancelled() { - return Err("channel source admission cancelled".into()); - } - self.report.candidate_tests += 1; - let Some(approval) = source.approve_guide_tube(curve, radius) else { - self.report.source_rejections += 1; - self.channel_front = None; - self.bulk_enabled = false; - return Ok(()); - }; - approvals.push(approval); - } - let mut queue = VecDeque::new(); - if recipe.reset { - let start = recipe.curves[0].start(); - let p = [start[0], start[1]]; - let pad = 64. * tolerance; - if !source.link_geometry_fits_radius(p, p, radius + pad) - || !self - .scene - .as_ref() - .ok_or("channel entry has no scene")? - .clear_disk( - p, - radius + pad, - position[2], - tolerance, - &mut 2_000_000, - cancel, - )? - { - self.channel_front = None; - self.bulk_enabled = false; - return Ok(()); - } - push_relink( - &mut queue, - position, - start, - clearance, - prototype.feed_mm_min, - plunge_feed, - Some(tangent(&recipe.curves[0], 0.)), - ); - self.report.channel_resets += 1; - self.report.reentries += 1; - } - queue.extend(recipe.curves.iter().map(|curve| Transfer { - curve: curve.clone(), - kind: MoveKind::Cut, - feed: prototype.feed_mm_min, - heading: None, - })); - self.transfer = queue; - self.source_approvals = approvals; - self.bulk = Some(BulkContour::Channel(recipe)); - self.report.status = "channel_contour"; - } else { - self.channel_front = None; - self.bulk_enabled = false; - } - return Ok(()); - } - if self.enclosed_front.is_some() { - return self.prepare_enclosed( - source, - position, - radius, - max_angle, - tolerance, - right, - prototype, - clearance, - plunge_feed, - cancel, - ); - } - let scene = self - .scene - .as_ref() - .ok_or("stock-front contour has no committed scene")?; - let material = scene.material_bounds(position[2]); - let continuing_convex = self - .convex_front - .as_ref() - .is_some_and(ConvexFront::has_commit); - // Keep the outer contours close to rectangular stock. Once peeling can - // no longer advance, switch to the retained-part hull using only the - // material envelope established by completed native recipes. - // The fitted rectangle performs a bounded search. Retain only actual - // successful proofs temporarily, then prune to the selected recipe. - let mut rectangle_approvals = Vec::new(); - let rectangle = if continuing_convex { - None - } else { - PeelContour::prepare_fitted( - material, - position[2], - radius, - minimum_radius, - max_angle, - boundary_budget, - tolerance, - right, - |curve| { - if cancel.is_cancelled() { - return Err("stock-front contour preparation cancelled".into()); - } - self.report.candidate_tests += 1; - let approval = source.approve_guide_tube(curve, radius); - let fits = approval.is_some(); - if let Some(approval) = approval { - rectangle_approvals.push(approval); - } - self.report.source_rejections += usize::from(!fits); - Ok(fits) - }, - )? - }; - let pad = 64. * tolerance; - let rectangle = if let Some(recipe) = rectangle { - let p = [recipe.start[0], recipe.start[1]]; - if source.link_geometry_fits_radius(p, p, radius + pad) - && scene.clear_disk( - p, - radius + pad, - position[2], - tolerance, - &mut 2_000_000, - cancel, - )? - { - Some(recipe) - } else { - None - } - } else { - None - }; - let Some(recipe) = rectangle else { - if !continuing_convex && let Some(front) = self.convex_front.as_mut() { - front.restrict_material(material, tolerance)?; - } - if !self.prepare_convex( - source, - position, - radius, - minimum_radius, - max_angle, - boundary_budget, - tolerance, - right, - prototype, - clearance, - plunge_feed, - cancel, - )? { - self.bulk_enabled = false; - } - return Ok(()); - }; - let mut queue = VecDeque::new(); - push_relink( - &mut queue, - position, - recipe.start, - clearance, - prototype.feed_mm_min, - plunge_feed, - Some(recipe.heading), - ); - for curve in &recipe.leads { - queue.push_back(Transfer { - curve: curve.clone(), - kind: MoveKind::Lead, - feed: prototype.feed_mm_min, - heading: None, - }); - } - for curve in &recipe.contour { - queue.push_back(Transfer { - curve: curve.clone(), - kind: MoveKind::Cut, - feed: prototype.feed_mm_min, - heading: None, - }); - } - if cancel.is_cancelled() { - return Err("stock-front contour preparation cancelled".into()); - } - self.source_approvals = recipe - .leads - .iter() - .chain(&recipe.contour) - .filter_map(|curve| { - rectangle_approvals - .iter() - .position(|p| p.matches(source, curve, radius, tolerance)) - .map(|i| rectangle_approvals.swap_remove(i)) - }) - .collect(); - self.bulk = Some(BulkContour::Rectangle(recipe)); - self.transfer = queue; - self.report.reentries += 1; - self.report.status = "bulk_contour"; - Ok(()) - } - #[allow(clippy::too_many_arguments)] - fn prepare_linear( - &mut self, - source: &PocketPlan, - position: Vec3, - radius: f64, - minimum: f64, - max_angle: f64, - right: bool, - prototype: &Motion, - tolerance: f64, - clearance: LinkHeights, - plunge_feed: f64, - cancel: &impl CancelSignal, - ) -> Result<(), String> { - if cancel.is_cancelled() { - return Err("linear continuation cancelled".into()); - } - let coverage = self - .coverage - .as_ref() - .ok_or("linear channel has no domain")?; - let orbit = coverage.seed_orbit.max(minimum).min(radius); - let scene = self.scene.as_ref().ok_or("linear channel has no scene")?; - let pad = 64. * tolerance; - if self.linear_rails.is_none() { - self.linear_rails = Some( - source - .front_channel_rails( - coverage.seed, - scene.material_bounds(position[2]), - radius + orbit + 2. * pad, - )? - .into(), - ); - } - loop { - if cancel.is_cancelled() { - return Err("linear continuation cancelled".into()); - } - if self.linear_front.is_none() { - // Admission can be interrupted inside the scene proof. Keep the - // unstarted proposal available until that proof has completed. - let Some(mut rail) = self.linear_rails.as_ref().unwrap().front().copied() else { - return Ok(()); - }; - let distance = |p: Point| (position[0] - p[0]).hypot(position[1] - p[1]); - if distance(rail.b) < distance(rail.a) { - std::mem::swap(&mut rail.a, &mut rail.b); - } - self.report.candidate_tests += 1; - if !source.guide_tube_fits(rail, radius + orbit + pad) - || !scene.clear_disk( - rail.a, - radius + orbit + pad, - position[2], - tolerance, - &mut 2_000_000, - cancel, - )? - { - self.linear_rails.as_mut().unwrap().pop_front(); - continue; - } - self.linear_rails.as_mut().unwrap().pop_front(); - self.linear_front = - LinearChannel::new(rail, position[2], orbit, radius, minimum, tolerance); - if self.linear_front.is_none() { - continue; - } - } - let recipe = self.linear_front.as_ref().unwrap().prepare( - position, - max_angle, - tolerance, - right, - |stroke| source.guide_tube_fits(stroke, radius), - cancel, - )?; - let Some(recipe) = recipe else { - self.linear_front = None; - continue; - }; - if recipe - .curves - .iter() - .any(|c| !source.guide_tube_fits(stroke_from_curve(c), radius)) - { - self.linear_front = None; - continue; - } - let mut queue = VecDeque::new(); - if recipe.reset { - let start = recipe.curves[0].start(); - let p = [start[0], start[1]]; - if !source.link_geometry_fits_radius(p, p, radius + pad) - || !scene.clear_disk( - p, - radius + pad, - position[2], - tolerance, - &mut 2_000_000, - cancel, - )? - { - self.linear_front = None; - continue; - } - push_relink( - &mut queue, - position, - start, - clearance, - prototype.feed_mm_min, - plunge_feed, - Some(tangent(&recipe.curves[0], 0.)), - ); - self.report.linear_resets += 1; - self.report.reentries += 1; - } - queue.extend(recipe.curves.iter().map(|c| Transfer { - curve: c.clone(), - kind: MoveKind::Cut, - feed: prototype.feed_mm_min, - heading: None, - })); - self.transfer = queue; - self.bulk = Some(BulkContour::Linear(recipe)); - self.report.status = "linear_channel"; - return Ok(()); - } - } - #[allow(clippy::too_many_arguments)] - pub fn next( - &mut self, - source: &PocketPlan, - stock: &Stock, - position: Vec3, - radius: f64, - minimum_radius: f64, - max_angle: f64, - material_on_right: bool, - prototype: Motion, - tolerance: f64, - clearance: LinkHeights, - plunge_feed: f64, - cancel: &impl CancelSignal, - ) -> Result, String> { - #[cfg(feature = "profile-planning")] - let _profile = crate::planning_profile::span("front.next"); - // A valid clearing recipe need not remove material. Check actual stock - // before starting one, so a repeated operation can finish at its seed. - // Only the existing whole-domain proof may declare coverage complete. - if !self.initial_coverage_checked { - let coverage = self - .coverage - .as_mut() - .ok_or("stock-front has no component coverage domain")?; - let revision = ( - self.identity - .ok_or("stock-front requires synchronized stock")?, - stock.generation(), - ); - let checked = if coverage - .material_gap(stock, revision, position, tolerance, cancel)? - .is_some() - { - // This proves remaining material, not a navigation target. - // A fixed recipe needs no target; if it cannot proceed, the - // generic steering branch obtains its original quadtree goal. - None - } else { - Some( - coverage.check( - self.scene - .as_ref() - .ok_or("stock-front requires committed stock")?, - stock, - position, - radius, - tolerance, - &mut self.report.coverage_tiles, - &mut self.report.coverage_envelopes, - &mut self.report.coverage_cache_hits, - &mut self.report.coverage_reused_branches, - cancel, - )?, - ) - }; - self.initial_coverage_checked = true; - match checked { - Some(CoverageResult::Complete) => { - self.report.coverage_complete = true; - self.report.completed_components += 1; - self.report.status = "covered"; - return Ok(None); - } - Some(CoverageResult::Gap(goal)) => self.goal = Some(goal), - None => {} - } - } - if self.transfer.is_empty() && self.bulk_enabled && !self.report.coverage_complete { - self.prepare_bulk( - source, - stock, - position, - radius, - minimum_radius, - max_angle, - material_on_right, - &prototype, - tolerance, - clearance, - plunge_feed, - cancel, - )?; - } - if self.transfer.is_empty() && !self.bulk_enabled && self.bulk_used_in_component { - self.prepare_linear( - source, - position, - radius, - minimum_radius, - max_angle, - material_on_right, - &prototype, - tolerance, - clearance, - plunge_feed, - cancel, - )?; - } - if let Some(transfer) = self.transfer.front() { - if cancel.is_cancelled() { - return Err("stock-front transfer cancelled".into()); - } - let motion = Motion { - curve: transfer.curve.clone(), - kind: transfer.kind, - feed_mm_min: transfer.feed, - ..prototype.clone() - }; - if motion.curve.start() != position { - return Err("stock-front transfer cursor mismatch".into()); - } - let lead = if matches!(motion.kind, MoveKind::Lead | MoveKind::Cut) { - if self.report.front_moves >= 8192 { - return Err("stock-front motion work limit; remaining coverage unproven".into()); - } - let approved = self.bulk.is_some() - && self - .source_approvals - .iter() - .any(|p| p.matches(source, &motion.curve, radius, tolerance)); - if !approved && !source.guide_tube_fits(stroke_from_curve(&motion.curve), radius) { - return Err("stock-front lead source unresolved; coverage unproven".into()); - } - let scene = self - .scene - .as_ref() - .ok_or("stock-front lead has no committed scene")?; - let certified_angle = self.bulk.as_ref().and_then(|b| b.certified_angle(&motion)); - let checked = if let Some(angle) = certified_angle { - (EngagementStatus::Bounded, angle) - } else { - let checked = scene.check_front( - &motion, - radius, - max_angle, - material_on_right, - EngagementOptions { - tolerance_mm: tolerance, - resolution_mm: (32. * tolerance).max(0.001), - max_nodes: 8192, - max_work: 2_000_000, - ..Default::default() - }, - cancel, - )?; - (checked.status, checked.upper_angle_deg) - }; - if checked.0 != EngagementStatus::Bounded { - if self.bulk.is_some() { - // No completed shell exists: retain actual swept - // supports, abandon only the proposed remainder. - self.bulk = None; - self.convex_front = None; - self.enclosed_front = None; - self.linear_front = None; - self.bulk_enabled = false; - self.transfer.clear(); - self.report.bulk_abandoned += 1; - return self.next( - source, - stock, - position, - radius, - minimum_radius, - max_angle, - material_on_right, - prototype, - tolerance, - clearance, - plunge_feed, - cancel, - ); - } - return Err( - "stock-front lead engagement/side unresolved; coverage unproven".into(), - ); - } - let novelty = if self.bulk.is_some() { - // The recipe has already fixed this curve. Ranking its - // potential removal cannot change the selected motion. - None - } else { - let (_, novelty, _) = potential_score( - scene, - stock, - &motion, - radius, - material_on_right, - tolerance, - &mut 2_000_000, - self.goal, - self.coverage - .as_ref() - .ok_or("stock-front lead has no coverage domain")? - .goal_pad, - cancel, - )?; - Some(novelty) - }; - Some((checked.1, novelty)) - } else { - None - }; - if cancel.is_cancelled() { - return Err("stock-front transfer cancelled".into()); - } - let transfer = self.transfer.pop_front().unwrap(); - self.pending_novelty = lead.is_some_and(|(_, novelty)| novelty == Some(true)); - if let Some((angle, novelty)) = lead { - self.report.front_moves += 1; - self.report.max_bounded_engagement_deg = - self.report.max_bounded_engagement_deg.max(angle); - match novelty { - Some(true) => { - self.report.productive_candidates += 1; - self.navigation_steps = 0; - } - Some(false) => { - self.report.navigation_moves += 1; - self.navigation_steps += 1; - } - None => self.report.unranked_contour_moves += 1, - } - } - if let Some(heading) = transfer.heading { - self.pending_heading = Some((motion.id, heading)); - } - if motion.kind != MoveKind::Cut { - self.report.reentry_moves += 1; - } - return Ok(Some(motion)); - } - if self.report.coverage_complete { - return Ok(None); - } - self.report.status = "steering"; - if self.report.front_moves >= 8192 { - self.report.status = "work_limit_coverage_unproven"; - return Err("stock-front motion work limit; remaining coverage unproven".into()); - } - let heading = self - .heading - .ok_or("stock-front requires a committed flat floor seed")?; - let scene = self - .scene - .as_ref() - .ok_or("stock-front requires committed stock")?; - let coverage = self - .coverage - .as_mut() - .ok_or("stock-front has no component coverage domain")?; - let mut coverage_work = 20_000_000; - let goal_known_clear = if let Some(goal) = self.goal { - let pad = coverage.goal_pad; - let bounds = [goal.map(|v| v - pad), goal.map(|v| v + pad)]; - scene.clear_box(bounds, position[2], &mut coverage_work, cancel)? - || stock.bounds_clear(bounds, position[2], &mut coverage_work, cancel)? - } else { - true - }; - if goal_known_clear { - let had_goal = self.goal.is_some(); - let checked = coverage.check( - scene, - stock, - position, - radius, - tolerance, - &mut self.report.coverage_tiles, - &mut self.report.coverage_envelopes, - &mut self.report.coverage_cache_hits, - &mut self.report.coverage_reused_branches, - cancel, - )?; - if had_goal { - self.progress_epoch += 1; - self.visited.clear(); - self.report.coverage_goals += 1; - } - match checked { - CoverageResult::Complete => { - self.report.coverage_complete = true; - self.report.completed_components += 1; - self.report.status = "covered"; - return Ok(None); - } - CoverageResult::Gap(goal) => self.goal = Some(goal), - } - } - let sign = if material_on_right { 1. } else { -1. }; - let options = EngagementOptions { - tolerance_mm: tolerance, - resolution_mm: (tolerance * 32.).max(0.001), - max_nodes: 8192, - max_work: 2_000_000, - ..Default::default() - }; - let mut navigation = Vec::new(); - let mut ranking_work = 2_000_000; - let mut proposals = Vec::with_capacity(MAX_FRONT_PROPOSALS); - let mut rank_error = None; - let mut curvatures = vec![self.curvature, 0.]; - for i in -8..=8 { - curvatures.push(i as f64 * sign / (4. * radius)); - } - for k in [ - -0.25, -0.125, -0.0625, -0.03125, 0.03125, 0.0625, 0.125, 0.25, - ] { - curvatures.push(self.curvature + k / radius); - } - curvatures.extend([-1. / minimum_radius, 1. / minimum_radius]); - if let Some(goal) = self.goal { - let target = coverage.centre_near(goal, tolerance)?; - if let Some(k) = goal_curvature(position, heading, target, tolerance) { - // A tangent circle through a remaining-domain centre supplies - // geometry-dependent proposals between the fixed grid choices. - // Blends let admission choose a gentler approach to the front. - // None of these proposals carries clearance/engagement authority. - curvatures.extend([k, k * 0.5, (k + self.curvature) * 0.5]); - } - } - curvatures.sort_by(f64::total_cmp); - curvatures.dedup_by(|a, b| (*a - *b).abs() < 1e-9); - // Local cleanup follows a remaining-coverage goal with the validated - // curvature order. Bulk contours handle coherent high-volume advances. - - 'steering: for k in curvatures { - if k != 0. && k.recip().abs() + tolerance < minimum_radius { - continue; - } - let mut previous_length: Option = None; - for scale in [4., 2., 1., 0.5, 0.25, 0.125, 0.0625, 0.03125] { - if cancel.is_cancelled() { - return Err("stock-front steering cancelled".into()); - } - let length = (radius * scale).min(if k == 0. { - f64::INFINITY - } else { - PI / 2. / k.abs() - }); - if previous_length.is_some_and(|old| (old - length).abs() < tolerance) { - continue; - } - previous_length = Some(length); - let curve = candidate(position, heading, k, length); - let stroke = stroke_from_curve(&curve); - self.report.candidate_tests += 1; - if !source.guide_tube_fits(stroke, radius) { - self.report.source_rejections += 1; - continue; - } - let end = curve.end(); - let end_heading = tangent(&curve, 1.); - let recovery = candidate( - end, - end_heading, - sign / minimum_radius, - TAU * minimum_radius, - ); - let recovery_fits = source.guide_tube_fits(stroke_from_curve(&recovery), radius); - if !recovery_fits { - self.report.recovery_rejections += 1; - } - let motion = Motion { - curve, - ..prototype.clone() - }; - let ranked = goal_score( - scene, - stock, - &motion, - radius, - material_on_right, - tolerance, - &mut ranking_work, - self.goal, - coverage.goal_pad, - cancel, - ); - let (score, novelty, tier) = match ranked { - Ok(rank) => rank, - Err(e) if ranking_work == 0 && !e.contains("cancelled") => { - // Preserve the ranked prefix. Its highest actually - // admitted member can still be returned, as with the - // former incremental checked-best selection. - rank_error = Some(e); - break 'steering; - } - Err(e) => return Err(e), - }; - let score = score * if recovery_fits { 1. } else { 0.9 }; - if score <= tolerance { - navigation.push(((k - sign / minimum_radius).abs(), motion)); - continue; - } - if proposals.len() >= MAX_FRONT_PROPOSALS { - return Err("stock-front candidate buffer work limit; coverage unproven".into()); - } - proposals.push(FrontProposal { - score, - motion, - novelty, - tier, - }); - } - } - let mut best = admit_ranked_front( - proposals, - rank_error, - scene, - radius, - max_angle, - material_on_right, - options, - &mut self.report, - cancel, - )?; - if best.is_none() && self.navigation_steps < 16 { - // Reach another part of the front through admitted tangent LINKS. - // They are not an empty-stock assertion or a startup exception. - navigation.sort_by(|a, b| a.0.total_cmp(&b.0)); - for (_, mut motion) in navigation { - let checked = scene.check_front( - &motion, - radius, - max_angle, - material_on_right, - options, - cancel, - )?; - if checked.status == EngagementStatus::Bounded { - motion.kind = MoveKind::Link; - best = Some((0., motion, checked.upper_angle_deg, false, 0)); - break; - } - } - } - if best.is_none() && self.bulk_used_in_component { - // A recorded straight-edge transition had a useful 4r advance near - // k=-0.109/r between coarse choices; the old grid chose a 1r oscillation. - // Rescue a stalled post-bulk cleanup with the remaining budget. - let mut refinement_work = ranking_work.min(1_000_000); - let refined = refine_long_advance( - scene, - stock, - position, - heading, - radius, - minimum_radius, - max_angle, - material_on_right, - &prototype, - tolerance, - self.goal, - coverage.goal_pad, - &mut refinement_work, - |curve| { - self.report.candidate_tests += 1; - if !source.guide_tube_fits(stroke_from_curve(curve), radius) { - self.report.source_rejections += 1; - return None; - } - let recovery = candidate( - curve.end(), - tangent(curve, 1.), - sign / minimum_radius, - TAU * minimum_radius, - ); - let fits = source.guide_tube_fits(stroke_from_curve(&recovery), radius); - self.report.recovery_rejections += usize::from(!fits); - Some(if fits { 1. } else { 0.9 }) - }, - cancel, - )?; - self.report.steering_budget_stops += usize::from(refined.budget_stopped); - best = refined.best; - } - let Some((_, mut motion, angle, novelty, _)) = best else { - // Re-evaluate the WHOLE remaining domain; a failed candidate set is - // neither completed coverage nor proof of an actual violation. - let goal = match coverage.check( - scene, - stock, - position, - radius, - tolerance, - &mut self.report.coverage_tiles, - &mut self.report.coverage_envelopes, - &mut self.report.coverage_cache_hits, - &mut self.report.coverage_reused_branches, - cancel, - )? { - CoverageResult::Complete => { - self.report.coverage_complete = true; - self.report.completed_components += 1; - self.report.status = "covered"; - return Ok(None); - } - CoverageResult::Gap(goal) => goal, - }; - let search = |segment_entry| { - plan_reentry( - scene, - source, - stock, - coverage.seed, - coverage.seed_orbit, - minimum_radius, - max_angle, - coverage.goal_pad, - coverage.centre_near(goal, tolerance)?, - position, - goal, - radius, - tolerance, - material_on_right, - self.progress_epoch, - &self.visited, - segment_entry, - 1_000_000, - &prototype, - clearance, - plunge_feed, - cancel, - ) - }; - // Share the existing two-million-work ceiling across distinct - // proposal families. No cursor/stock mutation occurs during either - // search; the fallback must independently prove its descent/exit. - let result = match search(true) { - Ok(Some(found)) => Some(found), - Ok(None) => search(false)?, - Err(e) if e.contains("work limit") && !e.contains("cancelled") => search(false)?, - Err(e) => return Err(e), - }; - let Some((key, mut queue, truncated)) = result else { - self.report.status = "steering_stalled_coverage_unproven"; - return Err( - "stock-front cannot reach remaining coverage through proven-clear re-entry" - .into(), - ); - }; - // Replace only the approach to an already checked re-entry pose. - // Keep the lead and its chosen heading; a proven empty horizontal - // link may change direction there without introducing engagement. - let mut link_work = 100_000; - let linked = clear_reentry_link( - scene, - source, - stock, - position, - radius, - tolerance, - &prototype, - &mut queue, - &mut link_work, - cancel, - ); - self.report.cleared_link_work += 100_000 - link_work; - match linked { - Ok(true) => self.report.cleared_reentry_links += 1, - Ok(false) => {} - Err(e) if link_work == 0 && !e.contains("cancelled") => { - self.report.cleared_link_budget_stops += 1; - } - Err(e) => return Err(e), - } - if cancel.is_cancelled() { - return Err("stock-front re-entry cancelled".into()); - } - self.goal = Some(goal); - self.report.reentry_budget_stops += usize::from(truncated); - self.visited.insert(key); - self.pending_novelty = false; - self.transfer = queue; - self.report.reentries += 1; - self.report.status = "reentering"; - let transfer = self - .transfer - .pop_front() - .ok_or("stock-front empty re-entry")?; - let motion = Motion { - curve: transfer.curve, - kind: transfer.kind, - feed_mm_min: transfer.feed, - ..prototype - }; - if let Some(heading) = transfer.heading { - self.pending_heading = Some((motion.id, heading)); - } - self.report.reentry_moves += 1; - return Ok(Some(motion)); - }; - if cancel.is_cancelled() { - return Err("stock-front steering cancelled".into()); - } - self.pending_novelty = novelty; - if novelty { - self.navigation_steps = 0; - self.report.productive_candidates += 1; - } else { - motion.kind = MoveKind::Link; - self.navigation_steps += 1; - self.report.navigation_moves += 1; - } - self.report.front_moves += 1; - self.report.max_bounded_engagement_deg = self.report.max_bounded_engagement_deg.max(angle); - Ok(Some(motion)) - } -} -/// Rank only immutable, source-admitted proposals. A stable descending order -/// preserves the old first-in-generator tie choice. First jointly bounded is -/// the highest-ranked proposal admitted by the shared continuous proof. -/// Uncertainty, ranking, point probes and exhausted work never admit a motion. -#[allow(clippy::too_many_arguments)] -fn admit_ranked_front( - mut proposals: Vec, - rank_error: Option, - scene: &EngagementScene, - radius: f64, - max_angle: f64, - right: bool, - options: EngagementOptions, - report: &mut FrontReport, - cancel: &impl CancelSignal, -) -> Result, String> { - if cancel.is_cancelled() { - return Err("stock-front steering cancelled".into()); - } - if proposals.len() > MAX_FRONT_PROPOSALS { - return Err("stock-front candidate buffer work limit; coverage unproven".into()); - } - proposals.sort_by(|a, b| { - b.tier - .cmp(&a.tier) - .then_with(|| b.score.total_cmp(&a.score)) - }); - let mut selected = None; - for proposal in proposals { - if cancel.is_cancelled() { - return Err("stock-front steering cancelled".into()); - } - // One continuous tree shares the angular unions for total contact and - // the instantaneous forbidden half. Separate queries rebuild the same - // history geometry. Neither an uncertain side nor a 360deg contact - // allowance may admit a candidate without both whole-motion proofs. - let checked = - scene.check_front(&proposal.motion, radius, max_angle, right, options, cancel)?; - if checked.status != EngagementStatus::Bounded { - report.joint_rejections += 1; - continue; - } - selected = Some(( - proposal.score, - proposal.motion, - checked.upper_angle_deg, - proposal.novelty, - proposal.tier, - )); - break; - } - if cancel.is_cancelled() { - return Err("stock-front steering cancelled".into()); - } - if let Some(error) = rank_error { - if selected.is_none() { - return Err(error); - } - report.steering_budget_stops += 1; - } - Ok(selected) -} - -/// Bounded search, not an assumption that contact is monotone in curvature. -/// Every returned candidate has its OWN source and joint whole-motion proof. -#[allow(clippy::too_many_arguments)] -fn refine_long_advance( - scene: &EngagementScene, - stock: &Stock, - position: Vec3, - heading: f64, - radius: f64, - minimum_radius: f64, - max_angle: f64, - right: bool, - prototype: &Motion, - tolerance: f64, - goal: Option, - goal_pad: f64, - work: &mut u64, - mut source_score: impl FnMut(&Curve) -> Option, - cancel: &impl CancelSignal, -) -> Result { - #[cfg(feature = "profile-planning")] - let _profile = crate::planning_profile::span("front.refine"); - let extent = (PI / (8. * radius)).min(minimum_radius.recip()); - let step = extent / 4.; - let mut best: Option = None; - let mut best_curvature = 0.; - let mut tested: Vec = Vec::with_capacity(19); - let mut budget_stopped = false; - // Nine initial probes, then at most ten local midpoint probes. Neither - // an unsafe midpoint nor a failed source check rules out its neighbours. - for round in 0..=5 { - let anchor = best_curvature; - let probes = if round == 0 { - (-4..=4).map(|i| i as f64 * step).collect::>() - } else { - let delta = step / 2f64.powi(round); - vec![anchor - delta, anchor + delta] - }; - for k in probes { - if cancel.is_cancelled() { - return Err("stock-front curvature search cancelled".into()); - } - if k.abs() > extent || tested.iter().any(|old| (*old - k).abs() * radius < 1e-12) { - continue; - } - if *work == 0 { - budget_stopped = true; - break; - } - *work -= 1; - tested.push(k); - let curve = candidate(position, heading, k, 4. * radius); - let Some(preference) = source_score(&curve) else { - continue; - }; - let motion = Motion { - curve, - ..prototype.clone() - }; - let ranked = potential_score( - scene, stock, &motion, radius, right, tolerance, work, goal, goal_pad, cancel, - ); - let (score, novelty, tier) = match ranked { - Ok(rank) => rank, - Err(error) if *work == 0 && !error.contains("cancelled") => { - budget_stopped = true; - break; - } - Err(error) => return Err(error), - }; - let score = score * preference; - if tier < 2 - || best.as_ref().is_some_and(|(old, _, _, _, old_tier)| { - tier < *old_tier || (tier == *old_tier && score <= *old) - }) - { - continue; - } - if *work == 0 { - budget_stopped = true; - break; - } - let checked = scene.check_front( - &motion, - radius, - max_angle, - right, - EngagementOptions { - tolerance_mm: tolerance, - resolution_mm: (32. * tolerance).max(0.001), - max_nodes: 8192, - max_work: *work, - ..Default::default() - }, - cancel, - )?; - *work = work.saturating_sub(checked.support_tests + checked.index_visits); - if checked.status == EngagementStatus::Bounded { - best = Some((score, motion, checked.upper_angle_deg, novelty, tier)); - best_curvature = k; - } - } - if budget_stopped || best.is_none() { - break; - } - } - Ok(RefinedAdvance { - best, - budget_stopped, - }) -} - -fn goal_curvature(p: Vec3, heading: f64, target: Point, tolerance: f64) -> Option { - let d = [target[0] - p[0], target[1] - p[1]]; - let length = d[0].hypot(d[1]); - if length <= tolerance || !length.is_finite() { - return None; - } - let (sin, cos) = heading.sin_cos(); - Some(2. * (-sin * (d[0] / length) + cos * (d[1] / length)) / length) -} - -/// Optional optimization. Mutate the queue only after a whole-footprint proof; -/// uncertainty, work exhaustion and cancellation retain the original approach. -#[allow(clippy::too_many_arguments)] -fn clear_reentry_link( - scene: &EngagementScene, - source: &PocketPlan, - stock: &Stock, - position: Vec3, - radius: f64, - tolerance: f64, - prototype: &Motion, - queue: &mut VecDeque, - work: &mut u64, - cancel: &impl CancelSignal, -) -> Result { - let Some(plunge_index) = queue.iter().position(|t| t.kind == MoveKind::Plunge) else { - return Ok(false); - }; - let plunge = &queue[plunge_index]; - let end = plunge.curve.end(); - if position[2] != end[2] || position == end { - return Ok(false); - } - let Some(feed) = prototype.feed_mm_min else { - return Ok(false); - }; - let length = (end[0] - position[0]).hypot(end[1] - position[1]); - let fed_approach: f64 = queue - .iter() - .take(plunge_index + 1) - .filter_map(|t| { - t.feed - .map(|f| (t.curve.end()[2] - t.curve.start()[2]).abs() / f) - }) - .sum(); - if length / feed >= fed_approach { - return Ok(false); - } - let curve = Curve::Line { - start: position, - end, - }; - if !source.guide_tube_fits(stroke_from_curve(&curve), radius) { - return Ok(false); - } - let motion = Motion { - curve, - kind: MoveKind::Link, - ..prototype.clone() - }; - let mut stock_work = *work as usize; - let potential = - stock.may_remove_material(&motion, radius, 0., tolerance, &mut stock_work, cancel)?; - *work = stock_work as u64; - if potential { - let guard = crate::verification::path_error(&motion, tolerance) - + 512. * f64::EPSILON * (1. + radius); - if !scene.clear_line( - [position[0], position[1]], - [end[0], end[1]], - radius + guard, - position[2], - tolerance, - work, - cancel, - )? { - return Ok(false); - } - } - if cancel.is_cancelled() { - return Err("stock-front clear link cancelled".into()); - } - let heading = plunge.heading; - queue.drain(..=plunge_index); - queue.push_front(Transfer { - curve: motion.curve, - kind: MoveKind::Link, - feed: Some(feed), - heading, - }); - Ok(true) -} - -fn candidate(p: Vec3, heading: f64, curvature: f64, length: f64) -> Curve { - if curvature == 0. { - return Curve::Line { - start: p, - end: [ - p[0] + length * heading.cos(), - p[1] + length * heading.sin(), - p[2], - ], - }; - } - let c = [ - p[0] - heading.sin() / curvature, - p[1] + heading.cos() / curvature, - p[2], - ]; - let a = (p[1] - c[1]).atan2(p[0] - c[0]); - let sweep = length * curvature; - let r = curvature.recip().abs(); - Curve::Arc { - start: p, - end: [ - c[0] + r * (a + sweep).cos(), - c[1] + r * (a + sweep).sin(), - p[2], - ], - center: c, - plane: Plane::Xy, - sweep_rad: sweep, - } -} -fn stroke_from_curve(curve: &Curve) -> Stroke { - let (a, b) = (curve.start(), curve.end()); - Stroke { - a: [a[0], a[1]], - b: [b[0], b[1]], - arc: match *curve { - Curve::Arc { - center, sweep_rad, .. - } => Some(([center[0], center[1]], sweep_rad)), - _ => None, - }, - } -} -fn tangent(curve: &Curve, f: f64) -> f64 { - match *curve { - Curve::Line { start, end } => (end[1] - start[1]).atan2(end[0] - start[0]), - Curve::Arc { - start, - center, - sweep_rad, - .. - } => { - (start[1] - center[1]).atan2(start[0] - center[0]) - + f * sweep_rad - + sweep_rad.signum() * PI / 2. - } - _ => unreachable!(), - } -} -#[allow(clippy::too_many_arguments)] -fn potential_score( - scene: &EngagementScene, - stock: &Stock, - motion: &Motion, - r: f64, - right: bool, - tolerance: f64, - remaining_work: &mut u64, - goal: Option, - goal_pad: f64, - cancel: &impl CancelSignal, -) -> Result<(f64, bool, u8), String> { - #[cfg(feature = "profile-planning")] - let _profile = crate::planning_profile::span("front.area_rank"); - let path = motion.curve.prepare(tolerance)?; - let side = if right { -1. } else { 1. }; - let mut potential = 0.; - let mut count: f64 = 0.; - let spec = stock.spec(); - let [nx, ny] = stock.dimensions(); - let step = stock.cell_widths_mm(); - // Sample each travel interval at its midpoint. Right endpoints miss all - // removal when a corner clip finishes within the first quarter of a move. - for f in [0.125, 0.375, 0.625, 0.875] { - let p = path.position(f)?; - let heading = tangent(&motion.curve, f); - for ray in 0..8 { - let a = (ray as f64 + 0.5) / 16.; - let weight = (PI * a).cos(); - // Air and already-cleared columns are zero contact, not absent - // observations. Conditioning the denominator on potential stock - // inflated air-heavy traverses to a fully productive score. - count += weight; - let angle = heading + side * PI * a; - let interior = r - 4. * tolerance; - let q: Point = [p[0] + interior * angle.cos(), p[1] + interior * angle.sin()]; - // Transport of the cutter disk adds area only on its FORWARD - // boundary: ds * max(feed_direction dot outward_normal,0). - // Suppress boundary already covered by this candidate's prefix, - // especially the inner side of a tight turn. Ranking only. - let boundary = [p[0] + r * angle.cos(), p[1] + r * angle.sin()]; - if crate::verification::circle_axis_distance(motion, &path, [0., f], boundary) - .is_some_and(|d| d < r - 8. * tolerance) - { - continue; - } - if (0..2).any(|k| q[k] < spec.min_mm[k] || q[k] >= spec.max_mm[k]) { - continue; - } - let x = ((q[0] - spec.min_mm[0]) / step[0]) as usize; - let y = ((q[1] - spec.min_mm[1]) / step[1]) as usize; - if x >= nx || y >= ny || stock.cells()[y * nx + x].upper_mm <= p[2] { - continue; - } - let near = scene - .point_near_cleared_sweep( - q, - p[2], - (0.002 * r).max(32. * tolerance), - remaining_work, - cancel, - )? - .ok_or("stock-front ranking work limit; remaining coverage unproven")?; - if !near { - potential += weight; - } - } - } - // A ranking heuristic, not evidence of positive material or completion. - let sampled = path.length_mm() * r * potential / count.max(1.); - let mut hits_goal = false; - let directed = if let Some(goal) = goal { - let start = motion.curve.start(); - let old = (start[0] - goal[0]).hypot(start[1] - goal[1]); - let distance = crate::verification::circle_axis_distance(motion, &path, [0., 1.], goal) - .unwrap_or(f64::INFINITY); - let end = motion.curve.end(); - let gain = (old - (end[0] - goal[0]).hypot(end[1] - goal[1])).max(0.); - let cover = ((r - 2. * goal_pad) - distance).clamp(0., goal_pad) / goal_pad; - hits_goal = cover > 0.; - gain + cover * r - } else { - 0. - }; - Ok(( - if potential > 0. { - sampled + 0.05 * r * directed - } else { - r * directed - }, - potential > 0., - if potential > 0. { - 3 - } else if hits_goal { - 2 - } else if directed > 0. { - 1 - } else { - 0 - }, - )) -} - -#[allow(clippy::too_many_arguments)] -fn goal_score( - scene: &EngagementScene, - stock: &Stock, - motion: &Motion, - r: f64, - right: bool, - tolerance: f64, - remaining_work: &mut u64, - goal: Option, - goal_pad: f64, - cancel: &impl CancelSignal, -) -> Result<(f64, bool, u8), String> { - #[cfg(feature = "profile-planning")] - let _profile = crate::planning_profile::span("front.goal_rank"); - let path = motion.curve.prepare(tolerance)?; - let side = if right { -1. } else { 1. }; - let mut potential = 0.; - let mut count: f64 = 0.; - let spec = stock.spec(); - let [nx, ny] = stock.dimensions(); - let step = stock.cell_widths_mm(); - for f in [0.25, 0.5, 0.75, 1.] { - let p = path.position(f)?; - let heading = tangent(&motion.curve, f); - for a in [0.25, 0.5, 0.75] { - let angle = heading + side * PI * a; - let interior = r - 4. * tolerance; - let q: Point = [p[0] + interior * angle.cos(), p[1] + interior * angle.sin()]; - if (0..2).any(|k| q[k] < spec.min_mm[k] || q[k] >= spec.max_mm[k]) { - continue; - } - let x = ((q[0] - spec.min_mm[0]) / step[0]) as usize; - let y = ((q[1] - spec.min_mm[1]) / step[1]) as usize; - if x >= nx || y >= ny || stock.cells()[y * nx + x].upper_mm <= p[2] { - continue; - } - count += 1.; - let near = scene - .point_near_cleared_sweep( - q, - p[2], - (0.002 * r).max(32. * tolerance), - remaining_work, - cancel, - )? - .ok_or("stock-front ranking work limit; remaining coverage unproven")?; - if !near { - potential += goal.map_or(1., |goal| { - 1. / (1. + (q[0] - goal[0]).hypot(q[1] - goal[1]) / r) - }); - } - } - } - // A ranking heuristic, not evidence of positive material or completion. - let sampled = path.length_mm() * potential / count.max(1.); - let mut hits_goal = false; - let directed = if let Some(goal) = goal { - let start = motion.curve.start(); - let old = (start[0] - goal[0]).hypot(start[1] - goal[1]); - let distance = crate::verification::circle_axis_distance(motion, &path, [0., 1.], goal) - .unwrap_or(f64::INFINITY); - let end = motion.curve.end(); - let gain = (old - (end[0] - goal[0]).hypot(end[1] - goal[1])).max(0.); - let cover = ((r - 2. * goal_pad) - distance).clamp(0., goal_pad) / goal_pad; - hits_goal = cover > 0.; - gain + cover * r - } else { - 0. - }; - Ok(( - sampled + directed, - potential > 0., - if potential > 0. || hits_goal { - 2 - } else if directed > 0. { - 1 - } else { - 0 - }, - )) -} - -/// Retract and feed heights for relinks (the operation's heights). -#[derive(Clone, Copy, Debug)] -pub(crate) struct LinkHeights { - pub retract: f64, - pub feed: f64, -} -impl From for LinkHeights { - /// Link at one height (clearance). - fn from(z: f64) -> Self { - Self { - retract: z, - feed: z, - } - } -} -/// Leave the cut at feed up to the feed height, rapid up to the retract -/// height, across, and down to the feed height; plunge to `target` at feed. -/// With all heights equal (the default) this is: feed up, rapid across, -/// plunge down. -fn push_relink( - queue: &mut VecDeque, - position: Vec3, - target: Vec3, - heights: LinkHeights, - retract_feed: Option, - plunge_feed: f64, - heading: Option, -) { - let travel = heights.retract.max(position[2]); - let lifted = [position[0], position[1], heights.feed.max(position[2])]; - let mut steps: Vec<(Vec3, MoveKind, Option, Option)> = vec![ - (lifted, MoveKind::Retract, retract_feed, None), - ( - [position[0], position[1], travel], - MoveKind::Rapid, - None, - None, - ), - ([target[0], target[1], travel], MoveKind::Rapid, None, None), - ]; - if heights.feed < travel && heights.feed > target[2] { - steps.push(( - [target[0], target[1], heights.feed], - MoveKind::Rapid, - None, - None, - )); - } - steps.push((target, MoveKind::Plunge, Some(plunge_feed), heading)); - let mut at = position; - for (end, kind, feed, heading) in steps { - if end != at { - queue.push_back(Transfer { - curve: Curve::Line { start: at, end }, - kind, - feed, - heading, - }); - at = end; - } - } -} -struct Transfer { - curve: Curve, - kind: MoveKind, - feed: Option, - heading: Option, -} -struct FrontCoverage { - domain: PreparedRegion, - material: Option, - // Bound to the same immutable centre/domain construction and synchronized - // native history as this owner. Never expose it as general empty stock. - inflation: f64, - enclosed_complete: bool, - // Coverage only: a tile may contain protected material outside the domain. - // Never expose this as empty stock or use it for motion/descent admission. - // The owning driver binds all checks to one component, floor, immutable - // operation and monotone native sweep history; foreign/undo states fail - // synchronize before these proofs can be reused. - covered_tiles: HashSet, - clear_hint: Option, - split_tiles: HashSet, - centres: PreparedRegion, - goal_pad: f64, - seed_orbit: f64, - bounds: Bounds, - seed: Point, - key: (usize, usize), - floor: f64, -} -enum CoverageResult { - Complete, - Gap(Point), -} -impl FrontCoverage { - #[allow(clippy::too_many_arguments)] - fn new( - domain: PreparedRegion, - seed: Point, - key: (usize, usize), - floor: f64, - tolerance: f64, - boundary_budget: f64, - seed_orbit: f64, - centres: PreparedRegion, - inflation: f64, - ) -> Result { - let mut bounds: Option = None; - for component in &domain.definition().components { - for boundary in std::iter::once(&component.outer).chain(&component.holes) { - for stroke in Stroke::from_boundary(boundary) { - let b = stroke.curve(floor).prepare(tolerance)?.bounds(); - let b = Bounds { - min: [b.min[0], b.min[1]], - max: [b.max[0], b.max[1]], - }; - bounds = Some(bounds.map_or(b, |old| old.union(b))); - } - } - } - Ok(Self { - domain, - material: None, - inflation, - enclosed_complete: false, - covered_tiles: HashSet::new(), - clear_hint: None, - split_tiles: HashSet::new(), - centres, - goal_pad: boundary_budget / 4., - seed_orbit, - bounds: bounds.unwrap_or(Bounds { - min: seed, - max: seed, - }), - seed, - key, - floor, - }) - } - /// Positive material witness for the initial search, NEVER completion or - /// clearance. At most ten deterministic cells are considered. A cell lower - /// bound encloses its whole physical column from below; strict domain - /// clearance encloses a small neighborhood of its centre inside the requested - /// region. Their intersection therefore contains unremoved material above - /// this actual floor. No sweep/stock certificate is inferred from sampling. - /// The immutable stock borrow and synchronized revision bind this one call; - /// no witness is cached across native transactions. Uncertainty falls back. - fn material_gap( - &self, - stock: &Stock, - revision: (u64, u64), - position: Vec3, - tolerance: f64, - cancel: &impl CancelSignal, - ) -> Result, String> { - if cancel.is_cancelled() { - return Err("stock-front material witness cancelled".into()); - } - if revision != (stock.identity(), stock.generation()) - || position[2] != self.floor - || self.domain.definition().components.is_empty() - { - return Ok(None); - } - let spec = stock.spec(); - let [nx, ny] = stock.dimensions(); - let step = stock.cell_widths_mm(); - let low: Point = std::array::from_fn(|k| self.bounds.min[k].max(spec.min_mm[k])); - let high: Point = std::array::from_fn(|k| self.bounds.max[k].min(spec.max_mm[k])); - if (0..2).any(|k| low[k] >= high[k]) { - return Ok(None); - } - let index = |p: Point| { - let x = ((p[0] - spec.min_mm[0]) / step[0]) - .floor() - .clamp(0., (nx - 1) as f64) as usize; - let y = ((p[1] - spec.min_mm[1]) / step[1]) - .floor() - .clamp(0., (ny - 1) as f64) as usize; - y * nx + x - }; - let mut candidates = vec![index([position[0], position[1]])]; - for x in [0.125, 0.5, 0.875] { - for y in [0.125, 0.5, 0.875] { - let i = index([ - low[0] + x * (high[0] - low[0]), - low[1] + y * (high[1] - low[1]), - ]); - if !candidates.contains(&i) { - candidates.push(i); - } - } - } - candidates.sort_by(|a, b| { - let distance = |i| { - let p = stock.cell_center(i).unwrap(); - (p[0] - position[0]).hypot(p[1] - position[1]) - }; - distance(*a).total_cmp(&distance(*b)) - }); - let probe = step[0].min(step[1]) / 8.; - for index in candidates { - if cancel.is_cancelled() { - return Err("stock-front material witness cancelled".into()); - } - let p = stock.cell_center(index).unwrap(); - let guard = 64. * tolerance - + 4096. - * f64::EPSILON - * (1. - + p[0].abs() - + p[1].abs() - + self.floor.abs() - + spec.max_mm[2].abs() - + probe); - if probe <= guard || stock.cells()[index].lower_mm <= self.floor + guard { - continue; - } - let q = self.domain.query(p)?; - if q.signed_clearance_mm - .is_some_and(|d| d > q.uncertainty_mm + probe + guard) - { - return Ok(Some(p)); - } - } - Ok(None) - } - /// A geometric search position, NEVER a clearance certificate. Project - /// to the real line/arc centre boundary rather than quantizing to stock cells. - fn centre_near(&self, p: Point, tolerance: f64) -> Result { - let q = self.centres.query(p)?; - if q.signed_clearance_mm.is_some_and(|d| d > q.uncertainty_mm) { - return Ok(p); - } - let mut best = None; - let mut distance = f64::INFINITY; - for component in &self.centres.definition().components { - for boundary in std::iter::once(&component.outer).chain(&component.holes) { - for s in Stroke::from_boundary(boundary) { - let nearest = if let Some((c, sweep)) = s.arc { - let start = (s.a[1] - c[1]).atan2(s.a[0] - c[0]); - let angle = (p[1] - c[1]).atan2(p[0] - c[0]); - let travel = if sweep > 0. { - (angle - start).rem_euclid(TAU) - } else { - (start - angle).rem_euclid(TAU) - }; - if travel <= sweep.abs() || sweep.abs() >= TAU { - let r = (s.a[0] - c[0]).hypot(s.a[1] - c[1]); - [c[0] + r * angle.cos(), c[1] + r * angle.sin()] - } else if (p[0] - s.a[0]).hypot(p[1] - s.a[1]) - < (p[0] - s.b[0]).hypot(p[1] - s.b[1]) - { - s.a - } else { - s.b - } - } else { - let d = [s.b[0] - s.a[0], s.b[1] - s.a[1]]; - let l = d[0] * d[0] + d[1] * d[1]; - let t = if l == 0. { - 0. - } else { - ((p[0] - s.a[0]) * d[0] + (p[1] - s.a[1]) * d[1]) / l - } - .clamp(0., 1.); - [s.a[0] + t * d[0], s.a[1] + t * d[1]] - }; - let d = (p[0] - nearest[0]).hypot(p[1] - nearest[1]); - if d < distance { - distance = d; - best = Some(nearest); - } - } - } - } - let mut c = best.ok_or("stock-front centre component has no boundary")?; - if distance > tolerance { - let inset = 32. * tolerance + self.centres.definition().boundary_error_mm; - for k in 0..2 { - c[k] += (c[k] - p[k]) * inset / distance; - } - } - Ok(c) - } - /// Morton path with a leading root bit. At depth<=28 it fits in u64. - /// A parent is covered only when all four child tiles have proofs. Keep - /// children too, so already queued nodes remain hits after parent folding. - /// Saturation merely stops memoization; the original proof still runs. - fn remember_covered(&mut self, mut tile: u64) { - while self.covered_tiles.len() + self.split_tiles.len() < 262144 { - self.covered_tiles.insert(tile); - if tile == 1 { - break; - } - let siblings = tile & !3; - if !(0..4).all(|q| self.covered_tiles.contains(&(siblings | q))) { - break; - } - tile >>= 2; - } - } - #[allow(clippy::too_many_arguments)] - fn check( - &mut self, - scene: &EngagementScene, - stock: &Stock, - position: Vec3, - radius: f64, - tolerance: f64, - tiles: &mut usize, - envelopes: &mut usize, - cache_hits: &mut usize, - reused_branches: &mut usize, - cancel: &impl CancelSignal, - ) -> Result { - #[cfg(feature = "profile-planning")] - let _profile = crate::planning_profile::span("front.coverage"); - if cancel.is_cancelled() { - return Err("stock-front coverage cancelled".into()); - } - if self.domain.definition().components.is_empty() { - return Ok(CoverageResult::Complete); - } - if self.enclosed_complete { - *envelopes += 1; - return Ok(CoverageResult::Complete); - } - let mut work = 20_000_000u64; - if let Some(material) = &self.material - && material.excludes_domain(&self.domain, self.floor, tolerance, &mut work, cancel)? - { - *envelopes += 1; - return Ok(CoverageResult::Complete); - } - let mut nodes = 0usize; - let mut stack = VecDeque::from([(self.bounds, 0u8, 1u64)]); - let segments = self.domain.summary().segments as u64; - while let Some((b, depth, tile)) = stack.pop_front() { - if cancel.is_cancelled() { - return Err("stock-front coverage cancelled".into()); - } - nodes += 1; - *tiles += 1; - if nodes > 262144 { - return Err("stock-front coverage work limit; coverage unproven".into()); - } - if self.covered_tiles.contains(&tile) { - *cache_hits += 1; - continue; - } - let p: Point = std::array::from_fn(|k| (b.min[k] + b.max[k]) / 2.); - let half = (b.max[0] - b.min[0]).hypot(b.max[1] - b.min[1]) / 2.; - // A previously split node cannot acquire a new gap: its geometry - // is fixed, and any proved-clear goal box stays clear as native - // sweeps remove material. Only its children need new proofs. - // Still check the root to recognize stock that became wholly clear. - if tile != 1 && self.split_tiles.contains(&tile) { - *reused_branches += 1; - } else { - if work < segments + 1 { - return Err("stock-front coverage work limit; coverage unproven".into()); - } - work -= segments + 1; - let q = { - #[cfg(feature = "profile-planning")] - let _profile = crate::planning_profile::span("coverage.domain_query"); - self.domain.query(p)? - }; - let guard = 1024. * f64::EPSILON * (1. + p[0].abs() + p[1].abs() + half + radius); - if q.signed_clearance_mm - .is_some_and(|d| d + half + q.uncertainty_mm + guard < 0.) - { - self.remember_covered(tile); - continue; - } - if let Some(material) = &self.material - && material.excludes_box( - [b.min, b.max], - self.floor, - tolerance, - &mut work, - cancel, - )? - { - self.remember_covered(tile); - continue; - } - if scene.clear_box_with_hint( - [b.min, b.max], - self.floor, - &mut self.clear_hint, - &mut work, - cancel, - )? || stock.bounds_clear([b.min, b.max], self.floor, &mut work, cancel)? - { - self.remember_covered(tile); - continue; - } - // This point is only a steering counterexample candidate. It does - // not certify material/violation; completion still needs ALL tiles. - if half <= radius / 2. { - let pad = self.goal_pad; - let goal_bounds = [p.map(|v| v - pad), p.map(|v| v + pad)]; - let goal_clear = - scene.clear_box_with_hint( - goal_bounds, - self.floor, - &mut self.clear_hint, - &mut work, - cancel, - )? || stock.bounds_clear(goal_bounds, self.floor, &mut work, cancel)?; - if goal_clear - && (0..2) - .all(|k| b.min[k] >= goal_bounds[0][k] && b.max[k] <= goal_bounds[1][k]) - { - self.remember_covered(tile); - continue; - } - if !goal_clear - && (q - .signed_clearance_mm - .is_some_and(|d| d > q.uncertainty_mm + guard) - || depth >= 28 - || half <= (16. * tolerance).min(pad / 2.)) - { - return Ok(CoverageResult::Gap(p)); - } - } - } - if depth >= 28 { - return Err( - "stock-front coverage subdivision unresolved; coverage unproven".into(), - ); - } - // At most65535 retained branch nodes describe262141 total tree - // nodes, within the original per-check visit bound. Cache pressure - // falls back to the unchanged proof rather than dropping a region. - if self.split_tiles.len() < 65535 - && self.covered_tiles.len() + self.split_tiles.len() < 262144 - { - self.split_tiles.insert(tile); - } - let mut children = Vec::with_capacity(4); - for quadrant in 0..4 { - let bounds = Bounds { - min: std::array::from_fn(|k| { - if quadrant & (1 << k) == 0 { - b.min[k] - } else { - p[k] - } - }), - max: std::array::from_fn(|k| { - if quadrant & (1 << k) == 0 { - p[k] - } else { - b.max[k] - } - }), - }; - let mid: Point = std::array::from_fn(|k| (bounds.min[k] + bounds.max[k]) / 2.); - let distance = (mid[0] - position[0]).hypot(mid[1] - position[1]); - children.push((distance, bounds, (tile << 2) | quadrant)); - } - children.sort_by(|a, b| a.0.total_cmp(&b.0)); - for (_, child, key) in children { - stack.push_back((child, depth + 1, key)); - } - } - Ok(CoverageResult::Complete) - } -} - -type ReentryKey = (u64, u64, u8, usize); -#[allow(clippy::too_many_arguments, clippy::type_complexity)] -fn plan_reentry( - scene: &EngagementScene, - source: &PocketPlan, - stock: &Stock, - seed: Point, - seed_orbit: f64, - minimum_radius: f64, - max_angle: f64, - goal_pad: f64, - projected_centre: Point, - position: Vec3, - goal: Point, - radius: f64, - tolerance: f64, - right: bool, - progress: usize, - visited: &HashSet, - segment_entry: bool, - work_limit: u64, - prototype: &Motion, - clearance: LinkHeights, - plunge_feed: f64, - cancel: &impl CancelSignal, -) -> Result, bool)>, String> { - #[cfg(feature = "profile-planning")] - let _profile = crate::planning_profile::span("front.reentry"); - let [nx, ny] = stock.dimensions(); - let stride = nx.max(ny).div_ceil(256).max(1); - let mut polar = vec![seed]; - for scale in [0.25, 0.5, 0.75, 0.9] { - for i in 0..16 { - let a = TAU * i as f64 / 16.; - polar.push([ - seed[0] + seed_orbit * scale * a.cos(), - seed[1] + seed_orbit * scale * a.sin(), - ]); - } - } - let mut candidates: Vec<_> = polar - .into_iter() - .chain((0..ny).step_by(stride).flat_map(|y| { - (0..nx) - .step_by(stride) - .filter_map(move |x| stock.cell_center(y * nx + x)) - })) - .map(|p| (p, None)) - .collect(); - let mut recovery_centres = vec![projected_centre]; - // Original outside-stock space is available along EVERY face, not just - // near the one entry seed. The forbidden half of a turning cutter reaches - // hypot(tool_radius, axis_radius) from its circle centre. Use that as a - // search stand-off; full source/clearance/contact/side checks below remain - // the authority. No future circle is emitted or marked cleared here. - let spec = stock.spec(); - let stand_off = radius.hypot(minimum_radius) + 64. * tolerance; - if segment_entry { - for axis in 0..2 { - for side in [0, 1] { - let mut centre: Point = - std::array::from_fn(|k| goal[k].clamp(spec.min_mm[k], spec.max_mm[k])); - centre[axis] = if side == 0 { - spec.min_mm[axis] - stand_off - } else { - spec.max_mm[axis] + stand_off - }; - recovery_centres.push(centre); - } - } - } - for centre in recovery_centres { - for i in 0..32 { - let a = TAU * i as f64 / 32.; - candidates.push(( - [ - centre[0] + minimum_radius * a.cos(), - centre[1] + minimum_radius * a.sin(), - ], - Some(a + if right { PI / 2. } else { -PI / 2. }), - )); - } - } - let mut work = work_limit; - if segment_entry { - for inset in [128. * tolerance, 0.05 * minimum_radius] { - candidates.extend( - scene - .reentry_positions(goal, position[2], inset, right, &mut work, cancel)? - .into_iter() - .map(|(p, heading)| (p, Some(heading))), - ); - } - } - // Nearest to the goal first; each distance computed once (stable sort on - // the same keys: the same order as comparing recomputed distances). - let mut keyed: Vec<(f64, (Point, Option))> = candidates - .into_iter() - .map(|c| ((c.0[0] - goal[0]).hypot(c.0[1] - goal[1]), c)) - .collect(); - keyed.sort_by(|a, b| a.0.total_cmp(&b.0)); - let candidates = keyed.into_iter().map(|(_, c)| c); - // Error-only attribution, in the same existing shared work units: - // source/history, stock, full disk, ranking, joint total/side (last reserved). - let mut costs = [work_limit - work, 0, 0, 0, 0, 0]; - let mut best: Option<(f64, u8, Point, f64, ReentryKey, Option)> = None; - let mut truncated = false; - let sign = if right { 1. } else { -1. }; - 'search: for (mut p, hint) in candidates { - let canonical = (p[0].to_bits(), p[1].to_bits()); - if (p[0] - position[0]).hypot(p[1] - position[1]) < 1e-9 { - p = [position[0], position[1]]; - } - if cancel.is_cancelled() { - return Err("stock-front re-entry cancelled".into()); - } - if work == 0 { - if best.is_some() { - truncated = true; - break; - } - return Err("stock-front re-entry search work limit; coverage unproven".into()); - } - work -= 1; - costs[0] += 1; - let distance = (p[0] - goal[0]).hypot(p[1] - goal[1]); - if !segment_entry - && best - .as_ref() - .is_some_and(|b| distance - minimum_radius >= -b.0) - { - break; - } - let source_work = source.link_work_per_query() as u64; - if work < source_work { - if best.is_some() { - truncated = true; - break; - } - return Err("stock-front re-entry source work limit; coverage unproven".into()); - } - work -= source_work; - costs[0] += source_work; - let pad = 64. * tolerance; - if !source.link_geometry_fits_radius(p, p, radius + pad) { - continue; - } - let query = Motion { - curve: Curve::Line { - start: [p[0], p[1], position[2]], - end: [p[0] + pad, p[1], position[2]], - }, - ..prototype.clone() - }; - let stock_before = work; - let mut stock_work = work as usize; - let potential = - stock.may_remove_material(&query, radius, 0., tolerance, &mut stock_work, cancel)?; - work = stock_work as u64; - costs[1] += stock_before - work; - let mut clearance_proven = !potential; - if potential && !segment_entry { - let before = work; - let disk = scene.clear_disk(p, radius + pad, position[2], tolerance, &mut work, cancel); - costs[2] += before - work; - match disk { - Ok(true) => clearance_proven = true, - Ok(false) => continue, - Err(e) if best.is_some() && work == 0 && !e.contains("cancelled") => { - truncated = true; - break 'search; - } - Err(e) => return Err(e), - } - } - if potential && segment_entry { - let before = work; - let possible = scene.disk_may_be_clear(p, radius + pad, position[2], &mut work, cancel); - costs[2] += before - work; - if !possible? { - continue; - } - } - let base = (goal[1] - p[1]).atan2(goal[0] - p[0]) + sign * PI / 2.; - let headings = hint - .into_iter() - .chain((0..16).map(|offset| base + offset as f64 * TAU / 16.)); - // A near-goal pose may have many inadmissible directions. Reserve - // search work for other poses instead of spending the whole re-entry - // budget proving one pose unhelpful. This limits proposals, not proof - // accuracy: an unresolved candidate is never accepted. - let pose_floor = work.saturating_sub(65_536); - for heading in headings { - if cancel.is_cancelled() { - return Err("stock-front heading search cancelled".into()); - } - let sector = (heading.rem_euclid(TAU) * 32. / TAU).floor() as u8; - let key = (canonical.0, canonical.1, sector, progress); - if visited.contains(&key) { - continue; - } - if !segment_entry { - let curve = candidate( - [p[0], p[1], position[2]], - heading, - sign / minimum_radius, - TAU * minimum_radius, - ); - let Curve::Arc { center, .. } = curve else { - unreachable!() - }; - let centre = [center[0], center[1]]; - let score = -(centre[0] - goal[0]).hypot(centre[1] - goal[1]); - if best.as_ref().is_some_and(|b| score <= b.0) { - continue; - } - if work < source_work { - if best.is_some() { - truncated = true; - break 'search; - } - return Err("stock-front recovery heading work limit; coverage unproven".into()); - } - work -= source_work; - costs[0] += source_work; - if !source.link_geometry_fits_radius(centre, centre, radius + minimum_radius) { - continue; - } - let lookahead = Motion { - curve, - ..prototype.clone() - }; - let before = work; - let rank = goal_score( - scene, - stock, - &lookahead, - radius, - right, - tolerance, - &mut work, - Some(goal), - goal_pad, - cancel, - ); - costs[3] += before - work; - let (_, _, tier) = match rank { - Ok(rank) => rank, - Err(e) if best.is_some() && work == 0 && !e.contains("cancelled") => { - truncated = true; - break 'search; - } - Err(e) => return Err(e), - }; - if tier < 2 { - continue; - } - if work == 0 { - if best.is_some() { - truncated = true; - break 'search; - } - return Err("stock-front recovery proof work limit; coverage unproven".into()); - } - let checked = scene.check_front( - &lookahead, - radius, - max_angle, - right, - EngagementOptions { - tolerance_mm: tolerance, - resolution_mm: (32. * tolerance).max(0.001), - max_nodes: 8192, - max_work: work, - ..Default::default() - }, - cancel, - )?; - costs[4] += (checked.support_tests + checked.index_visits).min(work); - work = work.saturating_sub(checked.support_tests + checked.index_visits); - if checked.status == EngagementStatus::Bounded { - best = Some((score, tier, p, heading, key, None)); - } - continue; - } - // Search the actual forward segment, not an entire hypothetical - // recovery orbit. The latter can be empty/useless even when a - // gentle outward advance from this same clear pose is productive. - for curve in reentry_leads( - [p[0], p[1], position[2]], - heading, - radius, - minimum_radius, - right, - ) { - if work.saturating_sub(pose_floor) <= source_work { - continue 'search; - } - if cancel.is_cancelled() { - return Err("stock-front lead search cancelled".into()); - } - if work < source_work { - if best.is_some() { - truncated = true; - break 'search; - } - return Err(format!( - "stock-front heading work limit; coverage unproven; goal={goal:?}, candidate={p:?}, source/stock/disk/rank/jointFront/reserved={costs:?}" - )); - } - work -= source_work; - costs[0] += source_work; - if !source.guide_tube_fits(stroke_from_curve(&curve), radius) { - continue; - } - let lookahead = Motion { - curve, - ..prototype.clone() - }; - let before = work; - let ranked = goal_score( - scene, - stock, - &lookahead, - radius, - right, - tolerance, - &mut work, - Some(goal), - goal_pad, - cancel, - ); - costs[3] += before - work; - let (score, _, tier) = match ranked { - Ok(rank) => rank, - Err(e) if best.is_some() && work == 0 && !e.contains("cancelled") => { - truncated = true; - break 'search; - } - Err(e) => { - return Err(format!( - "{e}; re-entry goal={goal:?}, candidate={p:?}, heading={heading}, source/stock/disk/rank/jointFront/reserved={costs:?}" - )); - } - }; - if tier < 2 - || best.as_ref().is_some_and(|(old, old_tier, ..)| { - tier < *old_tier || (tier == *old_tier && score <= *old) - }) - { - continue; - } - if work == 0 { - if best.is_some() { - truncated = true; - break 'search; - } - return Err("stock-front lead work limit; coverage unproven".into()); - } - let options = EngagementOptions { - tolerance_mm: tolerance, - resolution_mm: (32. * tolerance).max(0.001), - max_nodes: 8192, - max_work: work.saturating_sub(pose_floor).max(1), - ..Default::default() - }; - let checked = - scene.check_front(&lookahead, radius, max_angle, right, options, cancel)?; - costs[4] += (checked.support_tests + checked.index_visits).min(work); - work = work.saturating_sub(checked.support_tests + checked.index_visits); - if checked.status != EngagementStatus::Bounded { - continue; - } - if !clearance_proven { - // First find a useful, fully checked forward move. An - // expensive whole-disk union proof for a pose with no - // usable exit cannot contribute a re-entry candidate. - // Descent is still forbidden until this proof succeeds. - let before = work; - let disk = scene.clear_disk( - p, - radius + pad, - position[2], - tolerance, - &mut work, - cancel, - ); - costs[2] += before - work; - match disk { - Ok(true) => clearance_proven = true, - Ok(false) => continue 'search, - Err(e) if best.is_some() && work == 0 && !e.contains("cancelled") => { - truncated = true; - break 'search; - } - Err(e) => return Err(e), - } - } - // Positions are sorted by distance to the remaining goal. - // Compare useful advances from this pose before choosing: the - // first admissible tiny arc must not hide a longer useful one. - best = Some((score, tier, p, heading, key, Some(lookahead.curve))); - } - } - if segment_entry && best.is_some() { - break; - } - } - let Some((_, _, p, heading, key, lead)) = best else { - return Ok(None); - }; - let down = [p[0], p[1], position[2]]; - let mut queue = VecDeque::new(); - push_relink( - &mut queue, - position, - down, - clearance, - prototype.feed_mm_min, - plunge_feed, - Some(heading), - ); - if let Some(lead) = lead { - queue.push_back(Transfer { - curve: lead, - kind: MoveKind::Lead, - feed: prototype.feed_mm_min, - heading: None, - }); - } - Ok(Some((key, queue, truncated))) -} - -/// Candidate geometry only. No candidate carries stock-clearance authority. -/// Short advances do not always reach material from a clear descent disk: the -/// first quarter of a recovery turn can be air. Include longer turns in the -/// requested sense without requiring an orbit for other useful advances. -/// The caller must prove source and continuous contact/side before queueing. -fn reentry_leads( - position: Vec3, - heading: f64, - radius: f64, - minimum_radius: f64, - right: bool, -) -> Vec { - let sign = if right { 1. } else { -1. }; - let mut curvatures = vec![ - 0., - -sign / (4. * radius), - sign / (4. * radius), - -sign / radius, - sign / radius, - -sign / minimum_radius, - sign / minimum_radius, - ]; - curvatures.dedup_by(|a, b| (*a - *b).abs() < 1e-9); - let mut result = Vec::new(); - for sweep in [PI, TAU] { - result.push(candidate( - position, - heading, - sign / minimum_radius, - sweep * minimum_radius, - )); - } - for k in curvatures { - let mut previous: Option = None; - for scale in [4., 1., 0.25, 0.0625] { - let length = (radius * scale).min(if k == 0. { - f64::INFINITY - } else { - PI / (2. * k.abs()) - }); - if previous.is_some_and(|old| (old - length).abs() < 1e-9) { - continue; - } - previous = Some(length); - result.push(candidate(position, heading, k, length)); - } - } - result -} - -#[cfg(test)] -mod ranking_tests { - use super::*; - use crate::stock::StockSpec; - #[test] - fn initial_material_witness_uses_strict_domain_and_current_stock_lower_bounds() { - use crate::{ - planar::{Boundary, Component, ConstructionOptions, PlanarRegion}, - stock::HeightBounds, - }; - let square = |a, b| Boundary { - vertices: vec![[a, a, 0.], [b, a, 0.], [b, b, 0.], [a, b, 0.]], - }; - let definition = PlanarRegion { - version: 1, - units: "mm".into(), - name: "coverage".into(), - boundary_error_mm: 0., - source: serde_json::Value::Null, - components: vec![Component { - outer: square(2., 8.), - holes: vec![square(4., 6.)], - }], - }; - let make = |definition: &PlanarRegion| { - FrontCoverage::new( - definition.prepare(ConstructionOptions::default()).unwrap(), - [2.5, 2.5], - (0, 0), - 5., - 1e-5, - 0.01, - 0.5, - definition.prepare(ConstructionOptions::default()).unwrap(), - 0., - ) - .unwrap() - }; - let coverage = make(&definition); - let stock = Stock::new(StockSpec { - version: 1, - units: "mm".into(), - min_mm: [0., 0., 0.], - max_mm: [10., 10., 10.], - cell_size_mm: 0.25, - max_cells: 10000, - }) - .unwrap(); - let revision = (stock.identity(), stock.generation()); - let point = coverage - .material_gap(&stock, revision, [2., 2., 5.], 1e-5, &|| false) - .unwrap() - .unwrap(); - // Independent rectangle/hole membership; no classifier result reused. - assert!(point.iter().all(|v| *v > 2. && *v < 8.)); - assert!(point.iter().any(|v| *v < 4. || *v > 6.)); - assert_eq!(stock.cells()[0].lower_mm, 10.); - assert!( - coverage - .material_gap(&stock, revision, [2., 2., 4.], 1e-5, &|| false) - .unwrap() - .is_none() - ); - assert!( - coverage - .material_gap( - &stock, - (revision.0, revision.1 + 1), - [2., 2., 5.], - 1e-5, - &|| false - ) - .unwrap() - .is_none() - ); - assert!( - coverage - .material_gap(&stock, revision, [2., 2., 5.], 1e-5, &|| true) - .is_err() - ); - let foreign = Stock::from_snapshot(stock.snapshot()).unwrap(); - assert!( - coverage - .material_gap(&foreign, revision, [2., 2., 5.], 1e-5, &|| false) - .unwrap() - .is_none() - ); - let mut snapshot = stock.snapshot(); - for (i, h) in snapshot.cells.iter_mut().enumerate() { - let p = stock.cell_center(i).unwrap(); - if p.iter().all(|v| *v >= 1. && *v <= 9.) && p.iter().any(|v| *v < 4.7 || *v > 5.3) { - *h = HeightBounds { - lower_mm: 5., - upper_mm: 5., - }; - } - } - let cleared = Stock::from_snapshot(snapshot).unwrap(); - assert!( - coverage - .material_gap( - &cleared, - (cleared.identity(), cleared.generation()), - [2., 2., 5.], - 1e-5, - &|| false - ) - .unwrap() - .is_none() - ); - let scene = EngagementScene::new(cleared.spec().clone(), vec![]).unwrap(); - let mut oracle = make(&definition); - let (mut tiles, mut envelopes, mut hits, mut branches) = (0, 0, 0, 0); - assert!(matches!( - oracle - .check( - &scene, - &cleared, - [2., 2., 5.], - 1., - 1e-5, - &mut tiles, - &mut envelopes, - &mut hits, - &mut branches, - &|| false - ) - .unwrap(), - CoverageResult::Complete - )); - // A partial job with definite remaining material still supplies a Gap. - let mut partial = cleared.snapshot(); - let index = stock - .cells() - .iter() - .enumerate() - .find(|(i, _)| stock.cell_center(*i) == Some(point)) - .unwrap() - .0; - partial.cells[index] = HeightBounds { - lower_mm: 10., - upper_mm: 10., - }; - let partial = Stock::from_snapshot(partial).unwrap(); - assert_eq!( - coverage - .material_gap( - &partial, - (partial.identity(), partial.generation()), - [2., 2., 5.], - 1e-5, - &|| false - ) - .unwrap(), - Some(point) - ); - let mut uncertain = stock.snapshot(); - for h in &mut uncertain.cells { - h.lower_mm = 5. + 1e-5; - } - let uncertain = Stock::from_snapshot(uncertain).unwrap(); - assert!( - coverage - .material_gap( - &uncertain, - (uncertain.identity(), uncertain.generation()), - [2., 2., 5.], - 1e-5, - &|| false - ) - .unwrap() - .is_none() - ); - let mut uncertain_domain = definition; - uncertain_domain.boundary_error_mm = 1.; - assert!( - make(&uncertain_domain) - .material_gap(&stock, revision, [2., 2., 5.], 1e-5, &|| false) - .unwrap() - .is_none() - ); - } - #[test] - fn clear_reentry_link_preserves_queue_on_uncertainty_work_limit_and_cancel() { - let m: crate::stream::StreamManifest = - serde_json::from_str(include_str!("../fixtures/operations/adaptive-pocket.json")) - .unwrap(); - let crate::pocket::Operation::AdaptivePocket(op) = m.operations[0].clone() else { - panic!("fixture") - }; - let source = PocketPlan::prepare( - op.pocket, - &m.tools[0], - m.stock.height().unwrap(), - m.initial_position_mm, - 1, - &|| false, - ) - .unwrap(); - let stock = Stock::new(m.stock.height().unwrap().clone()).unwrap(); - let prior = Motion { - id: 1, - operation: "prior".into(), - tool: "t".into(), - kind: MoveKind::Cut, - feed_mm_min: Some(600.), - curve: Curve::Arc { - start: [7.5, 5., 9.], - end: [7.5, 5., 9.], - center: [7., 5., 9.], - plane: Plane::Xy, - sweep_rad: TAU, - }, - }; - let scene = EngagementScene::new( - m.stock.height().unwrap().clone(), - vec![ClearedSweep::from_motion(&prior, 4., 1e-5).unwrap()], - ) - .unwrap(); - let empty = EngagementScene::new(m.stock.height().unwrap().clone(), vec![]).unwrap(); - let make_queue = || { - VecDeque::from([ - Transfer { - curve: Curve::Line { - start: [5., 5., 9.], - end: [5., 5., 12.], - }, - kind: MoveKind::Retract, - feed: Some(600.), - heading: None, - }, - Transfer { - curve: Curve::Line { - start: [5., 5., 12.], - end: [9., 5., 12.], - }, - kind: MoveKind::Rapid, - feed: None, - heading: None, - }, - Transfer { - curve: Curve::Line { - start: [9., 5., 12.], - end: [9., 5., 9.], - }, - kind: MoveKind::Plunge, - feed: Some(150.), - heading: Some(0.5), - }, - Transfer { - curve: Curve::Line { - start: [9., 5., 9.], - end: [9.5, 5., 9.], - }, - kind: MoveKind::Lead, - feed: Some(600.), - heading: None, - }, - ]) - }; - for (known, mut budget, cancelled) in [ - (&empty, 100000, false), - (&scene, 0, false), - (&scene, 100000, true), - ] { - let mut queue = make_queue(); - let result = clear_reentry_link( - known, - &source, - &stock, - [5., 5., 9.], - 1., - 1e-5, - &prior, - &mut queue, - &mut budget, - &|| cancelled, - ); - assert!(!matches!(result, Ok(true))); - if cancelled { - assert!(result.unwrap_err().contains("cancelled")); - } - for (got, expected) in queue.iter().zip(make_queue()) { - assert_eq!( - (&got.curve, got.kind, got.feed, got.heading), - ( - &expected.curve, - expected.kind, - expected.feed, - expected.heading - ) - ); - } - assert_eq!(queue.len(), 4); - } - let mut queue = make_queue(); - assert!( - clear_reentry_link( - &scene, - &source, - &stock, - [5., 5., 9.], - 1., - 1e-5, - &prior, - &mut queue, - &mut 100000, - &|| false - ) - .unwrap() - ); - assert_eq!(queue.len(), 2); - assert_eq!(queue[0].kind, MoveKind::Link); - assert_eq!(queue[0].curve.start(), [5., 5., 9.]); - assert_eq!(queue[0].curve.end(), [9., 5., 9.]); - assert_eq!(queue[0].heading, Some(0.5)); - assert_eq!(queue[1].kind, MoveKind::Lead); - } - #[test] - fn cancelling_channel_entry_proof_retains_the_unstarted_rail() { - use std::cell::Cell; - let mut m: crate::stream::StreamManifest = - serde_json::from_str(include_str!("../fixtures/operations/adaptive-pocket.json")) - .unwrap(); - m.tools[0].cutter.diameter_mm = 2.; - m.tools[0].cutter.shank_diameter_mm = 2.; - let crate::pocket::Operation::AdaptivePocket(mut op) = m.operations.remove(0) else { - panic!("fixture"); - }; - op.pocket.floor_z_mm = 9.; - op.pocket.stepover_mm = 0.5; - let source = PocketPlan::prepare( - op.pocket, - &m.tools[0], - m.stock.height().unwrap(), - m.initial_position_mm, - 1, - &|| false, - ) - .unwrap(); - let seed = [5., 5.]; - let (centres, domain) = source.front_component_region(seed, 1.49).unwrap(); - let prior = Motion { - id: 1, - operation: "prior".into(), - tool: "large".into(), - kind: MoveKind::Cut, - feed_mm_min: Some(600.), - curve: Curve::Arc { - start: [5.5, 5., 9.], - end: [5.5, 5., 9.], - center: [5., 5., 9.], - plane: Plane::Xy, - sweep_rad: TAU, - }, - }; - let mut driver = FrontDriver::new(&m.tools[0]); - driver.scene = Some( - EngagementScene::new( - m.stock.height().unwrap().clone(), - vec![ClearedSweep::from_motion(&prior, 3., 1e-5).unwrap()], - ) - .unwrap(), - ); - driver.coverage = Some( - FrontCoverage::new(domain, seed, (0, 0), 9., 1e-5, 0.01, 0.5, centres, 1.49).unwrap(), - ); - let rail = Stroke::line(seed, [9., 5.]); - driver.linear_rails = Some(VecDeque::from([rail])); - let polls = Cell::new(0); - let cancel = || { - polls.set(polls.get() + 1); - polls.get() >= 3 - }; - let result = driver.prepare_linear( - &source, - [5., 5., 9.], - 1., - 0.2, - 82., - true, - &prior, - 1e-5, - LinkHeights::from(12.), - 150., - &cancel, - ); - assert!(result.unwrap_err().contains("cancelled")); - assert!( - driver.transfer.is_empty() && driver.pending.is_none() && driver.linear_front.is_none() - ); - assert_eq!(driver.linear_rails.as_ref().unwrap().len(), 1); - driver - .prepare_linear( - &source, - [5., 5., 9.], - 1., - 0.2, - 82., - true, - &prior, - 1e-5, - LinkHeights::from(12.), - 150., - &|| false, - ) - .unwrap(); - assert!(driver.linear_front.is_some()); - assert!(!driver.transfer.is_empty()); - assert!(driver.linear_rails.as_ref().unwrap().is_empty()); - assert_eq!(driver.report.linear_resets, 1); - } - #[test] - fn coverage_memo_keeps_protected_stock_and_is_bound_to_floor_domain_and_identity() { - use crate::planar::{Boundary, Component, ConstructionOptions, PlanarRegion}; - use crate::stock::HeightBounds; - let square = |a: f64, b: f64| Boundary { - vertices: vec![[a, a, 0.], [b, a, 0.], [b, b, 0.], [a, b, 0.]], - }; - let domain = PlanarRegion { - version: 1, - units: "mm".into(), - name: "protected centre".into(), - boundary_error_mm: 0., - source: serde_json::Value::Null, - components: vec![Component { - outer: square(0., 8.), - holes: vec![square(2., 6.)], - }], - }; - let make = |definition: &PlanarRegion, floor| { - let prepared = definition.prepare(ConstructionOptions::default()).unwrap(); - FrontCoverage::new( - definition.prepare(ConstructionOptions::default()).unwrap(), - [1., 1.], - (0, 0), - floor, - 1e-5, - 0.01, - 0.5, - prepared, - 0., - ) - .unwrap() - }; - let spec = StockSpec { - version: 1, - units: "mm".into(), - min_mm: [0., 0., 0.], - max_mm: [8., 8., 10.], - cell_size_mm: 0.25, - max_cells: 2000, - }; - let initial = Stock::new(spec.clone()).unwrap(); - let mut snapshot = initial.snapshot(); - for (i, h) in snapshot.cells.iter_mut().enumerate() { - let p = initial.cell_center(i).unwrap(); - if p.iter().any(|v| *v < 3. || *v > 5.) { - *h = HeightBounds { - lower_mm: 9., - upper_mm: 9., - }; - } - } - let stock = Stock::from_snapshot(snapshot).unwrap(); - let scene = EngagementScene::new(spec, vec![]).unwrap(); - let mut coverage = make(&domain, 9.); - let (mut tiles, mut envelopes, mut hits, mut branches) = (0, 0, 0, 0); - assert!(matches!( - coverage - .check( - &scene, - &stock, - [1., 1., 9.], - 1., - 1e-5, - &mut tiles, - &mut envelopes, - &mut hits, - &mut branches, - &|| false - ) - .unwrap(), - CoverageResult::Complete - )); - assert!(coverage.covered_tiles.contains(&1)); - assert!(stock.cells().iter().any(|h| h.lower_mm == 10.)); - let old_tiles = tiles; - assert!(matches!( - coverage - .check( - &scene, - &stock, - [7., 7., 9.], - 1., - 1e-5, - &mut tiles, - &mut envelopes, - &mut hits, - &mut branches, - &|| false - ) - .unwrap(), - CoverageResult::Complete - )); - assert_eq!(tiles, old_tiles + 1); - assert!(hits > 0); - assert!( - coverage - .check( - &scene, - &stock, - [7., 7., 9.], - 1., - 1e-5, - &mut tiles, - &mut envelopes, - &mut hits, - &mut branches, - &|| true - ) - .is_err() - ); - // A new floor/domain must start without any of those coverage proofs. - let mut opened = domain.clone(); - opened.components[0].holes.clear(); - for mut other in [make(&domain, 8.), make(&opened, 9.)] { - assert!(other.covered_tiles.is_empty()); - assert!(matches!( - other - .check( - &scene, - &stock, - [4., 4., other.floor], - 1., - 1e-5, - &mut tiles, - &mut envelopes, - &mut hits, - &mut branches, - &|| false - ) - .unwrap(), - CoverageResult::Gap(_) - )); - } - // Reusing split nodes must still find the same unresolved material as - // fresh checks, even when changing pose changes breadth-first ordering. - let mut gap_snapshot = stock.snapshot(); - for (i, h) in gap_snapshot.cells.iter_mut().enumerate() { - let p = stock.cell_center(i).unwrap(); - if p.iter().all(|v| *v > 0.75 && *v < 1.25) { - *h = HeightBounds { - lower_mm: 10., - upper_mm: 10., - }; - } - } - let gap_stock = Stock::from_snapshot(gap_snapshot).unwrap(); - let mut retained = make(&domain, 9.); - let mut reused = 0; - for p in [[7., 7., 9.], [1., 1., 9.], [7., 1., 9.], [1., 7., 9.]] { - let mut cold = make(&domain, 9.); - let expected = cold - .check( - &scene, - &gap_stock, - p, - 1., - 1e-5, - &mut 0, - &mut 0, - &mut 0, - &mut 0, - &|| false, - ) - .unwrap(); - let actual = retained - .check( - &scene, - &gap_stock, - p, - 1., - 1e-5, - &mut 0, - &mut 0, - &mut 0, - &mut reused, - &|| false, - ) - .unwrap(); - match (expected, actual) { - (CoverageResult::Gap(a), CoverageResult::Gap(b)) => assert_eq!(a, b), - _ => panic!("unresolved requested stock must remain a gap"), - } - } - assert!(reused > 0); - assert!(!retained.covered_tiles.contains(&1)); - - let fixture: crate::stream::StreamManifest = - serde_json::from_str(include_str!("../fixtures/operations/adaptive-pocket.json")) - .unwrap(); - let mut driver = FrontDriver::new(&fixture.tools[0]); - driver.synchronize(&stock, 1., 1e-5, &|| false).unwrap(); - driver.coverage = Some(coverage); - let restored = Stock::from_snapshot(stock.snapshot()).unwrap(); - assert_eq!(restored.generation(), stock.generation()); - assert!(driver.synchronize(&restored, 1., 1e-5, &|| false).is_err()); - driver.synchronize(&stock, 1., 1e-5, &|| false).unwrap(); - assert!(driver.coverage.unwrap().covered_tiles.contains(&1)); - } - - #[test] - fn ranked_admission_matches_incremental_native_choice_ties_and_exhausted_prefix() { - let spec = StockSpec { - version: 1, - units: "mm".into(), - min_mm: [0., 0., 0.], - max_mm: [20., 20., 10.], - cell_size_mm: 1., - max_cells: 1000, - }; - let stock = Stock::new(spec.clone()).unwrap(); - // This real flat sweep is wholly outside stock. Keeping its index - // makes zero ranking work genuinely exhaust a primitive/index query. - let old = Motion { - id: 0, - operation: "prior".into(), - tool: "t".into(), - kind: MoveKind::Cut, - feed_mm_min: Some(600.), - curve: Curve::Line { - start: [-2., -2., 5.], - end: [-1.8, -2., 5.], - }, - }; - let scene = EngagementScene::new( - spec, - vec![ClearedSweep::from_motion(&old, 1., 1e-5).unwrap()], - ) - .unwrap(); - let limit = 2. * 0.75f64.acos().to_degrees(); - let options = EngagementOptions::default(); - for right in [true, false] { - let heading = if right { PI / 2. } else { -PI / 2. }; - let goal = Some([0.1, if right { 10.1 } else { 9.9 }]); - let curves = [ - candidate([-0.8, 10., 5.], heading, 0., 0.125), - candidate([-0.8, 10., 5.], heading, if right { -0.5 } else { 0.5 }, PI), - candidate([-0.8, 10., 5.], heading, 0., 0.25), - candidate([-0.8, 10., 5.], heading, 0., 0.25), - ]; - let proposals = || { - curves - .iter() - .enumerate() - .map(|(i, curve)| { - // Independent whole-source certificate: every axis bounding - // box plus1.1mm fits this free machining envelope. - let b = curve.prepare(1e-5).unwrap().bounds(); - assert!((0..2).all(|k| b.min[k] - 1.1 > -3. && b.max[k] + 1.1 < 23.)); - let motion = Motion { - id: i as u64 + 1, - curve: curve.clone(), - ..old.clone() - }; - let (score, novelty, tier) = goal_score( - &scene, - &stock, - &motion, - 1., - right, - 1e-5, - &mut 200000, - goal, - 0.0025, - &|| false, - ) - .unwrap(); - assert!(score > 1e-5); - FrontProposal { - score, - motion, - novelty, - tier, - } - }) - .collect::>() - }; - let ranked = proposals(); - assert!( - ranked[1].score > ranked[2].score, - "highest rank must be genuinely unsafe" - ); - assert_eq!(ranked[2].score, ranked[3].score, "two equal safe ranks"); - // Independent reference control flow, using ACTUAL native - // total/side queries rather than a synthetic boolean predicate. - let mut reference: Option = None; - for p in &ranked { - if reference.as_ref().is_some_and(|(score, _, _, _, tier)| { - p.tier < *tier || (p.tier == *tier && p.score <= *score) - }) { - continue; - } - let a = scene - .check(&p.motion, 1., limit, options, &|| false) - .unwrap(); - if a.status == EngagementStatus::Bounded - && scene - .check_material_side(&p.motion, 1., right, options, &|| false) - .unwrap() - .status - == EngagementStatus::Bounded - { - reference = Some(( - p.score, - p.motion.clone(), - a.upper_angle_deg, - p.novelty, - p.tier, - )); - } - } - assert_eq!( - reference.as_ref().unwrap().1.id, - 3, - "first safe tie in generator order" - ); - let mut report = FrontReport::default(); - let selected = admit_ranked_front( - ranked, - None, - &scene, - 1., - limit, - right, - options, - &mut report, - &|| false, - ) - .unwrap(); - assert_eq!(selected, reference); - assert_eq!( - report.joint_rejections, 1, - "unsafe best rank was actually checked" - ); - // A contact bound, even 360deg, cannot admit the wrong material - // side. This line has the same bounded contact as the safe tie, - // but reversed feed puts stock on the forbidden half throughout. - let mut wrong_side = proposals().remove(2); - wrong_side.motion.id = 100; - wrong_side.motion.curve = candidate([-0.8, 10., 5.], heading + PI, 0., 0.25); - wrong_side.score *= 2.; - assert_eq!( - scene - .check(&wrong_side.motion, 1., limit, options, &|| false) - .unwrap() - .status, - EngagementStatus::Bounded - ); - assert_eq!( - scene - .check_material_side(&wrong_side.motion, 1., right, options, &|| false) - .unwrap() - .status, - EngagementStatus::Unresolved - ); - let wrong = wrong_side.motion.clone(); - let mut safe_ties = proposals(); - let second_tie = safe_ties.pop().unwrap(); - let first_tie = safe_ties.pop().unwrap(); - let mut report = FrontReport::default(); - let side_selected = admit_ranked_front( - vec![wrong_side, first_tie, second_tie], - None, - &scene, - 1., - 360., - right, - options, - &mut report, - &|| false, - ) - .unwrap() - .unwrap(); - assert_eq!(side_selected.1.id, 3); - assert_eq!(report.joint_rejections, 1); - // Reuse neither a successful side witness nor a past failure - // across calls. The same candidate reverses safety with feed side. - let opposite = scene - .check_front(&wrong, 1., limit, !right, options, &|| false) - .unwrap(); - assert_eq!(opposite.status, EngagementStatus::Bounded); - let error = goal_score( - &scene, - &stock, - &proposals()[3].motion, - 1., - right, - 1e-5, - &mut 0, - goal, - 0.0025, - &|| false, - ) - .unwrap_err(); - assert!(error.contains("work limit")); - let mut prefix = proposals(); - prefix.pop(); - let mut report = FrontReport::default(); - assert_eq!( - admit_ranked_front( - prefix, - Some(error.clone()), - &scene, - 1., - limit, - right, - options, - &mut report, - &|| false - ) - .unwrap(), - reference - ); - assert_eq!(report.steering_budget_stops, 1); - let unsafe_only = vec![proposals().remove(1)]; - assert_eq!( - admit_ranked_front( - unsafe_only, - Some(error.clone()), - &scene, - 1., - limit, - right, - options, - &mut FrontReport::default(), - &|| false - ) - .unwrap_err(), - error - ); - let exhausted = EngagementOptions { - max_work: 0, - ..options - }; - assert!( - admit_ranked_front( - proposals(), - None, - &scene, - 1., - limit, - right, - exhausted, - &mut FrontReport::default(), - &|| false - ) - .unwrap() - .is_none() - ); - assert!( - admit_ranked_front( - proposals(), - None, - &scene, - 1., - limit, - right, - options, - &mut FrontReport::default(), - &|| true - ) - .unwrap_err() - .contains("cancelled") - ); - } - } - - #[test] - fn clear_reentry_can_need_more_than_a_quarter_turn_before_cutting() { - let spec = StockSpec { - version: 1, - units: "mm".into(), - min_mm: [0., 0., 0.], - max_mm: [20., 20., 10.], - cell_size_mm: 1., - max_cells: 1000, - }; - let stock = Stock::new(spec.clone()).unwrap(); - let scene = EngagementScene::new(spec, vec![]).unwrap(); - for right in [true, false] { - // Whole forbidden-side support of a turning radius-.2 cutter is - // hypot(1,.2) from the circle centre. The bottom of the circle - // supplies a clear descent; its first quarter remains in air. - let stand_off = 1f64.hypot(0.2) + 0.001; - let start = [10., -stand_off - 0.2, 5.]; - let heading = if right { 0. } else { PI }; - let prototype = Motion { - id: 1, - operation: "delayed-entry".into(), - tool: "t".into(), - kind: MoveKind::Lead, - curve: candidate(start, heading, if right { 5. } else { -5. }, PI * 0.1), - feed_mm_min: Some(600.), - }; - let score = |curve| { - goal_score( - &scene, - &stock, - &Motion { - curve, - ..prototype.clone() - }, - 1., - right, - 1e-5, - &mut 200000, - None, - 0.0025, - &|| false, - ) - .unwrap() - }; - assert_eq!(score(prototype.curve.clone()).2, 0, "first quarter is air"); - assert!( - scene - .clear_disk( - [start[0], start[1]], - 1.00064, - 5., - 1e-5, - &mut 200000, - &|| false - ) - .unwrap() - ); - let curve = reentry_leads(start, heading, 1., 0.2, right) - .into_iter() - .find(|curve| { - matches!(curve, Curve::Arc { sweep_rad, .. } if sweep_rad.abs() >= PI) - && score(curve.clone()).2 >= 2 - }) - .expect("long turn reaches the front after an empty first quarter"); - let checked = scene - .check_front( - &Motion { - curve, - ..prototype.clone() - }, - 1., - 2. * 0.75f64.acos().to_degrees(), - right, - EngagementOptions::default(), - &|| false, - ) - .unwrap(); - assert_eq!(checked.status, EngagementStatus::Bounded); - } - } - #[test] - fn recorded_straight_front_has_a_long_checked_advance_between_coarse_curvatures() { - let data: serde_json::Value = serde_json::from_str(include_str!( - "../fixtures/operations/stock-front-straight-transition.json" - )) - .unwrap(); - let manifest: crate::stream::StreamManifest = - serde_json::from_value(data["manifest"].clone()).unwrap(); - let history: Vec = serde_json::from_value(data["history"].clone()).unwrap(); - let old_next: Motion = serde_json::from_value(data["old_next"].clone()).unwrap(); - let tool = manifest.tools[0].prepare().unwrap(); - let mut stock = Stock::new(manifest.stock.height().unwrap().clone()).unwrap(); - let mut scene = - EngagementScene::new(manifest.stock.height().unwrap().clone(), vec![]).unwrap(); - for motion in &history { - let delta = stock - .preview_sweep(&tool, motion, 1., manifest.sweep, &|| false) - .unwrap(); - stock.apply_delta(&delta).unwrap(); - if motion.kind != MoveKind::Rapid && motion.curve.start()[2] == motion.curve.end()[2] { - scene - .append(ClearedSweep::from_motion(motion, 1., 1e-5).unwrap()) - .unwrap(); - } - } - let start = history.last().unwrap().curve.end(); - assert_eq!(start, old_next.curve.start()); - let heading = tangent(&history.last().unwrap().curve, 1.); - let score = |motion: &Motion| { - potential_score( - &scene, - &stock, - motion, - 1., - true, - 1e-5, - &mut 2_000_000, - None, - 0.0025, - &|| false, - ) - .unwrap() - .0 - }; - let old_score = score(&old_next); - let crate::pocket::Operation::Roughing(op) = &manifest.operations[0] else { - panic!("roughing fixture") - }; - // Independent sufficient source certificate for this left-edge case: - // whole curve bounds lie in the expanded stock envelope and strictly - // left of every retained triangle that can reach this cutting floor. - let part_x = op - .target - .triangles - .iter() - .filter(|triangle| { - triangle - .iter() - .any(|p| p[2] >= start[2] - op.bottom_allowance_mm) - }) - .flatten() - .map(|p| p[0]) - .fold(f64::INFINITY, f64::min); - let mut work = 1_000_000; - let refined = refine_long_advance( - &scene, - &stock, - start, - heading, - 1., - 0.2, - 2. * 0.75f64.acos().to_degrees(), - true, - &old_next, - 1e-5, - None, - 0.0025, - &mut work, - |curve| { - let b = curve.prepare(1e-5).unwrap().bounds(); - let reserve = 1. + op.radial_allowance_mm + 0.01; - if b.max[0] + reserve < part_x - && (0..2).all(|k| { - b.min[k] - reserve > manifest.stock.height().unwrap().min_mm[k] - 3. - && b.max[k] + reserve < manifest.stock.height().unwrap().max_mm[k] + 3. - }) - { - Some(1.) - } else { - None - } - }, - &|| false, - ) - .unwrap(); - let (rank, motion, angle, novel, _) = refined.best.expect("long checked continuation"); - eprintln!( - "recorded straight-front old length={} score={old_score}; refined length={} score={rank}, angle={angle}, work={}", - old_next.curve.prepare(1e-5).unwrap().length_mm(), - motion.curve.prepare(1e-5).unwrap().length_mm(), - 1_000_000 - work - ); - assert!(novel && rank > old_score * 1.5); - assert_eq!(motion.curve.start(), start); - assert!(motion.curve.prepare(1e-5).unwrap().length_mm() >= 3.99); - assert!(angle <= 2. * 0.75f64.acos().to_degrees()); - assert!(!refined.budget_stopped); - assert_eq!( - scene - .check_material_side(&motion, 1., true, EngagementOptions::default(), &|| false) - .unwrap() - .status, - EngagementStatus::Bounded - ); - assert!( - refine_long_advance( - &scene, - &stock, - start, - heading, - 1., - 0.2, - 90., - true, - &old_next, - 1e-5, - None, - 0.0025, - &mut 1_000_000, - |_| Some(1.), - &|| true - ) - .err() - .unwrap() - .contains("cancelled") - ); - let limited = refine_long_advance( - &scene, - &stock, - start, - heading, - 1., - 0.2, - 90., - true, - &old_next, - 1e-5, - None, - 0.0025, - &mut 0, - |_| Some(1.), - &|| false, - ) - .unwrap(); - assert!(limited.best.is_none() && limited.budget_stopped); - } - #[test] - fn useful_reentry_advance_does_not_require_a_productive_full_recovery_orbit() { - let spec = StockSpec { - version: 1, - units: "mm".into(), - min_mm: [0., 0., 0.], - max_mm: [20., 20., 10.], - cell_size_mm: 1., - max_cells: 1000, - }; - let stock = Stock::new(spec.clone()).unwrap(); - let scene = EngagementScene::new(spec, vec![]).unwrap(); - let start = [-1.001, 10., 5.]; - for right in [true, false] { - let sign = if right { 1. } else { -1. }; - let heading = sign * PI / 2.; - let prototype = Motion { - id: 1, - operation: "reentry".into(), - tool: "t".into(), - kind: MoveKind::Lead, - curve: candidate(start, heading, sign / 0.2, TAU * 0.2), - feed_mm_min: Some(600.), - }; - // A whole guarded descent disk is initially outside the stock. - assert!( - scene - .clear_disk([-1.001, 10.], 1.00064, 5., 1e-5, &mut 200000, &|| false) - .unwrap() - ); - let rank = |motion: &Motion| { - potential_score( - &scene, - &stock, - motion, - 1., - right, - 1e-5, - &mut 200000, - None, - 0.0025, - &|| false, - ) - .unwrap() - }; - // The old mandatory recovery circle lies entirely in air. - assert!(!rank(&prototype).1); - let admitted = reentry_leads(start, heading, 1., 0.2, right) - .into_iter() - .map(|curve| Motion { - curve, - ..prototype.clone() - }) - .find(|motion| { - rank(motion).1 - && scene - .check_front( - motion, - 1., - 2. * 0.75f64.acos().to_degrees(), - right, - EngagementOptions::default(), - &|| false, - ) - .unwrap() - .status - == EngagementStatus::Bounded - }) - .expect("a checked partial advance reaches material on the requested side"); - assert_eq!(admitted.curve.start(), start); - assert!(admitted.curve.end()[0] > start[0] + 0.05); - assert!(admitted.curve.prepare(1e-5).unwrap().length_mm() >= 0.5); - if let Curve::Arc { sweep_rad, .. } = admitted.curve { - assert!(sweep_rad.abs() <= PI / 2.); - } - } - } - #[test] - fn air_heavy_motion_does_not_score_as_fully_productive() { - let spec = StockSpec { - version: 1, - units: "mm".into(), - min_mm: [0., 0., 0.], - max_mm: [20., 20., 10.], - cell_size_mm: 1., - max_cells: 1000, - }; - let stock = Stock::new(spec.clone()).unwrap(); - let scene = EngagementScene::new(spec, vec![]).unwrap(); - let score = |start, end| { - let motion = Motion { - id: 1, - operation: "rank".into(), - tool: "t".into(), - kind: MoveKind::Cut, - curve: Curve::Line { start, end }, - feed_mm_min: Some(600.), - }; - potential_score( - &scene, - &stock, - &motion, - 1., - true, - 1e-5, - &mut 200000, - None, - 0.0025, - &|| false, - ) - .unwrap() - }; - // Equal 4mm paths. One only clips the stock corner during its first - // quarter, then spends the rest in air; the other encounters material - // throughout. This exercises the real geometry/stock ranking query. - let (air, air_novel, air_tier) = score([1., -0.8, 5.], [-3., -0.8, 5.]); - let (bulk, bulk_novel, bulk_tier) = score([10., 10., 5.], [6., 10., 5.]); - assert!(air_novel && bulk_novel); - assert_eq!(air_tier, bulk_tier); - assert!(air < 1. && bulk > 3.9, "air={air}, bulk={bulk}"); - } - #[test] - fn forward_swept_area_ranking_distinguishes_chip_width_from_side_contact() { - let spec = StockSpec { - version: 1, - units: "mm".into(), - min_mm: [0., 0., 0.], - max_mm: [20., 20., 10.], - cell_size_mm: 1., - max_cells: 1000, - }; - let stock = Stock::new(spec.clone()).unwrap(); - let scene = EngagementScene::new(spec, vec![]).unwrap(); - let area = |width: f64| { - let x = -(1. - width); - let motion = Motion { - id: 1, - operation: "rank".into(), - tool: "t".into(), - kind: MoveKind::Cut, - curve: Curve::Line { - start: [x, 5., 5.], - end: [x, 9., 5.], - }, - feed_mm_min: Some(600.), - }; - potential_score( - &scene, - &stock, - &motion, - 1., - true, - 1e-5, - &mut 200000, - None, - 0.0025, - &|| false, - ) - .unwrap() - .0 - }; - // Against a straight wall the exact new area is travel*radial width. - // Quadrature is a ranking approximation, never a motion certificate. - let wide = area(0.25) / 4.; - let thin = area(0.02) / 4.; - assert!(wide > 0.2 && wide < 0.35, "wide chip estimate {wide}"); - assert!(thin < 0.05, "thin chip estimate {thin}"); - assert!( - wide > 6. * thin, - "side-contact point count cannot resolve width: {wide}/{thin}" - ); - } -} diff --git a/src/adaptive_front/channel.rs b/src/adaptive_front/channel.rs deleted file mode 100644 index 58640219..00000000 --- a/src/adaptive_front/channel.rs +++ /dev/null @@ -1,610 +0,0 @@ -//! Continuous capsule advances along an exact circular rail from a native seed. -//! This bootstrap never marks the requested domain covered. See method contract. -use crate::{ - Point, - motion::{Curve, Motion, MoveKind, Plane, Vec3}, - planar::PlanarRegion, - pocket::Stroke, - stock::CancelSignal, -}; -use std::f64::consts::{PI, TAU}; - -pub(super) struct ChannelFront { - centre: Point, - rail: f64, - seed: Point, - tip: Point, - angle: f64, - progress: f64, - floor: f64, - orbit: f64, - cutter: f64, - minimum: f64, - guard: f64, - epoch: usize, - inner_axis: Option, -} -pub(super) struct ChannelRecipe { - pub curves: Vec, - pub reset: bool, - inner_axis: Option, - angle: f64, - progress: f64, - tip: Point, - epoch: usize, - cutter: f64, - tolerance: f64, - cursor: usize, -} -fn distance(a: Point, b: Point) -> f64 { - (a[0] - b[0]).hypot(a[1] - b[1]) -} -impl ChannelFront { - pub fn new( - centres: &PlanarRegion, - seed: &Motion, - cutter: f64, - minimum: f64, - tolerance: f64, - ) -> Option { - let Curve::Arc { - start, - end, - center, - plane: Plane::Xy, - sweep_rad, - } = seed.curve - else { - return None; - }; - if seed.kind != MoveKind::Cut || start != end || sweep_rad.abs() != TAU { - return None; - } - let tip = [center[0], center[1]]; - let orbit = distance([start[0], start[1]], tip); - let guard = 64. * tolerance - + 8192. * f64::EPSILON * (1. + tip[0].abs() + tip[1].abs() + cutter + orbit); - if orbit + guard / 8. < minimum || orbit > cutter || orbit <= 8. * guard { - return None; - } - if centres.components.len() != 1 || centres.components[0].holes.is_empty() { - return None; - } - // Circular topology supplies a rail proposal only. Original whole-tube - // source admission is mandatory before the owner is enabled. - for boundary in - std::iter::once(¢res.components[0].outer).chain(¢res.components[0].holes) - { - let strokes = Stroke::from_boundary(boundary); - let Some((centre, _)) = strokes.first().and_then(|s| s.arc) else { - continue; - }; - let mut sweep = 0.; - let authored_radius = distance(strokes[0].a, centre); - if !strokes.iter().all(|s| { - s.arc.is_some_and(|(c, a)| { - sweep += a; - distance(c, centre) <= guard / 8. - && (distance(s.a, centre) - authored_radius).abs() <= guard / 8. - }) - }) || (sweep.abs() - TAU).abs() > 1e-10 - { - continue; - } - let rail = distance(tip, centre); - if rail <= cutter + orbit + 4. * guard || rail - orbit + tolerance < minimum { - continue; - } - return Some(Self { - centre, - rail, - seed: tip, - tip, - angle: (tip[1] - centre[1]).atan2(tip[0] - centre[0]), - progress: 0., - floor: start[2], - orbit, - cutter, - minimum, - guard, - epoch: 0, - inner_axis: None, - }); - } - None - } - pub fn rail_tube(&self) -> (Stroke, f64) { - ( - Stroke { - a: self.seed, - b: self.seed, - arc: Some((self.centre, TAU)), - }, - self.cutter + self.orbit + self.guard / 8., - ) - } - pub fn prepare( - &self, - position: Vec3, - max_angle: f64, - tolerance: f64, - right: bool, - cancel: &impl CancelSignal, - ) -> Result, String> { - if cancel.is_cancelled() { - return Err("channel contour cancelled".into()); - } - if self.progress >= TAU { - return Ok(None); - } - if position[2] != self.floor { - return Err("channel contour floor changed".into()); - } - let (r, s, g) = (self.cutter, self.orbit, self.guard); - let clear = r + s - g; - let half = max_angle.to_radians() / 2.; - let mut delta = ((clear * clear - r * r * half.sin().powi(2)).max(0.).sqrt() - - r * half.cos() - - s - - 4. * g) - .min(s / 4.); - let mut cap = 0.; - for _ in 0..16 { - if delta <= 32. * tolerance { - return Ok(None); - } - let a = s + delta + g / 8.; - cap = 2. - * ((clear * clear - a * a - r * r) / (2. * a * r)) - .clamp(-1., 1.) - .acos(); - if cap.to_degrees() <= max_angle - && cap / 2. + ((delta + g / 8.) / s).asin() < PI / 2. - g / s - { - break; - } - delta /= 2.; - } - if cap.to_degrees() > max_angle - || cap / 2. + ((delta + g / 8.) / s).asin() >= PI / 2. - g / s - { - return Ok(None); - } - let progress = (self.progress + delta / self.rail).min(TAU); - let theta = self.angle + progress; - let tip = if progress == TAU { - self.seed - } else { - [ - self.centre[0] + self.rail * theta.cos(), - self.centre[1] + self.rail * theta.sin(), - ] - }; - let normal = |p: Point| { - [ - (p[0] - self.centre[0]) / self.rail, - (p[1] - self.centre[1]) / self.rail, - ] - }; - let old = normal(self.tip); - let new = normal(tip); - let sign = if right { 1. } else { -1. }; - let side = - |p: Point, n: Point, k: f64| [p[0] + k * s * n[0], p[1] + k * s * n[1], self.floor]; - let a = side(self.tip, old, sign); - let b = side(tip, new, sign); - let c = side(tip, new, -sign); - let d = side(self.tip, old, -sign); - let centre = [self.centre[0], self.centre[1], self.floor]; - let advance = progress - self.progress; - let mut curves = Vec::with_capacity(6); - if self.epoch == 0 && position != a { - if (distance([position[0], position[1]], self.tip) - s).abs() > g / 8. { - return Ok(None); - } - let old_angle = (position[1] - self.tip[1]).atan2(position[0] - self.tip[0]); - let next_angle = (a[1] - self.tip[1]).atan2(a[0] - self.tip[0]); - let mut sweep = sign * ((sign * (next_angle - old_angle)).rem_euclid(TAU)); - if sweep.abs() < 1e-10 { - sweep = sign * TAU; - } - curves.push(Curve::Arc { - start: position, - end: a, - center: [self.tip[0], self.tip[1], self.floor], - plane: Plane::Xy, - sweep_rad: sweep, - }); - } else if position != a { - return Err("channel seam mismatch".into()); - } - let side_curve = Curve::Arc { - start: a, - end: b, - center: centre, - plane: Plane::Xy, - sweep_rad: advance, - }; - curves.push(side_curve.clone()); - curves.push(Curve::Arc { - start: b, - end: c, - center: [tip[0], tip[1], self.floor], - plane: Plane::Xy, - sweep_rad: sign * PI, - }); - curves.push(Curve::Arc { - start: c, - end: d, - center: centre, - plane: Plane::Xy, - sweep_rad: -advance, - }); - curves.push(Curve::Arc { - start: d, - end: a, - center: [self.tip[0], self.tip[1], self.floor], - plane: Plane::Xy, - sweep_rad: sign * PI, - }); - curves.push(side_curve); - for curve in &curves { - if cancel.is_cancelled() { - return Err("channel contour cancelled".into()); - } - curve.prepare(tolerance)?; - let Curve::Arc { start, center, .. } = curve else { - unreachable!() - }; - if distance([start[0], start[1]], [center[0], center[1]]) + tolerance < self.minimum { - return Ok(None); - } - let motion = Motion { - id: 0, - operation: String::new(), - tool: String::new(), - kind: MoveKind::Cut, - feed_mm_min: None, - curve: curve.clone(), - }; - if crate::verification::path_error(&motion, tolerance) > g / 8. { - return Ok(None); - } - } - Ok(Some(ChannelRecipe { - curves, - reset: false, - inner_axis: None, - angle: cap.to_degrees(), - progress, - tip, - epoch: self.epoch, - cutter: r, - tolerance, - cursor: 0, - })) - } - /// Propose concentric cleanup only after the actual channel closes. Radius - /// selection is a heuristic; these curves have NO analytic admission token. - /// The parent checks source, descent and continuous engagement against stock. - pub fn prepare_inner( - &self, - max_angle: f64, - tolerance: f64, - right: bool, - fits: impl Fn(Stroke) -> bool, - cancel: &impl CancelSignal, - ) -> Result, String> { - if cancel.is_cancelled() { - return Err("channel inner contour cancelled".into()); - } - if self.progress < TAU { - return Ok(None); - } - let r = self.cutter; - let old = self - .inner_axis - .unwrap_or(self.rail - self.orbit + self.guard); - let inner = old - r + self.guard; - let half = (max_angle * 0.4).to_radians(); - let mut target = (r * half.cos() - + (inner * inner - (r * half.sin()).powi(2)).max(0.).sqrt()) - .max(self.minimum); - let circle = |radius: f64| Stroke { - a: [self.centre[0] + radius, self.centre[1]], - b: [self.centre[0] + radius, self.centre[1]], - arc: Some((self.centre, TAU)), - }; - if target >= old - 32. * tolerance || !fits(circle(old)) { - return Ok(None); - } - if !fits(circle(target)) { - let mut high = old; - for _ in 0..48 { - if cancel.is_cancelled() { - return Err("channel inner contour cancelled".into()); - } - let mid = (target + high) / 2.; - if fits(circle(mid)) { - high = mid; - } else { - target = mid; - } - } - target = high; - } - if old - target <= 32. * tolerance { - return Ok(None); - } - let sign = if right { 1. } else { -1. }; - let s = self.orbit; - let centre = [self.centre[0], self.centre[1], self.floor]; - let lead_centre = [centre[0] + target + s, centre[1], self.floor]; - let start = [lead_centre[0], lead_centre[1] + sign * s, self.floor]; - let end = [centre[0] + target, centre[1], self.floor]; - Ok(Some(ChannelRecipe { - curves: vec![ - Curve::Arc { - start, - end, - center: lead_centre, - plane: Plane::Xy, - sweep_rad: sign * PI / 2., - }, - Curve::Arc { - start: end, - end, - center: centre, - plane: Plane::Xy, - sweep_rad: -sign * TAU, - }, - ], - reset: true, - inner_axis: Some(target), - angle: 0., - progress: self.progress, - tip: self.tip, - epoch: self.epoch, - cutter: r, - tolerance, - cursor: 0, - })) - } - pub fn committed(&mut self, recipe: &ChannelRecipe) -> Result<(), String> { - if recipe.epoch != self.epoch - || recipe.cursor != recipe.curves.len() - || (recipe.inner_axis.is_none() && recipe.progress <= self.progress) - { - return Err("channel contour incomplete or mismatched recipe".into()); - } - self.tip = recipe.tip; - self.progress = recipe.progress; - if let Some(axis) = recipe.inner_axis { - self.inner_axis = Some(axis); - } - self.epoch += 1; - Ok(()) - } -} -impl ChannelRecipe { - pub fn expects(&self, motion: &Motion, radius: f64, tolerance: f64) -> Result { - if motion.kind == MoveKind::Rapid || motion.curve.start()[2] != motion.curve.end()[2] { - return Ok(false); - } - if radius != self.cutter - || tolerance > self.tolerance - || motion.kind != MoveKind::Cut - || self.curves.get(self.cursor) != Some(&motion.curve) - { - return Err("channel whole native commit mismatch".into()); - } - Ok(true) - } - pub fn advance(&mut self) -> bool { - self.cursor += 1; - self.cursor == self.curves.len() - } - pub fn certified_angle(&self, motion: &Motion) -> Option { - (self.inner_axis.is_none() - && motion.kind == MoveKind::Cut - && self.curves.get(self.cursor) == Some(&motion.curve)) - .then_some(self.angle) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::engagement::{ClearedSweep, EngagementOptions, EngagementScene, EngagementStatus}; - use crate::stock::Stock; - use crate::stream::StreamManifest; - - fn motion(curve: Curve) -> Motion { - Motion { - id: 1, - operation: "channel".into(), - tool: "t1".into(), - kind: MoveKind::Cut, - feed_mm_min: Some(600.), - curve, - } - } - #[test] - fn capsules_obey_continuous_contact_side_tangency_and_actual_stock() { - for right in [false, true] { - let mut m: StreamManifest = serde_json::from_str(include_str!( - "../../fixtures/operations/adaptive-pocket.json" - )) - .unwrap(); - let shift = if right { [0., 0.] } else { [100., -80.] }; - for (k, v) in shift.iter().enumerate() { - m.stock.height_mut().unwrap().min_mm[k] += v; - m.stock.height_mut().unwrap().max_mm[k] += v; - } - let centre = [13. + shift[0], 13. + shift[1]]; - let angle = 0.41_f64; - let seed = [centre[0] + 6.5 * angle.cos(), centre[1] + 6.5 * angle.sin()]; - let p = [seed[0], seed[1] + 1., 9.]; - let mut prior = motion(Curve::Arc { - start: p, - end: p, - center: [seed[0], seed[1], 9.], - plane: Plane::Xy, - sweep_rad: if right { TAU } else { -TAU }, - }); - let mut region = PlanarRegion::circle("centre ring", centre, 7.).unwrap(); - region.components[0].holes.push( - PlanarRegion::circle("protected centre", centre, 6.) - .unwrap() - .components - .remove(0) - .outer, - ); - let mut owner = ChannelFront::new(®ion, &prior, 2., 1., 1e-5).unwrap(); - let mut stock = Stock::new(m.stock.height().unwrap().clone()).unwrap(); - let tool = m.tools[0].prepare().unwrap(); - let delta = stock - .preview_sweep(&tool, &prior, 1., m.sweep, &|| false) - .unwrap(); - stock.apply_delta(&delta).unwrap(); - let mut scene = EngagementScene::new( - m.stock.height().unwrap().clone(), - vec![ClearedSweep::from_motion(&prior, 2., 1e-5).unwrap()], - ) - .unwrap(); - let mut count = 0; - while let Some(mut recipe) = owner - .prepare(prior.curve.end(), 90., 1e-5, right, &|| false) - .unwrap() - { - assert!(owner.committed(&recipe).is_err()); - for curve in recipe.curves.clone() { - let next = motion(curve); - assert_eq!(next.curve.start(), prior.curve.end()); - let a = super::super::tangent(&prior.curve, 1.); - let b = super::super::tangent(&next.curve, 0.); - assert!( - (a - b).sin().abs() < 1e-8 && (a - b).cos() > 0., - "C1 join {a}/{b}" - ); - let checked = scene - .check_front(&next, 2., 90., right, EngagementOptions::default(), &|| { - false - }) - .unwrap(); - assert_eq!( - checked.status, - EngagementStatus::Bounded, - "recipe{count}, {next:?}: {checked:?}" - ); - assert!(recipe.expects(&next, 2., 1e-5).unwrap()); - assert!(recipe.expects(&next, 1.9, 1e-5).is_err()); - assert!(recipe.expects(&next, 2., 1e-4).is_err()); - let delta = stock - .preview_sweep(&tool, &next, 1., m.sweep, &|| false) - .unwrap(); - stock.apply_delta(&delta).unwrap(); - scene - .append(ClearedSweep::from_motion(&next, 2., 1e-5).unwrap()) - .unwrap(); - recipe.advance(); - prior = next; - } - owner.committed(&recipe).unwrap(); - assert!(owner.committed(&recipe).is_err()); - count += 1; - assert!(count < 1000); - } - assert!(count > 100); - assert_eq!(owner.progress, TAU); - let mut checked = 0; - for (i, h) in stock.cells().iter().enumerate() { - let radius = distance(stock.cell_center(i).unwrap(), centre); - if (radius - 6.5).abs() < 2.6 { - assert!( - h.upper_mm <= 9. + 4. * m.sweep.tolerance_mm, - "band cell{radius}: {h:?}" - ); - checked += 1; - } - if radius < 3.1 { - assert!(h.lower_mm >= 10. - 4. * m.sweep.tolerance_mm); - } - } - assert!(checked > 100); - // Finish toward a physical 3 mm island through independent scene - // checks, not through the bootstrap's disk certificate. - let mut inner_count = 0; - while let Some(mut recipe) = owner - .prepare_inner( - 90., - 1e-5, - right, - |stroke| { - let axis = distance(stroke.a, centre); - (5.0001..=8.).contains(&axis) - }, - &|| false, - ) - .unwrap() - { - assert!(recipe.reset); - let start = recipe.curves[0].start(); - assert!( - scene - .clear_disk( - [start[0], start[1]], - 2.00064, - 9., - 1e-5, - &mut 2_000_000, - &|| false - ) - .unwrap() - ); - assert!(owner.committed(&recipe).is_err()); - for curve in recipe.curves.clone() { - let next = motion(curve); - assert!(recipe.certified_angle(&next).is_none()); - let checked = scene - .check_front(&next, 2., 90., right, EngagementOptions::default(), &|| { - false - }) - .unwrap(); - assert_eq!( - checked.status, - EngagementStatus::Bounded, - "inner {next:?}: {checked:?}" - ); - let delta = stock - .preview_sweep(&tool, &next, 1., m.sweep, &|| false) - .unwrap(); - stock.apply_delta(&delta).unwrap(); - scene - .append(ClearedSweep::from_motion(&next, 2., 1e-5).unwrap()) - .unwrap(); - recipe.advance(); - } - owner.committed(&recipe).unwrap(); - assert!(owner.committed(&recipe).is_err()); - inner_count += 1; - assert!(inner_count < 10); - } - assert!(inner_count > 0); - for (i, h) in stock.cells().iter().enumerate() { - let radius = distance(stock.cell_center(i).unwrap(), centre); - if radius > 3.4 && radius < 9.1 { - assert!(h.upper_mm <= 9. + 4. * m.sweep.tolerance_mm); - } - if radius < 2.7 { - assert!(h.lower_mm >= 10. - 4. * m.sweep.tolerance_mm); - } - } - assert!( - owner - .prepare(prior.curve.end(), 90., 1e-5, right, &|| true) - .is_err() - ); - } - } -} diff --git a/src/adaptive_front/convex.rs b/src/adaptive_front/convex.rs deleted file mode 100644 index 0923e602..00000000 --- a/src/adaptive_front/convex.rs +++ /dev/null @@ -1,1366 +0,0 @@ -//! Coherent convex parallel fronts. Only the owner of matching whole native -//! recipes may advance the material envelope. See docs/convex-front.md. -use super::{candidate, tangent}; -use crate::{ - Point, - motion::{Curve, Motion, MoveKind, Plane, Vec3}, - planar::{Component, ConstructionOptions, PlanarRegion, PreparedRegion}, - pocket::{Stroke, stroke_distance}, - stock::CancelSignal, -}; -use robust::{Coord, orient2d}; - -fn sub(a: Point, b: Point) -> Point { - [a[0] - b[0], a[1] - b[1]] -} -fn dot(a: Point, b: Point) -> f64 { - a[0] * b[0] + a[1] * b[1] -} -fn norm(a: Point) -> f64 { - a[0].hypot(a[1]) -} -fn orient(a: Point, b: Point, c: Point) -> f64 { - orient2d( - Coord { x: a[0], y: a[1] }, - Coord { x: b[0], y: b[1] }, - Coord { x: c[0], y: c[1] }, - ) -} -pub(super) fn hull(mut points: Vec) -> Vec { - points.sort_by(|a, b| a[0].total_cmp(&b[0]).then(a[1].total_cmp(&b[1]))); - points.dedup(); - fn half(iter: impl Iterator) -> Vec { - let mut h = Vec::new(); - for p in iter { - while h.len() > 1 && orient(h[h.len() - 2], h[h.len() - 1], p) <= 0. { - h.pop(); - } - h.push(p); - } - h - } - let mut a = half(points.iter().copied()); - let mut b = half(points.iter().rev().copied()); - a.pop(); - b.pop(); - a.extend(b); - a -} - -pub(super) struct ConvexFront { - vertices: Vec, - normals: Vec, - edge: usize, - distance: f64, - floor: f64, - minimum_axis: f64, - previous: Option<(Vec3, f64, f64)>, // real closed-contour seam, axis radius, face parameter -} -pub(super) struct ConvexContour { - pub start: Vec3, - pub heading: f64, - pub leads: Vec, - pub contour: Vec, - pub reset: bool, - pub angle: f64, - radius: f64, - tolerance: f64, - cursor: usize, - distance: f64, - axis: f64, - seam: f64, - bounds: [Point; 2], -} -/// All remaining material is inside this convex body offset by `distance`. -/// Constructed only from a fully consumed contour, never from a proposed hull. -pub(super) struct ConvexMaterial { - vertices: Vec, - distance: f64, - floor: f64, -} - -impl ConvexMaterial { - /// Coverage-domain certificate only: all remaining requested material is - /// inside C offset distance. A separating supporting plane excludes this - /// ENTIRE rectangle. This must never be used as a stock/motion clearance. - pub(super) fn excludes_box( - &self, - bounds: [Point; 2], - floor: f64, - tolerance: f64, - work: &mut u64, - cancel: &impl CancelSignal, - ) -> Result { - if cancel.is_cancelled() { - return Err("convex coverage cancelled".into()); - } - if floor < self.floor { - return Ok(false); - } - let charge = self.vertices.len() as u64 * 2 + 1; - if *work < charge { - return Err("stock-front coverage work limit; coverage unproven".into()); - } - *work -= charge; - let scale = bounds - .into_iter() - .flatten() - .chain(self.vertices.iter().flatten().copied()) - .map(f64::abs) - .fold(1., f64::max); - let guard = 64. * tolerance + 8192. * f64::EPSILON * (1. + scale + self.distance); - for i in 0..self.vertices.len() { - if i.is_multiple_of(64) && cancel.is_cancelled() { - return Err("convex coverage cancelled".into()); - } - let a = self.vertices[i]; - let b = self.vertices[(i + 1) % self.vertices.len()]; - let edge = sub(b, a); - let length = norm(edge); - let normal = [edge[1] / length, -edge[0] / length]; - let nearest = std::array::from_fn(|k| bounds[usize::from(normal[k] < 0.)][k]); - if dot(sub(nearest, a), normal) > self.distance + guard { - return Ok(true); - } - } - Ok(false) - } - /// A connected material body is wholly inside a hole if one of its points - /// is inside and the ENTIRE hole boundary stays separated from the body. - /// This also handles concave holes without treating endpoint tests as proof. - pub fn excludes_domain( - &self, - domain: &PreparedRegion, - floor: f64, - tolerance: f64, - work: &mut u64, - cancel: &impl CancelSignal, - ) -> Result { - #[cfg(feature = "profile-planning")] - let _profile = crate::planning_profile::span("coverage.material"); - if cancel.is_cancelled() { - return Err("convex coverage cancelled".into()); - } - // Another component could request an island nested in this hole. - if floor < self.floor || domain.definition().components.len() != 1 { - return Ok(false); - } - 'holes: for hole in &domain.definition().components[0].holes { - let n = hole.vertices.len() as u64; - let charge = n - .saturating_add(1) - .saturating_pow(2) - .saturating_add(n.saturating_mul(self.vertices.len() as u64 + 1)); - if charge > *work { - return Ok(false); - } - *work -= charge; - if cancel.is_cancelled() { - return Err("convex coverage cancelled".into()); - } - let definition = PlanarRegion { - version: 1, - units: "mm".into(), - name: "coverage exclusion".into(), - boundary_error_mm: domain.definition().boundary_error_mm, - source: serde_json::Value::Null, - components: vec![Component { - outer: hole.clone(), - holes: vec![], - }], - }; - let Ok(exclusion) = definition.prepare(ConstructionOptions { - tolerance_mm: tolerance, - }) else { - continue; - }; - let strokes = Stroke::from_boundary(&exclusion.definition().components[0].outer); - let magnitude = self - .vertices - .iter() - .flatten() - .copied() - .chain(strokes.iter().flat_map(|s| { - s.a.into_iter() - .chain(s.b) - .chain(s.arc.into_iter().flat_map(|(c, _)| c)) - })) - .map(f64::abs) - .fold(1., f64::max); - let guard = 64. * tolerance + 8192. * f64::EPSILON * (1. + magnitude + self.distance); - let inside = exclusion.query(self.vertices[0])?; - if !inside - .signed_clearance_mm - .is_some_and(|d| d > self.distance + inside.uncertainty_mm + guard) - { - continue; - } - for stroke in strokes { - if cancel.is_cancelled() { - return Err("convex coverage cancelled".into()); - } - // Boundary wholly inside C has positive separation from its - // edges, but zero separation from the filled material body. - if (0..self.vertices.len()).all(|i| { - orient( - self.vertices[i], - self.vertices[(i + 1) % self.vertices.len()], - stroke.a, - ) >= 0. - }) { - continue 'holes; - } - let curve = stroke.curve(self.floor); - if curve.prepare(tolerance).is_err() { - continue 'holes; - } - let path_error = crate::verification::path_error( - &Motion { - id: 0, - operation: String::new(), - tool: String::new(), - kind: MoveKind::Cut, - feed_mm_min: None, - curve, - }, - tolerance, - ); - let required = self.distance + inside.uncertainty_mm + guard + path_error; - if !required.is_finite() { - continue 'holes; - } - for i in 0..self.vertices.len() { - if cancel.is_cancelled() { - return Err("convex coverage cancelled".into()); - } - let edge = Stroke::line( - self.vertices[i], - self.vertices[(i + 1) % self.vertices.len()], - ); - let separation = stroke_distance(edge, stroke); - if !separation.is_finite() || separation <= required { - continue 'holes; - } - } - } - return Ok(true); - } - Ok(false) - } -} -impl ConvexFront { - pub fn new( - points: Vec, - material: [Point; 2], - floor: f64, - minimum_axis: f64, - tolerance: f64, - ) -> Option { - if points.len() < 3 - || points.len() > 4096 - || points.iter().flatten().any(|x| !x.is_finite()) - { - return None; - } - let vertices = hull(points); - if vertices.len() < 3 { - return None; - } - let mut normals = Vec::new(); - let mut longest = 0.; - let mut edge = 0; - for i in 0..vertices.len() { - let d = sub(vertices[(i + 1) % vertices.len()], vertices[i]); - let length = norm(d); - if length <= 128. * tolerance { - return None; - } - normals.push([d[1] / length, -d[0] / length]); - if length > longest { - longest = length; - edge = i; - } - } - let mut result = Self { - vertices, - normals, - edge, - distance: 0., - floor, - minimum_axis, - previous: None, - }; - // Distance to a convex set is convex: rectangle vertices bound its - // ENTIRE original material domain, not merely four sampled positions. - result.distance = result.material_distance(material) + 64. * tolerance; - Some(result) - } - fn material_distance(&self, material: [Point; 2]) -> f64 { - let mut distance: f64 = 0.; - for x in [material[0][0], material[1][0]] { - for y in [material[0][1], material[1][1]] { - distance = distance.max(self.point_distance([x, y])); - } - } - distance - } - /// Before the first convex recipe, intersect its envelope with the current - /// authoritative material rectangle left by completed native peeling. - pub fn restrict_material( - &mut self, - material: [Point; 2], - tolerance: f64, - ) -> Result<(), String> { - if self.has_commit() { - return Err("cannot restart a committed convex front".into()); - } - self.distance = self - .distance - .min(self.material_distance(material) + 64. * tolerance); - Ok(()) - } - fn point_distance(&self, p: Point) -> f64 { - let mut inside = true; - let mut distance = f64::INFINITY; - for i in 0..self.vertices.len() { - let a = self.vertices[i]; - let b = self.vertices[(i + 1) % self.vertices.len()]; - inside &= orient(a, b, p) >= 0.; - let d = sub(b, a); - let t = (dot(sub(p, a), d) / dot(d, d)).clamp(0., 1.); - distance = distance.min(norm(sub(p, [a[0] + t * d[0], a[1] + t * d[1]]))); - } - if inside { 0. } else { distance } - } - #[allow(clippy::too_many_arguments)] - pub fn prepare( - &self, - position: Vec3, - radius: f64, - minimum_radius: f64, - max_angle: f64, - boundary_budget: f64, - tolerance: f64, - right: bool, - cancel: &impl CancelSignal, - ) -> Result, String> { - if cancel.is_cancelled() { - return Err("convex front cancelled".into()); - } - if position[2] != self.floor { - return Err("convex front floor changed".into()); - } - let scale = self - .vertices - .iter() - .flatten() - .map(|x| x.abs()) - .fold(radius.max(1.), f64::max); - let guard = 64. * tolerance + 8192. * f64::EPSILON * (1. + scale + radius + self.distance); - let width = radius * (1. - (max_angle.to_radians() / 2.).cos()); - let step = width - boundary_budget / 4. - 4. * guard; - if step <= 4. * guard || step >= radius { - return Ok(None); - } - let axis = (self.distance + radius - step).max(self.minimum_axis); - let distance = axis - radius + guard; - if distance >= self.distance - 32. * tolerance || axis < minimum_radius { - return Ok(None); - } - let n = self.normals[self.edge]; - let a = self.vertices[self.edge]; - let b = self.vertices[(self.edge + 1) % self.vertices.len()]; - let edge_length = norm(sub(b, a)); - let t = if right { sub(a, b) } else { sub(b, a) }; - let t = [t[0] / edge_length, t[1] / edge_length]; - let origin = if right { b } else { a }; - let pad = 64. * tolerance; - let old = self.previous.filter(|(p, _, _)| *p == position); - let shifted = |start_axis: f64| -> Option<(f64, f64, f64)> { - let shift = start_axis - axis; - if shift <= 0. || shift >= radius { - return None; - } - let side_radius = shift * (2. * radius - shift) / (2. * (radius - shift)); - let lead_radius = minimum_radius - .max(radius / 2.) - .max(shift / 2.) - .max(1.05 * side_radius); - let theta = (1. - shift / (2. * lead_radius)).clamp(-1., 1.).acos(); - Some((lead_radius, theta, 2. * lead_radius * theta.sin())) - }; - let mut reset = true; - let mut start_axis = self.distance + radius + 2. * pad; - let mut u = 0.; - if let Some((_, old_axis, old_u)) = old - && let Some((_, _, length)) = shifted(old_axis) - && old_u + length + 128. * tolerance < edge_length - { - reset = false; - start_axis = old_axis; - u = old_u; - } - let Some((lead_radius, theta, length)) = shifted(start_axis) else { - return Ok(None); - }; - if reset { - u = (edge_length - length) / 2.; - } - if u <= 128. * tolerance || u + length >= edge_length - 128. * tolerance { - return Ok(None); - } - let point = |axis: f64, u: f64| { - [ - origin[0] + u * t[0] + axis * n[0], - origin[1] + u * t[1] + axis * n[1], - self.floor, - ] - }; - // A reset disk of radius r+pad is outside the AUTHORITATIVE old - // convex envelope: its inward support is D+pad. Native history is not - // inferred from height cells. A continuing lead uses the actual pose. - let start = if reset { - point(start_axis, u) - } else { - position - }; - let heading = t[1].atan2(t[0]); - let sign = if right { -1. } else { 1. }; - let first = candidate(start, heading, sign / lead_radius, lead_radius * theta); - let second = candidate( - first.end(), - tangent(&first, 1.), - -sign / lead_radius, - lead_radius * theta, - ); - let q = second.end(); - let seam = u + length; - let expected = point(axis, seam); - let deviation = (q[0] - expected[0]).hypot(q[1] - expected[1]); - if deviation > guard / 8. { - return Ok(None); - } - let mut contour = Vec::with_capacity(2 * self.vertices.len() + 1); - let side_fits = |start: Vec3, end: Vec3, n: Point| { - let d = [end[0] - start[0], end[1] - start[1]]; - let length = norm(d); - if length <= 128. * tolerance { - return false; - } - let direction = [d[0] / length, d[1] / length]; - let outward = if right { - [-direction[1], direction[0]] - } else { - [direction[1], -direction[0]] - }; - dot(outward, n) > 0. - && dot(direction, n).abs() < (axis - self.distance - guard / 4.) / radius - }; - let lifted = |v: Point, n: Point| [v[0] + axis * n[0], v[1] + axis * n[1], self.floor]; - let first_start = lifted(origin, n); - let mut cursor = q; - for k in 0..self.vertices.len() { - if cancel.is_cancelled() { - return Err("convex contour cancelled".into()); - } - let i = if right { - (self.edge + self.vertices.len() - k) % self.vertices.len() - } else { - (self.edge + k) % self.vertices.len() - }; - let j = if right { - (i + self.vertices.len() - 1) % self.vertices.len() - } else { - (i + 1) % self.vertices.len() - }; - let vertex = if right { - self.vertices[i] - } else { - self.vertices[(i + 1) % self.vertices.len()] - }; - let end = lifted(vertex, self.normals[i]); - if !side_fits(cursor, end, self.normals[i]) { - return Ok(None); - } - contour.push(Curve::Line { start: cursor, end }); - let next = lifted(vertex, self.normals[j]); - let ni = self.normals[i]; - let nj = self.normals[j]; - let sweep = (ni[0] * nj[1] - ni[1] * nj[0]).atan2(dot(ni, nj)); - if sweep.signum() != sign || sweep.abs() >= std::f64::consts::PI { - return Ok(None); - } - contour.push(Curve::Arc { - start: end, - end: next, - center: [vertex[0], vertex[1], self.floor], - plane: Plane::Xy, - sweep_rad: sweep, - }); - cursor = next; - } - if norm(sub( - [cursor[0], cursor[1]], - [first_start[0], first_start[1]], - )) > guard / 8. - { - return Ok(None); - } - if !side_fits(cursor, q, n) { - return Ok(None); - } - contour.push(Curve::Line { - start: cursor, - end: q, - }); - let leads = vec![first, second]; - let mut error: f64 = deviation; - for curve in leads.iter().chain(&contour) { - curve.prepare(tolerance)?; - error = error.max(crate::verification::path_error( - &Motion { - id: 1, - operation: "convex-front".into(), - tool: "convex-front".into(), - kind: MoveKind::Cut, - curve: curve.clone(), - feed_mm_min: Some(1.), - }, - tolerance, - )); - } - if error > guard / 8. { - return Ok(None); - } - // Full support-plane cap, at EVERY line/vertex-arc position. The - // collar encloses axis arithmetic/path errors. S leads are NOT covered - // here: FrontDriver requires its original continuous joint checker. - let cosine = (axis - self.distance - guard / 4.) / radius; - if cosine <= 0. || cosine > 1. { - return Ok(None); - } - let angle = 2. * cosine.acos().to_degrees(); - if angle > max_angle { - return Ok(None); - } - let bounds = [ - std::array::from_fn(|k| { - self.vertices - .iter() - .map(|v| v[k]) - .fold(f64::INFINITY, f64::min) - - distance - }), - std::array::from_fn(|k| { - self.vertices - .iter() - .map(|v| v[k]) - .fold(f64::NEG_INFINITY, f64::max) - + distance - }), - ]; - Ok(Some(ConvexContour { - start, - heading, - leads, - contour, - reset, - angle, - radius, - tolerance, - cursor: 0, - distance, - axis, - seam, - bounds, - })) - } - pub fn committed(&mut self, recipe: &ConvexContour) -> Result<(), String> { - if recipe.cursor != recipe.leads.len() + recipe.contour.len() - || recipe.distance >= self.distance - || recipe.start[2] != self.floor - { - return Err("convex contour incomplete or mismatched recipe".into()); - } - self.distance = recipe.distance; - self.previous = Some(( - recipe.contour.last().unwrap().end(), - recipe.axis, - recipe.seam, - )); - Ok(()) - } - pub fn has_commit(&self) -> bool { - self.previous.is_some() - } - pub fn material_envelope(&self) -> Option { - (self.has_commit() && self.distance.is_finite() && self.distance >= 0.).then(|| { - ConvexMaterial { - vertices: self.vertices.clone(), - distance: self.distance, - floor: self.floor, - } - }) - } -} -impl ConvexContour { - pub fn expects(&self, motion: &Motion, radius: f64, tolerance: f64) -> Result { - if motion.kind == MoveKind::Rapid || motion.curve.start()[2] != motion.curve.end()[2] { - return Ok(false); - } - if radius != self.radius || tolerance > self.tolerance { - return Err("convex contour cutter/accuracy changed".into()); - } - let expected = self - .leads - .iter() - .chain(&self.contour) - .nth(self.cursor) - .ok_or("convex contour receipt exhausted")?; - if &motion.curve != expected || !matches!(motion.kind, MoveKind::Lead | MoveKind::Cut) { - return Err("convex contour whole native commit mismatch".into()); - } - Ok(true) - } - pub fn advance(&mut self) -> bool { - self.cursor += 1; - self.cursor == self.leads.len() + self.contour.len() - } - pub fn certified_angle(&self, motion: &Motion) -> Option { - (self.cursor >= self.leads.len() - && self.contour.get(self.cursor - self.leads.len()) == Some(&motion.curve) - && motion.kind == MoveKind::Cut) - .then_some(self.angle) - } - pub fn envelope(&self) -> ([Point; 2], f64) { - (self.bounds, self.start[2]) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use std::f64::consts::{PI, TAU}; - - fn motion(curve: Curve, kind: MoveKind) -> Motion { - Motion { - id: 1, - operation: "contour".into(), - tool: "cutter".into(), - kind, - curve, - feed_mm_min: Some(600.), - } - } - - fn coverage_domain(holes: Vec, error: f64) -> PreparedRegion { - PlanarRegion { - version: 1, - units: "mm".into(), - name: "coverage geometry".into(), - boundary_error_mm: error, - source: serde_json::Value::Null, - components: vec![Component { - outer: crate::planar::Boundary { - vertices: vec![ - [-20., -20., 0.], - [20., -20., 0.], - [20., 20., 0.], - [-20., 20., 0.], - ], - }, - holes, - }], - } - .prepare(ConstructionOptions::default()) - .unwrap() - } - - #[test] - fn material_containment_checks_whole_lines_arcs_floor_and_uncertainty() { - let square = |r: f64| crate::planar::Boundary { - vertices: vec![[-r, -r, 0.], [r, -r, 0.], [r, r, 0.], [-r, r, 0.]], - }; - let body = ConvexMaterial { - vertices: hull(vec![[-1., -1.], [1., -1.], [1., 1.], [-1., 1.]]), - distance: 0.2, - floor: 5., - }; - let circle = PlanarRegion::circle("circular exclusion", [0., 0.], 2.).unwrap(); - for hole in [square(1.4), circle.components[0].outer.clone()] { - let domain = coverage_domain(vec![hole], 0.); - assert!( - body.excludes_domain(&domain, 5., 1e-5, &mut 10000, &|| false) - .unwrap() - ); - assert!( - body.excludes_domain(&domain, 6., 1e-5, &mut 10000, &|| false) - .unwrap() - ); - assert!( - !body - .excludes_domain(&domain, 4.99999, 1e-5, &mut 10000, &|| false) - .unwrap() - ); - assert!( - !body - .excludes_domain(&domain, 5., 1e-5, &mut 0, &|| false) - .unwrap() - ); - assert!( - body.excludes_domain(&domain, 5., 1e-5, &mut 10000, &|| true) - .is_err() - ); - } - // All C vertices lie inside this circle, but their offset disks do not. - let small = PlanarRegion::circle("tight circle", [0., 0.], 1.5).unwrap(); - let domain = coverage_domain(vec![small.components[0].outer.clone()], 0.); - assert!( - !body - .excludes_domain(&domain, 5., 1e-5, &mut 10000, &|| false) - .unwrap() - ); - for (hole, error) in [(square(1.2), 0.), (square(1.2001), 0.), (square(1.3), 0.15)] { - assert!( - !body - .excludes_domain( - &coverage_domain(vec![hole], error), - 5., - 1e-5, - &mut 10000, - &|| false - ) - .unwrap() - ); - } - } - - #[test] - fn material_containment_is_rigid_transform_invariant() { - for (angle, shift) in [(0.41_f64, [0., 0.]), (-1.17, [10000., -20000.])] { - let transform = |p: Point| { - [ - p[0] * angle.cos() - p[1] * angle.sin() + shift[0], - p[0] * angle.sin() + p[1] * angle.cos() + shift[1], - ] - }; - let body = ConvexMaterial { - vertices: hull( - [[-1., -1.], [1., -1.], [1., 1.], [-1., 1.]] - .into_iter() - .map(transform) - .collect(), - ), - distance: 0.2, - floor: 5., - }; - for (curved, radius, expected) in [ - (false, 1.4, true), - (false, 1.2, false), - (true, 2., true), - (true, 1.5, false), - ] { - let hole = if curved { - PlanarRegion::circle("rotated circle", [0., 0.], radius) - .unwrap() - .components[0] - .outer - .clone() - } else { - crate::planar::Boundary { - vertices: vec![ - [-radius, -radius, 0.], - [radius, -radius, 0.], - [radius, radius, 0.], - [-radius, radius, 0.], - ], - } - }; - let mut definition = coverage_domain(vec![hole], 0.).definition().clone(); - for component in &mut definition.components { - for boundary in - std::iter::once(&mut component.outer).chain(component.holes.iter_mut()) - { - for vertex in &mut boundary.vertices { - let p = transform([vertex[0], vertex[1]]); - vertex[0] = p[0]; - vertex[1] = p[1]; - } - } - } - let domain = definition.prepare(ConstructionOptions::default()).unwrap(); - assert_eq!( - body.excludes_domain(&domain, 5., 1e-5, &mut 10000, &|| false) - .unwrap(), - expected, - "angle={angle} shift={shift:?} curved={curved} radius={radius}" - ); - } - } - } - - #[test] - fn material_containment_rejects_concave_gaps_and_nested_requested_components() { - let body = ConvexMaterial { - vertices: hull(vec![[-1., -1.], [1., -1.], [1., 1.], [-1., 1.]]), - distance: 0.2, - floor: 5., - }; - // Every hull vertex lies well inside the excluded U, and all hole - // vertices lie outside C. Only whole-edge separation finds the gap. - let notch = crate::planar::Boundary { - vertices: vec![ - [-2., -2., 0.], - [2., -2., 0.], - [2., 2., 0.], - [0.4, 2., 0.], - [0.4, -1.5, 0.], - [-0.4, -1.5, 0.], - [-0.4, 2., 0.], - [-2., 2., 0.], - ], - }; - let mut exclusion = coverage_domain(vec![], 0.).definition().clone(); - exclusion.components[0].outer = notch.clone(); - let exclusion = exclusion.prepare(ConstructionOptions::default()).unwrap(); - for p in &body.vertices { - assert!(exclusion.query(*p).unwrap().signed_clearance_mm.unwrap() > 0.2); - } - let domain = coverage_domain(vec![notch], 0.); - assert!(domain.query([0., 0.]).unwrap().signed_clearance_mm.unwrap() > 0.); - assert!( - !body - .excludes_domain(&domain, 5., 1e-5, &mut 10000, &|| false) - .unwrap() - ); - - let hole = PlanarRegion::circle("hole", [0., 0.], 3.).unwrap(); - let mut nested = coverage_domain(vec![hole.components[0].outer.clone()], 0.) - .definition() - .clone(); - nested.components.extend( - PlanarRegion::circle("requested island", [0., 0.], 0.5) - .unwrap() - .components, - ); - let nested = nested.prepare(ConstructionOptions::default()).unwrap(); - assert!(nested.query([0., 0.]).unwrap().signed_clearance_mm.unwrap() > 0.); - assert!( - !body - .excludes_domain(&nested, 5., 1e-5, &mut 10000, &|| false) - .unwrap() - ); - } - - #[test] - fn material_envelope_is_unavailable_until_the_entire_recipe_commits() { - let mut front = ConvexFront::new( - vec![[-1., -1.], [1., -1.], [1., 1.], [-1., 1.]], - [[-4., -4.], [4., 4.]], - 5., - 1.1, - 1e-5, - ) - .unwrap(); - assert!(front.material_envelope().is_none()); - let mut recipe = front - .prepare([-6., 0., 5.], 1., 0.2, 82., 0.01, 1e-5, true, &|| false) - .unwrap() - .unwrap(); - assert!(front.committed(&recipe).is_err()); - assert!(front.material_envelope().is_none()); - finish(&mut front, &mut recipe); - let material = front.material_envelope().unwrap(); - assert_eq!(material.floor, 5.); - assert_eq!(material.distance, recipe.distance); - assert!( - front.committed(&recipe).is_err(), - "replaying a completed recipe is not progress" - ); - } - fn angle_on(angle: f64, start: f64, sweep: f64) -> bool { - let travel = if sweep > 0. { - angle - start - } else { - start - angle - }; - travel.rem_euclid(TAU) <= sweep.abs() + 1e-10 - } - // Independent analytic extrema of v.n throughout an arc's rotating normal. - fn maximum_dot(v: Point, start: f64, sweep: f64) -> f64 { - let at = |a: f64| v[0] * a.cos() + v[1] * a.sin(); - let mut result = at(start).max(at(start + sweep)); - if angle_on(v[1].atan2(v[0]), start, sweep) { - result = result.max(v[0].hypot(v[1])); - } - result - } - fn finish(front: &mut ConvexFront, recipe: &mut ConvexContour) { - let old = front.distance; - let curves: Vec<_> = recipe - .leads - .iter() - .chain(&recipe.contour) - .cloned() - .collect(); - for (i, curve) in curves.into_iter().enumerate() { - let kind = if i < recipe.leads.len() { - MoveKind::Lead - } else { - MoveKind::Cut - }; - let m = motion(curve, kind); - assert!(recipe.expects(&m, 1., 1e-5).unwrap()); - assert_eq!(recipe.certified_angle(&m).is_some(), kind == MoveKind::Cut); - let complete = recipe.advance(); - assert_eq!(complete, i + 1 == recipe.leads.len() + recipe.contour.len()); - // A partly consumed recipe cannot update its owner's material bound. - assert_eq!(front.distance, old); - if complete { - front.committed(recipe).unwrap(); - } - } - } - - #[test] - fn rotated_convex_contours_have_whole_curve_support_and_correct_material_side() { - let shapes = [ - vec![[-6., -4.], [6., -4.], [6., 4.], [-6., 4.]], - vec![[-6., -3.], [1., -5.], [6., -1.], [4., 5.], [-5., 4.]], - ]; - for shape in shapes { - for angle in [0_f64, 0.37, 1.21] { - for shift in [[0., 0.], [12000., -8000.]] { - let points: Vec = shape - .iter() - .map(|p| { - [ - shift[0] + p[0] * angle.cos() - p[1] * angle.sin(), - shift[1] + p[0] * angle.sin() + p[1] * angle.cos(), - ] - }) - .collect(); - let material = [ - std::array::from_fn(|k| { - points.iter().map(|p| p[k]).fold(f64::INFINITY, f64::min) - 2. - }), - std::array::from_fn(|k| { - points - .iter() - .map(|p| p[k]) - .fold(f64::NEG_INFINITY, f64::max) - + 2. - }), - ]; - for right in [false, true] { - let mut front = - ConvexFront::new(points.clone(), material, 2., 1.101, 1e-5).unwrap(); - let mut position = [material[0][0] - 1., material[0][1], 2.]; - let mut count = 0; - let mut resets = 0; - while let Some(mut recipe) = front - .prepare(position, 1., 0.2, 82., 0.01, 1e-5, right, &|| false) - .unwrap() - { - count += 1; - assert!(count < 100); - resets += usize::from(recipe.reset); - assert!(recipe.distance < front.distance); - assert!(recipe.angle <= 82.); - // Normal-distance support bounds contact continuously, - // including every intermediate normal of every vertex arc. - let mut maximum_path_error: f64 = 0.; - let mut cursor = recipe.start; - for curve in recipe.leads.iter().chain(&recipe.contour) { - assert_eq!(curve.start(), cursor); - let error = crate::verification::path_error( - &motion(curve.clone(), MoveKind::Cut), - 1e-5, - ); - assert!(error < recipe.distance - (recipe.axis - 1.)); - maximum_path_error = maximum_path_error.max(error); - cursor = curve.end(); - } - assert_eq!(cursor, recipe.contour[0].start()); - assert!( - 2. * (recipe.axis - front.distance - maximum_path_error) - .acos() - .to_degrees() - <= recipe.angle - ); - let mut total_turn = 0.; - for curve in &recipe.contour { - match *curve { - Curve::Line { start, end } => { - let d = [end[0] - start[0], end[1] - start[1]]; - let length = d[0].hypot(d[1]); - let n = if right { - [-d[1] / length, d[0] / length] - } else { - [d[1] / length, -d[0] / length] - }; - let support = points - .iter() - .map(|p| p[0] * n[0] + p[1] * n[1]) - .fold(f64::NEG_INFINITY, f64::max); - for p in [start, end] { - assert!( - (p[0] * n[0] + p[1] * n[1] - support - recipe.axis) - .abs() - < 1e-7 - ); - } - } - Curve::Arc { - start, - end, - center, - sweep_rad, - plane: Plane::Xy, - } => { - assert_eq!(sweep_rad.is_sign_negative(), right); - assert!(sweep_rad.abs() < PI); - total_turn += sweep_rad; - for p in [start, end] { - assert!( - ((p[0] - center[0]).hypot(p[1] - center[1]) - - recipe.axis) - .abs() - < 1e-7 - ); - } - let start_angle = - (start[1] - center[1]).atan2(start[0] - center[0]); - for p in &points { - assert!( - maximum_dot( - [p[0] - center[0], p[1] - center[1]], - start_angle, - sweep_rad - ) < 1e-7 - ); - } - } - _ => panic!("unexpected convex contour curve"), - } - } - assert!((total_turn.abs() - TAU).abs() < 1e-10); - position = cursor; - finish(&mut front, &mut recipe); - } - assert!(count > 5); - assert!(resets > 1, "finite face must eventually exhaust"); - assert!(front.distance < 0.102); - } - } - } - } - } - - #[test] - fn transition_uses_remaining_material_and_receipts_match_exact_curves() { - let points = vec![[-6., -4.], [6., -4.], [6., 4.], [-6., 4.]]; - let mut front = - ConvexFront::new(points, [[-20., -20.], [20., 20.]], 2., 1.101, 1e-5).unwrap(); - let old = front.distance; - front - .restrict_material([[-6.2, -4.2], [6.2, 4.2]], 1e-5) - .unwrap(); - assert!(front.distance < 0.284 && front.distance < old); - let restricted = front.distance; - front - .restrict_material([[-30., -30.], [30., 30.]], 1e-5) - .unwrap(); - assert_eq!(front.distance, restricted); - let mut recipe = front - .prepare([0., -5., 2.], 1., 0.2, 82., 0.01, 1e-5, true, &|| false) - .unwrap() - .unwrap(); - let mut m = motion(recipe.leads[0].clone(), MoveKind::Lead); - assert!(recipe.certified_angle(&m).is_none()); - assert!(recipe.expects(&m, 1.1, 1e-5).is_err()); - assert!(recipe.expects(&m, 1., 2e-5).is_err()); - m.curve = recipe.contour[0].clone(); - assert!(recipe.expects(&m, 1., 1e-5).is_err()); - assert!(recipe.certified_angle(&m).is_none()); - m.kind = MoveKind::Rapid; - assert!(!recipe.expects(&m, 1., 1e-5).unwrap()); - assert!(!front.has_commit()); - finish(&mut front, &mut recipe); - assert!( - front - .restrict_material([[-6.1, -4.1], [6.1, 4.1]], 1e-5) - .is_err() - ); - assert!(front.distance < 0.102); - } - - #[test] - fn degenerate_short_faces_and_cancelled_proposals_do_not_create_envelopes() { - assert!( - ConvexFront::new( - vec![[0., 0.], [1., 0.], [2., 0.]], - [[-1., -1.], [3., 1.]], - 2., - 1.1, - 1e-5 - ) - .is_none() - ); - assert!( - ConvexFront::new( - vec![[0., 0.], [1e-4, 0.], [0., 1e-4]], - [[-1., -1.], [1., 1.]], - 2., - 1.1, - 1e-5 - ) - .is_none() - ); - let front = ConvexFront::new( - vec![[0., 0.], [0.1, 0.], [0.1, 0.1], [0., 0.1]], - [[-1., -1.], [1., 1.]], - 2., - 1.1, - 1e-5, - ) - .unwrap(); - assert!( - front - .prepare([0., 0., 2.], 1., 0.2, 82., 0.01, 1e-5, true, &|| false) - .unwrap() - .is_none() - ); - assert!( - front - .prepare([0., 0., 2.], 1., 0.2, 82., 0.01, 1e-5, true, &|| true) - .is_err() - ); - assert!(!front.has_commit()); - } - #[test] - fn opposite_curvature_leads_pass_continuous_checks_against_real_sweeps() { - use crate::engagement::{ - ClearedSweep, EngagementOptions, EngagementScene, EngagementStatus, - }; - use crate::stock::StockSpec; - for right in [false, true] { - for angle in [0_f64, 0.39] { - let points = [[-6., -3.], [1., -5.], [6., -1.], [4., 5.], [-5., 4.]].map(|p| { - [ - p[0] * angle.cos() - p[1] * angle.sin(), - p[0] * angle.sin() + p[1] * angle.cos(), - ] - }); - let material = [[-9., -9.], [9., 9.]]; - let mut front = - ConvexFront::new(points.to_vec(), material, 2., 1.101, 1e-5).unwrap(); - let mut scene = EngagementScene::new( - StockSpec { - version: 1, - units: "mm".into(), - min_mm: [-9., -9., 0.], - max_mm: [9., 9., 3.], - cell_size_mm: 0.5, - max_cells: 10000, - }, - vec![], - ) - .unwrap(); - let mut position = [-10., 0., 2.]; - let mut resets = 0; - let mut count = 0; - while let Some(mut recipe) = front - .prepare(position, 1., 0.2, 82., 0.01, 1e-5, right, &|| false) - .unwrap() - { - count += 1; - assert!(count < 100); - resets += usize::from(recipe.reset); - for (i, curve) in recipe.leads.iter().chain(&recipe.contour).enumerate() { - let m = motion( - curve.clone(), - if i < recipe.leads.len() { - MoveKind::Lead - } else { - MoveKind::Cut - }, - ); - if m.kind == MoveKind::Lead { - let checked = scene - .check_front( - &m, - 1., - 82., - right, - EngagementOptions { - tolerance_mm: 1e-5, - resolution_mm: 0.001, - max_nodes: 8192, - max_work: 2_000_000, - ..Default::default() - }, - &|| false, - ) - .unwrap(); - assert_eq!( - checked.status, - EngagementStatus::Bounded, - "right={right}, rotation={angle}, contour={count}, lead={i}, {checked:?}" - ); - } - // Only actual full curve supports, no synthetic hull or - // rectangular-shell hints in this independent lead check. - scene - .append(ClearedSweep::from_motion(&m, 1., 1e-5).unwrap()) - .unwrap(); - } - position = recipe.contour.last().unwrap().end(); - finish(&mut front, &mut recipe); - } - assert!(resets > 1); - assert!(front.distance < 0.102); - } - } - } - - #[test] - fn concavities_and_spaces_between_islands_remain_in_original_coverage_domain() { - use crate::{ - planar::Boundary, - pocket::{Operation, PocketPlan}, - stream::StreamManifest, - }; - let m: StreamManifest = serde_json::from_str(include_str!( - "../../fixtures/operations/adaptive-pocket.json" - )) - .unwrap(); - let Operation::AdaptivePocket(op) = m.operations[0].clone() else { - panic!("adaptive fixture") - }; - let boundary = |points: &[[f64; 2]]| Boundary { - vertices: points.iter().map(|p| [p[0], p[1], 0.]).collect(), - }; - let cases = [ - ( - vec![boundary(&[ - [8., 8.], - [18., 8.], - [18., 11.], - [11., 11.], - [11., 18.], - [8., 18.], - ])], - [13.5, 13.5], - ), - ( - vec![ - boundary(&[[6., 8.], [9., 8.], [9., 18.], [6., 18.]]), - boundary(&[[17., 8.], [20., 8.], [20., 18.], [17., 18.]]), - ], - [13., 13.], - ), - ]; - for (holes, gap) in cases { - let mut pocket = op.pocket.clone(); - pocket.region.components[0].outer = - boundary(&[[0., 0.], [26., 0.], [26., 26.], [0., 26.]]); - pocket.region.components[0].holes = holes; - let plan = PocketPlan::prepare_guides( - pocket, - &m.tools[0], - m.stock.height().unwrap(), - m.initial_position_mm, - 1, - Some(2.2), - &|| false, - ) - .unwrap(); - let front = ConvexFront::new( - plan.front_obstacles([3., 3.]).unwrap(), - [[0., 0.], [26., 26.]], - 8., - plan.cutter_axis_clearance(2.), - 1e-5, - ) - .unwrap(); - assert_eq!( - front.point_distance(gap), - 0., - "proposal hull encloses the accessible gap" - ); - let (_, domain) = plan.front_component_region([3., 3.], 2.19).unwrap(); - let query = domain.query(gap).unwrap(); - assert!( - query.signed_clearance_mm.unwrap() > query.uncertainty_mm, - "original coverage must still require material inside the convex hull" - ); - let material = ConvexMaterial { - vertices: front.vertices.clone(), - distance: 0.1, - floor: 8., - }; - assert!( - !material - .excludes_domain(&domain, 8., 1e-5, &mut 100000, &|| false) - .unwrap() - ); - } - } - #[test] - fn committed_material_support_planes_exclude_whole_boxes_only_at_valid_floors() { - for angle in [0f64, 0.37, 1.6] { - for shift in [[0., 0.], [100_000., -200_000.]] { - let transform = |p: Point| { - [ - shift[0] + p[0] * angle.cos() - p[1] * angle.sin(), - shift[1] + p[0] * angle.sin() + p[1] * angle.cos(), - ] - }; - let body = ConvexMaterial { - vertices: [[-1., -1.], [1., -1.], [1., 1.], [-1., 1.]] - .map(transform) - .to_vec(), - distance: 0.2, - floor: 5., - }; - for (x, expected) in [ - (1.3, true), - (1.2, false), - (1.19, false), - (0., false), - (-1.3, true), - ] { - let p = transform([x, 0.]); - let bounds = [p.map(|v| v - 0.01), p.map(|v| v + 0.01)]; - assert_eq!( - body.excludes_box(bounds, 5., 1e-5, &mut 100, &|| false) - .unwrap(), - expected - ); - assert!( - !body - .excludes_box(bounds, 4., 1e-5, &mut 100, &|| false) - .unwrap() - ); - assert!( - body.excludes_box(bounds, 5., 1e-5, &mut 0, &|| false) - .is_err() - ); - assert!( - body.excludes_box(bounds, 5., 1e-5, &mut 100, &|| true) - .is_err() - ); - } - // Centre outside is insufficient when the rectangle crosses C. - let p = transform([1.3, 0.]); - let crossing = [p.map(|v| v - 1.), p.map(|v| v + 1.)]; - assert!( - !body - .excludes_box(crossing, 5., 1e-5, &mut 100, &|| false) - .unwrap() - ); - } - } - } -} diff --git a/src/adaptive_front/enclosed.rs b/src/adaptive_front/enclosed.rs deleted file mode 100644 index 8fe87cef..00000000 --- a/src/adaptive_front/enclosed.rs +++ /dev/null @@ -1,1267 +0,0 @@ -//! Growing convex pocket pieces from a real full floor seed. The owner binds -//! every completed contour to exact native sweeps before advancing its scale. -use super::convex::hull; -use crate::{ - Point, - motion::{Curve, Motion, MoveKind, Plane, Vec3}, - planar::PlanarRegion, - pocket::Stroke, - stock::CancelSignal, -}; -use robust::{Coord, orient2d}; -use std::f64::consts::{PI, TAU}; - -fn sub(a: Point, b: Point) -> Point { - [a[0] - b[0], a[1] - b[1]] -} -fn length(a: Point) -> f64 { - a[0].hypot(a[1]) -} -fn orientation(a: Point, b: Point, c: Point) -> f64 { - orient2d( - Coord { x: a[0], y: a[1] }, - Coord { x: b[0], y: b[1] }, - Coord { x: c[0], y: c[1] }, - ) -} -fn turn(a: Point, b: Point, ccw: bool) -> f64 { - let raw = (a[0] * b[1] - a[1] * b[0]).atan2(a[0] * b[0] + a[1] * b[1]); - if ccw { - raw.rem_euclid(TAU) - } else { - -(-raw).rem_euclid(TAU) - } -} - -pub(super) fn growth_step( - r: f64, - s: f64, - guard: f64, - max_angle: f64, - tolerance: f64, -) -> Option<(f64, f64)> { - let clear = r + s - guard; - let half = max_angle.to_radians() / 2.; - let mut delta = ((clear * clear - r * r * half.sin().powi(2)).max(0.).sqrt() - - r * half.cos() - - s - - 4. * guard) - .min(s / 4.); - let mut angle = 0.; - for _ in 0..16 { - if delta <= 32. * tolerance { - return None; - } - let a = s + delta + guard / 8.; - angle = 2. - * ((clear * clear - a * a - r * r) / (2. * a * r)) - .clamp(-1., 1.) - .acos(); - let deviation = ((delta + guard / 8.) / s).asin(); - if angle.to_degrees() <= max_angle && angle / 2. + deviation < PI / 2. - guard / s { - break; - } - delta /= 2.; - } - if angle.to_degrees() > max_angle - || angle / 2. + ((delta + guard / 8.) / s).asin() >= PI / 2. - guard / s - { - return None; - } - Some((delta, angle)) -} - -struct DiskStage { - centre: Point, - radius: f64, - direction: Point, - distance: f64, -} - -pub(super) struct EnclosedFront { - disks: Vec, - pieces: Vec<[Point; 3]>, - seed: Point, - floor: f64, - radius: f64, - cutter: f64, - guard: f64, - piece: usize, - scale: f64, - coverage_radius: Option, - tolerance: f64, -} -pub(super) struct EnclosedContour { - pub start: Vec3, - pub heading: f64, - pub reset: bool, - pub leads: Vec, - pub contour: Vec, - angle: f64, - piece: usize, - scale: f64, - cutter: f64, - tolerance: f64, - cursor: usize, -} -impl EnclosedFront { - fn new_circular( - region: &PlanarRegion, - seed_motion: &Motion, - cutter: f64, - minimum: f64, - tolerance: f64, - ) -> Option { - let Curve::Arc { - start, - end, - center, - plane: Plane::Xy, - sweep_rad, - } = seed_motion.curve - else { - return None; - }; - if seed_motion.kind != MoveKind::Cut || start != end || sweep_rad.abs() != TAU { - return None; - } - let seed = [center[0], center[1]]; - let radius = length(sub([start[0], start[1]], seed)); - let guard = 64. * tolerance - + 8192. * f64::EPSILON * (1. + seed[0].abs() + seed[1].abs() + radius + cutter); - if radius > cutter || radius + guard / 8. < minimum || radius <= 4. * guard { - return None; - } - let strokes = Stroke::from_boundary(®ion.components[0].outer); - let (centre, _) = strokes.first()?.arc?; - let boundary_radius = length(sub(strokes[0].a, centre)); - let mut sweep = 0.; - if !strokes.iter().all(|s| { - s.arc.is_some_and(|(c, a)| { - sweep += a; - length(sub(c, centre)) <= guard / 8. - && (length(sub(s.a, centre)) - boundary_radius).abs() <= guard / 8. - }) - }) || (sweep.abs() - TAU).abs() > 1e-10 - { - return None; - } - // The centre region has already reserved the minimum orbit. Recover - // the final axis radius; original-source tube checks still admit it. - let target = boundary_radius + minimum; - let d = length(sub(centre, seed)); - if target + guard / 8. < radius + d { - return None; - } - let direction = if d > 0. { - [(centre[0] - seed[0]) / d, (centre[1] - seed[1]) / d] - } else { - [1., 0.] - }; - let first = ((target - radius + d) / 2.).max(0.); - let second = (first - d).max(0.); - let mut disks = Vec::new(); - if first > 0. { - disks.push(DiskStage { - centre: seed, - radius, - direction, - distance: first, - }); - } - if second > 0. { - disks.push(DiskStage { - centre: [ - seed[0] + direction[0] * first, - seed[1] + direction[1] * first, - ], - radius: radius + first, - direction: [-direction[0], -direction[1]], - distance: second, - }); - } - if disks.is_empty() { - return None; - } - Some(Self { - disks, - pieces: Vec::new(), - seed, - floor: start[2], - radius, - cutter, - guard, - piece: 0, - scale: 0., - coverage_radius: None, - tolerance, - }) - } - - fn prepare_circular( - &self, - position: Vec3, - max_angle: f64, - tolerance: f64, - right: bool, - cancel: &impl CancelSignal, - ) -> Result, String> { - let Some(stage) = self.disks.get(self.piece) else { - return Ok(None); - }; - if position[2] != self.floor { - return Err("circular front floor changed".into()); - } - let old_radius = stage.radius + stage.distance * self.scale; - let Some((delta, angle)) = - growth_step(self.cutter, old_radius, self.guard, max_angle, tolerance) - else { - return Ok(None); - }; - // The inner unswept core must remain inside the preceding clear disk, - // including when the growing axis radius is larger than the cutter. - let scale = (self.scale + delta.min(self.cutter) / (2. * stage.distance)).min(1.); - let centre_at = |scale: f64| { - [ - stage.centre[0] + stage.direction[0] * stage.distance * scale, - stage.centre[1] + stage.direction[1] * stage.distance * scale, - self.floor, - ] - }; - let old_centre = centre_at(self.scale); - let centre = centre_at(scale); - let start = [ - stage.centre[0] - stage.direction[0] * stage.radius, - stage.centre[1] - stage.direction[1] * stage.radius, - self.floor, - ]; - let old_offset = [position[0] - old_centre[0], position[1] - old_centre[1]]; - if (length(old_offset) - old_radius).abs() > self.guard / 8. { - return Ok(None); - } - let seam = [-stage.direction[0], -stage.direction[1]]; - let mut leads = Vec::new(); - if position != start { - let mut sweep = turn(old_offset, seam, right); - if sweep.abs() < 1e-10 { - sweep = if right { TAU } else { -TAU }; - } - leads.push(Curve::Arc { - start: position, - end: start, - center: old_centre, - plane: Plane::Xy, - sweep_rad: sweep, - }); - } - let contour = vec![Curve::Arc { - start, - end: start, - center: centre, - plane: Plane::Xy, - sweep_rad: if right { TAU } else { -TAU }, - }]; - for curve in leads.iter().chain(&contour) { - if cancel.is_cancelled() { - return Err("circular front cancelled".into()); - } - curve.prepare(tolerance)?; - let m = Motion { - id: 0, - operation: String::new(), - tool: String::new(), - kind: MoveKind::Cut, - curve: curve.clone(), - feed_mm_min: None, - }; - if crate::verification::path_error(&m, tolerance) > self.guard / 8. { - return Ok(None); - } - } - Ok(Some(EnclosedContour { - start, - heading: seam[1].atan2(seam[0]) + if right { PI / 2. } else { -PI / 2. }, - reset: false, - leads, - contour, - angle: angle.to_degrees(), - piece: self.piece, - scale, - cutter: self.cutter, - tolerance, - cursor: 0, - })) - } - - pub fn new( - region: &PlanarRegion, - seed_motion: &Motion, - cutter: f64, - minimum_radius: f64, - tolerance: f64, - ) -> Option { - if region.components.len() != 1 || !region.components[0].holes.is_empty() { - return None; - } - let boundary = ®ion.components[0].outer; - if boundary.vertices.iter().any(|p| p[2] != 0.) { - return Self::new_circular(region, seed_motion, cutter, minimum_radius, tolerance); - } - if boundary.vertices.len() > 4096 || boundary.vertices.iter().any(|p| p[2] != 0.) { - return None; - } - let vertices = hull(boundary.vertices.iter().map(|p| [p[0], p[1]]).collect()); - // Collinear/concave input declines to the original full coverage planner. - if vertices.len() < 3 || vertices.len() != boundary.vertices.len() { - return None; - } - let Curve::Arc { - start, - end, - center, - plane: Plane::Xy, - sweep_rad, - } = seed_motion.curve - else { - return None; - }; - if seed_motion.kind != MoveKind::Cut || start != end || sweep_rad.abs() != TAU { - return None; - } - let seed = [center[0], center[1]]; - let seed_radius = (start[0] - seed[0]).hypot(start[1] - seed[1]); - let roundoff = 256. - * f64::EPSILON - * (1. + seed[0].abs() + seed[1].abs() + seed_radius + minimum_radius); - if seed_radius > cutter || seed_radius + roundoff < minimum_radius { - return None; - } - let radius = minimum_radius.min(seed_radius); - let magnitude = vertices - .iter() - .flatten() - .map(|v| v.abs()) - .fold(cutter.max(1.), f64::max); - let guard = 64. * tolerance + 8192. * f64::EPSILON * (1. + magnitude + cutter + radius); - if radius <= 4. * guard { - return None; - } - let mut pieces = Vec::new(); - for i in 0..vertices.len() { - let a = vertices[i]; - let b = vertices[(i + 1) % vertices.len()]; - let area = orientation(a, b, seed); - if area < 0. { - return None; - } - if area == 0. { - continue; - } - if area <= 128. * tolerance * length(sub(b, a)) { - return None; - } - pieces.push([seed, a, b]); - } - if pieces.is_empty() { - return None; - } - Some(Self { - disks: Vec::new(), - pieces, - seed, - floor: start[2], - radius, - cutter, - guard, - piece: 0, - scale: 0., - // The actual seed must cover its central core even after erosion - // by the sweep/path reserve. A nominal circle of cutter radius - // alone does not prove a filled disk. Near equality keeps fallback. - coverage_radius: (seed_radius + 2. * guard < cutter - && crate::verification::path_error(seed_motion, tolerance) <= guard / 8.) - .then_some(radius + cutter - guard), - tolerance, - }) - } - pub fn prepare( - &self, - position: Vec3, - max_angle: f64, - tolerance: f64, - right: bool, - cancel: &impl CancelSignal, - ) -> Result, String> { - if cancel.is_cancelled() { - return Err("enclosed contour cancelled".into()); - } - if !self.disks.is_empty() { - return self.prepare_circular(position, max_angle, tolerance, right, cancel); - } - let Some(piece) = self.pieces.get(self.piece) else { - return Ok(None); - }; - if position[2] != self.floor { - return Err("enclosed contour floor changed".into()); - } - let r = self.cutter; - let s = self.radius; - let Some((delta, angle)) = growth_step(r, s, self.guard, max_angle, tolerance) else { - return Ok(None); - }; - let longest = piece - .iter() - .map(|p| length(sub(*p, self.seed))) - .fold(0., f64::max); - let scale = (self.scale + delta / longest).min(1.); - let vertices = piece.map(|v| { - [ - self.seed[0] + scale * (v[0] - self.seed[0]), - self.seed[1] + scale * (v[1] - self.seed[1]), - ] - }); - let mut normals = [[0.; 2]; 3]; - for i in 0..3 { - let d = sub(piece[(i + 1) % 3], piece[i]); - let l = length(d); - if l * scale <= 128. * tolerance { - return Ok(None); - } - normals[i] = [d[1] / l, -d[0] / l]; - } - // Anchor at the real seed. Its corner and seam stay fixed throughout - // homothetic growth, so successive contours meet with the same tangent. - let seam = [normals[2][0] + normals[0][0], normals[2][1] + normals[0][1]]; - let l = length(seam); - if l < 1e-10 { - return Ok(None); - } - let seam = [seam[0] / l, seam[1] / l]; - let lifted = |v: Point, n: Point| [v[0] + s * n[0], v[1] + s * n[1], self.floor]; - let start = lifted(self.seed, seam); - let heading = seam[1].atan2(seam[0]) + if right { PI / 2. } else { -PI / 2. }; - let mut contour = Vec::with_capacity(8); - let mut cursor = start; - let first = if right { 0 } else { 2 }; - let first_end = lifted(self.seed, normals[first]); - contour.push(Curve::Arc { - start: cursor, - end: first_end, - center: [self.seed[0], self.seed[1], self.floor], - plane: Plane::Xy, - sweep_rad: turn(seam, normals[first], right), - }); - cursor = first_end; - for k in 0..3 { - if cancel.is_cancelled() { - return Err("enclosed contour cancelled".into()); - } - let edge = if right { k } else { 2 - k }; - let vertex = if right { (edge + 1) % 3 } else { edge }; - let end = lifted(vertices[vertex], normals[edge]); - let tangent = [end[0] - cursor[0], end[1] - cursor[1]]; - let tangent_length = length(tangent); - let tilt = ((tangent[0] * normals[edge][0] + tangent[1] * normals[edge][1]) - / tangent_length) - .abs() - .clamp(0., 1.) - .asin(); - if !tilt.is_finite() - || angle / 2. + ((delta + self.guard / 8.) / s).asin() + tilt - >= PI / 2. - self.guard / s - { - return Ok(None); - } - contour.push(Curve::Line { start: cursor, end }); - cursor = end; - let next_normal = if k == 2 { - seam - } else { - normals[if right { - (edge + 1) % 3 - } else { - (edge + 2) % 3 - }] - }; - let next = if k == 2 { - start - } else { - lifted(vertices[vertex], next_normal) - }; - contour.push(Curve::Arc { - start: cursor, - end: next, - center: [vertices[vertex][0], vertices[vertex][1], self.floor], - plane: Plane::Xy, - sweep_rad: turn(normals[edge], next_normal, right), - }); - cursor = next; - } - let mut leads = Vec::new(); - let reset = ((position[0] - self.seed[0]).hypot(position[1] - self.seed[1]) - s).abs() - > self.guard / 8.; - if !reset && position != start { - let n = [ - (position[0] - self.seed[0]) / s, - (position[1] - self.seed[1]) / s, - ]; - let mut sweep = turn(n, seam, right); - if sweep.abs() < 1e-10 { - sweep = if right { TAU } else { -TAU }; - } - leads.push(Curve::Arc { - start: position, - end: start, - center: [self.seed[0], self.seed[1], self.floor], - plane: Plane::Xy, - sweep_rad: sweep, - }); - } - for curve in leads.iter().chain(&contour) { - curve.prepare(tolerance)?; - let m = Motion { - id: 1, - operation: "enclosed".into(), - tool: "cutter".into(), - kind: MoveKind::Cut, - curve: curve.clone(), - feed_mm_min: Some(1.), - }; - if crate::verification::path_error(&m, tolerance) > self.guard / 8. { - return Ok(None); - } - } - Ok(Some(EnclosedContour { - start, - heading, - reset, - leads, - contour, - angle: angle.to_degrees(), - piece: self.piece, - scale, - cutter: r, - tolerance, - cursor: 0, - })) - } - /// Coverage only, after ALL native fan contours commit. The seed's filled - /// disk starts the induction. For successive convex triangles A subset B, - /// Hausdorff growth is <=delta<=orbit/4. Their rounded boundaries are swept - /// with cutter reserve: the new exterior collar is swept, while B's interior - /// is within delta of A and already clear. The possible inward unswept collar - /// remains in A offset (orbit+cutter-guard), since delta<2*(cutter-guard). - /// Thus every completed fan triangle offset coverage_radius is cleared. - /// Dilation distributes over the complete fan union. Construction uncertainty - /// and an additional guard must fit before this proves the requested domain. - /// No partial fan, circle stage, proposed path or sampled pose supplies proof. - pub fn covers_offset( - &self, - inflation: f64, - error: f64, - floor: f64, - cutter: f64, - tolerance: f64, - ) -> bool { - !self.pieces.is_empty() - && self.disks.is_empty() - && self.piece == self.pieces.len() - && self.scale == 0. - && floor == self.floor - && cutter == self.cutter - && tolerance == self.tolerance - && inflation.is_finite() - && inflation >= 0. - && error.is_finite() - && error >= 0. - && self - .coverage_radius - .is_some_and(|radius| inflation + error + self.guard < radius) - } - pub fn committed(&mut self, recipe: &EnclosedContour) -> Result<(), String> { - if recipe.piece != self.piece - || recipe.cursor != recipe.leads.len() + recipe.contour.len() - || recipe.scale <= self.scale - { - return Err("enclosed contour incomplete or mismatched recipe".into()); - } - self.scale = recipe.scale; - if self.scale == 1. { - self.piece += 1; - self.scale = 0.; - } - Ok(()) - } -} -impl EnclosedContour { - pub fn expects(&self, motion: &Motion, radius: f64, tolerance: f64) -> Result { - if motion.kind == MoveKind::Rapid || motion.curve.start()[2] != motion.curve.end()[2] { - return Ok(false); - } - if radius != self.cutter || tolerance > self.tolerance { - return Err("enclosed cutter/accuracy changed".into()); - } - let expected = self - .leads - .iter() - .chain(&self.contour) - .nth(self.cursor) - .ok_or("enclosed recipe exhausted")?; - if &motion.curve != expected || !matches!(motion.kind, MoveKind::Lead | MoveKind::Cut) { - return Err("enclosed whole native commit mismatch".into()); - } - Ok(true) - } - pub fn advance(&mut self) -> bool { - self.cursor += 1; - self.cursor == self.leads.len() + self.contour.len() - } - pub fn certified_angle(&self, motion: &Motion) -> Option { - (self.cursor >= self.leads.len() - && self.contour.get(self.cursor - self.leads.len()) == Some(&motion.curve) - && motion.kind == MoveKind::Cut) - .then_some(self.angle) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::{ - engagement::{ClearedSweep, EngagementOptions, EngagementScene, EngagementStatus}, - planar::{Boundary, Component}, - stock::StockSpec, - }; - fn motion(curve: Curve) -> Motion { - Motion { - id: 1, - operation: "pocket".into(), - tool: "cutter".into(), - kind: MoveKind::Cut, - curve, - feed_mm_min: Some(600.), - } - } - fn region(points: Vec) -> PlanarRegion { - PlanarRegion { - version: 1, - units: "mm".into(), - name: "pocket".into(), - boundary_error_mm: 0., - source: serde_json::Value::Null, - components: vec![Component { - outer: Boundary { - vertices: points.into_iter().map(|p| [p[0], p[1], 0.]).collect(), - }, - holes: vec![], - }], - } - } - #[test] - fn circular_growth_clears_offset_and_centred_seeds_with_continuous_contact() { - use crate::{stock::Stock, stream::StreamManifest}; - for right in [false, true] { - for (offset, target) in [(0.9, 2.), (0., 2.), (1., 5.)] { - let mut m: StreamManifest = serde_json::from_str(include_str!( - "../../fixtures/operations/adaptive-pocket.json" - )) - .unwrap(); - let shift = if right { [0., 0.] } else { [100., -80.] }; - for (k, v) in shift.iter().enumerate() { - m.stock.height_mut().unwrap().min_mm[k] += v; - m.stock.height_mut().unwrap().max_mm[k] += v; - } - m.tools[0].id = "cutter".into(); - let centre = [13. + shift[0], 13. + shift[1]]; - let angle = 0.41_f64; - let seed = [ - centre[0] + offset * angle.cos(), - centre[1] + offset * angle.sin(), - ]; - let start = [seed[0], seed[1] + 1., 9.]; - let mut prior = motion(Curve::Arc { - start, - end: start, - center: [seed[0], seed[1], 9.], - plane: Plane::Xy, - sweep_rad: if right { TAU } else { -TAU }, - }); - let minimum = if right { 1. } else { 0.25 }; - let region = PlanarRegion::circle("centre disk", centre, target - minimum).unwrap(); - let mut front = EnclosedFront::new(®ion, &prior, 2., minimum, 1e-5).unwrap(); - assert_eq!(front.disks.len(), 2); - let mut stock = Stock::new(m.stock.height().unwrap().clone()).unwrap(); - let tool = m.tools[0].prepare().unwrap(); - let delta = stock - .preview_sweep(&tool, &prior, 1., m.sweep, &|| false) - .unwrap(); - stock.apply_delta(&delta).unwrap(); - let mut scene = EngagementScene::new( - m.stock.height().unwrap().clone(), - vec![ClearedSweep::from_motion(&prior, 2., 1e-5).unwrap()], - ) - .unwrap(); - let mut count = 0; - while let Some(mut recipe) = front - .prepare(prior.curve.end(), 90., 1e-5, right, &|| false) - .unwrap() - { - assert!(!recipe.reset); - assert!(front.committed(&recipe).is_err()); - for (i, curve) in recipe - .leads - .iter() - .chain(&recipe.contour) - .cloned() - .collect::>() - .into_iter() - .enumerate() - { - let mut next = motion(curve); - if i < recipe.leads.len() { - next.kind = MoveKind::Lead; - } - assert_eq!(next.curve.start(), prior.curve.end()); - let a = super::super::tangent(&prior.curve, 1.); - let b = super::super::tangent(&next.curve, 0.); - assert!((a - b).sin().abs() < 1e-8 && (a - b).cos() > 0.); - let Curve::Arc { start, center, .. } = next.curve else { - unreachable!() - }; - let axis = length(sub([start[0], start[1]], [center[0], center[1]])); - assert!( - axis + length(sub([center[0], center[1]], centre)) <= target + 1e-7 - ); - assert!(axis + 1e-7 >= minimum); - let checked = scene - .check_front( - &next, - 2., - 90., - right, - EngagementOptions::default(), - &|| false, - ) - .unwrap(); - assert_eq!( - checked.status, - EngagementStatus::Bounded, - "right={right} offset={offset} target={target}: {next:?}; {checked:?}" - ); - assert!(recipe.expects(&next, 2., 1e-5).unwrap()); - assert!(recipe.expects(&next, 1.9, 1e-5).is_err()); - assert!(recipe.expects(&next, 2., 1e-4).is_err()); - let delta = stock - .preview_sweep(&tool, &next, 1., m.sweep, &|| false) - .unwrap(); - stock.apply_delta(&delta).unwrap(); - scene - .append(ClearedSweep::from_motion(&next, 2., 1e-5).unwrap()) - .unwrap(); - recipe.advance(); - prior = next; - } - front.committed(&recipe).unwrap(); - assert!(front.committed(&recipe).is_err()); - count += 1; - assert!(count < 100); - } - assert_eq!(front.piece, front.disks.len()); - assert!(count > 2); - let mut cleared = 0; - for (i, h) in stock.cells().iter().enumerate() { - let d = length(sub(stock.cell_center(i).unwrap(), centre)); - if d < target + 2. - 0.4 { - assert!(h.upper_mm <= 9. + 4. * m.sweep.tolerance_mm); - cleared += 1; - } - if d > target + 2. + 0.4 { - assert!(h.lower_mm >= 10. - 4. * m.sweep.tolerance_mm); - } - } - assert!(cleared > 100); - assert!( - front - .prepare(prior.curve.end(), 90., 1e-5, right, &|| true) - .is_err() - ); - } - } - } - #[test] - fn growing_fan_contours_obey_independent_continuous_engagement_and_side_checks() { - for right in [false, true] { - for rotation in [0_f64, 0.41] { - let points = [[-0.3, -0.3], [1.1, -0.3], [1.1, 1.1], [-0.3, 1.1]].map(|p| { - [ - p[0] * rotation.cos() - p[1] * rotation.sin(), - p[0] * rotation.sin() + p[1] * rotation.cos(), - ] - }); - let seed = motion(Curve::Arc { - start: [0.5, 0., 2.], - end: [0.5, 0., 2.], - center: [0., 0., 2.], - plane: Plane::Xy, - sweep_rad: if right { TAU } else { -TAU }, - }); - let mut front = - EnclosedFront::new(®ion(points.to_vec()), &seed, 1., 0.2, 1e-5).unwrap(); - let mut scene = EngagementScene::new( - StockSpec { - version: 1, - units: "mm".into(), - min_mm: [-3., -3., 0.], - max_mm: [3., 3., 3.], - cell_size_mm: 0.2, - max_cells: 10000, - }, - vec![ClearedSweep::from_motion(&seed, 1., 1e-5).unwrap()], - ) - .unwrap(); - let mut position = seed.curve.end(); - let mut count = 0; - while let Some(mut recipe) = front - .prepare(position, 82., 1e-5, right, &|| false) - .unwrap() - { - count += 1; - assert!(count < 300); - if recipe.reset { - assert!( - scene - .clear_disk( - [recipe.start[0], recipe.start[1]], - 1.00064, - 2., - 1e-5, - &mut 2_000_000, - &|| false - ) - .unwrap() - ); - position = recipe.start; - } - assert!(front.committed(&recipe).is_err()); - let curves: Vec<_> = recipe - .leads - .iter() - .chain(&recipe.contour) - .cloned() - .collect(); - for (i, c) in curves.into_iter().enumerate() { - assert_eq!(c.start(), position); - let mut m = motion(c); - if i < recipe.leads.len() { - m.kind = MoveKind::Lead; - } - assert!(recipe.expects(&m, 1., 1e-5).unwrap()); - let checked = scene - .check_front( - &m, - 1., - 82., - right, - EngagementOptions { - tolerance_mm: 1e-5, - resolution_mm: 0.001, - max_nodes: 8192, - max_work: 2_000_000, - ..Default::default() - }, - &|| false, - ) - .unwrap(); - assert_eq!( - checked.status, - EngagementStatus::Bounded, - "sense={right},rotation={rotation},recipe={count},curve={i},{checked:?}" - ); - scene - .append(ClearedSweep::from_motion(&m, 1., 1e-5).unwrap()) - .unwrap(); - position = m.curve.end(); - if recipe.advance() { - front.committed(&recipe).unwrap(); - } - } - } - assert_eq!(front.piece, 4); - assert!(count > 20); - // Entire boxes inside the final convex component must be clear - // using only actual swept curves, without a synthetic envelope. - assert!( - scene - .clear_box([[-0.1, -0.1], [0.1, 0.1]], 2., &mut 2_000_000, &|| false) - .unwrap() - ); - } - } - } - #[test] - fn completed_fans_cover_the_whole_offset_by_independent_sweep_union() { - use super::super::{CoverageResult, FrontCoverage}; - use crate::{planar::ConstructionOptions, stock::Stock}; - for right in [false, true] { - for r in [0.25, 4.] { - for shift in [[0., 0., 0.], [10_000., -20_000., 30_000.]] { - for points in [ - vec![[-0.3, -0.3], [1.1, -0.3], [1.1, 1.1], [-0.3, 1.1]], - vec![ - [-0.3, -0.3], - [1.1, -0.3], - [1.4, 0.6], - [0.6, 1.4], - [-0.3, 1.1], - ], - ] { - let tolerance = 1e-5 * r; - let floor = shift[2] + 2. * r; - let definition = region( - points - .into_iter() - .map(|p| [shift[0] + r * p[0], shift[1] + r * p[1]]) - .collect(), - ); - let seed = motion(Curve::Arc { - start: [shift[0] + 0.5 * r, shift[1], floor], - end: [shift[0] + 0.5 * r, shift[1], floor], - center: [shift[0], shift[1], floor], - plane: Plane::Xy, - sweep_rad: if right { TAU } else { -TAU }, - }); - let mut front = - EnclosedFront::new(&definition, &seed, r, 0.2 * r, tolerance).unwrap(); - let inflation = 1.2 * r - 0.02 * r; - let options = ConstructionOptions { - tolerance_mm: tolerance, - }; - let centres = definition.prepare(options).unwrap(); - let domain = centres.offset_prepared(-inflation).unwrap().into_parts().1; - let error = centres.definition().boundary_error_mm - + domain.definition().boundary_error_mm; - assert!(!front.covers_offset(inflation, error, floor, r, tolerance)); - let spec = StockSpec { - version: 1, - units: "mm".into(), - min_mm: [shift[0] - 3. * r, shift[1] - 3. * r, shift[2]], - max_mm: [shift[0] + 4. * r, shift[1] + 4. * r, shift[2] + 3. * r], - cell_size_mm: 0.2 * r, - max_cells: 10000, - }; - let stock = Stock::new(spec.clone()).unwrap(); - let mut scene = EngagementScene::new( - spec, - vec![ClearedSweep::from_motion(&seed, r, tolerance).unwrap()], - ) - .unwrap(); - let mut position = seed.curve.end(); - let mut count = 0; - while let Some(mut recipe) = front - .prepare(position, 82., tolerance, right, &|| false) - .unwrap() - { - count += 1; - assert!(count < 1000); - assert!(!front.covers_offset(inflation, error, floor, r, tolerance)); - assert!(front.committed(&recipe).is_err()); - let curves: Vec<_> = recipe - .leads - .iter() - .chain(&recipe.contour) - .cloned() - .collect(); - for (i, curve) in curves.into_iter().enumerate() { - let mut m = motion(curve); - if i < recipe.leads.len() { - m.kind = MoveKind::Lead; - } - assert!(recipe.expects(&m, r, tolerance).unwrap()); - // Missing even the final native curve cannot publish coverage. - assert!( - !front.covers_offset(inflation, error, floor, r, tolerance) - ); - scene - .append(ClearedSweep::from_motion(&m, r, tolerance).unwrap()) - .unwrap(); - position = m.curve.end(); - recipe.advance(); - } - front.committed(&recipe).unwrap(); - } - assert!(front.covers_offset(inflation, error, floor, r, tolerance)); - for (i, e, z, cutter, t) in [ - (1.2 * r, error, floor, r, tolerance), - (inflation, 0.1 * r, floor, r, tolerance), - (inflation, error, floor - r, r, tolerance), - (inflation, error, floor, r * 0.9, tolerance), - (inflation, error, floor, r, tolerance * 2.), - ] { - assert!(!front.covers_offset(i, e, z, cutter, t)); - } - // Original full-domain quadtree oracle sees only actual swept - // curves and untouched solid stock. No fan/filled-shape shortcut. - let mut oracle = FrontCoverage::new( - domain, - [shift[0], shift[1]], - (0, 0), - floor, - tolerance, - 0.02 * r, - 0.5 * r, - centres, - inflation, - ) - .unwrap(); - let (mut tiles, mut envelopes, mut hits, mut branches) = (0, 0, 0, 0); - assert!(matches!( - oracle - .check( - &scene, - &stock, - position, - r, - tolerance, - &mut tiles, - &mut envelopes, - &mut hits, - &mut branches, - &|| false - ) - .unwrap(), - CoverageResult::Complete - )); - assert!(tiles > 1); - assert_eq!(envelopes, 0); - } - } - } - } - } - - #[test] - fn completed_fan_requires_the_final_full_native_receipt_and_same_stock() { - use super::super::{BulkContour, CoverageResult, FrontCoverage, FrontDriver}; - use crate::{planar::ConstructionOptions, stock::Stock, stream::StreamManifest}; - let mut m: StreamManifest = serde_json::from_str(include_str!( - "../../fixtures/operations/adaptive-pocket.json" - )) - .unwrap(); - m.tools[0].id = "cutter".into(); - m.tools[0].cutter.diameter_mm = 2.; - m.tools[0].cutter.shank_diameter_mm = 2.; - let tool = m.tools[0].prepare().unwrap(); - let mut stock = Stock::new(m.stock.height().unwrap().clone()).unwrap(); - let mut driver = FrontDriver::new(&m.tools[0]); - driver.synchronize(&stock, 1., 1e-5, &|| false).unwrap(); - let seed = motion(Curve::Arc { - start: [8.5, 8., 9.], - end: [8.5, 8., 9.], - center: [8., 8., 9.], - plane: Plane::Xy, - sweep_rad: TAU, - }); - driver.emitted(&stock, &seed); - stock - .apply_delta( - &stock - .preview_sweep(&tool, &seed, 1., m.sweep, &|| false) - .unwrap(), - ) - .unwrap(); - driver.synchronize(&stock, 1., 1e-5, &|| false).unwrap(); - let definition = region(vec![[7.7, 7.7], [9.1, 7.7], [9.1, 9.1], [7.7, 9.1]]); - let centres = definition.prepare(ConstructionOptions::default()).unwrap(); - let domain = centres.offset_prepared(-1.18).unwrap().into_parts().1; - driver.coverage = Some( - FrontCoverage::new(domain, [8., 8.], (0, 0), 9., 1e-5, 0.02, 0.5, centres, 1.18) - .unwrap(), - ); - driver.enclosed_front = - Some(EnclosedFront::new(&definition, &seed, 1., 0.2, 1e-5).unwrap()); - let mut position = seed.curve.end(); - let mut recipes = 0; - while let Some(recipe) = driver - .enclosed_front - .as_ref() - .unwrap() - .prepare(position, 82., 1e-5, true, &|| false) - .unwrap() - { - assert!(!driver.coverage.as_ref().unwrap().enclosed_complete); - recipes += 1; - assert!(recipes < 300); - let curves: Vec<_> = recipe - .leads - .iter() - .chain(&recipe.contour) - .cloned() - .collect(); - let lead_count = recipe.leads.len(); - let last = curves.len() - 1; - driver.bulk = Some(BulkContour::Enclosed(recipe)); - for (i, curve) in curves.into_iter().enumerate() { - let mut next = motion(curve); - next.id = seed.id + recipes * 100 + i as u64; - if i < lead_count { - next.kind = MoveKind::Lead; - } - driver.emitted(&stock, &next); - if i == last { - // No native transaction and a partial last curve both leave - // the entire component unproved, including its final recipe. - assert!(driver.synchronize(&stock, 1., 1e-5, &|| false).is_err()); - let mut partial = stock.clone(); - partial - .apply_delta( - &stock - .preview_sweep(&tool, &next, 0.5, m.sweep, &|| false) - .unwrap(), - ) - .unwrap(); - assert!(driver.synchronize(&partial, 1., 1e-5, &|| false).is_err()); - assert!(!driver.coverage.as_ref().unwrap().enclosed_complete); - } - let delta = stock - .preview_sweep(&tool, &next, 1., m.sweep, &|| false) - .unwrap(); - stock.apply_delta(&delta).unwrap(); - driver.synchronize(&stock, 1., 1e-5, &|| false).unwrap(); - position = next.curve.end(); - } - } - assert!(driver.coverage.as_ref().unwrap().enclosed_complete); - let foreign = Stock::from_snapshot(stock.snapshot()).unwrap(); - assert!(driver.synchronize(&foreign, 1., 1e-5, &|| false).is_err()); - driver.synchronize(&stock, 1., 1e-5, &|| false).unwrap(); - let coverage = driver.coverage.as_mut().unwrap(); - let (mut tiles, mut envelopes, mut hits, mut branches) = (0, 0, 0, 0); - assert!( - coverage - .check( - driver.scene.as_ref().unwrap(), - &stock, - position, - 1., - 1e-5, - &mut tiles, - &mut envelopes, - &mut hits, - &mut branches, - &|| true - ) - .is_err() - ); - assert!(matches!( - coverage - .check( - driver.scene.as_ref().unwrap(), - &stock, - position, - 1., - 1e-5, - &mut tiles, - &mut envelopes, - &mut hits, - &mut branches, - &|| false - ) - .unwrap(), - CoverageResult::Complete - )); - assert_eq!((tiles, envelopes), (0, 1)); - } - - #[test] - fn seed_disk_error_reserve_and_unsupported_circles_keep_coverage_fallback() { - let polygon = region(vec![[-0.3, -0.3], [1.1, -0.3], [1.1, 1.1], [-0.3, 1.1]]); - for radius in [1., 1. - 1e-5, 0.5] { - let seed = motion(Curve::Arc { - start: [radius, 0., 2.], - end: [radius, 0., 2.], - center: [0., 0., 2.], - plane: Plane::Xy, - sweep_rad: TAU, - }); - let front = EnclosedFront::new(&polygon, &seed, 1., 0.2, 1e-5).unwrap(); - assert_eq!(front.coverage_radius.is_some(), radius == 0.5); - let circle = PlanarRegion::circle("circle", [0., 0.], 2.).unwrap(); - let circular = EnclosedFront::new(&circle, &seed, 1., 0.2, 1e-5).unwrap(); - assert!(circular.coverage_radius.is_none()); - } - } - - #[test] - fn unsupported_geometry_or_incomplete_seed_does_not_create_clearance() { - let polygon = region(vec![[-0.3, -0.3], [1.1, -0.3], [1.1, 1.1], [-0.3, 1.1]]); - let seed = motion(Curve::Arc { - start: [0.5, 0., 2.], - end: [0.5, 0., 2.], - center: [0., 0., 2.], - plane: Plane::Xy, - sweep_rad: TAU, - }); - let valid = - |r: &PlanarRegion, m: &Motion| EnclosedFront::new(r, m, 1., 0.2, 1e-5).is_some(); - assert!(valid(&polygon, &seed)); - let mut partial = seed.clone(); - if let Curve::Arc { sweep_rad, .. } = &mut partial.curve { - *sweep_rad = PI; - } - assert!(!valid(&polygon, &partial)); - partial = seed.clone(); - partial.kind = MoveKind::Rapid; - assert!(!valid(&polygon, &partial)); - let concave = region(vec![[-1., -1.], [2., -1.], [2., 2.], [0.5, 0.5], [-1., 2.]]); - assert!(!valid(&concave, &seed)); - let mut holes = polygon.clone(); - holes.components[0].holes.push(Boundary { - vertices: vec![[0., 0., 0.], [0.1, 0., 0.], [0., 0.1, 0.]], - }); - assert!(!valid(&holes, &seed)); - let mut curved = polygon.clone(); - curved.components[0].outer.vertices[0][2] = 0.1; - assert!(!valid(&curved, &seed)); - let outside = region(vec![[3., 3.], [4., 3.], [4., 4.], [3., 4.]]); - assert!(!valid(&outside, &seed)); - } - - #[test] - fn cancellation_and_partial_recipe_leave_the_cleared_envelope_unchanged() { - use std::cell::Cell; - let polygon = region(vec![[-0.3, -0.3], [1.1, -0.3], [1.1, 1.1], [-0.3, 1.1]]); - let seed = motion(Curve::Arc { - start: [0.5, 0., 2.], - end: [0.5, 0., 2.], - center: [0., 0., 2.], - plane: Plane::Xy, - sweep_rad: TAU, - }); - let mut front = EnclosedFront::new(&polygon, &seed, 1., 0.2, 1e-5).unwrap(); - let calls = Cell::new(0); - assert!( - front - .prepare(seed.curve.end(), 82., 1e-5, true, &|| { - calls.set(calls.get() + 1); - calls.get() >= 3 - }) - .is_err() - ); - assert_eq!((front.piece, front.scale), (0, 0.)); - assert!( - front - .prepare([0.5, 0., 1.], 82., 1e-5, true, &|| false) - .is_err() - ); - let mut recipe = front - .prepare(seed.curve.end(), 82., 1e-5, true, &|| false) - .unwrap() - .unwrap(); - let m = motion(recipe.contour[0].clone()); - assert!(recipe.expects(&m, 1.1, 1e-5).is_err()); - assert!(recipe.expects(&m, 1., 2e-5).is_err()); - assert!(!recipe.advance()); - assert!(front.committed(&recipe).is_err()); - assert_eq!((front.piece, front.scale), (0, 0.)); - } -} diff --git a/src/adaptive_front/linear_channel.rs b/src/adaptive_front/linear_channel.rs deleted file mode 100644 index 689e6387..00000000 --- a/src/adaptive_front/linear_channel.rs +++ /dev/null @@ -1,449 +0,0 @@ -//! Native-commit-owned straight channel and independently admitted side cleanup. -use super::enclosed::growth_step; -use crate::{ - Point, - motion::{Curve, Motion, MoveKind, Plane, Vec3}, - pocket::Stroke, - stock::CancelSignal, -}; -use std::f64::consts::{PI, TAU}; - -pub(super) struct LinearChannel { - start: Point, - end: Point, - direction: Point, - length: f64, - floor: f64, - orbit: f64, - cutter: f64, - guard: f64, - seeded: bool, - progress: f64, - offsets: [f64; 2], - side: usize, - epoch: usize, -} -enum Completion { - Seed, - Advance(f64), - Side(usize, f64), -} -pub(super) struct LinearRecipe { - pub curves: Vec, - pub reset: bool, - completion: Completion, - angle: Option, - epoch: usize, - cutter: f64, - tolerance: f64, - cursor: usize, -} -impl LinearChannel { - pub fn new( - rail: Stroke, - floor: f64, - orbit: f64, - cutter: f64, - minimum: f64, - tolerance: f64, - ) -> Option { - let length = (rail.b[0] - rail.a[0]).hypot(rail.b[1] - rail.a[1]); - let guard = 64. * tolerance - + 8192. - * f64::EPSILON - * (1. - + rail.a[0].abs() - + rail.a[1].abs() - + rail.b[0].abs() - + rail.b[1].abs() - + cutter - + orbit); - if rail.arc.is_some() - || !length.is_finite() - || length <= 32. * tolerance - || orbit < minimum - || orbit > cutter - || orbit <= 4. * guard - { - return None; - } - Some(Self { - start: rail.a, - end: rail.b, - direction: [ - (rail.b[0] - rail.a[0]) / length, - (rail.b[1] - rail.a[1]) / length, - ], - length, - floor, - orbit, - cutter, - guard, - seeded: false, - progress: 0., - offsets: [orbit; 2], - side: 0, - epoch: 0, - }) - } - pub fn prepare( - &self, - position: Vec3, - max_angle: f64, - tolerance: f64, - right: bool, - fits: impl Fn(Stroke) -> bool, - cancel: &impl CancelSignal, - ) -> Result, String> { - if cancel.is_cancelled() { - return Err("linear channel cancelled".into()); - } - if position[2] != self.floor { - return Err("linear channel floor changed".into()); - } - let n = [self.direction[1], -self.direction[0]]; - let sign = if right { 1. } else { -1. }; - let lift = |p: Point, k: f64| [p[0] + k * n[0], p[1] + k * n[1], self.floor]; - let arc = |start, end, centre: Point, sweep| Curve::Arc { - start, - end, - center: [centre[0], centre[1], self.floor], - plane: Plane::Xy, - sweep_rad: sweep, - }; - let (curves, reset, completion, angle) = if !self.seeded { - let p = lift(self.start, sign * self.orbit); - ( - vec![arc(p, p, self.start, sign * TAU)], - true, - Completion::Seed, - None, - ) - } else if self.progress < self.length { - let Some((delta, angle)) = - growth_step(self.cutter, self.orbit, self.guard, max_angle, tolerance) - else { - return Ok(None); - }; - let progress = (self.progress + delta).min(self.length); - let point = |d: f64| { - if d == self.length { - self.end - } else { - [ - self.start[0] + d * self.direction[0], - self.start[1] + d * self.direction[1], - ] - } - }; - let old = point(self.progress); - let new = point(progress); - let a = lift(old, sign * self.orbit); - let b = lift(new, sign * self.orbit); - let c = lift(new, -sign * self.orbit); - let d = lift(old, -sign * self.orbit); - if position != a { - return Err("linear channel seam mismatch".into()); - } - let side = Curve::Line { start: a, end: b }; - ( - vec![ - side.clone(), - arc(b, c, new, sign * PI), - Curve::Line { start: c, end: d }, - arc(d, a, old, sign * PI), - side, - ], - false, - Completion::Advance(progress), - Some(angle.to_degrees()), - ) - } else { - let step = self.cutter * (1. - (max_angle.to_radians() / 2.).cos()) * 0.8; - let mut found = None; - for side in self.side..2 { - if cancel.is_cancelled() { - return Err("linear cleanup cancelled".into()); - } - let old = self.offsets[side]; - let mut target = old + step; - let stroke = |offset: f64| { - let offset = if side == 0 { offset } else { -offset }; - let a = lift(self.start, offset); - let b = lift(self.end, offset); - Stroke::line([a[0], a[1]], [b[0], b[1]]) - }; - if !fits(stroke(old)) { - continue; - } - if !fits(stroke(target)) { - let mut low = old; - for _ in 0..48 { - if cancel.is_cancelled() { - return Err("linear cleanup cancelled".into()); - } - let mid = (low + target) / 2.; - if fits(stroke(mid)) { - low = mid; - } else { - target = mid; - } - } - target = low; - } - if target - old <= 32. * tolerance { - continue; - } - let line = stroke(target); - let forward = (side == 0) == right; - let (a, b) = if forward { - (line.a, line.b) - } else { - (line.b, line.a) - }; - found = Some(( - vec![Curve::Line { - start: [a[0], a[1], self.floor], - end: [b[0], b[1], self.floor], - }], - true, - Completion::Side(side, target), - None, - )); - break; - } - let Some(found) = found else { - return Ok(None); - }; - found - }; - for curve in &curves { - if cancel.is_cancelled() { - return Err("linear channel cancelled".into()); - } - curve.prepare(tolerance)?; - let m = Motion { - id: 0, - operation: String::new(), - tool: String::new(), - kind: MoveKind::Cut, - curve: curve.clone(), - feed_mm_min: None, - }; - if crate::verification::path_error(&m, tolerance) > self.guard / 8. { - return Ok(None); - } - } - Ok(Some(LinearRecipe { - curves, - reset, - completion, - angle, - epoch: self.epoch, - cutter: self.cutter, - tolerance, - cursor: 0, - })) - } - pub fn committed(&mut self, recipe: &LinearRecipe) -> Result<(), String> { - if recipe.epoch != self.epoch || recipe.cursor != recipe.curves.len() { - return Err("linear channel incomplete or replayed recipe".into()); - } - match recipe.completion { - Completion::Seed if !self.seeded => self.seeded = true, - Completion::Advance(p) if self.seeded && p > self.progress && p <= self.length => { - self.progress = p - } - Completion::Side(side, offset) - if self.progress == self.length - && side >= self.side - && offset > self.offsets[side] => - { - self.side = side; - self.offsets[side] = offset; - } - _ => return Err("linear channel recipe mismatch".into()), - } - self.epoch += 1; - Ok(()) - } -} -impl LinearRecipe { - pub fn expects(&self, motion: &Motion, radius: f64, tolerance: f64) -> Result { - if motion.kind == MoveKind::Rapid || motion.curve.start()[2] != motion.curve.end()[2] { - return Ok(false); - } - if radius != self.cutter - || tolerance > self.tolerance - || motion.kind != MoveKind::Cut - || self.curves.get(self.cursor) != Some(&motion.curve) - { - return Err("linear channel native commit mismatch".into()); - } - Ok(true) - } - pub fn advance(&mut self) -> bool { - self.cursor += 1; - self.cursor == self.curves.len() - } - pub fn certified_angle(&self, motion: &Motion) -> Option { - if motion.kind == MoveKind::Cut && self.curves.get(self.cursor) == Some(&motion.curve) { - self.angle - } else { - None - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::{ - engagement::{ClearedSweep, EngagementOptions, EngagementScene, EngagementStatus}, - stock::Stock, - stream::StreamManifest, - }; - #[test] - fn straight_capsules_and_side_passes_preserve_contact_stock_and_native_progress() { - for right in [false, true] { - let shift = if right { [0., 0.] } else { [100., -80.] }; - let angle = if right { 0_f64 } else { 0.41 }; - let t = [angle.cos(), angle.sin()]; - let n = [t[1], -t[0]]; - let centre = [5. + shift[0], 5. + shift[1]]; - let point = |u: f64| [centre[0] + u * t[0], centre[1] + u * t[1]]; - let rail = Stroke::line(point(-6.), point(6.)); - let mut owner = LinearChannel::new(rail, 9., 0.5, 1., 0.2, 1e-5).unwrap(); - let mut m: StreamManifest = serde_json::from_str(include_str!( - "../../fixtures/operations/adaptive-pocket.json" - )) - .unwrap(); - m.stock.height_mut().unwrap().min_mm = [2. + shift[0], 2. + shift[1], 0.]; - m.stock.height_mut().unwrap().max_mm = [8. + shift[0], 8. + shift[1], 10.]; - m.stock.height_mut().unwrap().cell_size_mm = 0.2; - m.tools[0].cutter.diameter_mm = 2.; - m.tools[0].cutter.shank_diameter_mm = 2.; - let tool = m.tools[0].prepare().unwrap(); - let mut stock = Stock::new(m.stock.height().unwrap().clone()).unwrap(); - let mut scene = - EngagementScene::new(m.stock.height().unwrap().clone(), vec![]).unwrap(); - let mut position = [rail.a[0], rail.a[1], 9.]; - let mut prior: Option = None; - let mut count = 0; - let mut resets = 0; - let lateral = |p: Point| (p[0] - centre[0]) * n[0] + (p[1] - centre[1]) * n[1]; - while let Some(mut recipe) = owner - .prepare( - position, - 82., - 1e-5, - right, - |stroke| lateral(stroke.a).abs() <= 0.8 && lateral(stroke.b).abs() <= 0.8, - &|| false, - ) - .unwrap() - { - assert!(owner.committed(&recipe).is_err()); - if recipe.reset { - position = recipe.curves[0].start(); - prior = None; - resets += 1; - assert!( - scene - .clear_disk( - [position[0], position[1]], - 1.00064, - 9., - 1e-5, - &mut 2_000_000, - &|| false - ) - .unwrap() - ); - } - for curve in recipe.curves.clone() { - assert_eq!(curve.start(), position); - if let Some(old) = &prior { - let a = super::super::tangent(old, 1.); - let b = super::super::tangent(&curve, 0.); - assert!((a - b).sin().abs() < 1e-8 && (a - b).cos() > 0.); - } - let source_extent = match &curve { - Curve::Line { start, end } => lateral([start[0], start[1]]) - .abs() - .max(lateral([end[0], end[1]]).abs()), - Curve::Arc { start, center, .. } => { - lateral([center[0], center[1]]).abs() - + (start[0] - center[0]).hypot(start[1] - center[1]) - } - _ => panic!("planar primitive required"), - }; - assert!(source_extent <= 0.8 + 1e-8); - let motion = Motion { - id: 1, - operation: "channel".into(), - tool: "t1".into(), - kind: MoveKind::Cut, - feed_mm_min: Some(600.), - curve: curve.clone(), - }; - let checked = scene - .check_front( - &motion, - 1., - 82., - right, - EngagementOptions::default(), - &|| false, - ) - .unwrap(); - assert_eq!( - checked.status, - EngagementStatus::Bounded, - "{motion:?}: {checked:?}" - ); - assert!(recipe.expects(&motion, 1., 1e-5).unwrap()); - assert!(recipe.expects(&motion, 0.9, 1e-5).is_err()); - assert!(recipe.expects(&motion, 1., 1e-4).is_err()); - let delta = stock - .preview_sweep(&tool, &motion, 1., m.sweep, &|| false) - .unwrap(); - stock.apply_delta(&delta).unwrap(); - scene - .append(ClearedSweep::from_motion(&motion, 1., 1e-5).unwrap()) - .unwrap(); - if !recipe.advance() { - assert!(owner.committed(&recipe).is_err()); - } - position = curve.end(); - prior = Some(curve); - } - owner.committed(&recipe).unwrap(); - assert!(owner.committed(&recipe).is_err()); - count += 1; - assert!(count < 300); - } - assert!(owner.seeded && owner.progress == owner.length); - assert!(resets >= 5); - let mut cleared = 0; - let mut protected = 0; - for (i, h) in stock.cells().iter().enumerate() { - let d = lateral(stock.cell_center(i).unwrap()).abs(); - if d < 1.5 { - assert!(h.upper_mm <= 9. + 4. * m.sweep.tolerance_mm); - cleared += 1; - } - if d > 2.1 { - assert!(h.lower_mm >= 10. - 4. * m.sweep.tolerance_mm); - protected += 1; - } - } - assert!(cleared > 100 && protected > 100); - assert!( - owner - .prepare(position, 82., 1e-5, right, |_| true, &|| true) - .is_err() - ); - } - } -} diff --git a/src/adaptive_front/peeling.rs b/src/adaptive_front/peeling.rs deleted file mode 100644 index 2f7c532c..00000000 --- a/src/adaptive_front/peeling.rs +++ /dev/null @@ -1,914 +0,0 @@ -//! Stock-derived bulk contours. Proposed geometry is never cleared history. -use super::{candidate, tangent}; -use crate::{ - Point, - motion::{Curve, Motion, MoveKind, Plane, Vec3}, -}; -use std::f64::consts::FRAC_PI_2; - -pub(super) struct PeelContour { - pub start: Vec3, - pub heading: f64, - pub leads: Vec, - pub contour: Vec, - remaining: usize, - cursor: usize, - bounds: [Point; 2], - floor: f64, - radius: f64, - tolerance: f64, - engagement_angle: Option, -} - -impl PeelContour { - fn limits( - old: [Point; 2], - radius: f64, - max_angle: f64, - boundary_budget: f64, - tolerance: f64, - ) -> (f64, f64) { - let scale = old - .into_iter() - .flatten() - .map(f64::abs) - .fold(radius.max(1.), f64::max); - let guard = 64. * tolerance + 8192. * f64::EPSILON * (1. + scale + radius); - let width = radius * (1. - (max_angle.to_radians() / 2.).cos()); - (guard, width - boundary_budget / 4. - guard) - } - - #[allow(clippy::too_many_arguments)] - pub fn prepare( - old: [Point; 2], - floor: f64, - radius: f64, - minimum_radius: f64, - max_angle: f64, - boundary_budget: f64, - tolerance: f64, - right: bool, - ) -> Result, String> { - let (_, step) = Self::limits(old, radius, max_angle, boundary_budget, tolerance); - Self::prepare_insets( - old, - floor, - radius, - minimum_radius, - max_angle, - boundary_budget, - tolerance, - right, - [[step; 2]; 2], - ) - } - - /// Source fitting proposes geometry only. A failed probe does not prove - /// intervening positions infeasible; every retained recipe has its OWN - /// whole-source admission. Actual contact/side and native commits remain - /// mandatory in FrontDriver. Four bounded searches let a blocked face stop - /// without forcing all the other stock faces into local recovery orbits. - #[allow(clippy::too_many_arguments)] - pub fn prepare_fitted( - old: [Point; 2], - floor: f64, - radius: f64, - minimum_radius: f64, - max_angle: f64, - boundary_budget: f64, - tolerance: f64, - right: bool, - mut fits: impl FnMut(&Curve) -> Result, - ) -> Result, String> { - let Some(uniform) = Self::prepare( - old, - floor, - radius, - minimum_radius, - max_angle, - boundary_budget, - tolerance, - right, - )? - else { - return Ok(None); - }; - if uniform.fits_all(&mut fits)? { - return Ok(Some(uniform)); - } - let (_, step) = Self::limits(old, radius, max_angle, boundary_budget, tolerance); - let mut insets = [[0.; 2]; 2]; - let Some(mut best) = Self::prepare_insets( - old, - floor, - radius, - minimum_radius, - max_angle, - boundary_budget, - tolerance, - right, - insets, - )? - else { - return Ok(None); - }; - if !best.fits_all(&mut fits)? { - return Ok(None); - } - for side in 0..2 { - for axis in 0..2 { - let mut lo = 0.; - let mut hi = step; - // First try a full authored-width advance of this face; then - // at most twelve smaller trials. No unchecked interpolation. - for attempt in 0..=12 { - let delta = if attempt == 0 { step } else { (lo + hi) / 2. }; - let mut trial = insets; - trial[side][axis] = delta; - if let Some(recipe) = Self::prepare_insets( - old, - floor, - radius, - minimum_radius, - max_angle, - boundary_budget, - tolerance, - right, - trial, - )? && recipe.fits_all(&mut fits)? - { - lo = delta; - best = recipe; - if attempt == 0 { - break; - } - } else { - hi = delta; - } - if hi - lo <= 32. * tolerance { - break; - } - } - insets[side][axis] = lo; - } - } - // Do not repeat a contour that cannot shrink the conservatively - // bounded material rectangle by a meaningful numerical reserve. - Ok((0..2) - .any(|k| { - best.bounds[0][k] - old[0][k] > 32. * tolerance - || old[1][k] - best.bounds[1][k] > 32. * tolerance - }) - .then_some(best)) - } - - fn fits_all( - &self, - fits: &mut impl FnMut(&Curve) -> Result, - ) -> Result { - for curve in self.leads.iter().chain(&self.contour) { - if !fits(curve)? { - return Ok(false); - } - } - Ok(true) - } - - #[allow(clippy::too_many_arguments)] - fn prepare_insets( - old: [Point; 2], - floor: f64, - radius: f64, - minimum_radius: f64, - max_angle: f64, - boundary_budget: f64, - tolerance: f64, - right: bool, - insets: [Point; 2], - ) -> Result, String> { - if radius < minimum_radius { - return Ok(None); - } - let scale = old - .into_iter() - .flatten() - .map(f64::abs) - .fold(radius.max(1.), f64::max); - let (guard, step) = Self::limits(old, radius, max_angle, boundary_budget, tolerance); - if step <= 4. * guard || step > radius { - return Ok(None); - } - if insets - .into_iter() - .flatten() - .any(|d| !d.is_finite() || d < 0. || d > step) - { - return Err("stock-front contour inset exceeds authored width".into()); - } - let inner: [Point; 2] = [ - std::array::from_fn(|k| old[0][k] + insets[0][k]), - std::array::from_fn(|k| old[1][k] - insets[1][k]), - ]; - if (0..2).any(|k| inner[1][k] - inner[0][k] <= guard) { - return Ok(None); - } - let pad = 64. * tolerance; - let left_step = insets[0][0]; - let shift = left_step + 2. * pad; - // For the restoring S arc, wrong-side clearance against a straight - // front requires r-step+R(1-cos u)-r*sin u>0. Its minimum gives - // R >= step*(2r-step)/(2*(r-step)); leave search headroom above it. - let side_radius = left_step * (2. * radius - left_step) / (2. * (radius - left_step)); - let lead_radius = minimum_radius - .max(radius / 2.) - .max(shift / 2.) - .max(1.05 * side_radius); - let theta = (1. - shift / (2. * lead_radius)).clamp(-1., 1.).acos(); - let length = 2. * lead_radius * theta.sin(); - if length / 2. + guard >= inner[1][1] - inner[0][1] { - return Ok(None); - } - let start = [ - old[0][0] - radius - 2. * pad, - inner[0][1] - length / 2., - floor, - ]; - let first = candidate(start, FRAC_PI_2, -lead_radius.recip(), lead_radius * theta); - let second = candidate( - first.end(), - tangent(&first, 1.), - lead_radius.recip(), - lead_radius * theta, - ); - let q = second.end(); - let point = |x, y| [x, y, floor]; - let [lo, hi] = inner; - let left = lo[0] - radius; - let top = hi[1] + radius; - let east = hi[0] + radius; - let bottom = lo[1] - radius; - let line = |a, b| Curve::Line { start: a, end: b }; - let arc = |a, b, c| Curve::Arc { - start: a, - end: b, - center: c, - plane: Plane::Xy, - sweep_rad: -FRAC_PI_2, - }; - let mut leads = vec![first, second]; - let mut contour = vec![ - line(q, point(left, hi[1])), - arc(point(left, hi[1]), point(lo[0], top), point(lo[0], hi[1])), - line(point(lo[0], top), point(hi[0], top)), - arc(point(hi[0], top), point(east, hi[1]), point(hi[0], hi[1])), - line(point(east, hi[1]), point(east, lo[1])), - arc( - point(east, lo[1]), - point(hi[0], bottom), - point(hi[0], lo[1]), - ), - line(point(hi[0], bottom), point(lo[0], bottom)), - arc( - point(lo[0], bottom), - point(left, lo[1]), - point(lo[0], lo[1]), - ), - line(point(left, lo[1]), q), - ]; - if !right { - for curve in leads.iter_mut().chain(contour.iter_mut()) { - match curve { - Curve::Line { start, end } => { - start[1] = inner[0][1] + inner[1][1] - start[1]; - end[1] = inner[0][1] + inner[1][1] - end[1]; - } - Curve::Arc { - start, - end, - center, - sweep_rad, - .. - } => { - for p in [start, end, center] { - p[1] = inner[0][1] + inner[1][1] - p[1]; - } - *sweep_rad = -*sweep_rad; - } - _ => unreachable!(), - } - } - } - let mut maximum_error: f64 = 0.; - for curve in leads.iter().chain(&contour) { - let motion = Motion { - id: 1, - operation: "shell".into(), - tool: "shell".into(), - kind: MoveKind::Cut, - curve: curve.clone(), - feed_mm_min: Some(1.), - }; - curve.prepare(tolerance)?; - maximum_error = maximum_error.max(crate::verification::path_error(&motion, tolerance)); - } - // Covers endpoint/trigonometric consistency errors as well as the - // tube-radius reserve. Tangent collars remain unknown. - let deviation = (q[0] - left).abs() + 64. * f64::EPSILON * (1. + scale + radius); - if 4. * (maximum_error + deviation) >= guard { - return Ok(None); - } - // Reserve the entire construction guard, not just the nominal inset: - // it exceeds four times path/endpoint error plus the seam/coordinate - // displacement. This also covers the rounded axis radius and reflected - // corner coordinates. Retain the generic engagement model's angular - // reserve too, at a scale enclosing every contour endpoint. Insufficient - // authored margin keeps generic admission rather than raising its limit. - let inset = insets.into_iter().flatten().fold(0f64, f64::max) + guard; - let numeric = 2048. * f64::EPSILON * (1. + scale.max(floor.abs()) + 2. * radius); - let angular = (8. * (numeric / radius).sqrt()).min(std::f64::consts::PI); - let engagement_angle = (inset < radius) - .then(|| { - (2. * (1. - inset / radius).acos() + 2. * angular + 64. * f64::EPSILON.sqrt()) - .to_degrees() - }) - .filter(|angle| angle.is_finite() && *angle < 180. && *angle <= max_angle); - // Whole-shell certificate, with no endpoint sampling: side-strip - // distances to straight axes are convex, so box-corner maxima suffice. - // The worst inner corner has distance hypot(r-guard,guard) Result { - if motion.kind == MoveKind::Rapid || motion.curve.start()[2] != motion.curve.end()[2] { - return Ok(false); - } - if radius != self.radius || sweep_tolerance > self.tolerance { - return Err("stock-front contour cutter radius/sweep accuracy changed".into()); - } - let expected = self - .leads - .iter() - .chain(&self.contour) - .nth(self.cursor) - .ok_or("stock-front contour receipt cursor exhausted")?; - if &motion.curve != expected || !matches!(motion.kind, MoveKind::Lead | MoveKind::Cut) { - return Err("stock-front contour commit does not match expected whole curve".into()); - } - Ok(true) - } - pub fn committed(&mut self) -> Option<([Point; 2], f64)> { - self.cursor += 1; - self.remaining -= 1; - (self.remaining == 0).then_some((self.bounds, self.floor)) - } - - /// Joint contact and material-side bound for the WHOLE expected contour - /// curve, relative to the preceding committed material rectangle. - /// - /// A straight face has contact cap <=2*acos(1-a), where a is the largest - /// guarded inset divided by cutter radius. At a rounded corner, rotate - /// axes so material is x,y>=0 and the cutter centre is (sx-r*cos(t), - /// sy-r*sin(t)), t in[0,pi/2]. Enlarging both insets to a*r gives contact - /// vx>=cos(t)-a, vy>=sin(t)-a. Its width is at most - /// acos(cos(t)-a)+acos(sin(t)-a)-pi/2, whose maximum is at t=0 or pi/2: - /// acos(1-a)+asin(a)<=2*acos(1-a). The derivative has sign sin(t)-cos(t) - /// for 0 Option { - let index = self.cursor.checked_sub(self.leads.len())?; - let expected = self.contour.get(index)?; - if motion.kind != MoveKind::Cut || &motion.curve != expected { - return None; - } - match expected { - Curve::Line { start, end } if start[0] == end[0] || start[1] == end[1] => { - self.engagement_angle - } - Curve::Arc { - plane: Plane::Xy, - sweep_rad, - .. - } if sweep_rad.abs() == FRAC_PI_2 => self.engagement_angle, - _ => None, - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::{ - engagement::{EngagementOptions, EngagementScene, EngagementStatus}, - stock::StockSpec, - }; - #[test] - fn rectangular_certificates_match_independent_continuous_checks_across_scales() { - let mut certified = 0; - for radius in [0.25, 1., 10.] { - for shift in [[0., 0., 0.], [10_000., -20_000., 0.], [0., 0., 20_000.]] { - let old = [ - [shift[0], shift[1]], - [shift[0] + 32. * radius, shift[1] + 28. * radius], - ]; - let floor = shift[2] + 8. * radius; - let scene = EngagementScene::new( - StockSpec { - version: 1, - units: "mm".into(), - min_mm: [old[0][0], old[0][1], shift[2]], - max_mm: [old[1][0], old[1][1], shift[2] + 10. * radius], - cell_size_mm: radius, - max_cells: 10000, - }, - vec![], - ) - .unwrap(); - for right in [true, false] { - for limit in [30., 90., 160.] { - let step = PeelContour::limits(old, radius, limit, 0.01 * radius, 1e-5).1; - for insets in [ - [[step; 2]; 2], - [[0., step], [step / 3., 0.]], - [[step / 2., 0.], [0., step * 0.8]], - ] { - let mut recipe = PeelContour::prepare_insets( - old, - floor, - radius, - radius * 0.2, - limit, - 0.01 * radius, - 1e-5, - right, - insets, - ) - .unwrap() - .unwrap(); - let curves: Vec<_> = recipe - .leads - .iter() - .chain(&recipe.contour) - .cloned() - .collect(); - let mut local = 0; - for (i, curve) in curves.into_iter().enumerate() { - let m = Motion { - id: i as u64 + 1, - operation: "rectangle".into(), - tool: "mill".into(), - kind: if i < recipe.leads.len() { - MoveKind::Lead - } else { - MoveKind::Cut - }, - curve, - feed_mm_min: Some(600.), - }; - if let Some(angle) = recipe.certified_angle(&m) { - assert!(angle <= limit && angle < 180.); - // This scene has the original solid rectangle and NO - // cleared sweeps or recipe certificates. The generic - // continuous algorithm independently proves both metrics. - let check = scene - .check_front( - &m, - radius, - angle, - right, - EngagementOptions { - tolerance_mm: 1e-5, - resolution_mm: 0.001, - max_nodes: 8192, - max_work: 2_000_000, - ..Default::default() - }, - &|| false, - ) - .unwrap(); - assert_eq!( - check.status, - EngagementStatus::Bounded, - "r={radius},shift={shift:?},sense={right},limit={limit},curve={i},angle={angle},check={check:?}" - ); - local += 1; - } - assert!(recipe.expects(&m, radius, 1e-5).unwrap()); - let done = recipe.committed(); - assert_eq!(done.is_some(), i == 10); - } - assert!(local >= 7, "expected four corners and three straight sides"); - certified += local; - } - } - } - } - } - assert!(certified >= 1134); - } - - #[test] - fn rectangular_certificate_needs_expected_cursor_curve_kind_and_margin() { - let make = |budget| { - PeelContour::prepare([[0., 0.], [32., 28.]], 8., 1., 0.2, 90., budget, 1e-5, true) - .unwrap() - .unwrap() - }; - let mut recipe = make(0.01); - let mut m = Motion { - id: 1, - operation: "rectangle".into(), - tool: "mill".into(), - kind: MoveKind::Cut, - curve: recipe.contour[1].clone(), - feed_mm_min: Some(600.), - }; - assert!(recipe.certified_angle(&m).is_none()); // leads have no certificate - for i in 0..3 { - let curve = recipe - .leads - .iter() - .chain(&recipe.contour) - .nth(i) - .unwrap() - .clone(); - let next = Motion { curve, ..m.clone() }; - assert!(recipe.expects(&next, 0.9, 1e-5).is_err()); - assert!(recipe.expects(&next, 1., 1e-4).is_err()); - assert!(recipe.expects(&next, 1., 1e-5).unwrap()); - assert!(recipe.committed().is_none()); - } - assert!(recipe.certified_angle(&m).is_some()); - m.kind = MoveKind::Lead; - assert!(recipe.certified_angle(&m).is_none()); - m.kind = MoveKind::Cut; - if let Curve::Arc { sweep_rad, .. } = &mut m.curve { - *sweep_rad = -*sweep_rad; - } - assert!(recipe.certified_angle(&m).is_none()); - m.curve = recipe.contour[1].clone(); - if let Curve::Arc { - start, end, center, .. - } = &mut m.curve - { - start[2] -= 1.; - end[2] -= 1.; - center[2] -= 1.; - } - assert!(recipe.certified_angle(&m).is_none()); - let mut no_margin = make(0.); - no_margin.cursor = no_margin.leads.len() + 1; - m.curve = no_margin.contour[1].clone(); - assert!(no_margin.certified_angle(&m).is_none()); - no_margin.cursor = no_margin.leads.len() + no_margin.contour.len(); - assert!(no_margin.certified_angle(&m).is_none()); - } - #[test] - fn a_source_blocked_face_does_not_stop_other_stock_faces() { - for right in [true, false] { - for part_top in [18.99, 19.] { - let fits = |curve: &Curve| -> Result { - let b = curve.prepare(1e-5)?.bounds(); - // Independent sufficient certificate: the WHOLE axis - // bounding box stays one cutter radius from this solid. - Ok(b.max[0] <= 9.5 - || b.min[0] >= 22.5 - || b.max[1] <= 9.5 - || b.min[1] >= part_top + 1.) - }; - let p = PeelContour::prepare_fitted( - [[9., 9.], [23., 19.]], - 8., - 1., - 0.2, - 2. * 0.75f64.acos().to_degrees(), - 0.01, - 1e-5, - right, - fits, - ) - .unwrap() - .expect("three faces can still advance"); - assert!(p.bounds[0][0] > 9.24 && p.bounds[0][1] > 9.24); - assert!(p.bounds[1][0] < 22.76); - assert!(p.bounds[1][1] >= part_top && p.bounds[1][1] < part_top + 0.002); - assert!(p.fits_all(&mut { fits }).unwrap()); - // Mirror direction must preserve the actual asymmetric shell, - // rather than reflecting its tight top face onto the bottom. - let spec = StockSpec { - version: 1, - units: "mm".into(), - min_mm: [9., 9., 0.], - max_mm: [23., 19., 10.], - cell_size_mm: 0.4, - max_cells: 10000, - }; - let scene = EngagementScene::new(spec, vec![]).unwrap(); - for curve in p.leads.iter().chain(&p.contour) { - let m = Motion { - id: 1, - operation: "asymmetric".into(), - tool: "t".into(), - kind: MoveKind::Cut, - curve: curve.clone(), - feed_mm_min: Some(600.), - }; - let checked = scene - .check_front( - &m, - 1., - 2. * 0.75f64.acos().to_degrees(), - right, - EngagementOptions::default(), - &|| false, - ) - .unwrap(); - assert_eq!(checked.status, EngagementStatus::Bounded, "{curve:?}"); - } - } - } - assert!( - PeelContour::prepare_fitted( - [[0., 0.], [32., 28.]], - 8., - 1., - 0.2, - 90., - 0.01, - 1e-5, - true, - |_| Ok(false) - ) - .unwrap() - .is_none() - ); - assert_eq!( - PeelContour::prepare_fitted( - [[0., 0.], [32., 28.]], - 8., - 1., - 0.2, - 90., - 0.01, - 1e-5, - true, - |_| Err("cancelled".into()) - ) - .err() - .unwrap(), - "cancelled" - ); - } - #[test] - fn stock_contour_entry_and_curves_have_continuous_front_admission() { - let spec = StockSpec { - version: 1, - units: "mm".into(), - min_mm: [0., 0., 0.], - max_mm: [32., 28., 10.], - cell_size_mm: 0.4, - max_cells: 10000, - }; - for (right, angle) in [true, false].into_iter().flat_map(|right| { - [30., 2. * 0.75f64.acos().to_degrees(), 160.] - .into_iter() - .map(move |a| (right, a)) - }) { - let scene = EngagementScene::new(spec.clone(), vec![]).unwrap(); - let p = PeelContour::prepare( - [[0., 0.], [32., 28.]], - 8., - 1., - 0.2, - angle, - 0.01, - 1e-5, - right, - ) - .unwrap() - .unwrap(); - for (i, curve) in p.leads.iter().chain(&p.contour).enumerate() { - let m = Motion { - id: i as u64 + 1, - operation: "bulk".into(), - tool: "t".into(), - kind: MoveKind::Cut, - curve: curve.clone(), - feed_mm_min: Some(600.), - }; - let r = scene - .check_front( - &m, - 1., - angle, - right, - EngagementOptions { - max_nodes: 8192, - max_work: 2_000_000, - ..Default::default() - }, - &|| false, - ) - .unwrap(); - assert_eq!( - r.status, - EngagementStatus::Bounded, - "sense={right},angle={angle},curve={i},{r:?}" - ); - } - } - } - - #[test] - fn actual_recipe_covers_the_whole_claimed_shell_by_convex_and_radial_bounds() { - let corners = |b: [Point; 2]| [b[0], [b[0][0], b[1][1]], b[1], [b[1][0], b[0][1]]]; - let distance_to_segment = |p: Point, a: Vec3, b: Vec3| { - let d = [b[0] - a[0], b[1] - a[1]]; - let t = (((p[0] - a[0]) * d[0] + (p[1] - a[1]) * d[1]) / (d[0] * d[0] + d[1] * d[1])) - .clamp(0., 1.); - (p[0] - a[0] - t * d[0]).hypot(p[1] - a[1] - t * d[1]) - }; - for (shift, insets) in [[0., 0.], [10000., -20000.]].into_iter().flat_map(|shift| { - [ - None, - Some([[0., 0.23], [0.12, 0.]]), - Some([[0.15, 0.], [0., 0.22]]), - Some([[0.005, 0.01], [0.18, 0.07]]), - ] - .into_iter() - .map(move |insets| (shift, insets)) - }) { - for right in [true, false] { - let old = [shift, [shift[0] + 32., shift[1] + 28.]]; - let step = - PeelContour::limits(old, 1., 2. * 0.75f64.acos().to_degrees(), 0.01, 1e-5).1; - let recipe = PeelContour::prepare_insets( - old, - 8., - 1., - 0.2, - 2. * 0.75f64.acos().to_degrees(), - 0.01, - 1e-5, - right, - insets.unwrap_or([[step; 2]; 2]), - ) - .unwrap() - .unwrap(); - let b = recipe.bounds; - let mut axes = [vec![], vec![], vec![], vec![]]; - let mut arcs = 0; - for curve in &recipe.contour { - let motion = Motion { - id: 1, - operation: "proof".into(), - tool: "t".into(), - kind: MoveKind::Cut, - curve: curve.clone(), - feed_mm_min: Some(600.), - }; - let error = crate::verification::path_error(&motion, 1e-5); - match *curve { - Curve::Line { start, end } => { - let vertical = (end[1] - start[1]).abs() > (end[0] - start[0]).abs(); - let mid = [(start[0] + end[0]) / 2., (start[1] + end[1]) / 2.]; - let (side, region) = if vertical { - let left = mid[0] < (b[0][0] + b[1][0]) / 2.; - let lo = start[1].min(end[1]); - let hi = start[1].max(end[1]); - // The two left segments share q. Extend only - // their corner ends to the guarded rectangle. - let yl = if lo < b[0][1] + 0.01 { b[0][1] } else { lo }; - let yh = if hi > b[1][1] - 0.01 { b[1][1] } else { hi }; - ( - if left { 0 } else { 1 }, - if left { - [[old[0][0], yl], [b[0][0], yh]] - } else { - [[b[1][0], yl], [old[1][0], yh]] - }, - ) - } else { - let bottom = mid[1] < (b[0][1] + b[1][1]) / 2.; - ( - if bottom { 2 } else { 3 }, - if bottom { - [[b[0][0], old[0][1]], [b[1][0], b[0][1]]] - } else { - [[b[0][0], b[1][1]], [b[1][0], old[1][1]]] - }, - ) - }; - axes[side].push(if vertical { - [region[0][1], region[1][1]] - } else { - [region[0][0], region[1][0]] - }); - if (0..2).any(|k| region[0][k] >= region[1][k]) { - // A stationary face has no shell strip. - continue; - } - // Distance to a segment is convex: corner maxima - // certify every interior point of this strip box. - let max = corners(region) - .into_iter() - .map(|p| distance_to_segment(p, start, end)) - .fold(0f64, f64::max); - assert!(max + error < 1., "uncleared whole side strip: {max}"); - } - Curve::Arc { - start, - end, - center, - sweep_rad, - .. - } => { - arcs += 1; - let low_x = center[0] < (b[0][0] + b[1][0]) / 2.; - let low_y = center[1] < (b[0][1] + b[1][1]) / 2.; - let region = [ - [ - if low_x { old[0][0] } else { b[1][0] }, - if low_y { old[0][1] } else { b[1][1] }, - ], - [ - if low_x { b[0][0] } else { old[1][0] }, - if low_y { b[0][1] } else { old[1][1] }, - ], - ]; - if (0..2).any(|k| region[0][k] >= region[1][k]) { - // Degenerate corner belongs to the adjoining - // straight strip or the retained rectangle. - continue; - } - let u = [start[0] - center[0], start[1] - center[1]]; - let v = [end[0] - center[0], end[1] - center[1]]; - let mut far: f64 = 0.; - for p in corners(region) { - let d = [p[0] - center[0], p[1] - center[1]]; - // Two linear halfplanes enclose the WHOLE - // box in this actual quarter-arc sector. - assert!(sweep_rad.signum() * (u[0] * d[1] - u[1] * d[0]) >= 0.); - assert!(sweep_rad.signum() * (v[0] * d[1] - v[1] * d[0]) <= 0.); - far = far.max(d[0].hypot(d[1])); - } - let nearest: Point = std::array::from_fn(|k| { - center[k].clamp(region[0][k], region[1][k]) - }); - let near = (nearest[0] - center[0]).hypot(nearest[1] - center[1]); - let radius = u[0].hypot(u[1]); - assert!( - (near - radius).abs().max((far - radius).abs()) + error < 1., - "uncleared whole corner quadrant" - ); - } - _ => panic!("flat recipe expected"), - } - } - assert_eq!(arcs, 4); - assert_eq!( - axes.iter().map(Vec::len).collect::>(), - vec![2, 1, 1, 1] - ); - axes[0].sort_by(|a, b| a[0].total_cmp(&b[0])); - assert_eq!(axes[0][0][0], b[0][1]); - assert_eq!(axes[0][0][1], axes[0][1][0]); - assert_eq!(axes[0][1][1], b[1][1]); - } - } - } -} diff --git a/src/engagement.rs b/src/engagement.rs index 153d12fa..817b4f00 100644 --- a/src/engagement.rs +++ b/src/engagement.rs @@ -495,9 +495,6 @@ enum Metric { WrongSide { material_on_right: bool, }, - Front { - material_on_right: bool, - }, } impl EngagementScene { @@ -550,37 +547,6 @@ impl EngagementScene { pub(crate) fn stock_spec(&self) -> &StockSpec { &self.stock } - /// Conditional geometric premise, just like a ClearedSweep. The planner - /// must bind a completed shell recipe to actual full native stock commits. - /// Original StockSpec and its physical height cells are never changed. - pub(crate) fn append_rectangular_shell( - &mut self, - bounds: [Point; 2], - floor: f64, - ) -> Result<(), String> { - let old = self.material_bounds(floor); - if !floor.is_finite() - || bounds.iter().flatten().any(|v| !v.is_finite()) - || (0..2).any(|k| { - bounds[0][k] >= bounds[1][k] || bounds[0][k] < old[0][k] || bounds[1][k] > old[1][k] - }) - { - return Err("invalid or non-nested committed rectangular shell".into()); - } - if let Some((_, previous)) = self - .rectangular_shells - .iter_mut() - .find(|(z, _)| *z == floor) - { - *previous = bounds; - } else { - if self.rectangular_shells.len() >= 4096 { - return Err("rectangular shell floor limit exceeded".into()); - } - self.rectangular_shells.push((floor, bounds)); - } - Ok(()) - } pub(crate) fn material_bounds(&self, z: f64) -> [Point; 2] { let mut result = [ [self.stock.min_mm[0], self.stock.min_mm[1]], @@ -709,27 +675,6 @@ impl EngagementScene { cancel, ) } - /// Joint continuous front admission. One interval tree shares all geometric - /// angular unions; success requires BOTH total contact and the entire - /// instantaneous forbidden half to be bounded throughout the whole motion. - pub(crate) fn check_front( - &self, - motion: &Motion, - radius: f64, - max_angle_deg: f64, - material_on_right: bool, - options: EngagementOptions, - cancel: &impl CancelSignal, - ) -> Result { - self.check_metric( - motion, - radius, - max_angle_deg, - options, - Metric::Front { material_on_right }, - cancel, - ) - } /// Heuristic for candidate ranking ONLY. Point queries are not sweep, /// stock, productivity or remaining-material certificates. pub(crate) fn point_near_cleared_sweep( @@ -781,90 +726,6 @@ impl EngagementScene { } Ok(Some(false)) } - /// Candidate poses near the recent cleared front. Geometric ranking ONLY: - /// a point on/near a committed axis is not a padded empty disk certificate. - /// The caller must still prove source, full disk, engagement and side. - pub(crate) fn reentry_positions( - &self, - goal: Point, - floor: f64, - inset: f64, - material_on_right: bool, - work: &mut u64, - cancel: &impl CancelSignal, - ) -> Result, String> { - if cancel.is_cancelled() { - return Err("stock-front history search cancelled".into()); - } - let mut positions = Vec::new(); - for support in self.supports.iter().rev().take(128) { - if cancel.is_cancelled() { - return Err("stock-front history search cancelled".into()); - } - if *work == 0 { - return Err("stock-front history search work limit; coverage unproven".into()); - } - *work -= 1; - if support.floor > floor { - continue; - } - let poses = match support.shape { - Shape::Line { - a, unit, length, .. - } => { - let t = dot([goal[0] - a[0], goal[1] - a[1]], unit).clamp(0., length); - [t, length / 2.].map(|t| { - ( - [a[0] + t * unit[0], a[1] + t * unit[1]], - unit[1].atan2(unit[0]), - ) - }) - } - Shape::Arc { - a, - b, - c, - radius, - angle, - sweep, - } => { - let theta = (goal[1] - c[1]).atan2(goal[0] - c[0]); - let travel = if sweep > 0. { - angular::wrap_tau(theta - angle) - } else { - angular::wrap_tau(angle - theta) - }; - let closest = if travel <= sweep.abs() { - travel * sweep.signum() - } else if distance(goal, a) < distance(goal, b) { - 0. - } else { - sweep - }; - [closest, sweep / 2.].map(|travel| { - let theta = angle + travel; - ( - [c[0] + radius * theta.cos(), c[1] + radius * theta.sin()], - theta + sweep.signum() * PI / 2., - ) - }) - } - }; - let side = if material_on_right { 1. } else { -1. }; - for (p, heading) in poses { - // Nudge toward the cleared side. Exact path points alone may - // only fit the original radius, not a guarded descent disk. - positions.push(( - [ - p[0] - side * inset * heading.sin(), - p[1] + side * inset * heading.cos(), - ], - heading, - )); - } - } - Ok(positions) - } /// Whole closed XY box covered by committed empty columns or outside /// original stock. A centre-distance plus half-diagonal bound encloses ALL /// points. Reuses the swept-history index; no endpoint/point-sample proof. @@ -882,39 +743,6 @@ impl EngagementScene { }; self.clear_ball_witness(p, extent, z, work, cancel) } - /// A remembered index is only a search hint. Every use rechecks the - /// current support geometry, floor and complete query ball; even a hint - /// from another scene cannot manufacture a clearance premise. - pub(crate) fn clear_box_with_hint( - &self, - bounds: [Point; 2], - z: f64, - hint: &mut Option, - work: &mut u64, - cancel: &impl CancelSignal, - ) -> Result { - #[cfg(feature = "profile-planning")] - let _profile = crate::planning_profile::span("coverage.scene_box"); - let Some((p, extent)) = self.box_ball(bounds, z, cancel)? else { - return Ok(true); - }; - let numeric = 4096. * f64::EPSILON * (1. + p[0].abs() + p[1].abs() + extent); - if let Some(support) = hint.and_then(|i| self.supports.get(i)) { - if *work == 0 { - return Err("stock-front coverage work limit; coverage unproven".into()); - } - *work -= 1; - if ball_in_support(support, p, extent, z, numeric) { - return Ok(true); - } - } - if let Some(index) = self.find_ball_witness(p, extent, z, work, cancel)? { - *hint = Some(index); - Ok(true) - } else { - Ok(false) - } - } fn box_ball( &self, bounds: [Point; 2], @@ -1242,29 +1070,9 @@ impl EngagementScene { metric: Metric, cancel: &impl CancelSignal, ) -> Result { - if matches!(metric, Metric::Front { .. }) { - self.check_metric_mode::( - motion, - radius, - max_angle_deg, - options, - metric, - cancel, - ) - } else { - // Public angle inspection retains its full-history report; this - // optimization answers only the planner's joint admission question. - self.check_metric_mode::( - motion, - radius, - max_angle_deg, - options, - metric, - cancel, - ) - } + self.check_metric_mode::(motion, radius, max_angle_deg, options, metric, cancel) } - fn check_metric_mode( + fn check_metric_mode( &self, motion: &Motion, radius: f64, @@ -1278,7 +1086,6 @@ impl EngagementScene { Metric::Total => "engagement.total", Metric::Leading => "engagement.leading", Metric::WrongSide { .. } => "engagement.side", - Metric::Front { .. } => "engagement.front", }); if cancel.is_cancelled() { return Err("engagement query cancelled".into()); @@ -1347,7 +1154,7 @@ impl EngagementScene { report.upper_angle_deg = report.upper_angle_deg.max(upper.to_degrees()); continue; } - let Some(upper) = self.angular_bound::( + let Some(upper) = self.angular_bound::( &span, radius, &mut report, @@ -1361,11 +1168,7 @@ impl EngagementScene { return Ok(unresolved(report, UnresolvedReason::Work)); }; let deg = upper.to_degrees().min(360.); - // A joint side failure is encoded as TAU. An authored 360deg - // contact limit must never turn that forbidden-half failure into - // a successful one-sided front proof. - let side_unproved = matches!(metric, Metric::Front { .. }) && upper >= TAU; - if deg <= max_angle_deg && !side_unproved { + if deg <= max_angle_deg { report.upper_angle_deg = report.upper_angle_deg.max(deg); continue; } @@ -1390,7 +1193,7 @@ impl EngagementScene { b: f, error, }; - let Some(upper) = self.angular_bound::( + let Some(upper) = self.angular_bound::( &pose, radius, &mut report, @@ -1403,9 +1206,7 @@ impl EngagementScene { else { return Ok(unresolved(report, UnresolvedReason::Work)); }; - if upper.to_degrees().min(360.) > max_angle_deg - || (matches!(metric, Metric::Front { .. }) && upper >= TAU) - { + if upper.to_degrees().min(360.) > max_angle_deg { return Ok(unresolved(report, UnresolvedReason::Resolution)); } } @@ -1423,7 +1224,7 @@ impl EngagementScene { Ok(report) } #[allow(clippy::too_many_arguments)] - fn angular_bound( + fn angular_bound( &self, span: &Span<'_>, r: f64, @@ -1489,17 +1290,13 @@ impl EngagementScene { let delta = span.path.length_mm() * (span.b - span.a) / 2. + span.error; let mut contact_upper = TAU; let mut side_proved = *whole_side_proved; - let mut normalized = 0; - let mut interval_terms = 0; - let mut incremental = EARLY_UNION; let x_bounds = span.projection([1., 0.]); let y_bounds = span.projection([0., 1.]); let bounds = [ [x_bounds[0] - r - numeric, y_bounds[0] - r - numeric], [x_bounds[1] + r + numeric, y_bounds[1] + r + numeric], ]; - if let Metric::WrongSide { material_on_right } | Metric::Front { material_on_right } = - metric + if let Metric::WrongSide { material_on_right } = metric && REFUTE && !side_proved { @@ -1529,28 +1326,6 @@ impl EngagementScene { if report.support_tests + report.index_visits >= limit { return Ok(None); } - // Every interval already encloses clear angles for this WHOLE - // motion span. Their union can prove admission before older - // supports are visited; more cleared geometry cannot undo it. - // Complex fragmented sets use the original one-sort fallback. - if incremental && intervals.len() > 128 { - incremental = false; - } - if incremental - && merge_new_intervals(&mut intervals, &mut normalized, &mut interval_terms) - { - let (side, upper) = interval_metric_bound( - &intervals, - forbidden, - side_proved, - metric, - contact_upper, - interval_terms, - ); - if let Some(bound) = sufficient_metric_bound(metric, side, upper, max_angle_deg) { - return Ok(Some(bound)); - } - } report.index_visits += 1; let node = &self.index[node]; if node.min_floor > p3[2] { @@ -1583,8 +1358,7 @@ impl EngagementScene { if span.a == 0. && span.b == 1. { let right = match metric { Metric::Total | Metric::Leading => None, - Metric::WrongSide { material_on_right } - | Metric::Front { material_on_right } => Some(material_on_right), + Metric::WrongSide { material_on_right } => Some(material_on_right), }; if let Some((side, upper)) = whole_line_strip_bound(span, r, &support.shape, h, right, numeric, pad) @@ -1664,8 +1438,7 @@ impl EngagementScene { .acos() }; contact_upper = contact_upper.min(upper); - if let Metric::WrongSide { material_on_right } - | Metric::Front { material_on_right } = metric + if let Metric::WrongSide { material_on_right } = metric && !side_proved && span.a == 0. && span.b == 1. @@ -1780,12 +1553,8 @@ impl EngagementScene { } } } - if EARLY_UNION { - merge_new_intervals(&mut intervals, &mut normalized, &mut interval_terms); - } else { - intervals.sort_unstable_by(|a, b| a[0].total_cmp(&b[0])); - interval_terms = intervals.len(); - } + intervals.sort_unstable_by(|a, b| a[0].total_cmp(&b[0])); + let interval_terms = intervals.len(); Ok(Some( interval_metric_bound( &intervals, @@ -2044,42 +1813,11 @@ fn certainly_farther(shape: &Shape, p: Point, limit: f64) -> bool { (centre - radius).abs() > limit + slack } -/// Merge only existing known-empty intervals. Keep the original number of -/// arithmetic terms even after compression so the roundoff reserve never shrinks. -fn merge_new_intervals( - intervals: &mut Vec<[f64; 2]>, - normalized: &mut usize, - terms: &mut usize, -) -> bool { - #[cfg(feature = "profile-planning")] - let _profile = crate::planning_profile::span("engagement.merge"); - if intervals.len() == *normalized { - return false; - } - *terms += intervals.len() - *normalized; - intervals.sort_unstable_by(|a, b| a[0].total_cmp(&b[0])); - let mut written = 0; - for read in 0..intervals.len() { - let value = intervals[read]; - if written > 0 && value[0] <= intervals[written - 1][1] { - intervals[written - 1][1] = intervals[written - 1][1].max(value[1]); - } else { - intervals[written] = value; - written += 1; - } - } - intervals.truncate(written); - *normalized = written; - true -} - /// This world-angle sector depends on the query span, not the growing union. /// Compute it once while retaining the same whole-span turn and angular reserve. fn forbidden_sector(span: &Span<'_>, pad: f64, metric: Metric) -> Option<[f64; 2]> { let material_on_right = match metric { - Metric::WrongSide { material_on_right } | Metric::Front { material_on_right } => { - material_on_right - } + Metric::WrongSide { material_on_right } => material_on_right, Metric::Total | Metric::Leading => return None, }; let (heading, turn) = span_heading(span); @@ -2173,9 +1911,6 @@ fn interval_metric_bound( if matches!(metric, Metric::WrongSide { .. }) { return (side_proved, if side_proved { 0. } else { TAU }); } - if matches!(metric, Metric::Front { .. }) && !side_proved { - return (false, TAU); - } let mut clear = 0.; let mut end = 0.; for i in intervals { @@ -2203,11 +1938,6 @@ fn sufficient_metric_bound( Metric::Total | Metric::Leading if upper.to_degrees().min(360.) <= max_angle_deg => { Some(upper) } - Metric::Front { .. } - if side && upper < TAU && upper.to_degrees().min(360.) <= max_angle_deg => - { - Some(upper) - } _ => None, } } @@ -3020,92 +2750,6 @@ mod leading_tests { #[cfg(test)] mod full_column_tests { - #[test] - fn rectangular_shells_are_floor_tagged_and_preserve_original_stock() { - let spec = crate::stock::StockSpec { - version: 1, - units: "mm".into(), - min_mm: [0., 0., 0.], - max_mm: [20., 20., 10.], - cell_size_mm: 1., - max_cells: 1000, - }; - let mut s = super::EngagementScene::new(spec.clone(), vec![]).unwrap(); - s.append_rectangular_shell([[0.5, 0.5], [19.5, 19.5]], 5.) - .unwrap(); - assert_eq!(s.material_bounds(4.), [[0., 0.], [20., 20.]]); - assert_eq!(s.material_bounds(5.), [[0.5, 0.5], [19.5, 19.5]]); - assert_eq!(s.stock, spec); - assert!( - s.clear_box([[0.1, 9.], [0.4, 11.]], 5., &mut 10000, &|| false) - .unwrap() - ); - assert!( - !s.clear_box([[0.1, 9.], [0.4, 11.]], 4., &mut 10000, &|| false) - .unwrap() - ); - assert!( - s.clear_disk([0.25, 10.], 0.1, 5., 1e-5, &mut 10000, &|| false) - .unwrap() - ); - assert!( - !s.clear_disk([0.25, 10.], 0.1, 4., 1e-5, &mut 10000, &|| false) - .unwrap() - ); - assert!( - s.clear_disk([0.25, 10.], 0.1, 5., 1e-5, &mut 0, &|| false) - .is_err() - ); - assert!( - s.clear_box([[0.1, 9.], [0.4, 11.]], 5., &mut 10000, &|| true) - .is_err() - ); - assert!( - s.append_rectangular_shell([[0.4, 0.5], [19.5, 19.5]], 5.) - .is_err() - ); - let mut m = crate::motion::Motion { - id: 1, - operation: "shell".into(), - tool: "t".into(), - kind: crate::motion::MoveKind::Cut, - curve: crate::motion::Curve::Line { - start: [0.25, 9., 5.], - end: [0.25, 11., 5.], - }, - feed_mm_min: Some(600.), - }; - assert_eq!( - s.check_front( - &m, - 0.1, - 90., - true, - super::EngagementOptions::default(), - &|| false - ) - .unwrap() - .upper_angle_deg, - 0. - ); - m.curve = crate::motion::Curve::Line { - start: [0.25, 9., 4.], - end: [0.25, 11., 4.], - }; - assert_eq!( - s.check_front( - &m, - 0.1, - 90., - true, - super::EngagementOptions::default(), - &|| false - ) - .unwrap() - .status, - super::EngagementStatus::Unresolved - ); - } use super::*; use crate::motion::MoveKind; #[test] @@ -3193,84 +2837,6 @@ mod full_column_tests { EngagementScene::new(stock, supports).unwrap() } #[test] - fn coverage_hint_rechecks_full_geometry_depth_foreign_scene_budget_and_cancel() { - let history = scene(&[([0., 0.], 0.5, 5.)], 1.); - let query = [[-0.1, -0.1], [0.1, 0.1]]; - let mut hint = None; - assert!( - history - .clear_box_with_hint(query, 5., &mut hint, &mut 100, &|| false) - .unwrap() - ); - assert_eq!(hint, Some(0)); - // Same witness, independently checked on a neighboring complete box. - let nearby = [[0.2, 0.2], [0.4, 0.4]]; - let mut work = 1; - assert!( - history - .clear_box_with_hint(nearby, 5., &mut hint, &mut work, &|| false) - .unwrap() - ); - assert_eq!(work, 0); - for (bounds, depth) in [ - (query, 4.999), - ([[2., 2.], [2.1, 2.1]], 5.), - ([[-2., -2.], [2., 2.]], 5.), - ] { - assert!( - !history - .clear_box_with_hint(bounds, depth, &mut hint, &mut 100, &|| false) - .unwrap() - ); - } - // Index zero in a different scene refers to different material removal. - let foreign = scene(&[([6., 0.], 0.5, 5.)], 1.); - assert!( - !foreign - .clear_box_with_hint(query, 5., &mut hint, &mut 100, &|| false) - .unwrap() - ); - let empty = scene(&[], 1.); - assert!( - !empty - .clear_box_with_hint(query, 5., &mut hint, &mut 100, &|| false) - .unwrap() - ); - // A full annular sweep still leaves the entire central disk untouched. - let annulus = scene(&[([0., 0.], 3., 5.)], 1.); - assert!( - !annulus - .clear_box_with_hint(query, 5., &mut hint, &mut 100, &|| false) - .unwrap() - ); - for cancelled in [false, true] { - let mut work = if cancelled { 100 } else { 0 }; - let before = hint; - assert!( - history - .clear_box_with_hint(query, 5., &mut hint, &mut work, &|| cancelled) - .is_err() - ); - assert_eq!(hint, before); - assert_eq!(work, if cancelled { 100 } else { 0 }); - } - // Analytic filled-disk containment is independent of the lookup path. - for i in 0..80 { - let p = [i as f64 / 20. - 2., 0.3]; - let bounds = [[p[0] - 0.04, p[1] - 0.04], [p[0] + 0.04, p[1] + 0.04]]; - let result = history - .clear_box_with_hint(bounds, 5., &mut hint, &mut 100, &|| false) - .unwrap(); - assert_eq!( - result, - history.clear_box(bounds, 5., &mut 100, &|| false).unwrap() - ); - if result { - assert!(p[0].hypot(p[1]) + 0.04 * 2f64.sqrt() < 1.5); - } - } - } - #[test] fn reentry_point_rejection_cannot_certify_unsampled_interior() { let mut disks: Vec<_> = (0..16) .map(|i| { @@ -3301,113 +2867,9 @@ mod full_column_tests { .is_err() ); } - #[test] - fn incremental_union_combines_distinct_sweeps_over_whole_lines_and_turning_arcs() { - let disks: Vec<_> = (0..195) - .map(|i| { - let a = TAU * (i % 3) as f64 / 3.; - ([a.cos(), a.sin()], 0.4, 5.) - }) - .collect(); - let history = scene(&disks, 1.); - for curve in [ - Curve::Line { - start: [-0.01, 0., 5.], - end: [0.01, 0., 5.], - }, - Curve::Arc { - start: [0., 0., 5.], - end: [0.2 * 0.05_f64.cos() - 0.2, 0.2 * 0.05_f64.sin(), 5.], - center: [-0.2, 0., 5.], - plane: Plane::Xy, - sweep_rad: 0.05, - }, - ] { - let query = Motion { - id: 2, - operation: "combined-clearance".into(), - tool: "t".into(), - kind: MoveKind::Cut, - curve, - feed_mm_min: Some(600.), - }; - for right in [false, true] { - let metric = Metric::Front { - material_on_right: right, - }; - let current = history - .check_metric_mode::( - &query, - 1., - 1., - EngagementOptions::default(), - metric, - &|| false, - ) - .unwrap(); - let reference = history - .check_metric_mode::( - &query, - 1., - 1., - EngagementOptions::default(), - metric, - &|| false, - ) - .unwrap(); - assert_eq!(current.status, EngagementStatus::Bounded, "{current:?}"); - assert_eq!(reference.status, EngagementStatus::Bounded); - assert!( - current.support_tests * 8 < reference.support_tests, - "{current:?} vs {reference:?}" - ); - assert!(current.upper_angle_deg <= 1.); - // No single component disk encloses this whole circumference. - for disk in &disks[..3] { - assert_eq!( - scene(&[*disk], 1.) - .check_front( - &query, - 1., - 1., - right, - EngagementOptions::default(), - &|| false - ) - .unwrap() - .status, - EngagementStatus::Unresolved - ); - } - } - assert!( - history - .check_front(&query, 1., 1., true, EngagementOptions::default(), &|| true) - .is_err() - ); - assert_eq!( - history - .check_front( - &query, - 1., - 1., - true, - EngagementOptions { - max_work: 0, - ..Default::default() - }, - &|| false - ) - .unwrap() - .status, - EngagementStatus::Unresolved - ); - } - } /// The side refutation changes no result: random line and arc histories, - /// line and arc queries, both sides, both side metrics, with and without - /// the early union, and small work limits. Reports (status, bound, work + /// line and arc queries, both sides, and small work limits. Reports (status, bound, work /// counters, depth, reason) equal the full angular proof's. #[test] fn side_refutation_matches_the_full_angular_proof() { @@ -3523,181 +2985,52 @@ mod full_column_tests { ..Default::default() }; for right in [false, true] { - for metric in [ - Metric::Front { - material_on_right: right, - }, - Metric::WrongSide { - material_on_right: right, - }, - ] { - let pairs = [ - ( - scene.check_metric_mode::( - &query, - radius, - angle, - options, - metric, - &|| false, - ), - scene.check_metric_mode::( - &query, - radius, - angle, - options, - metric, - &|| false, - ), - ), - ( - scene.check_metric_mode::( - &query, - radius, - angle, - options, - metric, - &|| false, - ), - scene.check_metric_mode::( - &query, - radius, - angle, - options, - metric, - &|| false, - ), - ), - ]; - for (fast, full) in pairs { - let (fast, full) = ( - fast.map_err(|e| e.to_string()), - full.map_err(|e| e.to_string()), + let metric = Metric::WrongSide { + material_on_right: right, + }; + let (fast, full) = ( + scene + .check_metric_mode::( + &query, + radius, + angle, + options, + metric, + &|| false, + ) + .map_err(|e| e.to_string()), + scene + .check_metric_mode::( + &query, + radius, + angle, + options, + metric, + &|| false, + ) + .map_err(|e| e.to_string()), + ); + compared += 1; + match (&fast, &full) { + (Ok(a), Ok(b)) => { + assert_eq!( + format!("{a:?}"), + format!("{b:?}"), + "{query:?} r={radius} angle={angle}" ); - compared += 1; - match (&fast, &full) { - (Ok(a), Ok(b)) => { - assert_eq!( - format!("{a:?}"), - format!("{b:?}"), - "{query:?} r={radius} angle={angle}" - ); - if a.support_tests > 0 && a.upper_angle_deg >= 360. { - refuted += 1; - } - } - _ => assert_eq!(format!("{fast:?}"), format!("{full:?}")), + if a.support_tests > 0 && a.upper_angle_deg >= 360. { + refuted += 1; } } + _ => assert_eq!(format!("{fast:?}"), format!("{full:?}")), } } } } - assert!(compared > 4000, "{compared}"); + assert!(compared > 1000, "{compared}"); assert!(refuted > 100, "few rejections exercised: {refuted}"); } - #[test] - fn incremental_union_keeps_real_gaps_and_wrong_depths_unresolved() { - for floor in [5., 6.] { - let disks: Vec<_> = (0..195) - .map(|i| { - let a = TAU * (i % 3) as f64 / 3.; - ([1.5 * a.cos(), 1.5 * a.sin()], 0.1, floor) - }) - .collect(); - let history = scene(&disks, 1.); - let query = Motion { - id: 2, - operation: "uncleared-gaps".into(), - tool: "t".into(), - kind: MoveKind::Cut, - curve: Curve::Line { - start: [-0.01, 0., 5.], - end: [0.01, 0., 5.], - }, - feed_mm_min: Some(600.), - }; - for right in [false, true] { - for early in [false, true] { - let metric = Metric::Front { - material_on_right: right, - }; - let checked = if early { - history.check_metric_mode::( - &query, - 1., - 360., - EngagementOptions::default(), - metric, - &|| false, - ) - } else { - history.check_metric_mode::( - &query, - 1., - 360., - EngagementOptions::default(), - metric, - &|| false, - ) - } - .unwrap(); - assert_eq!(checked.status, EngagementStatus::Unresolved, "{checked:?}"); - } - } - } - } - - #[test] - fn fragmented_union_fallback_preserves_tiny_uncleared_gaps() { - let disks: Vec<_> = (0..200) - .map(|i| { - let a = TAU * i as f64 / 200.; - ([a.cos(), a.sin()], 0.001, 5.) - }) - .collect(); - let history = scene(&disks, 0.01); - let query = Motion { - id: 2, - operation: "fragmented".into(), - tool: "t".into(), - kind: MoveKind::Cut, - curve: Curve::Line { - start: [-0.001, 0., 5.], - end: [0.001, 0., 5.], - }, - feed_mm_min: Some(600.), - }; - for right in [false, true] { - let metric = Metric::Front { - material_on_right: right, - }; - let current = history - .check_metric_mode::( - &query, - 1., - 360., - EngagementOptions::default(), - metric, - &|| false, - ) - .unwrap(); - let reference = history - .check_metric_mode::( - &query, - 1., - 360., - EngagementOptions::default(), - metric, - &|| false, - ) - .unwrap(); - assert_eq!(current.status, EngagementStatus::Unresolved); - assert_eq!(reference.status, current.status); - assert_eq!(reference.support_tests, current.support_tests); - } - } #[test] fn finite_line_witness_proves_contact_and_side_without_scanning_older_history() { for shift in [[0., 0.], [10000., -20000.]] { @@ -3747,10 +3080,7 @@ mod full_column_tests { let side = scene .check_material_side(&query, 1., right, options, &|| false) .unwrap(); - let joint = scene - .check_front(&query, 1., 90., right, options, &|| false) - .unwrap(); - for bound in [&total, &side, &joint] { + for bound in [&total, &side] { assert_eq!(bound.status, EngagementStatus::Bounded, "{bound:?}"); assert_eq!(bound.nodes, 1); assert_eq!(bound.support_tests, 1); @@ -3758,42 +3088,32 @@ mod full_column_tests { } assert_eq!(side.upper_angle_deg, 0.); let exact = 2. * 0.8f64.acos().to_degrees(); - assert!(joint.upper_angle_deg >= exact && joint.upper_angle_deg < 90.); assert!(total.upper_angle_deg >= exact && total.upper_angle_deg < 90.); // A stricter peak limit must still fail despite the side // witness. A previous success cannot carry to the wrong // material side, another floor, or a zero work query. - for (limit, side, curve, work) in [ - (60., right, query.curve.clone(), 200000), - (360., !right, query.curve.clone(), 200000), - (90., right, query.curve.clone(), 0), - ( - 360., - right, - Curve::Line { - start: [query.curve.start()[0], query.curve.start()[1], 4.], - end: [query.curve.end()[0], query.curve.end()[1], 4.], - }, - 200000, - ), + let lower = Motion { + curve: Curve::Line { + start: [query.curve.start()[0], query.curve.start()[1], 4.], + end: [query.curve.end()[0], query.curve.end()[1], 4.], + }, + ..query.clone() + }; + let full = EngagementOptions { + max_work: 200000, + ..Default::default() + }; + let none = EngagementOptions { + max_work: 0, + ..Default::default() + }; + for refused in [ + scene.check(&query, 1., 60., full, &|| false), + scene.check(&query, 1., 90., none, &|| false), + scene.check_material_side(&query, 1., !right, full, &|| false), + scene.check_material_side(&lower, 1., right, full, &|| false), ] { - let refused = scene - .check_front( - &Motion { - curve, - ..query.clone() - }, - 1., - limit, - side, - EngagementOptions { - max_work: work, - ..Default::default() - }, - &|| false, - ) - .unwrap(); - assert_eq!(refused.status, EngagementStatus::Unresolved); + assert_eq!(refused.unwrap().status, EngagementStatus::Unresolved); } // Corroboration only: exact projection inequalities above // are the proof. Check the finite capsule and actual side. @@ -3806,9 +3126,10 @@ mod full_column_tests { assert!(shape_distance(&scene.supports[64].shape, q) < 0.999); } } + assert!(scene.check(&query, 1., 90., options, &|| true).is_err()); assert!( scene - .check_front(&query, 1., 90., right, options, &|| true) + .check_material_side(&query, 1., right, options, &|| true) .is_err() ); } @@ -3817,10 +3138,9 @@ mod full_column_tests { let end_query = motion(3, point(8., -0.2), point(10., -0.2)); assert_eq!( scene - .check_front( + .check_material_side( &end_query, 1., - 360., true, EngagementOptions::default(), &|| false, @@ -3831,17 +3151,10 @@ mod full_column_tests { ); let polls = std::cell::Cell::new(0); let cancelled = scene - .check_front( - &end_query, - 1., - 90., - true, - EngagementOptions::default(), - &|| { - polls.set(polls.get() + 1); - polls.get() > 3 - }, - ) + .check(&end_query, 1., 90., EngagementOptions::default(), &|| { + polls.set(polls.get() + 1); + polls.get() > 3 + }) .unwrap_err(); assert!(cancelled.contains("cancelled")); assert!(polls.get() > 3); @@ -3849,47 +3162,6 @@ mod full_column_tests { } } - #[test] - fn sufficient_filled_disk_contact_stops_only_after_both_front_bounds_pass() { - let base = scene(&[([0., 0.], 0.5, 5.)], 1.); - let history = - EngagementScene::new(base.stock.clone(), vec![base.supports[0].clone(); 65]).unwrap(); - let query = Motion { - id: 2, - operation: "early-contact".into(), - tool: "t".into(), - kind: MoveKind::Cut, - feed_mm_min: Some(600.), - curve: Curve::Arc { - start: [0.6, 0., 5.], - end: [0.6, 0., 5.], - center: [0., 0., 5.], - plane: Plane::Xy, - sweep_rad: TAU, - }, - }; - let options = EngagementOptions { - max_work: 2, - max_nodes: 1, - ..Default::default() - }; - let bounded = history - .check_front(&query, 1., 100., true, options, &|| false) - .unwrap(); - assert_eq!(bounded.status, EngagementStatus::Bounded); - assert_eq!(bounded.support_tests + bounded.index_visits, 2); - assert!(bounded.upper_angle_deg > 1. && bounded.upper_angle_deg < 100.); - for (angle, right) in [(1., true), (360., false)] { - assert_eq!( - history - .check_front(&query, 1., angle, right, options, &|| false) - .unwrap() - .status, - EngagementStatus::Unresolved - ); - } - } - #[test] fn filled_disk_proves_whole_forbidden_halves_without_claiming_all_contact_clear() { for shift in [[0., 0.], [10000., -20000.]] { @@ -3951,17 +3223,11 @@ mod full_column_tests { let total = filled.check(&query, 1., 100., options, &|| false).unwrap(); assert_eq!(total.status, EngagementStatus::Bounded); assert!(total.upper_angle_deg > 1., "whole cutter is NOT clear"); - let joint = filled - .check_front(&query, 1., 100., right, options, &|| false) - .unwrap(); - assert_eq!(joint.status, EngagementStatus::Bounded); - assert!(joint.upper_angle_deg > 1. && joint.upper_angle_deg <= 100.); assert_eq!( filled - .check_front( + .check_material_side( &query, 1., - 360., !right, EngagementOptions::default(), &|| false @@ -3969,14 +3235,13 @@ mod full_column_tests { .unwrap() .status, EngagementStatus::Unresolved, - "wrong side must remain unproved even at360deg" + "wrong side must remain unproved" ); assert_eq!( filled - .check_front( + .check_material_side( &query, 1., - 100., right, EngagementOptions { max_work: 0, @@ -3990,7 +3255,7 @@ mod full_column_tests { ); assert!( filled - .check_front(&query, 1., 100., right, options, &|| true) + .check_material_side(&query, 1., right, options, &|| true) .is_err() ); // CORROBORATION only. Whole proof is convexity for the @@ -4075,14 +3340,14 @@ mod full_column_tests { max_nodes: 1, ..Default::default() }; - let incomplete = history - .check_front(&query, 1., 1., right, root_only, &|| false) + let side = history + .check_material_side(&query, 1., right, root_only, &|| false) .unwrap(); + assert_eq!(side.status, EngagementStatus::Bounded, "{side:?}"); + let incomplete = history.check(&query, 1., 1., root_only, &|| false).unwrap(); assert_eq!(incomplete.status, EngagementStatus::Unresolved); let complete = history - .check_front(&query, 1., 1., right, EngagementOptions::default(), &|| { - false - }) + .check(&query, 1., 1., EngagementOptions::default(), &|| false) .unwrap(); assert_eq!(complete.status, EngagementStatus::Bounded); assert!(complete.maximum_depth > 0 && complete.nodes > 4); @@ -4098,14 +3363,9 @@ mod full_column_tests { } assert_eq!( history - .check_front( - &deeper, - 1., - 360., - right, - EngagementOptions::default(), - &|| false, - ) + .check_material_side(&deeper, 1., right, EngagementOptions::default(), &|| { + false + },) .unwrap() .status, EngagementStatus::Unresolved, @@ -4382,74 +3642,6 @@ mod full_column_tests { } } #[test] - fn joint_front_proof_requires_whole_contact_and_whole_forbidden_side() { - let filled = scene(&[([0., 0.], 0.5, 5.)], 1.); - for radius in [0.58, 0.7] { - for direction in [1., -1.] { - for right in [false, true] { - let p = [radius, 0., 5.]; - let query = Motion { - id: 1, - operation: "front".into(), - tool: "t".into(), - kind: MoveKind::Cut, - feed_mm_min: Some(600.), - curve: Curve::Arc { - start: p, - end: p, - center: [0., 0., 5.], - plane: Plane::Xy, - sweep_rad: direction * TAU, - }, - }; - let options = EngagementOptions::default(); - let total = filled.check(&query, 1., 83., options, &|| false).unwrap(); - let side = filled - .check_material_side(&query, 1., right, options, &|| false) - .unwrap(); - let joint = filled - .check_front(&query, 1., 83., right, options, &|| false) - .unwrap(); - assert_eq!( - joint.status == EngagementStatus::Bounded, - total.status == EngagementStatus::Bounded - && side.status == EngagementStatus::Bounded, - "radius={radius},direction={direction},right={right}: {joint:?}" - ); - if joint.status == EngagementStatus::Bounded { - assert!(joint.upper_angle_deg <= 83.); - } - let unlimited = filled - .check_front(&query, 1., 360., right, options, &|| false) - .unwrap(); - assert_eq!( - unlimited.status == EngagementStatus::Bounded, - side.status == EngagementStatus::Bounded - ); - let budget = filled - .check_front( - &query, - 1., - 83., - right, - EngagementOptions { - max_work: 1, - ..options - }, - &|| false, - ) - .unwrap(); - assert_eq!(budget.status, EngagementStatus::Unresolved); - assert!( - filled - .check_front(&query, 1., 83., right, options, &|| true) - .is_err() - ); - } - } - } - } - #[test] fn fixed_history_stack_preserves_order_at_the_full_supported_capacity() { for roots in [vec![18], (0..18).rev().collect()] { let mut reference = roots.clone(); diff --git a/src/entry.rs b/src/entry.rs index df393675..cfcbc910 100644 --- a/src/entry.rs +++ b/src/entry.rs @@ -78,7 +78,7 @@ pub(crate) enum EntryPolicy { /// stock proves (`PocketPlan::rest_ramp_moves`); adaptive clearing's /// engagement front into enclosed material, in place of the helix /// (`EngagementFrontPlan::ramp_pass`). Roughing's offset and raster layers -/// and the orbit strategies refuse it (`refuse_ramp`). It does not lift the +/// refuse it (`refuse_ramp`). It does not lift the /// need for a center-cutting cutter (`PocketOperation::validate_authoring`). /// /// The angle is a fact about the tool and material, so it has no default. @@ -495,8 +495,6 @@ pub struct UnenteredArea { /// `no_helix_allowed`: the same, with an entry that allows no helix. /// `tighter_than_planner_resolves`: the cutter fits with less play than /// the engagement front's steering grid works in. - /// `no_orbit_fits`: disk_front / stock_front, whose orbits sweep more - /// than the cutter. pub reason: &'static str, /// A tool-centre position in the area, and the extent of the tool /// centres the cutter fits at around it. @@ -505,10 +503,10 @@ pub struct UnenteredArea { pub max_mm: Point, pub level_z_mm: f64, pub cutter_radius_mm: f64, - /// The helix radii (or orbit radii) tried. + /// The helix radii tried. pub radii_tried_mm: Vec, - /// What the planner needs there and what the area leaves: a helix (or - /// orbit) radius, or for `tighter_than_planner_resolves` the play + /// What the planner needs there and what the area leaves: a helix + /// radius, or for `tighter_than_planner_resolves` the play /// between the cutter and the walls on each side. pub needed_mm: f64, #[serde(skip_serializing_if = "Option::is_none")] @@ -535,13 +533,6 @@ impl UnenteredArea { "engagement_front: {operation} has material at ({:.3}, {:.3}) for the level at Z{z}, where the cutter of radius {r} mm fits the region ({area}) but with less play to its walls than this planner works in (it needs {:.3} mm on each side at this cutter and width), so it has no way into that area. Use a Pocket there (its passes follow the walls' exact offset; entry=RampEntry(angle_deg), a helix or a plunge), a smaller cutter, or {keep_out}", at[0], at[1], self.needed_mm ), - "no_orbit_fits" => format!( - "{operation}: no orbit fits the area at ({:.3}, {:.3}) ({area}) for the level at Z{z}: this path strategy clears with orbits that sweep a disk of radius {} mm (cutter radius {r} + orbit radius {}), and that area is nowhere that wide, though the cutter fits it. Use path_strategy engagement_front (with entry=RampEntry(angle_deg) where no helix fits), a smaller orbit_radius_mm, a Pocket, a smaller cutter, or {keep_out}", - at[0], - at[1], - r + self.needed_mm, - self.needed_mm - ), reason => { let helix = if reason == "no_helix_allowed" { "the entry allows no helix (StockEdgeEntry(helix=None)), and none of its radii would fit".to_string() @@ -1080,15 +1071,11 @@ mod compact_tests { }; forward.push(Guide { stroke: Stroke::line(point(i), point(i + 1)), - radius: 0., - coverage: 0., edge: i, }); } forward.push(Guide { stroke: Stroke::line([1., 0.], [2., 0.]), - radius: 0., - coverage: 0., edge: 5000, }); let mut doubled = forward.clone(); diff --git a/src/lib.rs b/src/lib.rs index d65809cb..d9f3e7af 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -57,7 +57,6 @@ //! assert!(stock.volume().removed_upper_mm3 > 0.); //! ``` pub mod adaptive; -mod adaptive_front; pub mod buffers; pub mod chamfer; pub mod contour; diff --git a/src/navigation.rs b/src/navigation.rs index e43c1e0e..fddb91b7 100644 --- a/src/navigation.rs +++ b/src/navigation.rs @@ -67,41 +67,28 @@ impl Groups { #[derive(Clone, Copy)] pub(crate) struct Guide { pub(crate) stroke: Stroke, - pub(crate) radius: f64, - pub(crate) coverage: f64, pub(crate) edge: usize, } pub(crate) struct GuideGraph { pub(crate) tours: Vec>, - pub(crate) links: usize, pub(crate) work: usize, } pub(crate) struct GraphOptions { - pub bridge_radius: f64, - pub cutter_radius: f64, - pub coverage: f64, - pub local_sizing: bool, pub starting_work: usize, } pub(crate) fn graph( guides: &PocketPlan, - originals: Vec<(Stroke, f64, f64)>, + originals: Vec<(Stroke, f64)>, options: GraphOptions, cancel: &impl CancelSignal, ) -> Result { - let GraphOptions { - bridge_radius, - cutter_radius, - coverage, - local_sizing, - starting_work, - } = options; + let GraphOptions { starting_work } = options; let mut nodes = vec![]; let mut node_radii: Vec = vec![]; let mut ids = HashMap::new(); let mut edges = vec![]; let mut endpoints = vec![]; - for (s, radius, coverage) in originals { + for (s, radius) in originals { if cancel.is_cancelled() { return Err("adaptive navigation cancelled".into()); } @@ -117,8 +104,6 @@ pub(crate) fn graph( } edges.push(Guide { stroke: s, - radius, - coverage, edge: edges.len(), }); endpoints.push(pair); @@ -151,7 +136,7 @@ pub(crate) fn graph( candidates.sort_unstable_by(bridge_cmp); } let mut candidates = candidates.into_iter(); - let (mut links, mut work) = (0, starting_work); + let mut work = starting_work; loop { if groups.count <= guides.report().center_components { break; @@ -161,7 +146,7 @@ pub(crate) fn graph( } else { candidates.next() }; - let Some((preferred, _, a, b)) = candidate else { + let Some((_, _, a, b)) = candidate else { break; }; if cancel.is_cancelled() { @@ -175,32 +160,12 @@ pub(crate) fn graph( } work += guides.link_work_per_query(); // source sign query plus all source edge distances if guides.link_geometry_fits(nodes[a], nodes[b]) { - let mut radius = bridge_radius; - if preferred > bridge_radius { - work += guides.link_work_per_query(); - if local_sizing { - if let Some((lower, _)) = - guides.guide_radius_bounds(Stroke::line(nodes[a], nodes[b])) - { - radius = (lower - cutter_radius).min(preferred).max(bridge_radius); - } - } else if guides.link_geometry_fits_radius( - nodes[a], - nodes[b], - preferred + cutter_radius, - ) { - radius = preferred; - } - } groups.join(a, b); edges.push(Guide { stroke: Stroke::line(nodes[a], nodes[b]), - radius, - coverage, edge: edges.len(), }); endpoints.push([a, b]); - links += 1; } } let mut adjacent = vec![vec![]; nodes.len()]; @@ -251,7 +216,7 @@ pub(crate) fn graph( tours.push(tour); } } - Ok(GuideGraph { tours, links, work }) + Ok(GuideGraph { tours, work }) } #[cfg(test)] @@ -310,21 +275,23 @@ mod tests { let result = graph( &guides, vec![ - (Stroke::line(points[0], points[1]), 1., 1.), - (Stroke::line(points[2], points[3]), 1., 1.), + (Stroke::line(points[0], points[1]), 1.), + (Stroke::line(points[2], points[3]), 1.), ], - GraphOptions { - bridge_radius: 1., - cutter_radius: 2., - coverage: 1., - local_sizing: false, - starting_work: 0, - }, + GraphOptions { starting_work: 0 }, &|| false, ) .unwrap(); - assert_eq!(result.links, 1); assert_eq!(result.tours.len(), 1); + // One bridge link: every edge past the two originals is that link. + let mut links: Vec<_> = result.tours[0] + .iter() + .filter(|s| s.edge >= 2) + .map(|s| s.edge) + .collect(); + links.sort_unstable(); + links.dedup(); + assert_eq!(links.len(), 1); let bridges: Vec<_> = result.tours[0].iter().filter(|s| s.edge >= 2).collect(); assert!(!bridges.is_empty()); for bridge in bridges { diff --git a/src/operation.rs b/src/operation.rs index 0e042059..7079f219 100644 --- a/src/operation.rs +++ b/src/operation.rs @@ -1,6 +1,5 @@ //! Shared dispatch for native operations; motion/stock streaming stays common. use crate::{ - adaptive::{AdaptivePlan, AdaptiveReport}, chamfer::{ChamferPlan, ChamferReport}, contour::{ContourPlan, ContourReport}, deburr::{DeburrPlan, DeburrReport}, @@ -27,7 +26,6 @@ use serde::Serialize; #[serde(untagged)] pub enum OperationReport<'a> { Roughing(&'a RoughingReport), - Adaptive(&'a AdaptiveReport), AdaptiveFront(&'a crate::pocket_front::PocketFrontReport), Pocket(&'a PocketReport), Slot(&'a SlotReport), @@ -53,7 +51,6 @@ pub enum OperationReport<'a> { } pub enum OperationPlan { Roughing(Box), - Adaptive(Box), /// An adaptive pocket cleared by the engagement front (#190). AdaptiveFront(Box), Pocket(Box), @@ -286,21 +283,11 @@ impl OperationPlan { plan.refuse_no_cutter_position()?; Ok(Self::Pocket(Box::new(plan))) } - Operation::AdaptivePocket(p) - if p.path_strategy == crate::adaptive::AdaptivePathStrategy::EngagementFront => - { - Ok(Self::AdaptiveFront(Box::new( - crate::pocket_front::PocketFrontPlan::prepare_with_stock( - p, tool, stock, initial, first_id, cancel, - )?, - ))) - } - Operation::AdaptivePocket(p) => { - let plan = - AdaptivePlan::prepare_with_stock(p, tool, stock, initial, first_id, cancel)?; - plan.refuse_unentered()?; - Ok(Self::Adaptive(Box::new(plan))) - } + Operation::AdaptivePocket(p) => Ok(Self::AdaptiveFront(Box::new( + crate::pocket_front::PocketFrontPlan::prepare_with_stock( + p, tool, stock, initial, first_id, cancel, + )?, + ))), Operation::Roughing(p) => Ok(Self::Roughing(Box::new( RoughingPlan::prepare_with_stock(p, tool, stock, initial, first_id, cancel)?, ))), @@ -364,20 +351,11 @@ impl OperationPlan { Operation::Roughing(p) => Ok(Self::Roughing(Box::new(RoughingPlan::prepare( p, tool, stock, initial, first_id, cancel, )?))), - Operation::AdaptivePocket(p) - if p.path_strategy == crate::adaptive::AdaptivePathStrategy::EngagementFront => - { - Ok(Self::AdaptiveFront(Box::new( - crate::pocket_front::PocketFrontPlan::prepare( - p, tool, stock, initial, first_id, cancel, - )?, - ))) - } - Operation::AdaptivePocket(p) => { - let plan = AdaptivePlan::prepare(p, tool, stock, initial, first_id, cancel)?; - plan.refuse_unentered()?; - Ok(Self::Adaptive(Box::new(plan))) - } + Operation::AdaptivePocket(p) => Ok(Self::AdaptiveFront(Box::new( + crate::pocket_front::PocketFrontPlan::prepare( + p, tool, stock, initial, first_id, cancel, + )?, + ))), Operation::Waterline(p) => Ok(Self::Waterline(Box::new(WaterlinePlan::prepare( p, tool, stock, initial, first_id, cancel, )?))), @@ -443,7 +421,6 @@ impl OperationPlan { pub fn report(&self) -> OperationReport<'_> { match self { Self::Roughing(p) => OperationReport::Roughing(p.report()), - Self::Adaptive(p) => OperationReport::Adaptive(p.report()), Self::AdaptiveFront(p) => OperationReport::AdaptiveFront(p.report()), Self::Pocket(p) => OperationReport::Pocket(p.report()), Self::Slot(p) => OperationReport::Slot(p.report()), @@ -474,7 +451,6 @@ impl OperationPlan { pub fn progress(&self) -> Option { match self { Self::Roughing(p) => Some(p.progress()), - Self::Adaptive(p) => Some(p.progress()), Self::AdaptiveFront(p) => Some(p.progress()), Self::Pocket(p) => Some(p.progress()), Self::Contour(p) => Some(p.progress()), @@ -487,7 +463,6 @@ impl OperationPlan { pub fn prefix_events(&self) -> Vec { match self { Self::Roughing(p) => p.prefix_events(), - Self::Adaptive(p) => p.prefix_events(), Self::AdaptiveFront(p) => p.prefix_events(), Self::Pocket(p) => p.prefix_events(), Self::Slot(p) => p.prefix_events(), @@ -515,7 +490,6 @@ impl OperationPlan { pub fn suffix_events(&self) -> Vec { match self { Self::Roughing(p) => p.suffix_events(), - Self::Adaptive(p) => p.suffix_events(), Self::AdaptiveFront(p) => p.suffix_events(), Self::Pocket(p) => p.suffix_events(), Self::Slot(p) => p.suffix_events(), @@ -547,7 +521,6 @@ impl OperationPlan { ) -> Result, String> { match self { Self::Roughing(p) => p.next_motion_with_stock(stock, cancel), - Self::Adaptive(p) => p.next_motion_with_stock(stock, cancel), Self::AdaptiveFront(p) => p.next_motion_with_stock(stock, cancel), Self::Pocket(p) => p.next_motion_with_stock(stock, cancel), Self::Slot(p) => p.next_motion_with_stock(stock, cancel), @@ -588,7 +561,6 @@ impl OperationPlan { pub fn finish_report(&mut self, cancel: &impl CancelSignal) -> Result<(), String> { match self { Self::Roughing(p) => p.finish_report(cancel), - Self::Adaptive(p) => p.finish_report(cancel), Self::AdaptiveFront(p) => p.finish_report(cancel), Self::Pocket(p) => { p.finish_report(cancel)?; diff --git a/src/pocket.rs b/src/pocket.rs index 473be582..64224e1f 100644 --- a/src/pocket.rs +++ b/src/pocket.rs @@ -1167,6 +1167,7 @@ fn stroke_point(s: Stroke, fraction: f64) -> Point { ] } } +#[cfg(test)] fn farthest_point(s: Stroke, p: Point) -> f64 { let mut maximum = norm(s.a, p).max(norm(s.b, p)); if let Some((c, _)) = s.arc { @@ -1182,6 +1183,7 @@ fn farthest_point(s: Stroke, p: Point) -> f64 { } maximum } +#[cfg(test)] fn maximum_boundary_distance(s: Stroke, edge: Stroke) -> f64 { if let Some((center, boundary_sweep)) = edge.arc { // Actual boundary points are valid witnesses for every guide point. @@ -1330,30 +1332,6 @@ impl Crossing { } } -/// An actually successful whole-curve source check, scoped to the immutable -/// source geometry/error/allowance of one prepared pocket. Retaining the Arc -/// allocation prevents address reuse from impersonating a former owner. -pub(crate) struct GuideTubeApproval { - owner: Arc<()>, - curve: Curve, - radius: f64, - tolerance: f64, -} -impl GuideTubeApproval { - pub(crate) fn matches( - &self, - source: &PocketPlan, - curve: &Curve, - radius: f64, - tolerance: f64, - ) -> bool { - Arc::ptr_eq(&self.owner, &source.source_owner) - && &self.curve == curve - && self.radius == radius - && self.tolerance == tolerance - && source.operation.tolerance_mm == tolerance - } -} /// Committed-clearance scene shared by the plans that stream into one stock /// (for example every layer of a roughing operation). It validates itself /// against the stock's column history at each use, so sharing is always safe. @@ -1369,7 +1347,6 @@ pub(crate) type EntrySceneCache = Arc< pub struct PocketPlan { operation: PocketOperation, source: PreparedRegion, - source_owner: Arc<()>, centers: PreparedRegion, radius: f64, source_edges: Vec, @@ -1798,7 +1775,6 @@ impl PocketPlan { entry_helix_end: None, operation: op, source, - source_owner: Arc::new(()), centers: center, radius, source_edges, @@ -2003,12 +1979,8 @@ impl PocketPlan { } let mut graph = crate::navigation::graph( self, - strokes.iter().map(|s| (*s, 0., 0.)).collect(), + strokes.iter().map(|s| (*s, 0.)).collect(), crate::navigation::GraphOptions { - bridge_radius: 0., - cutter_radius: self.radius, - coverage: 0., - local_sizing: false, starting_work: work, }, cancel, @@ -2490,257 +2462,6 @@ impl PocketPlan { pub(crate) fn guide_strokes(&self) -> &[Stroke] { &self.strokes } - /// Offset for a physical cutter axis, retaining the source, allowance and - /// construction reserves. Adaptive guide radii additionally contain an - /// orbit radius; that spacing does not constrain a direct contour axis. - pub(crate) fn cutter_axis_clearance(&self, cutter_radius: f64) -> f64 { - cutter_radius + (self.report.applied_clearance_mm - self.radius) - } - /// Excluded linear loops of the selected ORIGINAL source component. These - /// are a proposal footprint only, never a substitute for whole-tube fit. - pub(crate) fn front_obstacles(&self, seed: Point) -> Result, String> { - for component in &self.source.definition().components { - let selected = PlanarRegion { - components: vec![component.clone()], - ..self.source.definition().clone() - } - .prepare(ConstructionOptions { - tolerance_mm: self.operation.tolerance_mm, - })?; - let q = selected.query(seed)?; - if !q - .signed_clearance_mm - .is_some_and(|d| d >= -2. * q.uncertainty_mm) - { - continue; - } - let count: usize = component.holes.iter().map(|h| h.vertices.len()).sum(); - if count > 4096 - || component - .holes - .iter() - .any(|h| h.vertices.iter().any(|p| p[2] != 0.)) - { - return Ok(vec![]); - } - return Ok(component - .holes - .iter() - .flat_map(|h| h.vertices.iter().map(|p| [p[0], p[1]])) - .collect()); - } - Ok(vec![]) - } - /// Same nominal morphological reachable domain as guide_residual, scoped - /// to the centre component owning a real admitted entry. No path authority. - pub(crate) fn front_component_region( - &self, - seed: Point, - inflation: f64, - ) -> Result<(PreparedRegion, PreparedRegion), String> { - let options = ConstructionOptions { - tolerance_mm: self.operation.tolerance_mm, - }; - let mut selected = None; - let mut best = f64::NEG_INFINITY; - for component in &self.centers.definition().components { - let region = PlanarRegion { - components: vec![component.clone()], - ..self.centers.definition().clone() - } - .prepare(options)?; - let q = region.query(seed)?; - if let Some(signed) = q.signed_clearance_mm - && signed >= -2. * q.uncertainty_mm - && signed > best - { - best = signed; - selected = Some(region); - } - } - let centres = selected.ok_or("stock-front entry has no matching centre component")?; - let domain = centres.offset_prepared(-inflation)?; - Ok((centres, domain.into_parts().1)) - } - /// Corridor proposals only: the caller must fit the complete tube against - /// the original source and prove the entry disk clear in committed stock. - pub(crate) fn front_channel_rails( - &self, - seed: Point, - material: [Point; 2], - margin: f64, - ) -> Result, String> { - let mut rails: Vec = Vec::new(); - let tolerance = self.operation.tolerance_mm; - for component in &self.source.definition().components { - if component.holes.len() < 2 { - continue; - } - let selected = PlanarRegion { - components: vec![component.clone()], - ..self.source.definition().clone() - } - .prepare(ConstructionOptions { - tolerance_mm: tolerance, - })?; - let q = selected.query(seed)?; - if !q - .signed_clearance_mm - .is_some_and(|d| d >= -2. * q.uncertainty_mm) - { - continue; - } - let edges: Vec<_> = component - .holes - .iter() - .enumerate() - .flat_map(|(i, h)| { - Stroke::from_boundary(h) - .into_iter() - .filter(|s| s.arc.is_none()) - .map(move |s| (i, s)) - }) - .collect(); - if edges.len() > 256 { - return Ok(rails); - } - let corners = [ - material[0], - [material[0][0], material[1][1]], - material[1], - [material[1][0], material[0][1]], - ]; - for (i, (hole, a)) in edges.iter().enumerate() { - let length = (a.b[0] - a.a[0]).hypot(a.b[1] - a.a[1]); - if length <= 32. * tolerance { - continue; - } - let t = [(a.b[0] - a.a[0]) / length, (a.b[1] - a.a[1]) / length]; - let n = [t[1], -t[0]]; - let dot = |p: Point, v: Point| p[0] * v[0] + p[1] * v[1]; - for (other, b) in &edges[i + 1..] { - if hole == other { - continue; - } - let bd = [b.b[0] - b.a[0], b.b[1] - b.a[1]]; - let bl = bd[0].hypot(bd[1]); - if bl <= 32. * tolerance - || (bd[0] * t[1] - bd[1] * t[0]).abs() > 4096. * f64::EPSILON * bl - { - continue; - } - let aa = dot(a.a, t); - let ab = dot(a.b, t); - let ba = dot(b.a, t); - let bb = dot(b.b, t); - if aa.max(ab).min(ba.max(bb)) - aa.min(ab).max(ba.min(bb)) <= 32. * tolerance { - continue; - } - let av = dot(a.a, n); - let bv = dot(b.a, n); - if (av - bv).abs() <= 2. * margin { - continue; - } - let v = (av + bv) / 2.; - let lo = corners - .iter() - .map(|&p| dot(p, t)) - .fold(f64::INFINITY, f64::min) - - margin; - let hi = corners - .iter() - .map(|&p| dot(p, t)) - .fold(f64::NEG_INFINITY, f64::max) - + margin; - let point = |u: f64| [u * t[0] + v * n[0], u * t[1] + v * n[1]]; - let rail = Stroke::line(point(lo), point(hi)); - let near = - |a: Point, b: Point| (a[0] - b[0]).hypot(a[1] - b[1]) <= 64. * tolerance; - if !rails.iter().any(|old| { - (near(old.a, rail.a) && near(old.b, rail.b)) - || (near(old.a, rail.b) && near(old.b, rail.a)) - }) { - rails.push(rail); - } - if rails.len() >= 64 { - return Ok(rails); - } - } - } - break; - } - Ok(rails) - } - pub(crate) fn guide_cover_region(&self, inflation: f64) -> Result { - Ok(self.centers.offset(-inflation)?.region) - } - /// Clip straight guides against a conservatively eroded covered domain. - /// Transform to the line's local XY frame and reuse analytic line/circle - /// scan intersections; parity ambiguity retains the whole original guide. - pub(crate) fn guides_outside( - &self, - cover: &PlanarRegion, - cancel: &impl CancelSignal, - ) -> Result, String> { - let edges: Vec<_> = cover - .components - .iter() - .flat_map(|c| std::iter::once(&c.outer).chain(&c.holes)) - .flat_map(Stroke::from_boundary) - .collect(); - let mut result = vec![]; - let guard = 8. * self.operation.tolerance_mm; - for &s in &self.strokes { - if cancel.is_cancelled() { - return Err("adaptive fine-guide clipping cancelled".into()); - } - if s.arc.is_some() { - result.push(s); - continue; - } - let length = norm(s.a, s.b); - let u = [(s.b[0] - s.a[0]) / length, (s.b[1] - s.a[1]) / length]; - let local = |p: Point| { - [ - (p[0] - s.a[0]) * u[0] + (p[1] - s.a[1]) * u[1], - -(p[0] - s.a[0]) * u[1] + (p[1] - s.a[1]) * u[0], - ] - }; - let mut xs: Vec<_> = edges - .iter() - .flat_map(|e| { - Crossing::split(Stroke { - a: local(e.a), - b: local(e.b), - arc: e.arc.map(|(c, sweep)| (local(c), sweep)), - }) - }) - .filter_map(|e| e.x_at(0.)) - .collect(); - xs.sort_by(f64::total_cmp); - if xs.len() % 2 != 0 { - result.push(s); - continue; - } - let mut cursor = 0f64; - let world = |d: f64| [s.a[0] + d * u[0], s.a[1] + d * u[1]]; - for pair in xs.as_chunks::<2>().0 { - let lo = (pair[0] + guard).clamp(0., length); - let hi = (pair[1] - guard).clamp(0., length); - if hi <= lo || hi <= cursor { - continue; - } - if lo > cursor { - result.push(Stroke::line(world(cursor), world(lo))); - } - cursor = cursor.max(hi); - } - if cursor < length { - result.push(Stroke::line(world(cursor), s.b)); - } - } - Ok(result) - } pub(crate) fn source_component( &self, p: Point, @@ -2753,9 +2474,9 @@ impl PocketPlan { pub(crate) fn link_work_per_query(&self) -> usize { 1 + 2 * self.source_edges.len() } - /// Original-region whole-guide tube radius interval. The lower bound - /// admits an entire line/arc; the upper bound limits possible local growth - /// and avoids splitting constant-clearance boundary guides needlessly. + /// Original-region whole-guide tube radius interval: the independent + /// reference `guide_tube_fits` is tested against. + #[cfg(test)] pub(crate) fn guide_radius_bounds(&self, stroke: Stroke) -> Option<(f64, f64)> { #[cfg(feature = "profile-planning")] let _profile = crate::planning_profile::span("source.guide_bounds"); @@ -2783,38 +2504,6 @@ impl PocketPlan { (upper - reserve + numeric + 8. * self.operation.tolerance_mm).max(0.), )) } - /// Boolean version of the original whole-guide lower-radius condition. - /// Every boundary must pass; a midpoint alone never admits the tube. Keep - /// subtraction order identical to guide_radius_bounds at guarded limits. - pub(crate) fn approve_guide_tube( - &self, - curve: &Curve, - radius: f64, - ) -> Option { - let (a, b) = (curve.start(), curve.end()); - let arc = match curve { - Curve::Line { .. } => None, - Curve::Arc { - center, - plane: Plane::Xy, - sweep_rad, - .. - } => Some(([center[0], center[1]], *sweep_rad)), - _ => return None, - }; - let stroke = Stroke { - a: [a[0], a[1]], - b: [b[0], b[1]], - arc, - }; - self.guide_tube_fits(stroke, radius) - .then(|| GuideTubeApproval { - owner: Arc::clone(&self.source_owner), - curve: curve.clone(), - radius, - tolerance: self.operation.tolerance_mm, - }) - } pub(crate) fn guide_tube_fits(&self, stroke: Stroke, required_radius: f64) -> bool { #[cfg(feature = "profile-planning")] let _profile = crate::planning_profile::span("source.guide_admission"); @@ -2846,20 +2535,6 @@ impl PocketPlan { .and_then(|q| q.signed_clearance_mm) .is_some_and(fits) } - pub(crate) fn guide_residual( - &self, - radius: f64, - ) -> Result { - #[cfg(feature = "profile-planning")] - let _profile = crate::planning_profile::span("guide.residual"); - let inflated = self.centers.offset_prepared(-radius)?; - let desired = self - .source - .offset_prepared(self.operation.radial_allowance_mm)?; - desired - .region() - .boolean_prepared(inflated.region(), Boolean::Difference) - } /// Deferred diagnostic work. Actual material removal can stream first; /// a pending or unknown residual must never be interpreted as all clear. pub fn finish_report(&mut self, cancel: &impl CancelSignal) -> Result<&PocketReport, String> { diff --git a/src/pocket/admission_tests.rs b/src/pocket/admission_tests.rs index fff10052..38c6876f 100644 --- a/src/pocket/admission_tests.rs +++ b/src/pocket/admission_tests.rs @@ -261,7 +261,6 @@ fn native_source_admission_measurement() { "Cargo.lock", "src/pocket.rs", "src/pocket/admission_tests.rs", - "src/adaptive_front.rs", "fixtures/operations/adaptive-pocket.json", ] .into_iter() @@ -282,72 +281,3 @@ fn native_source_admission_measurement() { serde_json::json!({"reference":report["reference"],"admission":report["admission"],"p95_ratio":ratio,"gates":report["gates"]}) ); } - -#[test] -fn source_approval_reuses_only_actual_complete_proofs_from_the_same_owner() { - let source = fixture(false, 0., [0., 0.], 0., 0., 1e-5); - let curve = Curve::Line { - start: [5., 5., 8.], - end: [6., 5., 8.], - }; - let approval = source - .approve_guide_tube(&curve, 0.5) - .expect("interior complete tube"); - assert!(source.guide_tube_fits(Stroke::line([5., 5.], [6., 5.]), 0.5)); - assert!(approval.matches(&source, &curve, 0.5, 1e-5)); - assert!(!approval.matches(&source, &curve, 0.6, 1e-5)); - assert!(!approval.matches(&source, &curve, 0.5, 2e-5)); - for changed in [ - Curve::Line { - start: [5., 5., 7.], - end: [6., 5., 7.], - }, - Curve::Line { - start: [5., 5., 8.], - end: [6.1, 5., 8.], - }, - Curve::Line { - start: [6., 5., 8.], - end: [5., 5., 8.], - }, - ] { - assert!(!approval.matches(&source, &changed, 0.5, 1e-5)); - } - let foreign = fixture(false, 0., [0., 0.], 0., 0., 1e-5); - assert!(!approval.matches(&foreign, &curve, 0.5, 1e-5)); - let outside = Curve::Line { - start: [-100., -100., 8.], - end: [-90., -100., 8.], - }; - assert!(source.approve_guide_tube(&outside, 0.5).is_none()); - let crossing = Curve::Line { - start: [5., 5., 8.], - end: [40., 5., 8.], - }; - assert!(source.approve_guide_tube(&crossing, 0.5).is_none()); - let curved = fixture(true, 0., [0., 0.], 0., 0., 1e-5); - let arc = Curve::Arc { - start: [20., 13., 8.], - end: [13., 20., 8.], - center: [13., 13., 8.], - plane: Plane::Xy, - sweep_rad: FRAC_PI_2, - }; - let arc_approval = curved.approve_guide_tube(&arc, 0.5).unwrap(); - assert!(arc_approval.matches(&curved, &arc, 0.5, 1e-5)); - let mut other_sweep = arc.clone(); - if let Curve::Arc { sweep_rad, .. } = &mut other_sweep { - *sweep_rad -= TAU; - } - assert!(!arc_approval.matches(&curved, &other_sweep, 0.5, 1e-5)); - let mut other_plane = arc; - if let Curve::Arc { plane, .. } = &mut other_plane { - *plane = Plane::Yz; - } - assert!(curved.approve_guide_tube(&other_plane, 0.5).is_none()); - let moved = source; - assert!(approval.matches(&moved, &curve, 0.5, 1e-5)); - drop(moved); - let replacement = fixture(false, 0., [0., 0.], 0., 0., 1e-5); - assert!(!approval.matches(&replacement, &curve, 0.5, 1e-5)); -} diff --git a/src/pocket_front.rs b/src/pocket_front.rs index baf59c76..0381312d 100644 --- a/src/pocket_front.rs +++ b/src/pocket_front.rs @@ -10,7 +10,7 @@ //! air), and every cutting stroke is proven within the contact angle of the //! declared width, acos(1 - w/r). use crate::{ - adaptive::{AdaptivePathStrategy, AdaptivePocketOperation, CuttingSense}, + adaptive::{AdaptivePocketOperation, CuttingSense}, entry::PocketEntry, motion::{Event, Motion, Vec3}, pocket::ResidualStatus, @@ -78,14 +78,7 @@ impl PocketFrontPlan { first_id: u64, cancel: &impl CancelSignal, ) -> Result { - debug_assert_eq!(op.path_strategy, AdaptivePathStrategy::EngagementFront); let pocket = &op.pocket; - if op.orbit_radius_mm.is_some() - || op.min_orbit_radius_mm.is_some() - || op.local_orbit_tolerance_mm.is_some() - { - return Err("engagement_front does not use orbits; leave orbit_radius_mm, min_orbit_radius_mm and local_orbit_tolerance_mm unset".into()); - } if pocket.max_stay_down_mm.is_some() || pocket.rest_tolerance_mm.is_some() { return Err("engagement_front links through its own proven-clear moves and plans from the committed stock; leave max_stay_down_mm and rest_tolerance_mm unset".into()); } diff --git a/src/regeneration.rs b/src/regeneration.rs index c77bc770..c40b9f0e 100644 --- a/src/regeneration.rs +++ b/src/regeneration.rs @@ -133,16 +133,14 @@ fn stock_digest(producer: &StreamProducer) -> Result { Ok(format!("{:x}", h.finalize())) } fn clearance_dependency(stock: &crate::stock::Stock, operation: &Operation) -> Option<[u8; 32]> { - use crate::{adaptive::AdaptivePathStrategy::StockFront, roughing::RoughingClearing}; + use crate::roughing::RoughingClearing; + // The engagement front reads the committed sweeps themselves + // (`Stock::committed_clearance_since`), not only the cell bounds the + // stock digest covers, so two stocks with equal cells but different + // committed sweeps must not share a cached plan. let sensitive = match operation { - Operation::AdaptivePocket(op) => op.path_strategy == StockFront, - Operation::Roughing(op) => matches!( - op.clearing, - RoughingClearing::Adaptive { - path_strategy: StockFront, - .. - } - ), + Operation::AdaptivePocket(_) => true, + Operation::Roughing(op) => matches!(op.clearing, RoughingClearing::Adaptive { .. }), _ => false, }; sensitive.then(|| stock.committed_clearance_fingerprint()) @@ -1286,7 +1284,6 @@ fn control_turn( mod clearance_key_tests { use super::*; use crate::{ - adaptive::AdaptivePathStrategy, motion::{Curve, MoveKind}, stock::{Stock, SweepOptions}, stream::StreamManifest, @@ -1325,11 +1322,8 @@ mod clearance_key_tests { b.snapshot(), "the height image alone cannot distinguish these sweeps" ); - let mut operation = manifest.operations[0].clone(); - let Operation::AdaptivePocket(adaptive) = &mut operation else { - panic!("fixture"); - }; - adaptive.path_strategy = AdaptivePathStrategy::StockFront; + let operation = manifest.operations[0].clone(); + assert!(matches!(operation, Operation::AdaptivePocket(_)), "fixture"); assert_ne!( clearance_dependency(&a, &operation), clearance_dependency(&b, &operation) @@ -1348,18 +1342,18 @@ mod clearance_key_tests { clearance_dependency(&a, &operation), clearance_dependency(&restored, &operation) ); - let Operation::AdaptivePocket(adaptive) = &mut operation else { + let Operation::AdaptivePocket(adaptive) = &operation else { unreachable!(); }; - adaptive.path_strategy = AdaptivePathStrategy::DiskFront; let raster = Operation::Pocket(adaptive.pocket.clone()); - assert_eq!(clearance_dependency(&a, &operation), None); assert_eq!(clearance_dependency(&a, &raster), None); - let rough: StreamManifest = - serde_json::from_str(include_str!("../fixtures/regressions/stock-front.json")).unwrap(); + let rough: StreamManifest = serde_json::from_str(include_str!( + "../fixtures/operations/roughing-open-block.json" + )) + .unwrap(); assert!( clearance_dependency(&a, &rough.operations[0]).is_some(), - "nested stock-front roughing also consumes the premise" + "adaptive roughing also consumes the premise" ); } } diff --git a/src/roughing.rs b/src/roughing.rs index b13fde39..c931cf74 100644 --- a/src/roughing.rs +++ b/src/roughing.rs @@ -2,8 +2,7 @@ //! See docs/retained-body-roughing.md; shadows are not tip-plane cross-sections. use crate::{ Point, - adaptive::{AdaptivePathStrategy, AdaptivePlan, AdaptivePocketOperation, CuttingSense}, - adaptive_front::FrontReport, + adaptive::{AdaptivePathStrategy, CuttingSense}, motion::{Coolant, Event, Motion, Vec3}, planar::{ Boolean, Boundary, Component, ConstructionOptions, FilledHoles, PlanarRegion, @@ -19,7 +18,7 @@ use crate::{ use robust::{Coord, orient2d}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; -use std::{collections::VecDeque, sync::OnceLock}; +use std::collections::VecDeque; mod engagement_front; pub(crate) mod parallel; @@ -655,15 +654,12 @@ pub enum RoughingClearing { routing: Option, }, Adaptive { - #[serde(default, skip_serializing_if = "AdaptivePathStrategy::is_default")] + /// Always written: a saved program states which planner made it. + #[serde(default)] path_strategy: AdaptivePathStrategy, #[serde(default, skip_serializing_if = "Option::is_none")] cutting_sense: Option, max_radial_engagement_mm: f64, - orbit_radius_mm: Option, - min_orbit_radius_mm: Option, - local_orbit_tolerance_mm: Option, - boundary_tolerance_mm: f64, }, } fn default_coverage_margin() -> f64 { @@ -872,7 +868,6 @@ pub struct RoughingReport { } enum LayerPlan { Pocket(Box), - Adaptive(Box), Engagement(Box), } impl LayerPlan { @@ -882,35 +877,30 @@ impl LayerPlan { fn refusal(&self) -> Option { match self { Self::Pocket(_) => None, - Self::Adaptive(p) => p.refusal(), Self::Engagement(p) => p.refusal(), } } fn construction_error_mm(&self) -> f64 { match self { Self::Pocket(p) => p.construction_error_mm(), - Self::Adaptive(p) => p.construction_error_mm(), Self::Engagement(p) => p.construction_error_mm(), } } fn activate(&mut self, p: Vec3, id: u64, spec: &StockSpec) -> Result<(), String> { match self { Self::Pocket(x) => x.activate_layer(p, id, spec), - Self::Adaptive(x) => x.activate_layer(p, id, spec), Self::Engagement(x) => x.activate_layer(p, id, spec), } } fn next(&mut self, s: &Stock, c: &impl CancelSignal) -> Result, String> { match self { Self::Pocket(x) => x.next_motion_with_stock(s, c), - Self::Adaptive(x) => x.next_motion_with_stock(s, c), Self::Engagement(x) => x.next_motion_with_stock(s, c), } } fn report(&self) -> serde_json::Value { let mut value = match self { Self::Pocket(x) => serde_json::to_value(x.report()).unwrap(), - Self::Adaptive(x) => serde_json::to_value(x.report()).unwrap(), Self::Engagement(x) => serde_json::to_value(x.report()).unwrap(), }; // Layer contours remain separately queryable through the shadow API. @@ -918,37 +908,21 @@ impl LayerPlan { value.as_object_mut().unwrap().remove("geometric_residual"); value } - fn front_progress(&self) -> Option { - if let Self::Adaptive(plan) = self { - let r = plan.report(); - return r.front.as_ref().map(|front| FrontProgress { - front: front.clone(), - max_bounded_engagement_deg: r.max_bounded_engagement_deg, - motions: r.motions, - seed_orbits: r.seed_orbits, - helical_entries: r.helical_entries, - }); - } - None - } fn entries(&self) -> (usize, usize) { match self { Self::Pocket(x) => (x.report().stock_edge_entries, x.report().helical_entries), - Self::Adaptive(x) => (x.report().stock_edge_entries, x.report().helical_entries), Self::Engagement(x) => (x.report().stock_edge_entries, x.report().helical_entries), } } fn prefix(&self) -> Vec { match self { Self::Pocket(x) => x.prefix_events(), - Self::Adaptive(x) => x.prefix_events(), Self::Engagement(x) => x.prefix_events(), } } fn suffix(&self) -> Vec { match self { Self::Pocket(x) => x.suffix_events(), - Self::Adaptive(x) => x.suffix_events(), Self::Engagement(x) => x.suffix_events(), } } @@ -960,30 +934,10 @@ impl LayerPlan { x.finish_report(c)?; Ok(()) } - Self::Adaptive(x) => x.finish_report(c), Self::Engagement(x) => x.finish_report(c), } } } -// Snapshot only at the existing successful-motion reporting boundary. Reading -// the live layer from report() would expose changes from a rejected/cancelled -// planner attempt that the previous public report intentionally did not publish. -struct FrontProgress { - front: FrontReport, - max_bounded_engagement_deg: f64, - motions: usize, - seed_orbits: usize, - helical_entries: usize, -} -impl FrontProgress { - fn apply(&self, report: &mut serde_json::Value) { - report["front"] = serde_json::to_value(&self.front).unwrap(); - report["max_bounded_engagement_deg"] = self.max_bounded_engagement_deg.into(); - report["motions"] = self.motions.into(); - report["seed_orbits"] = self.seed_orbits.into(); - report["helical_entries"] = self.helical_entries.into(); - } -} pub struct RoughingPlan { depth_parts: Vec<(crate::verification::ToolPart, f64, f64)>, /// The per-move reach check for the sections above the flutes, when the @@ -1002,8 +956,6 @@ pub struct RoughingPlan { prefix: Vec, suffix: Vec, report: RoughingReport, - front_progress: Option, - materialized_report: OnceLock, /// Why the first adaptive layer that made no motion left material it /// was asked to cut (an area no entry reaches, `LayerPlan::refusal`): /// the operation's refusal if no layer makes a motion (#250). @@ -1197,40 +1149,27 @@ impl RoughingPlan { + target.mesh.surface_error_mm + 32. * op.tolerance_mm }); - let (clearing, engagement, width, orbit) = match op.clearing { - RoughingClearing::Offset { .. } => ("offset", None, None, 0.), - RoughingClearing::Raster { .. } => ("raster", None, None, 0.), + let (clearing, engagement, width) = match op.clearing { + RoughingClearing::Offset { .. } => ("offset", None, None), + RoughingClearing::Raster { .. } => ("raster", None, None), RoughingClearing::Adaptive { max_radial_engagement_mm: w, - orbit_radius_mm, - path_strategy, .. } => { if !w.is_finite() || w <= 0. || w > r { return Err("adaptive roughing radial engagement must be positive and at most cutter radius".into()); } - // Width is an upper limit. A stricter native angle still - // honors it, including widths whose angle would exceed170deg. - let phi = if path_strategy == AdaptivePathStrategy::EngagementFront { - // The contact angle of a straight pass of width w, less - // the cutter's own trail: what engagement_front proves - // every stroke against. - (1. - w / r).acos().to_degrees() - } else { - (2. * (1. - w / r).acos()).to_degrees().min(170.) - }; + // The contact angle of a straight pass of width w, less the + // cutter's own trail: what the engagement front proves every + // stroke against. + let phi = (1. - w / r).acos().to_degrees(); if !(1. ..=170.).contains(&phi) { return Err("adaptive roughing engagement is outside native 1..170 degree circumference bound".into()); } - ( - "adaptive", - Some(phi), - Some(w), - orbit_radius_mm.unwrap_or(r / 2.), - ) + ("adaptive", Some(phi), Some(w)) } }; - let margin = 4. * (r + op.radial_allowance_mm + orbit.max(r)) + guard; + let margin = 4. * (2. * r + op.radial_allowance_mm) + guard; let bounds = [ [spec.min_mm[0] - margin, spec.min_mm[1] - margin], [spec.max_mm[0] + margin, spec.max_mm[1] + margin], @@ -1266,16 +1205,10 @@ impl RoughingPlan { // through the air beside the stock and the air the layers above cut // (a layer's pocket starts at the stock top while the flutes span // it). They refuse it. - if !matches!( - op.clearing, - RoughingClearing::Adaptive { - path_strategy: AdaptivePathStrategy::EngagementFront, - .. - } - ) { + if !matches!(op.clearing, RoughingClearing::Adaptive { .. }) { op.entry.refuse_ramp( &format!("roughing {}", op.id), - "offset and raster layers (and the disk_front and stock_front strategies) enter beside the stock or on a fitted helix, which the order and links of their passes are built on; AdaptiveClearing (path_strategy engagement_front) ramps into enclosed material", + "offset and raster layers enter beside the stock or on a fitted helix, which the order and links of their passes are built on; AdaptiveClearing (path_strategy engagement_front) ramps into enclosed material", )?; } let expanded = stock_region.prepare(options)?; @@ -1323,80 +1256,17 @@ impl RoughingPlan { }; front.validate( "roughing", - (!matches!( - op.clearing, - RoughingClearing::Adaptive { - path_strategy: AdaptivePathStrategy::EngagementFront, - .. - } - )) - .then_some(""), + (!matches!(op.clearing, RoughingClearing::Adaptive { .. })).then_some(""), )?; match op.clearing { RoughingClearing::Offset { coverage_margin_mm, .. } => crate::pocket::validate_offset_margin(r, coverage_margin_mm)?, - RoughingClearing::Adaptive { - path_strategy: AdaptivePathStrategy::EngagementFront, - orbit_radius_mm, - min_orbit_radius_mm, - local_orbit_tolerance_mm, - .. - } => { - if orbit_radius_mm.is_some() - || min_orbit_radius_mm.is_some() - || local_orbit_tolerance_mm.is_some() - { - return Err("engagement_front does not use orbits; leave orbit_radius_mm, min_orbit_radius_mm and local_orbit_tolerance_mm unset".into()); - } + RoughingClearing::Adaptive { .. } => { if op.omit_empty_cuts { return Err("engagement_front plans every pass from the committed stock; omit_empty_cuts does not apply".into()); } } - RoughingClearing::Adaptive { - path_strategy: AdaptivePathStrategy::DiskFront, - .. - } => { - // #167. disk_front covers a region it takes to be solid with - // orbits and never reads the stock. Roughing's region is the - // stock footprint grown by a margin, so that the stock's edge - // is no wall: disk_front then orbits through all the air - // beside the stock (75 m of 137 m on a 130 x 90 mm stock). - return Err( - "Roughing does not clear with path_strategy disk_front (also what a program \ - saved without path_strategy asks for): it treats the whole region as \ - material and never reads the stock, so it orbits through the air beside \ - the stock. Use path_strategy engagement_front, AdaptiveClearing's default; \ - disk_front remains AdaptivePocket's strategy" - .into(), - ); - } - RoughingClearing::Adaptive { - path_strategy, - cutting_sense, - orbit_radius_mm, - min_orbit_radius_mm, - local_orbit_tolerance_mm, - boundary_tolerance_mm, - .. - } => { - AdaptivePocketOperation { - pocket: template, - path_strategy, - cutting_sense, - orbit_radius_mm, - min_orbit_radius_mm, - local_orbit_tolerance_mm, - boundary_tolerance_mm, - max_engagement_deg: engagement.unwrap(), - clockwise: op.clockwise, - rapid_descent_clearance_mm: None, - ramp_clearance_mm: None, - link_feed_mm_min: None, - link_chip_thinning: false, - } - .validate_parameters(r)?; - } RoughingClearing::Raster { .. } => (), } let mut plans = VecDeque::new(); @@ -1569,7 +1439,6 @@ impl RoughingPlan { })) } RoughingClearing::Adaptive { - path_strategy: AdaptivePathStrategy::EngagementFront, max_radial_engagement_mm, cutting_sense, .. @@ -1588,41 +1457,10 @@ impl RoughingPlan { // for, not with the cusps between pass ends. .with_wall_runs(true), )), - RoughingClearing::Adaptive { - path_strategy, - cutting_sense, - orbit_radius_mm, - min_orbit_radius_mm, - local_orbit_tolerance_mm, - boundary_tolerance_mm, - .. - } => LayerPlan::Adaptive(Box::new(AdaptivePlan::prepare( - AdaptivePocketOperation { - pocket, - path_strategy, - cutting_sense, - orbit_radius_mm, - min_orbit_radius_mm, - local_orbit_tolerance_mm, - boundary_tolerance_mm, - max_engagement_deg: engagement.unwrap(), - clockwise: op.clockwise, - rapid_descent_clearance_mm: None, - ramp_clearance_mm: None, - link_feed_mm_min: None, - link_chip_thinning: false, - }, - tool, - &layer_spec, - initial, - 1, - &cancel, - )?)), }; if op.omit_empty_cuts { match &mut plan { LayerPlan::Pocket(p) => p.enable_empty_cuts(), - LayerPlan::Adaptive(p) => p.enable_empty_cuts(), LayerPlan::Engagement(_) => (), } } @@ -1637,9 +1475,6 @@ impl RoughingPlan { } let layer_guides = match &plan { LayerPlan::Pocket(p) => p.report().xy_strokes, - LayerPlan::Adaptive(p) => { - p.report().guide_strokes + p.report().navigation_links - } LayerPlan::Engagement(_) => 0, }; let report = RoughingLayerReport { @@ -1764,23 +1599,11 @@ impl RoughingPlan { prefix, suffix, report, - front_progress: None, - materialized_report: OnceLock::new(), refusal: None, }) } pub fn report(&self) -> &RoughingReport { - let Some(progress) = &self.front_progress else { - return &self.report; - }; - // Ordinary Rust borrows keep a returned snapshot valid until the next - // mutable planner call. Repeated readers share one materialization; - // generation without report consumers allocates no per-motion JSON. - self.materialized_report.get_or_init(|| { - let mut report = self.report.clone(); - progress.apply(&mut report.layers[report.active_layer].clearing); - report - }) + &self.report } /// Planning progress (#198): depth levels done of those planned, and for /// engagement-front clearing the active level's reachable material area. @@ -1855,7 +1678,6 @@ impl RoughingPlan { proof.maximum_upper_z_mm = Some(maximum); proof.generation = Some(stock.generation()); self.generation = Some(stock.generation()); - self.materialized_report.take(); } loop { check(cancel)?; @@ -1938,8 +1760,6 @@ impl RoughingPlan { self.next_id = m.id + 1; self.generation = Some(stock.generation() + 1); self.report.motions += 1; - self.front_progress = plan.front_progress(); - self.materialized_report.take(); return Ok(Some(m)); } if self.refusal.is_none() @@ -1952,8 +1772,6 @@ impl RoughingPlan { } plan.finish(cancel)?; self.report.layers[self.report.active_layer].clearing = plan.report(); - self.front_progress = None; - self.materialized_report.take(); self.report.completed_layers += 1; self.report.active_layer += 1; let memory = match self.plans.pop_front() { @@ -1971,7 +1789,6 @@ impl RoughingPlan { pub fn finish_report(&mut self, cancel: &impl CancelSignal) -> Result<(), String> { check(cancel)?; if self.plans.is_empty() { - self.materialized_report.take(); self.report.geometric_residual_status = if !self.report.layers.is_empty() && self .report diff --git a/src/stock.rs b/src/stock.rs index 40e21824..f74ddc8f 100644 --- a/src/stock.rs +++ b/src/stock.rs @@ -27,7 +27,6 @@ pub(crate) struct SweepReceipt { pub motion: Motion, pub tool: crate::tool::ToolAssembly, pub fraction: f64, - pub tolerance_mm: f64, } #[derive(Clone, Copy, Debug, Default)] @@ -594,6 +593,7 @@ impl CommittedColumns { self.tolerance_mm = self.tolerance_mm.max(tolerance_mm); } + #[cfg(test)] fn collect( &self, tolerance_mm: f64, @@ -893,6 +893,9 @@ impl Stock { pub(crate) fn last_sweep_receipt(&self) -> Option<&SweepReceipt> { self.last_receipt.as_deref() } + /// Every committed cleared sweep (tests; planners read only what is new + /// with `committed_clearance_since`). + #[cfg(test)] pub(crate) fn committed_clearance( &self, tolerance_mm: f64, @@ -1621,7 +1624,6 @@ impl Stock { motion: motion.clone(), tool: tool.definition().clone(), fraction, - tolerance_mm: options.tolerance_mm, }) }), }; @@ -2161,7 +2163,6 @@ impl Stock { motion: motion.clone(), tool: tool.definition().clone(), fraction, - tolerance_mm, }) }), }; diff --git a/tests/adaptive.rs b/tests/adaptive.rs index 6cd2b1bd..ee07622a 100644 --- a/tests/adaptive.rs +++ b/tests/adaptive.rs @@ -72,1568 +72,24 @@ fn curve_distance(c: &Curve, p: [f64; 2], maximum: bool) -> f64 { _ => panic!("unexpected helix"), } } -fn exposed(q: f64, r: f64, a: f64) -> f64 { - if q + r <= a { - return 0.; - } - if q >= a + r { - return 360.; - } - let x = (q * q + r * r - a * a) / (2. * q); - 2. * (-x / r).clamp(-1., 1.).acos().to_degrees() -} -fn notch_clearance(p: [f64; 2]) -> f64 { - (11. - p[0]).max(0.).hypot((11. - p[1]).max(0.)) -} -fn l_clearance(p: [f64; 2]) -> f64 { - (p[0] - 3.) - .min(p[1] - 3.) - .min(23. - p[0]) - .min(23. - p[1]) - .min(notch_clearance(p)) -} -fn assert_entire_l_sweep(c: &Curve, r: f64) { - let a = c.start(); - let b = c.end(); - let mut points = vec![[a[0], a[1]], [b[0], b[1]]]; - match *c { - Curve::Line { .. } => { - let d = [b[0] - a[0], b[1] - a[1]]; - let l = d[0] * d[0] + d[1] * d[1]; - let mut ts = vec![]; - if l > 0. { - ts.push(((11. - a[0]) * d[0] + (11. - a[1]) * d[1]) / l); - } - for k in 0..2 { - if d[k] != 0. { - ts.push((11. - a[k]) / d[k]); - } - } - points.extend( - ts.into_iter() - .filter(|t| (0. ..=1.).contains(t)) - .map(|t| [a[0] + t * d[0], a[1] + t * d[1]]), - ); - } - Curve::Arc { - center, sweep_rad, .. - } => { - let rho = dist([a[0], a[1]], [center[0], center[1]]); - let start = (a[1] - center[1]).atan2(a[0] - center[0]); - let mut angles = vec![ - 0., - PI / 2., - PI, - 3. * PI / 2., - (11. - center[1]).atan2(11. - center[0]), - ]; - let x = (11. - center[0]) / rho; - if x.abs() <= 1. { - angles.extend([x.acos(), -x.acos()]); - } - let y = (11. - center[1]) / rho; - if y.abs() <= 1. { - angles.extend([y.asin(), PI - y.asin()]); - } - points.extend( - angles - .into_iter() - .filter(|x| angle_on(*x, start, sweep_rad)) - .map(|x| [center[0] + rho * x.cos(), center[1] + rho * x.sin()]), - ); - } - _ => panic!("unexpected helix"), - } - for p in points { - assert!( - l_clearance(p) >= r - 1e-7, - "whole L sweep exits at{p:?}: {c:?}" - ); - } -} -fn exact_height(c: &Curve, p: [f64; 2]) -> f64 { - if curve_distance(c, p, false) <= 2. + 1e-10 { - c.start()[2].min(c.end()[2]) - } else { - f64::INFINITY - } -} -fn unrotate_curve(mut c: Curve) -> Curve { - let transform = |p: &mut Vec3| { - let old = *p; - p[0] = old[1]; - p[1] = 26. - old[0]; - }; - match &mut c { - Curve::Line { start, end } => { - transform(start); - transform(end); - } - Curve::Arc { - start, end, center, .. - } => { - transform(start); - transform(end); - transform(center); - } - _ => panic!("unexpected helix"), - } - c -} -fn curve_tangent(c: &Curve, end: bool) -> [f64; 2] { - let a = c.start(); - let b = c.end(); - let d = match *c { - Curve::Line { .. } => [b[0] - a[0], b[1] - a[1]], - Curve::Arc { - center, sweep_rad, .. - } => { - let p = if end { b } else { a }; - [ - -(p[1] - center[1]) * sweep_rad.signum(), - (p[0] - center[0]) * sweep_rad.signum(), - ] - } - _ => panic!("unexpected helix"), - }; - let n = d[0].hypot(d[1]); - [d[0] / n, d[1] / n] -} -#[test] -fn l_pocket_has_continuous_engagement_containment_coverage_and_actual_stock() { - let m = fixture(); - let cancel = AtomicBool::new(false); - let tool = m.tools[0].prepare().unwrap(); - for (cw, angle) in [(true, 90.), (false, 60.)] { - let mut op = operation(); - op.clockwise = cw; - op.max_engagement_deg = angle; - op.pocket.floor_z_mm = 9.; - if !cw { - for component in &mut op.pocket.region.components { - for p in &mut component.outer.vertices { - let old = *p; - p[0] = 26. - old[1]; - p[1] = old[0]; - } - } - } - let mut plan = AdaptivePlan::prepare( - op, - &m.tools[0], - m.stock.height().unwrap(), - m.initial_position_mm, - 1, - &cancel, - ) - .unwrap(); - assert_eq!( - plan.report().navigation_components, - 1, - "L route must join through the concavity" - ); - let mut stock = Stock::new(m.stock.height().unwrap().clone()).unwrap(); - let mut disk = None; - let mut curves: Vec = vec![]; - let mut old = m.initial_position_mm; - let mut clear = 0; - let mut seed = 0; - while let Some(motion) = plan.next_motion_with_stock(&stock, &cancel).unwrap() { - assert_eq!(motion.curve.start(), old); - old = motion.curve.end(); - if motion.kind == MoveKind::Plunge { - disk = None; - } - if motion.kind == MoveKind::Cut - || motion.kind == MoveKind::Link - || motion.kind == MoveKind::Plunge - { - let original = if cw { - motion.curve.clone() - } else { - unrotate_curve(motion.curve.clone()) - }; - assert_entire_l_sweep(&original, 2.); - } - if let Some(previous) = disk { - if matches!(motion.kind, MoveKind::Cut | MoveKind::Link) { - let q = curve_distance(&motion.curve, previous, true); - if exposed(q, 2., 3.) > angle + 1e-7 { - // Independently inspect every potentially touched whole cell. - let half = stock.cell_widths_mm()[0].hypot(stock.cell_widths_mm()[1]) / 2.; - for (i, h) in stock.cells().iter().enumerate() { - if curve_distance(&motion.curve, stock.cell_center(i).unwrap(), false) - <= 2. + half + 1e-7 - { - assert!( - h.upper_mm <= motion.curve.start()[2], - "uncertified engagement override: {motion:?}" - ); - } - } - clear += 1; - } - } - } else if motion.kind == MoveKind::Cut { - seed += 1; - assert_eq!(motion.feed_mm_min, Some(150.)); - } - if let Curve::Arc { - center, sweep_rad, .. - } = motion.curve - && motion.kind == MoveKind::Cut - { - assert!((sweep_rad.abs() - TAU).abs() < 1e-10); - disk = Some([center[0], center[1]]); - } - if let Some(previous) = curves.last() - && motion.curve.start()[2] == motion.curve.end()[2] - && previous.start()[2] == previous.end()[2] - && motion.curve.start()[2] < 10. - { - let incoming = curve_tangent(previous, true); - let outgoing = curve_tangent(&motion.curve, false); - assert!( - incoming[0] * outgoing[0] + incoming[1] * outgoing[1] > 1. - 1e-8, - "non-tangent corner: {previous:?} -> {:?}", - motion.curve.clone() - ); - } - let delta = stock - .preview_sweep(&tool, &motion, 1., m.sweep, &cancel) - .unwrap(); - stock.apply_delta(&delta).unwrap(); - curves.push(motion.curve); - } - plan.finish_report(&cancel).unwrap(); - let report = plan.report(); - assert_eq!(seed, 1); - assert_eq!(report.seed_orbits, 1); - assert!(report.turn_arcs > 0); - assert!(report.max_bounded_engagement_deg <= angle); - assert!(report.controlled_orbits > 10); - assert!( - report - .geometric_residual_area_mm2 - .is_some_and(|x| x > 0. && x < 15.) - ); - for (i, h) in stock.cells().iter().enumerate() { - let xy = stock.cell_center(i).unwrap(); - let actual = curves - .iter() - .map(|c| exact_height(c, xy)) - .fold(10f64, f64::min); - assert!( - h.lower_mm <= actual + 1e-6 && h.upper_mm >= actual - 1e-6, - "exact stock outside interval {xy:?}: {actual} {h:?}" - ); - let original_xy = if cw { xy } else { [xy[1], 26. - xy[0]] }; - if l_clearance(original_xy) > 3.01 { - assert!(actual <= 9. + 1e-7, "reachable core uncut at{xy:?}"); - } - if l_clearance(original_xy) < -1e-7 { - assert_eq!(actual, 10.); - } - } - assert!(stock.volume().removed_lower_mm3 > 180.); - assert!(stock.volume().removed_lower_mm3 <= 256.); - eprintln!( - "cw{cw} angle{angle} motions{} controlled{} clear{clear}", - report.motions, report.controlled_orbits - ); - } -} -#[test] -fn cancellation_during_final_residual_keeps_report_pending_and_retryable() { - use camlib::pocket::ResidualStatus; - use std::cell::Cell; - let m = fixture(); - let tool = m.tools[0].prepare().unwrap(); - let mut stock = Stock::new(m.stock.height().unwrap().clone()).unwrap(); - let mut plan = AdaptivePlan::prepare( - operation(), - &m.tools[0], - m.stock.height().unwrap(), - m.initial_position_mm, - 1, - &|| false, - ) - .unwrap(); - while let Some(motion) = plan.next_motion_with_stock(&stock, &|| false).unwrap() { - let delta = stock - .preview_sweep(&tool, &motion, 1., m.sweep, &|| false) - .unwrap(); - stock.apply_delta(&delta).unwrap(); - } - assert_eq!( - plan.report().geometric_residual_status, - ResidualStatus::Pending - ); - let pending = serde_json::to_value(plan.report()).unwrap(); - // Cancel between entry and publication, without a timing-dependent thread. - let entered = Cell::new(false); - let cancel = || entered.replace(true); - assert!( - plan.finish_report(&cancel) - .unwrap_err() - .contains("cancelled") - ); - assert_eq!(serde_json::to_value(plan.report()).unwrap(), pending); - plan.finish_report(&|| false).unwrap(); - assert_eq!( - plan.report().geometric_residual_status, - ResidualStatus::Estimated - ); - assert!(plan.report().geometric_residual.is_some()); - assert!(plan.report().geometric_residual_area_mm2.is_some()); - assert_eq!( - serde_json::to_value(plan.report()).unwrap()["motions"], - pending["motions"] - ); - let completed = serde_json::to_value(plan.report()).unwrap(); - plan.finish_report(&|| false).unwrap(); - assert_eq!(serde_json::to_value(plan.report()).unwrap(), completed); -} -#[test] -fn cancel_stale_stock_and_invalid_parameters_do_not_consume_the_cursor() { - let m = fixture(); - let cancel = AtomicBool::new(false); - let mut stock = Stock::new(m.stock.height().unwrap().clone()).unwrap(); - let mut plan = AdaptivePlan::prepare( - operation(), - &m.tools[0], - m.stock.height().unwrap(), - m.initial_position_mm, - 1, - &cancel, - ) - .unwrap(); - let first = plan - .next_motion_with_stock(&stock, &cancel) - .unwrap() - .unwrap(); - assert!( - plan.next_motion_with_stock(&stock, &cancel) - .unwrap_err() - .contains("commit") - ); - let delta = stock - .preview_sweep(&m.tools[0].prepare().unwrap(), &first, 1., m.sweep, &cancel) - .unwrap(); - stock.apply_delta(&delta).unwrap(); - cancel.store(true, std::sync::atomic::Ordering::Relaxed); - assert!(plan.next_motion_with_stock(&stock, &cancel).is_err()); - cancel.store(false, std::sync::atomic::Ordering::Relaxed); - let second = plan - .next_motion_with_stock(&stock, &cancel) - .unwrap() - .unwrap(); - assert_eq!(second.id, first.id + 1); - assert_eq!(second.curve.start(), first.curve.end()); - for radius in [0., -1., 3., f64::NAN] { - let mut op = operation(); - op.orbit_radius_mm = Some(radius); - assert!( - AdaptivePlan::prepare( - op, - &m.tools[0], - m.stock.height().unwrap(), - m.initial_position_mm, - 1, - &cancel - ) - .is_err() - ); - } -} -#[test] -fn circular_island_and_separate_components_keep_their_topology_and_single_seeds() { - check_circular_island_and_separate_components(false); -} -#[test] -fn stock_front_circular_island_and_separate_components_complete_with_actual_stock() { - check_circular_island_and_separate_components(true); -} -fn check_circular_island_and_separate_components(front: bool) { - let m = fixture(); - let cancel = AtomicBool::new(false); - let tool = m.tools[0].prepare().unwrap(); - for (annulus, local) in [(true, false), (false, false), (true, true), (false, true)] { - let mut op = operation(); - if front { - op.path_strategy = AdaptivePathStrategy::StockFront; - } - if local { - op.min_orbit_radius_mm = Some(0.25); - op.local_orbit_tolerance_mm = Some(0.05); - } - op.pocket.floor_z_mm = 9.; - op.pocket.stepover_mm = 1.; - let (source, expected) = if annulus { - let mut source = PlanarRegion::circle("annulus", [13., 13.], 10.).unwrap(); - source.components[0].holes.push( - PlanarRegion::circle("hole", [13., 13.], 3.) - .unwrap() - .components - .remove(0) - .outer, - ); - (source, 1) - } else { - let mut source = PlanarRegion::circle("two-pockets", [7., 13.], 4.).unwrap(); - source.components.extend( - PlanarRegion::circle("second", [19., 13.], 4.) - .unwrap() - .components, - ); - (source, 2) - }; - op.pocket.region = source; - let max_angle = op.max_engagement_deg; - let stock_guard = m.stock.height().unwrap().cell_size_mm * 2_f64.sqrt() / 2. - + op.boundary_tolerance_mm - + 4. * m.sweep.tolerance_mm; - let mut plan = AdaptivePlan::prepare( - op, - &m.tools[0], - m.stock.height().unwrap(), - m.initial_position_mm, - 1, - &cancel, - ) - .unwrap(); - assert_eq!(plan.report().navigation_components, expected); - let mut stock = Stock::new(m.stock.height().unwrap().clone()).unwrap(); - let mut motions = 0; - let mut nominal_seconds = 0.; - while let Some(motion) = plan - .next_motion_with_stock(&stock, &cancel) - .unwrap_or_else(|error| { - panic!( - "front={front} annulus={annulus} local={local} after{motions}moves: {error}; {}", - serde_json::to_string(plan.report()).unwrap() - ) - }) - { - if front { - assert!(motions < 10000, "island/component case did not complete"); - } - if matches!( - motion.kind, - MoveKind::Cut | MoveKind::Link | MoveKind::Plunge - ) { - if annulus { - assert!(curve_distance(&motion.curve, [13., 13.], false) >= 5. - 1e-7); - assert!(curve_distance(&motion.curve, [13., 13.], true) <= 8. + 1e-7); - } else { - assert!([[7., 13.], [19., 13.]].iter().any(|&p| curve_distance( - &motion.curve, - p, - true - ) <= 2. + 1e-7)); - } - } - let delta = stock - .preview_sweep(&tool, &motion, 1., m.sweep, &cancel) - .unwrap(); - stock.apply_delta(&delta).unwrap(); - nominal_seconds += motion.curve.prepare(m.sweep.tolerance_mm).unwrap().length_mm() - / motion.feed_mm_min.unwrap_or(6000.) * 60.; - motions += 1; - } - plan.finish_report(&cancel).unwrap(); - if front { - let report = plan.report().front.as_ref().unwrap(); - assert!(report.coverage_complete); - assert_eq!(report.completed_components, expected); - assert!(report.max_bounded_engagement_deg <= max_angle); - assert!(report.front_moves > 0); - if annulus { - assert!(motions <= 2500, "annular motion quality: {motions}"); - assert!( - report.reentries <= 100, - "annular reentry quality: {}", - report.reentries - ); - assert!( - nominal_seconds <= 500., - "annular cycle quality: {nominal_seconds}" - ); - assert!(report.channel_contours > 0); - } else { - assert!(motions <= 150, "circular pocket motion quality: {motions}"); - assert!( - report.reentries <= 4, - "circular pocket reentry quality: {}", - report.reentries - ); - assert!( - nominal_seconds <= 60., - "circular pocket cycle quality: {nominal_seconds}" - ); - assert!(report.enclosed_contours > 0); - } - let (mut cleared, mut protected) = (0, 0); - for (i, h) in stock.cells().iter().enumerate() { - let p = stock.cell_center(i).unwrap(); - let d = dist(p, [13., 13.]); - let reachable_interior = if annulus { - d > 3. + stock_guard && d < 10. - stock_guard - } else { - [[7., 13.], [19., 13.]] - .iter() - .any(|¢re| dist(p, centre) < 4. - stock_guard) - }; - if reachable_interior { - cleared += 1; - assert!( - h.upper_mm <= 9. + 4. * m.sweep.tolerance_mm, - "reachable stock remains at{p:?}: {h:?}; annulus={annulus} local={local}" - ); - } - if annulus && d < 3. - stock_guard { - protected += 1; - assert!( - h.lower_mm >= 10. - 4. * m.sweep.tolerance_mm, - "protected island removed at{p:?}: {h:?}" - ); - } - } - assert!(cleared > 100, "remaining-stock check must not be vacuous"); - if annulus { - assert!(protected > 10, "island check must not be vacuous"); - } - eprintln!( - "stock-front annulus={annulus} local={local}: {motions}moves, checked{cleared}cleared/{protected}protected cells; {}", - serde_json::to_string(report).unwrap() - ); - } - assert_eq!(plan.report().seed_orbits, expected); - assert!(motions > 10); - assert!(stock.volume().removed_lower_mm3 > 40.); - // The circular island remains stock, including its center cell. - if annulus { - for (i, h) in stock.cells().iter().enumerate() { - if dist(stock.cell_center(i).unwrap(), [13., 13.]) < 2.5 { - assert!(h.upper_mm >= 10.); - } - } - } - } -} -#[test] -fn stock_front_uses_actual_larger_tool_stock_for_corner_remainders() { - use camlib::{operation::OperationPlan, tool::PreparedAssembly}; - // This execution helper also independently encloses the entire axis curve - // in the analytic rectangular source. It does not sample motion poses. - fn execute( - plan: &mut OperationPlan, - stock: &mut Stock, - tool: &PreparedAssembly, - sweep: SweepOptions, - radius: f64, - mut position: Vec3, - mut next: u64, - ) -> (Vec, f64) { - let mut history = Vec::new(); - let mut cutting_length = 0.; - while let Some(motion) = plan - .next_motion_with_stock(stock, &|| false) - .unwrap_or_else(|error| { - panic!( - "upstream/rest incomplete after{}moves at{position:?}: {error}; {}", - history.len(), - serde_json::to_string(&plan.report()).unwrap() - ) - }) - { - assert!(history.len() < 10000, "upstream/rest did not complete"); - assert_eq!(motion.id, next); - assert_eq!(motion.curve.start(), position); - let path = motion.curve.prepare(1e-5).unwrap(); - if matches!( - motion.kind, - MoveKind::Cut | MoveKind::Link | MoveKind::Plunge - ) { - let bounds = path.bounds(); - for axis in 0..2 { - assert!(bounds.min[axis] >= 3. + radius - 1e-7); - assert!(bounds.max[axis] <= 23. - radius + 1e-7); - } - assert!(bounds.min[2] >= 9. - 1e-7); - } - if matches!(motion.kind, MoveKind::Cut | MoveKind::Link) { - cutting_length += path.length_mm(); - } - let delta = stock - .preview_sweep(tool, &motion, 1., sweep, &|| false) - .unwrap(); - stock.apply_delta(&delta).unwrap(); - position = motion.curve.end(); - next = motion.id + 1; - history.push(motion); - } - plan.finish_report(&|| false).unwrap(); - if let OperationPlan::Adaptive(adaptive) = plan { - let report = adaptive.report(); - let front = report.front.as_ref().unwrap(); - assert!(front.coverage_complete); - assert!(front.max_bounded_engagement_deg <= report.max_engagement_deg); - } - (history, cutting_length) - } - let m = fixture(); - let mut op = operation(); - op.path_strategy = AdaptivePathStrategy::StockFront; - op.pocket.floor_z_mm = 9.; - op.pocket.region = PlanarRegion { - version: 1, - units: "mm".into(), - name: "upstream rectangular pocket".into(), - boundary_error_mm: 0., - source: serde_json::Value::Null, - components: vec![Component { - outer: Boundary { - vertices: vec![[3., 3., 0.], [23., 3., 0.], [23., 23., 0.], [3., 23., 0.]], - }, - holes: vec![], - }], - }; - let small = &m.tools[0]; - let mut large = small.clone(); - large.id = "upstream-d8".into(); - large.cutter.id = "em8".into(); - large.cutter.diameter_mm = 8.; - large.cutter.shank_diameter_mm = 8.; - let mut upstream = op.pocket.clone(); - upstream.id = "upstream".into(); - upstream.tool = large.id.clone(); - upstream.tool_number = 2; - upstream.length_register = 2; - upstream.stepover_mm = 3.; - let mut stock = Stock::new(m.stock.height().unwrap().clone()).unwrap(); - let mut rough = OperationPlan::prepare_with_stock( - Operation::Pocket(upstream), - &large, - &stock, - m.initial_position_mm, - 1, - &|| false, - ) - .unwrap(); - let (large_history, _) = execute( - &mut rough, - &mut stock, - &large.prepare().unwrap(), - m.sweep, - 4., - m.initial_position_mm, - 1, - ); - let before = stock.volume(); - eprintln!("upstream D8 complete: {}moves", large_history.len()); - let last = large_history.last().unwrap(); - let (position, first_id) = (last.curve.end(), last.id + 1); - let mut fresh_stock = Stock::new(m.stock.height().unwrap().clone()).unwrap(); - let mut fresh = OperationPlan::prepare_with_stock( - Operation::AdaptivePocket(op.clone()), - small, - &fresh_stock, - position, - first_id, - &|| false, - ) - .unwrap(); - let (fresh_history, fresh_length) = execute( - &mut fresh, - &mut fresh_stock, - &small.prepare().unwrap(), - m.sweep, - 2., - position, - first_id, - ); - eprintln!( - "fresh D4 complete: {}moves/{fresh_length}mm Cut+Link", - fresh_history.len() - ); - let mut rest = OperationPlan::prepare_with_stock( - Operation::AdaptivePocket(op), - small, - &stock, - position, - first_id, - &|| false, - ) - .unwrap(); - let (rest_history, rest_length) = execute( - &mut rest, - &mut stock, - &small.prepare().unwrap(), - m.sweep, - 2., - position, - first_id, - ); - let report = serde_json::to_value(rest.report()).unwrap(); - eprintln!( - "upstream/rest: large{}moves fresh{}moves/{fresh_length}mm rest{}moves/{rest_length}mm; {report}", - large_history.len(), - fresh_history.len(), - rest_history.len(), - ); - assert_eq!(report["front"]["coverage_complete"], true); - assert!( - report["front"]["max_bounded_engagement_deg"] - .as_f64() - .unwrap() - <= 90. - ); - assert!(stock.volume().removed_lower_mm3 > before.removed_lower_mm3 + 0.1); - let floor_cut = |motion: &&Motion| { - matches!(motion.kind, MoveKind::Cut | MoveKind::Link) - && motion.curve.start()[2] == 9. - && motion.curve.end()[2] == 9. - }; - for probe in [[4., 4.], [22., 4.], [4., 22.], [22., 22.]] { - let before_distance = large_history - .iter() - .filter(|motion| { - matches!( - motion.kind, - MoveKind::Cut | MoveKind::Link | MoveKind::Plunge - ) - }) - .map(|motion| curve_distance(&motion.curve, probe, false)) - .fold(f64::INFINITY, f64::min); - let after_distance = rest_history - .iter() - .filter(floor_cut) - .map(|motion| curve_distance(&motion.curve, probe, false)) - .fold(f64::INFINITY, f64::min); - assert!(before_distance > 4. + 64. * m.sweep.tolerance_mm); - assert!(after_distance < 2. - 64. * m.sweep.tolerance_mm); - } - let mut interior = 0; - for (i, height) in stock.cells().iter().enumerate() { - let p = stock.cell_center(i).unwrap(); - if p.into_iter().all(|v| (8. ..18.).contains(&v)) { - interior += 1; - assert!(height.upper_mm <= 9. + 4. * m.sweep.tolerance_mm); - } - } - assert!(interior > 100); - assert!( - rest_length < fresh_length * 0.75, - "rest cutting travel{rest_length}mm must save against fresh{fresh_length}mm" - ); -} - -#[test] -fn precleared_stock_allows_long_advances_but_thin_material_does_not() { - let m = fixture(); - let cancel = AtomicBool::new(false); - let tool = m.tools[0].prepare().unwrap(); - for top in [9., 9.000001] { - let mut snapshot = Stock::new(m.stock.height().unwrap().clone()) - .unwrap() - .snapshot(); - for h in &mut snapshot.cells { - h.lower_mm = top; - h.upper_mm = top; - } - let mut stock = Stock::from_snapshot(snapshot).unwrap(); - let mut op = operation(); - op.pocket.floor_z_mm = 9.; - let mut plan = AdaptivePlan::prepare( - op, - &m.tools[0], - m.stock.height().unwrap(), - m.initial_position_mm, - 1, - &cancel, - ) - .unwrap(); - while let Some(motion) = plan.next_motion_with_stock(&stock, &cancel).unwrap() { - let delta = stock - .preview_sweep(&tool, &motion, 1., m.sweep, &cancel) - .unwrap(); - stock.apply_delta(&delta).unwrap(); - } - plan.finish_report(&cancel).unwrap(); - if top == 9. { - assert!(plan.report().stock_clear_advances > 10); - assert_eq!(plan.report().bounded_advances, 0); - } else { - assert!(plan.report().bounded_advances > 10); - } - } - let op: Operation = Operation::AdaptivePocket(operation()); - let mut wire = serde_json::to_value(op).unwrap(); - assert!(wire.get("id").is_some()); - assert!(wire.get("tool").is_some()); - assert!(wire.get("pocket").is_none()); - let _: Operation = serde_json::from_value(wire.clone()).unwrap(); - wire.as_object_mut() - .unwrap() - .insert("made_up".into(), 1.into()); - assert!(serde_json::from_value::(wire).is_err()); -} - -#[test] -fn rejected_clear_chord_restores_engagement_bound_on_a_tight_crescent() { - let m = fixture(); - let cancel = AtomicBool::new(false); - let mut op = operation(); - op.pocket.floor_z_mm = 9.; - op.pocket.stepover_mm = 0.5; - let mut source = PlanarRegion::circle("tight-crescent", [13., 13.], 3.5).unwrap(); - // Vertical semicircle anchors retain an unsplit left-side arc after erosion. - source.components[0].outer.vertices = vec![[13., 9.5, 1.], [13., 16.5, 1.]]; - source.components[0].holes.push( - PlanarRegion::circle("offset-hole", [16., 13.], 0.1) - .unwrap() - .components - .remove(0) - .outer, - ); - op.pocket.region = source; - let mut snapshot = Stock::new(m.stock.height().unwrap().clone()) - .unwrap() - .snapshot(); - snapshot.cells.fill(HeightBounds { - lower_mm: 9., - upper_mm: 9., - }); - let mut stock = Stock::from_snapshot(snapshot).unwrap(); - let tool = m.tools[0].prepare().unwrap(); - let mut plan = AdaptivePlan::prepare( - op, - &m.tools[0], - m.stock.height().unwrap(), - m.initial_position_mm, - 1, - &cancel, - ) - .unwrap(); - while let Some(motion) = plan.next_motion_with_stock(&stock, &cancel).unwrap() { - let delta = stock - .preview_sweep(&tool, &motion, 1., m.sweep, &cancel) - .unwrap(); - stock.apply_delta(&delta).unwrap(); - } - plan.finish_report(&cancel).unwrap(); - assert!(plan.report().chord_fallbacks > 0); - assert!(plan.report().bounded_advances > 0); - assert!(plan.report().max_bounded_engagement_deg <= 90.); -} - -#[test] -fn stock_front_emits_real_committed_source_admitted_material_side_moves() { - let m = fixture(); - let cancel = || false; - let tool = m.tools[0].prepare().unwrap(); - for (cw, rotate) in [(true, false), (false, false), (true, true)] { - let mut op = operation(); - op.path_strategy = AdaptivePathStrategy::StockFront; - op.cutting_sense = Some(if cw { - CuttingSense::Climb - } else { - CuttingSense::Conventional - }); - op.clockwise = cw; - op.pocket.floor_z_mm = 9.; - if rotate { - for component in &mut op.pocket.region.components { - for p in &mut component.outer.vertices { - let old = *p; - p[0] = 26. - old[1]; - p[1] = old[0]; - } - } - } - let r = tool.cutter().definition().diameter_mm / 2.; - let mut stock = Stock::new(m.stock.height().unwrap().clone()).unwrap(); - let mut plan = AdaptivePlan::prepare( - op.clone(), - &m.tools[0], - m.stock.height().unwrap(), - m.initial_position_mm, - 1, - &cancel, - ) - .unwrap(); - let mut history: Vec = vec![]; - let mut count = 0; - let mut startup_removed = 0.; - let mut front_length = 0.; - let mut maximum_front_length: f64 = 0.; - for _ in 0..100 { - let next = plan.next_motion_with_stock(&stock, &cancel); - let motion = match next { - Ok(Some(m)) => m, - other => panic!( - "front {cw} stopped after {count}: {other:?}; report={:?}, last={:?}", - plan.report().front, - history.last() - ), - }; - if motion.kind != MoveKind::Rapid { - assert_entire_l_sweep( - &if rotate { - unrotate_curve(motion.curve.clone()) - } else { - motion.curve.clone() - }, - r, - ); - } - let front = plan.report().front.as_ref().unwrap(); - assert_eq!( - plan.report().max_bounded_engagement_deg, - front.max_bounded_engagement_deg - ); - if front.front_moves > count { - if count == 0 { - startup_removed = stock.volume().removed_lower_mm3; - } - count = front.front_moves; - let previous = history.last().unwrap(); - // A proven-clear vertical re-entry ends at a stopped pose with - // a newly selected heading. Flat consecutive cuts remain G1. - if previous.curve.start()[2] == previous.curve.end()[2] { - let before = curve_tangent(&previous.curve, true); - let next = curve_tangent(&motion.curve, false); - assert!( - before[0] * next[0] + before[1] * next[1] >= 1. - 1e-9, - "front tangent discontinuity" - ); - } else { - assert_eq!(previous.kind, MoveKind::Plunge); - } - if let Curve::Arc { start, center, .. } = motion.curve { - assert!((start[0] - center[0]).hypot(start[1] - center[1]) >= r / 2. - 1e-8); - } - let length = motion - .curve - .prepare(op.pocket.tolerance_mm) - .unwrap() - .length_mm(); - front_length += length; - maximum_front_length = maximum_front_length.max(length); - // Independent sampled corroboration of material side and peak. - // Actual admission is whole-interval, never these probes. - let path = motion.curve.prepare(op.pocket.tolerance_mm).unwrap(); - for i in 0..=8 { - let f = i as f64 / 8.; - let p = path.position(f).unwrap(); - let heading = match motion.curve { - Curve::Line { start, end } => (end[1] - start[1]).atan2(end[0] - start[0]), - Curve::Arc { - start, - center, - sweep_rad, - .. - } => { - (start[1] - center[1]).atan2(start[0] - center[0]) - + f * sweep_rad - + sweep_rad.signum() * PI / 2. - } - _ => panic!("front helix"), - }; - let mut exposed = 0; - for j in 0..720 { - let theta = TAU * (j as f64 + 0.5) / 720.; - let q = [p[0] + r * theta.cos(), p[1] + r * theta.sin()]; - let empty = history.iter().any(|old| { - old.curve.start()[2] == old.curve.end()[2] - && old.curve.end()[2] <= p[2] - && old.kind != MoveKind::Rapid - && curve_distance(&old.curve, q, false) < r + 1e-9 - }); - if !empty { - exposed += 1; - let cross = heading.cos() * theta.sin() - heading.sin() * theta.cos(); - assert!( - if cw { cross <= 1e-8 } else { cross >= -1e-8 }, - "wrong side cw={cw} at {q:?}: {motion:?}" - ); - } - } - assert!(exposed as f64 * 0.5 <= op.max_engagement_deg + 0.5); - } - } - let delta = stock - .preview_sweep(&tool, &motion, 1., m.sweep, &cancel) - .unwrap(); - stock.apply_delta(&delta).unwrap(); - history.push(motion); - if count >= 30 { - break; - } - } - eprintln!( - "stock-front cw={cw},rotate={rotate}: {:?}, new lower removal={}mm3", - plan.report().front, - stock.volume().removed_lower_mm3 - startup_removed - ); - assert!(count >= 10, "front did not steer"); - assert!(maximum_front_length >= r, "front emitted only tiny steps"); - assert!( - front_length / count as f64 > r * 0.1, - "front dominated by tiny steps" - ); - assert!( - stock.volume().removed_lower_mm3 > startup_removed + 1., - "front removed no useful new volume beyond seed: {startup_removed} -> {}", - stock.volume().removed_lower_mm3 - ); - assert!(!plan.report().front.as_ref().unwrap().coverage_complete); - assert!(plan.finish_report(&cancel).is_err()); - } -} - -#[test] -fn stock_front_curved_recipes_use_native_commits() { - let m = fixture(); - let tool = m.tools[0].prepare().unwrap(); - for (annulus, local) in [(true, false), (true, true), (false, false), (false, true)] { - let mut op = operation(); - op.path_strategy = AdaptivePathStrategy::StockFront; - op.pocket.floor_z_mm = 9.; - op.pocket.stepover_mm = 1.; - if local { - op.min_orbit_radius_mm = Some(0.25); - op.local_orbit_tolerance_mm = Some(0.05); - } - let mut source = - PlanarRegion::circle("curved pocket", [13., 13.], if annulus { 10. } else { 4. }) - .unwrap(); - if annulus { - source.components[0].holes.push( - PlanarRegion::circle("hole", [13., 13.], 3.) - .unwrap() - .components - .remove(0) - .outer, - ); - } - op.pocket.region = source; - let mut plan = AdaptivePlan::prepare( - op, - &m.tools[0], - m.stock.height().unwrap(), - m.initial_position_mm, - 1, - &|| false, - ) - .unwrap(); - let mut stock = Stock::new(m.stock.height().unwrap().clone()).unwrap(); - let mut checked = false; - for _ in 0..25 { - let Some(motion) = plan.next_motion_with_stock(&stock, &|| false).unwrap() else { - break; - }; - let report = plan.report().front.as_ref().unwrap(); - if report.channel_committed_moves + report.enclosed_committed_moves > 0 && !checked { - let contours = (report.channel_contours, report.enclosed_contours); - let committed = ( - report.channel_committed_moves, - report.enclosed_committed_moves, - ); - let mut partial = stock.clone(); - let delta = partial - .preview_sweep(&tool, &motion, 0.5, m.sweep, &|| false) - .unwrap(); - partial.apply_delta(&delta).unwrap(); - assert!(plan.next_motion_with_stock(&partial, &|| false).is_err()); - let mut foreign = stock.clone(); - let delta = foreign - .preview_sweep(&tool, &motion, 1., m.sweep, &|| false) - .unwrap(); - foreign.apply_delta(&delta).unwrap(); - let foreign = Stock::from_snapshot(foreign.snapshot()).unwrap(); - assert!(plan.next_motion_with_stock(&foreign, &|| false).is_err()); - let report = plan.report().front.as_ref().unwrap(); - assert_eq!( - (report.channel_contours, report.enclosed_contours), - contours - ); - assert_eq!( - ( - report.channel_committed_moves, - report.enclosed_committed_moves - ), - committed - ); - checked = true; - } - let delta = stock - .preview_sweep(&tool, &motion, 1., m.sweep, &|| false) - .unwrap(); - stock.apply_delta(&delta).unwrap(); - } - let report = plan.report().front.as_ref().unwrap(); - assert!( - checked && report.channel_contours + report.enclosed_contours >= 2, - "annulus={annulus} local={local}: curved recipe not selected: {report:?}" - ); - assert_eq!(report.reentries, 0); - } -} - -#[test] -fn stock_front_requires_exact_native_full_commit_and_preserves_pending_on_refusal() { - let m = fixture(); - let tool = m.tools[0].prepare().unwrap(); - let mut op = operation(); - op.path_strategy = AdaptivePathStrategy::StockFront; - let mut stock = Stock::new(m.stock.height().unwrap().clone()).unwrap(); - let mut plan = AdaptivePlan::prepare( - op, - &m.tools[0], - m.stock.height().unwrap(), - m.initial_position_mm, - 1, - &|| false, - ) - .unwrap(); - let motion = plan - .next_motion_with_stock(&stock, &|| false) - .unwrap() - .unwrap(); - assert!(plan.next_motion_with_stock(&stock, &|| false).is_err()); - let mut wrong = motion.clone(); - wrong.curve = Curve::Line { - start: motion.curve.start(), - end: [0., 1., 12.], - }; - let delta = stock - .preview_sweep(&tool, &wrong, 1., m.sweep, &|| false) - .unwrap(); - let mut unrelated = stock.clone(); - unrelated.apply_delta(&delta).unwrap(); - assert!( - plan.next_motion_with_stock(&unrelated, &|| false) - .unwrap_err() - .contains("mismatch") - ); - let delta = stock - .preview_sweep(&tool, &motion, 1., m.sweep, &|| false) - .unwrap(); - let wire = serde_json::to_value(&delta).unwrap(); - assert!(wire.get("receipt").is_none()); - let decoded: StockDelta = serde_json::from_value(wire).unwrap(); - let mut replayed = stock.clone(); - replayed.apply_delta(&decoded).unwrap(); - assert!(plan.next_motion_with_stock(&replayed, &|| false).is_err()); - let mut other_tool = m.tools[0].clone(); - other_tool.cutter.diameter_mm = 3.; - let other_tool = other_tool.prepare().unwrap(); - let other_delta = stock - .preview_sweep(&other_tool, &motion, 1., m.sweep, &|| false) - .unwrap(); - let mut changed_tool = stock.clone(); - changed_tool.apply_delta(&other_delta).unwrap(); - assert!( - plan.next_motion_with_stock(&changed_tool, &|| false) - .is_err() - ); - let mut fractional = stock.clone(); - let partial = fractional - .preview_sweep(&tool, &motion, 0.5, m.sweep, &|| false) - .unwrap(); - fractional.apply_delta(&partial).unwrap(); - assert!(plan.next_motion_with_stock(&fractional, &|| false).is_err()); - let mut restored = stock.clone(); - restored.apply_delta(&delta).unwrap(); - let restored = Stock::from_snapshot(restored.snapshot()).unwrap(); - assert!(plan.next_motion_with_stock(&restored, &|| false).is_err()); - let mut undone = stock.clone(); - undone.apply_delta(&delta).unwrap(); - undone.undo_delta(&delta).unwrap(); - undone.apply_delta(&delta).unwrap(); - assert!(plan.next_motion_with_stock(&undone, &|| false).is_err()); - stock.apply_delta(&delta).unwrap(); - // Failed attempts did not consume the correct pending transaction. - assert!( - plan.next_motion_with_stock(&stock, &|| false) - .unwrap() - .is_some() - ); -} -#[test] -fn stock_front_cancellation_during_search_does_not_advance_pose_or_motion_id() { - use std::cell::Cell; - let m = fixture(); - let tool = m.tools[0].prepare().unwrap(); - let mut op = operation(); - op.path_strategy = AdaptivePathStrategy::StockFront; - let mut stock = Stock::new(m.stock.height().unwrap().clone()).unwrap(); - let mut reference_stock = stock.clone(); - let make = || { - AdaptivePlan::prepare( - op.clone(), - &m.tools[0], - m.stock.height().unwrap(), - m.initial_position_mm, - 1, - &|| false, - ) - .unwrap() - }; - let (mut plan, mut reference) = (make(), make()); - loop { - let motion = plan - .next_motion_with_stock(&stock, &|| false) - .unwrap() - .unwrap(); - let other = reference - .next_motion_with_stock(&reference_stock, &|| false) - .unwrap() - .unwrap(); - assert_eq!(motion, other); - let delta = stock - .preview_sweep(&tool, &motion, 1., m.sweep, &|| false) - .unwrap(); - stock.apply_delta(&delta).unwrap(); - let other = reference_stock - .preview_sweep(&tool, &other, 1., m.sweep, &|| false) - .unwrap(); - reference_stock.apply_delta(&other).unwrap(); - if plan.report().seed_orbits == 1 { - break; - } - } - let expected = reference - .next_motion_with_stock(&reference_stock, &|| false) - .unwrap() - .unwrap(); - let previous = plan.report().motions; - let polls = Cell::new(0); - let cancel = || { - polls.set(polls.get() + 1); - polls.get() >= 20 - }; - assert!( - plan.next_motion_with_stock(&stock, &cancel) - .unwrap_err() - .contains("cancelled") - ); - assert_eq!(plan.report().motions, previous); - assert_eq!( - plan.next_motion_with_stock(&stock, &|| false) - .unwrap() - .unwrap(), - expected - ); -} - -#[test] -fn stock_front_two_islands_continues_local_clearing_after_bulk() { - use camlib::pocket::{HelicalEntry, PocketEntry}; - let mut m = fixture(); - m.stock.height_mut().unwrap().max_mm = [20., 16., 10.]; - m.stock.height_mut().unwrap().cell_size_mm = 0.2; - m.tools[0].cutter.diameter_mm = 2.; - m.tools[0].cutter.shank_diameter_mm = 2.; - let tool = m.tools[0].prepare().unwrap(); - let mut op = operation(); - op.path_strategy = AdaptivePathStrategy::StockFront; - op.pocket.floor_z_mm = 9.; - op.pocket.stepover_mm = 0.25; - op.pocket.radial_allowance_mm = 0.1; - op.pocket.entry = Some(PocketEntry::StockEdgeOrHelix(HelicalEntry::default())); - op.max_engagement_deg = 2. * 0.75f64.acos().to_degrees(); - op.orbit_radius_mm = Some(0.5); - op.min_orbit_radius_mm = Some(0.2); - op.local_orbit_tolerance_mm = Some(0.05); - let rectangle = |a, b, c, d| Boundary { - vertices: vec![[a, b, 0.], [c, b, 0.], [c, d, 0.], [a, d, 0.]], - }; - op.pocket.region.name = "two islands".into(); - op.pocket.region.source = serde_json::Value::Null; - op.pocket.region.components = vec![Component { - outer: rectangle(-4., -4., 24., 20.), - holes: vec![rectangle(5., 4., 8., 10.), rectangle(12., 4., 15., 10.)], - }]; - let mut stock = Stock::new(m.stock.height().unwrap().clone()).unwrap(); - let mut position = [-2., -2., 12.]; - let mut next_id = 1; - let mut nominal_seconds = 0.; - let mut checked_linear_commit = false; - let mut plan = AdaptivePlan::prepare( - op, - &m.tools[0], - m.stock.height().unwrap(), - position, - next_id, - &|| false, - ) - .unwrap(); - while let Some(motion) = plan - .next_motion_with_stock(&stock, &|| false) - .unwrap_or_else(|e| { - panic!( - "mixed contour/local clearing stopped at {next_id}: {e}; {:?}", - plan.report().front - ) - }) - { - assert!(next_id <= 10000, "mixed clearing failed to complete"); - assert_eq!(motion.id, next_id); - assert_eq!(motion.curve.start(), position); - nominal_seconds += motion - .curve - .prepare(m.sweep.tolerance_mm) - .unwrap() - .length_mm() - / motion.feed_mm_min.unwrap_or(6000.) - * 60.; - let front = plan.report().front.as_ref().unwrap(); - if front.linear_committed_moves > 0 && !checked_linear_commit { - let before = (front.linear_contours, front.linear_committed_moves); - let mut partial = stock.clone(); - let delta = partial - .preview_sweep(&tool, &motion, 0.5, m.sweep, &|| false) - .unwrap(); - partial.apply_delta(&delta).unwrap(); - assert!(plan.next_motion_with_stock(&partial, &|| false).is_err()); - let mut foreign = stock.clone(); - let delta = foreign - .preview_sweep(&tool, &motion, 1., m.sweep, &|| false) - .unwrap(); - foreign.apply_delta(&delta).unwrap(); - let foreign = Stock::from_snapshot(foreign.snapshot()).unwrap(); - assert!(plan.next_motion_with_stock(&foreign, &|| false).is_err()); - let front = plan.report().front.as_ref().unwrap(); - assert_eq!( - (front.linear_contours, front.linear_committed_moves), - before - ); - checked_linear_commit = true; - } - let delta = stock - .preview_sweep(&tool, &motion, 1., m.sweep, &|| false) - .unwrap(); - stock.apply_delta(&delta).unwrap(); - position = motion.curve.end(); - next_id += 1; - } - plan.finish_report(&|| false).unwrap(); - let front = plan.report().front.as_ref().unwrap(); - assert!(front.coverage_complete); - assert!(checked_linear_commit); - assert!(next_id - 1 <= 1200, "multi-island motion quality"); - assert!(front.reentries <= 80, "multi-island reentry quality"); - assert!( - nominal_seconds <= 350., - "multi-island nominal cycle quality" - ); - assert!( - front.unranked_contour_moves > 0, - "must exercise fixed contours" - ); - assert!( - front.productive_candidates + front.navigation_moves + front.linear_committed_moves > 0, - "must exercise continuation after fixed contours" - ); - assert_eq!( - front.front_moves, - front.unranked_contour_moves + front.productive_candidates + front.navigation_moves - ); - assert!(front.max_bounded_engagement_deg <= 2. * 0.75f64.acos().to_degrees()); - let (mut cleared, mut protected) = (0, 0); - for (i, cell) in stock.cells().iter().enumerate() { - let [x, y] = stock.cell_center(i).unwrap(); - let inside = [(5., 8.), (12., 15.)] - .iter() - .any(|&(a, b)| x > a + 0.2 && x < b - 0.2 && y > 4.2 && y < 9.8); - let distance = |a: f64, b: f64| { - (a - x) - .max(0.) - .max(x - b) - .hypot((4. - y).max(0.).max(y - 10.)) - }; - if inside { - assert!( - cell.lower_mm >= 10. - 4. * m.sweep.tolerance_mm, - "protected island cell {x},{y}: {cell:?}" - ); - protected += 1; - } else if distance(5., 8.) > 1.5 && distance(12., 15.) > 1.5 { - assert!( - cell.upper_mm <= 9. + 4. * m.sweep.tolerance_mm, - "uncut reachable cell {x},{y}: {cell:?}" - ); - cleared += 1; - } - } - assert!(cleared > 100 && protected > 100); - eprintln!( - "mixed clearing: {}motions/{cleared}cleared/{protected}protected cells; {front:?}", - next_id - 1 - ); -} -#[test] -fn stock_front_repeated_convex_pocket_uses_native_coverage_but_rechecks_snapshot_uncertainty() { - use camlib::pocket::{HelicalEntry, PocketEntry}; - let mut m = fixture(); - m.tools[0].cutter.diameter_mm = 2.; - m.tools[0].cutter.shank_diameter_mm = 2.; - m.stock.height_mut().unwrap().min_mm = [12., 10., 0.]; - m.stock.height_mut().unwrap().max_mm = [20., 18., 10.]; - m.stock.height_mut().unwrap().cell_size_mm = 0.2; - let tool = m.tools[0].prepare().unwrap(); - let mut op = operation(); - op.path_strategy = AdaptivePathStrategy::StockFront; - op.pocket.floor_z_mm = 9.; - op.pocket.stepover_mm = 0.25; - op.pocket.radial_allowance_mm = 0.1; - op.pocket.entry = Some(PocketEntry::StockEdgeOrHelix(HelicalEntry::default())); - op.max_engagement_deg = 82.81924421854173; - op.orbit_radius_mm = Some(0.5); - op.min_orbit_radius_mm = Some(0.2); - op.local_orbit_tolerance_mm = Some(0.05); - op.pocket.region.name = "convex pocket".into(); - op.pocket.region.source = serde_json::Value::Null; - op.pocket.region.components = vec![Component { - outer: Boundary { - vertices: vec![ - [14., 12., 0.], - [18., 12., 0.], - [18., 16., 0.], - [14., 16., 0.], - ], - }, - holes: vec![], - }]; - let mut stock = Stock::new(m.stock.height().unwrap().clone()).unwrap(); - let original_volume = stock.volume().remaining_upper_mm3; - let mut position = [12., 10., 12.]; - let mut next_id = 1; - for run in 0..3 { - if run == 2 { - // A height snapshot drops exact sweep authority. Its boundary cells - // still straddle the floor, so it must not inherit the native skip. - stock = Stock::from_snapshot(stock.snapshot()).unwrap(); - } - let before = stock.volume().remaining_upper_mm3; - let mut plan = AdaptivePlan::prepare( - op.clone(), - &m.tools[0], - m.stock.height().unwrap(), - position, - next_id, - &|| false, - ) - .unwrap(); - while let Some(motion) = plan.next_motion_with_stock(&stock, &|| false).unwrap() { - assert_eq!(motion.id, next_id); - assert_eq!(motion.curve.start(), position); - assert!(plan.report().motions < if run == 1 { 16 } else { 2000 }); - let delta = stock - .preview_sweep(&tool, &motion, 1., m.sweep, &|| false) - .unwrap(); - stock.apply_delta(&delta).unwrap(); - position = motion.curve.end(); - next_id = motion.id + 1; - } - plan.finish_report(&|| false).unwrap(); - let report = plan.report(); - let front = report.front.as_ref().unwrap(); - assert!(front.coverage_complete); - assert_eq!(front.completed_components, 1); - assert_eq!( - front.front_moves, - front.productive_candidates + front.navigation_moves + front.unranked_contour_moves - ); - if run == 1 { - assert_eq!(front.enclosed_contours, 0); - assert_eq!(front.front_moves, 0); - assert_eq!(front.unranked_contour_moves, 0); - assert_eq!(front.reentries, 0); - } else { - assert!(front.enclosed_contours > 0); - assert_eq!(front.productive_candidates, 0); - assert_eq!(front.navigation_moves, 0); - assert_eq!(front.unranked_contour_moves, front.front_moves); - } - if run == 0 { - assert!(stock.volume().remaining_upper_mm3 < original_volume); - } else { - assert_eq!(stock.volume().remaining_upper_mm3, before); - } - eprintln!( - "convex pocket run {run}: {} motions, {} enclosed contours", - report.motions, front.enclosed_contours - ); - } -} -#[test] -fn stock_front_does_not_invent_productive_material_in_an_upstream_snapshot() { - let m = fixture(); - let tool = m.tools[0].prepare().unwrap(); - let mut op = operation(); - op.path_strategy = AdaptivePathStrategy::StockFront; - op.pocket.floor_z_mm = 9.; - let mut snapshot = Stock::new(m.stock.height().unwrap().clone()) - .unwrap() - .snapshot(); - snapshot.generation = 37; - for h in &mut snapshot.cells { - h.lower_mm = 9.; - h.upper_mm = 9.; - } - let mut stock = Stock::from_snapshot(snapshot).unwrap(); - let before = stock.volume().remaining_upper_mm3; - let mut plan = AdaptivePlan::prepare( - op, - &m.tools[0], - m.stock.height().unwrap(), - m.initial_position_mm, - 100, - &|| false, - ) - .unwrap(); - while let Some(motion) = plan.next_motion_with_stock(&stock, &|| false).unwrap() { - assert!( - plan.report().motions < 32, - "empty stock did not complete promptly" - ); - let delta = stock - .preview_sweep(&tool, &motion, 1., m.sweep, &|| false) - .unwrap(); - stock.apply_delta(&delta).unwrap(); - } - plan.finish_report(&|| false).unwrap(); - let report = plan.report().front.as_ref().unwrap(); - assert_eq!(report.productive_candidates, 0); - assert_eq!(report.navigation_moves, 0); - assert_eq!(report.front_moves, 0); - assert_eq!(report.reentries, 0); - assert!(report.coverage_complete); - assert_eq!(stock.volume().remaining_upper_mm3, before); -} /// #190: the adaptive pocket planned from the stock (`engagement_front`), on -/// the L pocket. The orbit planner covers the region with overlapping orbits -/// whatever the stock holds; this one follows the boundary between cut and -/// uncut stock, so nothing is cut twice. +/// the L pocket: it follows the boundary between cut and uncut stock, so +/// nothing is cut twice. #[test] fn engagement_front_pocket_clears_the_region_once_within_its_engagement() { use camlib::operation::OperationPlan; @@ -1663,11 +119,9 @@ fn engagement_front_pocket_clears_the_region_once_within_its_engagement() { }) .fold(f64::INFINITY, f64::min) }; - let length = |c: &Curve| c.prepare(1e-5).unwrap().length_mm(); - let run = |strategy: AdaptivePathStrategy| { + let run = || { let m = fixture(); - let mut op = operation(); - op.path_strategy = strategy; + let op = operation(); 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( @@ -1691,8 +145,7 @@ fn engagement_front_pocket_clears_the_region_once_within_its_engagement() { plan.finish_report(&cancel).unwrap(); (motions, stock, serde_json::to_value(plan.report()).unwrap()) }; - let (orbits, _, _) = run(AdaptivePathStrategy::DiskFront); - let (motions, stock, report) = run(AdaptivePathStrategy::EngagementFront); + let (motions, stock, report) = run(); // Independent of the planner: at depth, the cutter (radius 2) stays // inside the L and off its walls, over every curve. @@ -1748,25 +201,9 @@ 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); } - // Far less motion than the orbits for the same pocket. - let cut = |list: &[Motion]| -> f64 { - list.iter() - .filter(|m| !m.kind.is_rapid()) - .map(|m| length(&m.curve)) - .sum() - }; - assert!( - motions.len() * 3 < orbits.len() && cut(&motions) * 3. < cut(&orbits), - "{} moves, {:.0} mm against {} moves, {:.0} mm of orbits", - motions.len(), - cut(&motions), - orbits.len(), - cut(&orbits) - ); // The radial width is the stepover: wider than the cutter radius is refused. let m = fixture(); let mut op = operation(); - op.path_strategy = AdaptivePathStrategy::EngagementFront; op.pocket.stepover_mm = 2.5; let stock = Stock::new(m.stock.height().unwrap().clone()).unwrap(); let error = OperationPlan::prepare_with_stock( @@ -1800,7 +237,6 @@ fn front_run(edit: impl FnOnce(&mut AdaptivePocketOperation)) -> Result StreamManifest { - serde_json::from_str(include_str!( - "../fixtures/operations/adaptive-connected.json" - )) - .unwrap() -} -fn tapered_fixture() -> StreamManifest { - serde_json::from_str(include_str!("../fixtures/operations/adaptive-tapered.json")).unwrap() -} -fn operation() -> AdaptivePocketOperation { - let Operation::AdaptivePocket(p) = fixture().operations.remove(0) else { - panic!("fixture") - }; - p -} -fn dist(a: [f64; 2], b: [f64; 2]) -> f64 { - (a[0] - b[0]).hypot(a[1] - b[1]) -} -fn point(c: &Curve, f: f64) -> Vec3 { - let a = c.start(); - let b = c.end(); - if f == 0. { - return a; - } - if f == 1. { - return b; - } - match *c { - Curve::Line { .. } => std::array::from_fn(|k| a[k] + f * (b[k] - a[k])), - Curve::Arc { - center, sweep_rad, .. - } => { - let r = dist([a[0], a[1]], [center[0], center[1]]); - let angle = (a[1] - center[1]).atan2(a[0] - center[0]) + f * sweep_rad; - [ - center[0] + r * angle.cos(), - center[1] + r * angle.sin(), - a[2], - ] - } - _ => panic!("unexpected helix"), - } -} -fn angle_on(a: f64, start: f64, sweep: f64) -> bool { - let d = if sweep > 0. { - (a - start).rem_euclid(TAU) - } else { - (start - a).rem_euclid(TAU) - }; - sweep.abs() >= TAU - 1e-10 || d <= sweep.abs() + 1e-10 || d >= TAU - 1e-10 -} -fn slice(c: &Curve, lo: f64, hi: f64) -> Curve { - match *c { - Curve::Line { .. } => Curve::Line { - start: point(c, lo), - end: point(c, hi), - }, - Curve::Arc { - center, - sweep_rad, - plane, - .. - } => Curve::Arc { - start: point(c, lo), - end: point(c, hi), - center, - sweep_rad: sweep_rad * (hi - lo), - plane, - }, - _ => panic!("unexpected helix"), - } -} -fn path_distance(c: &Curve, p: [f64; 2], max: bool) -> f64 { - let a = c.start(); - let b = c.end(); - match *c { - Curve::Line { .. } => { - if max { - return dist([a[0], a[1]], p).max(dist([b[0], b[1]], p)); - } - let d = [b[0] - a[0], b[1] - a[1]]; - let l = d[0] * d[0] + d[1] * d[1]; - let t = if l > 0. { - (((p[0] - a[0]) * d[0] + (p[1] - a[1]) * d[1]) / l).clamp(0., 1.) - } else { - 0. - }; - dist([a[0] + t * d[0], a[1] + t * d[1]], p) - } - Curve::Arc { - center, sweep_rad, .. - } => { - let r = dist([a[0], a[1]], [center[0], center[1]]); - let d = dist([center[0], center[1]], p); - let start = (a[1] - center[1]).atan2(a[0] - center[0]); - let angle = (p[1] - center[1]).atan2(p[0] - center[0]) + if max { PI } else { 0. }; - let endpoints = [dist([a[0], a[1]], p), dist([b[0], b[1]], p)]; - let bound = if angle_on(angle, start, sweep_rad) { - if max { d + r } else { (d - r).abs() } - } else if max { - 0. - } else { - f64::INFINITY - }; - if max { - endpoints[0].max(endpoints[1]).max(bound) - } else { - endpoints[0].min(endpoints[1]).min(bound) - } - } - _ => panic!("unexpected helix"), - } -} -fn point_segment(p: [f64; 2], a: [f64; 2], b: [f64; 2]) -> f64 { - let d = [b[0] - a[0], b[1] - a[1]]; - let l = d[0] * d[0] + d[1] * d[1]; - let t = if l > 0. { - (((p[0] - a[0]) * d[0] + (p[1] - a[1]) * d[1]) / l).clamp(0., 1.) - } else { - 0. - }; - dist(p, [a[0] + t * d[0], a[1] + t * d[1]]) -} -fn cross(a: [f64; 2], b: [f64; 2]) -> f64 { - a[0] * b[1] - a[1] * b[0] -} -// Complete line/arc-to-segment minima from endpoint, stationary and intersection -// candidates. No endpoint sampling is used for original polygon containment. -fn path_segment(c: &Curve, a: [f64; 2], b: [f64; 2]) -> f64 { - let start = c.start(); - let end = c.end(); - let u = [b[0] - a[0], b[1] - a[1]]; - let l2 = u[0] * u[0] + u[1] * u[1]; - let mut best = point_segment([start[0], start[1]], a, b) - .min(point_segment([end[0], end[1]], a, b)) - .min(path_distance(c, a, false)) - .min(path_distance(c, b, false)); - match *c { - Curve::Line { .. } => { - let v = [end[0] - start[0], end[1] - start[1]]; - let det = cross(v, u); - if det != 0. { - let delta = [a[0] - start[0], a[1] - start[1]]; - let t = cross(delta, u) / det; - let s = cross(delta, v) / det; - if (0. ..=1.).contains(&t) && (0. ..=1.).contains(&s) { - return 0.; - } - } - } - Curve::Arc { - center, sweep_rad, .. - } => { - let r = dist([start[0], start[1]], [center[0], center[1]]); - let angle0 = (start[1] - center[1]).atan2(start[0] - center[0]); - let foot = ((center[0] - a[0]) * u[0] + (center[1] - a[1]) * u[1]) / l2; - let perpendicular = [ - a[0] + foot * u[0] - center[0], - a[1] + foot * u[1] - center[1], - ]; - let theta = perpendicular[1].atan2(perpendicular[0]); - for angle in [theta, theta + PI] { - let p = [center[0] + r * angle.cos(), center[1] + r * angle.sin()]; - let t = ((p[0] - a[0]) * u[0] + (p[1] - a[1]) * u[1]) / l2; - if (0. ..=1.).contains(&t) && angle_on(angle, angle0, sweep_rad) { - best = best.min(point_segment(p, a, b)); - } - } - let h2 = perpendicular[0] * perpendicular[0] + perpendicular[1] * perpendicular[1]; - if h2 <= r * r { - let delta = ((r * r - h2) / l2).sqrt(); - for t in [foot - delta, foot + delta] { - if (0. ..=1.).contains(&t) { - let p = [a[0] + t * u[0], a[1] + t * u[1]]; - if angle_on( - (p[1] - center[1]).atan2(p[0] - center[0]), - angle0, - sweep_rad, - ) { - return 0.; - } - } - } - } - } - _ => panic!("unexpected helix"), - } - best -} -fn source_clearance(p: [f64; 2], poly: &[[f64; 2]]) -> f64 { - let mut inside = false; - let mut nearest = f64::INFINITY; - for (&a, &b) in poly - .iter() - .zip(poly.iter().cycle().skip(1)) - .take(poly.len()) - { - if (a[1] > p[1]) != (b[1] > p[1]) - && p[0] < (b[0] - a[0]) * (p[1] - a[1]) / (b[1] - a[1]) + a[0] - { - inside = !inside; - } - nearest = nearest.min(point_segment(p, a, b)); - } - if inside { nearest } else { -nearest } -} -fn exposure(q: f64, a: f64) -> f64 { - if q + 2. <= a { - 0. - } else if q >= a + 2. { - 360. - } else { - let x = (q * q + 4. - a * a) / (2. * q); - 2. * (-x / 2.).clamp(-1., 1.).acos().to_degrees() - } -} -// Whole-parameter interval certificate using ALL independently reconstructed -// prior full-orbit disks. Different disks can cover different intervals. This -// verifies long cached-return moves without trusting planner cache labels. -fn certify_exposure(c: &Curve, disks: &[([f64; 2], f64)], limit: f64) { - let mut stack = vec![(0., 1., 0)]; - let mut work = 0; - while let Some((lo, hi, depth)) = stack.pop() { - let part = slice(c, lo, hi); - let mut pass = false; - for &(center, a) in disks.iter().rev() { - work += 1; - if exposure(path_distance(&part, center, true), a) <= limit + 1e-6 { - pass = true; - break; - } - } - if pass { - continue; - } - assert!( - depth < 24 && work < 50_000_000, - "uncertified exposure on {c:?}, interval {lo}..{hi}" - ); - let mid = (lo + hi) / 2.; - stack.extend([(lo, mid, depth + 1), (mid, hi, depth + 1)]); - } -} -#[test] -fn connected_cad_passage_uses_both_radii_one_seed_and_whole_move_certificates() { - let m = fixture(); - check_connected(m, 320., false); -} -#[test] -fn tapered_cad_passage_uses_clearance_derived_targets_and_whole_move_certificates() { - for clockwise in [true, false] { - let mut m = tapered_fixture(); - let Operation::AdaptivePocket(op) = &mut m.operations[0] else { - panic!("fixture"); - }; - op.clockwise = clockwise; - check_connected(m, 328., true); - } -} -fn check_connected(m: StreamManifest, area: f64, local: bool) { - m.validate().unwrap(); - let cancel = AtomicBool::new(false); - let Operation::AdaptivePocket(op) = m.operations[0].clone() else { - panic!("fixture"); - }; - let poly: Vec<_> = op.pocket.region.components[0] - .outer - .vertices - .iter() - .map(|p| [p[0], p[1]]) - .collect(); - let mut fixed = op.clone(); - fixed.min_orbit_radius_mm = None; - fixed.local_orbit_tolerance_mm = None; - let fixed = AdaptivePlan::prepare( - fixed, - &m.tools[0], - m.stock.height().unwrap(), - m.initial_position_mm, - 1, - &cancel, - ) - .unwrap(); - assert_eq!( - fixed.report().navigation_components, - 2, - "large swept disk must not fit the neck" - ); - let mut plan = AdaptivePlan::prepare( - op, - &m.tools[0], - m.stock.height().unwrap(), - m.initial_position_mm, - 1, - &cancel, - ) - .unwrap(); - assert_eq!( - plan.report().navigation_components, - 1, - "small guides must connect both rooms" - ); - let tool = m.tools[0].prepare().unwrap(); - let mut stock = Stock::new(m.stock.height().unwrap().clone()).unwrap(); - let mut disks = vec![]; - let mut curves = vec![]; - let mut plunges = 0; - let mut radii = vec![]; - let mut old = m.initial_position_mm; - while let Some(motion) = plan.next_motion_with_stock(&stock, &cancel).unwrap() { - assert_eq!(motion.curve.start(), old); - old = motion.curve.end(); - if motion.kind == MoveKind::Plunge { - plunges += 1; - disks.clear(); - } - if motion.kind != MoveKind::Rapid { - let start = motion.curve.start(); - assert!(source_clearance([start[0], start[1]], &poly) >= 2. - 1e-7); - for (&a, &b) in poly - .iter() - .zip(poly.iter().cycle().skip(1)) - .take(poly.len()) - { - assert!( - path_segment(&motion.curve, a, b) >= 2. - 1e-7, - "original polygon crossed: {motion:?}" - ); - } - if motion.kind != MoveKind::Retract - && motion.kind != MoveKind::Plunge - && !disks.is_empty() - { - certify_exposure(&motion.curve, &disks, 90.); - } - } - if let Curve::Arc { - center, - start, - sweep_rad, - .. - } = motion.curve - && motion.kind == MoveKind::Cut - { - assert!((sweep_rad.abs() - TAU).abs() < 1e-9); - let radius = dist([start[0], start[1]], [center[0], center[1]]); - if disks.is_empty() { - assert_eq!(motion.feed_mm_min, Some(150.)); - } - radii.push(radius); - disks.push(([center[0], center[1]], 2. + radius)); - } - let delta = stock - .preview_sweep(&tool, &motion, 1., m.sweep, &cancel) - .unwrap(); - stock.apply_delta(&delta).unwrap(); - curves.push(motion.curve); - } - plan.finish_report(&cancel).unwrap(); - let r = plan.report(); - assert_eq!(plunges, 1); - assert_eq!(r.seed_orbits, 1); - assert!(r.radius_growth_orbits > 0); - assert!(radii.iter().all(|x| *x >= 0.25 - 1e-8)); - assert!(r.committed_tube_advances > 0); - assert!(r.omitted_endpoint_orbits > 0); - assert!(radii.iter().any(|x| (*x - 1.).abs() < 1e-8)); - if !local { - assert!(radii.iter().any(|x| (*x - 0.25).abs() < 1e-8)); - } - assert!(r.max_bounded_engagement_deg <= 90.); - if local { - assert!(r.local_radius_splits > 0 && r.locally_sized_guides > 0 && r.local_radius_work > 0); - let mut separated = vec![]; - for &radius in &r.guide_orbit_radii_mm { - if separated - .last() - .is_none_or(|old: &f64| radius - *old > 0.04) - { - separated.push(radius); - } - } - assert!( - separated.len() > 2, - "local guide targets were only fixed scales: {:?}", - r.guide_orbit_radii_mm - ); - assert!( - r.guide_orbit_radii_mm.iter().any(|target| *target > 0.30 - && *target < 0.95 - && radii.iter().any(|actual| (actual - target).abs() < 1e-8)), - "no actual cutting orbit attained an intermediate guide target" - ); - } - for (i, h) in stock.cells().iter().enumerate() { - let xy = stock.cell_center(i).unwrap(); - let actual = curves - .iter() - .filter(|c| path_distance(c, xy, false) <= 2. + 1e-10) - .map(|c| c.start()[2].min(c.end()[2])) - .fold(10f64, f64::min); - assert!( - h.lower_mm <= actual + 1e-6 && h.upper_mm >= actual - 1e-6, - "exact stock outside interval {xy:?}: {actual},{h:?}" - ); - if source_clearance(xy, &poly) > 2.27 { - assert!( - actual <= 9. + 1e-7, - "small-radius reachable core uncut at{xy:?}" - ); - } - if source_clearance(xy, &poly) < -1e-7 { - assert_eq!(actual, 10.); - } - } - assert!(stock.volume().removed_lower_mm3 > 250.); - assert!(stock.volume().removed_lower_mm3 <= area + 1e-8); - eprintln!("{}", serde_json::to_string(r).unwrap()); -} - -#[test] -fn proven_air_has_no_cutting_orbits_while_a_thin_wafer_keeps_cutting() { - for m in [fixture(), tapered_fixture()] { - check_preclear(m); - } -} -fn check_preclear(m: StreamManifest) { - let cancel = AtomicBool::new(false); - let tool = m.tools[0].prepare().unwrap(); - let Operation::AdaptivePocket(op) = m.operations[0].clone() else { - panic!("fixture"); - }; - for top in [9., 9.000001] { - let mut snapshot = Stock::new(m.stock.height().unwrap().clone()) - .unwrap() - .snapshot(); - snapshot.cells.fill(HeightBounds { - lower_mm: top, - upper_mm: top, - }); - let mut stock = Stock::from_snapshot(snapshot).unwrap(); - let mut plan = AdaptivePlan::prepare( - op.clone(), - &m.tools[0], - m.stock.height().unwrap(), - m.initial_position_mm, - 1, - &cancel, - ) - .unwrap(); - let mut cuts = 0; - while let Some(motion) = plan.next_motion_with_stock(&stock, &cancel).unwrap() { - cuts += usize::from(motion.kind == MoveKind::Cut); - let delta = stock - .preview_sweep(&tool, &motion, 1., m.sweep, &cancel) - .unwrap(); - stock.apply_delta(&delta).unwrap(); - } - plan.finish_report(&cancel).unwrap(); - let r = plan.report(); - if top == 9. { - assert_eq!(cuts, 0, "{}", serde_json::to_string(r).unwrap()); - assert_eq!(r.seed_orbits, 0); - assert_eq!(r.controlled_orbits, 0); - assert_eq!(r.omitted_seed_orbits, 1); - assert!(r.omitted_endpoint_orbits > 20); - assert!(r.min_cutting_orbit_radius_mm.is_none()); - if op.local_orbit_tolerance_mm.is_none() { - assert!(r.motions < 500); - } - assert!(r.motions < 8 * (r.guide_strokes + r.navigation_links) + 10); - } else { - assert_eq!(r.seed_orbits, 1); - assert!(cuts > 100); - assert!(r.bounded_advances > 100); - assert!( - r.min_cutting_orbit_radius_mm - .is_some_and(|r| r >= 0.25 - 1e-8) - ); - } - } -} -#[test] -fn committed_tube_proofs_expire_at_depth_and_cancellation_preserves_growth_cursor() { - for m in [fixture(), tapered_fixture()] { - check_depth_cancel(m); - } -} -fn check_depth_cancel(m: StreamManifest) { - let cancel = AtomicBool::new(false); - let tool = m.tools[0].prepare().unwrap(); - let mut stock = Stock::new(m.stock.height().unwrap().clone()).unwrap(); - let Operation::AdaptivePocket(mut op) = m.operations[0].clone() else { - panic!("fixture"); - }; - op.pocket.floor_z_mm = 8.; - op.clockwise = false; - let mut plan = AdaptivePlan::prepare( - op, - &m.tools[0], - m.stock.height().unwrap(), - m.initial_position_mm, - 1, - &cancel, - ) - .unwrap(); - let mut disks = vec![]; - let mut depths = vec![]; - let mut checked_cancel = false; - while let Some(motion) = plan.next_motion_with_stock(&stock, &cancel).unwrap() { - if motion.kind == MoveKind::Plunge { - disks.clear(); - depths.push(motion.curve.end()[2]); - } - if matches!(motion.kind, MoveKind::Link | MoveKind::Cut) && !disks.is_empty() { - certify_exposure(&motion.curve, &disks, 90.); - } - if let Curve::Arc { center, start, .. } = motion.curve - && motion.kind == MoveKind::Cut - { - disks.push(( - [center[0], center[1]], - 2. + dist([start[0], start[1]], [center[0], center[1]]), - )); - } - if !checked_cancel && plan.report().radius_changes > 0 { - assert!( - plan.next_motion_with_stock(&stock, &cancel) - .unwrap_err() - .contains("commit") - ); - checked_cancel = true; - } - let delta = stock - .preview_sweep(&tool, &motion, 1., m.sweep, &cancel) - .unwrap(); - stock.apply_delta(&delta).unwrap(); - if checked_cancel && plan.report().radius_changes == 1 { - let before = plan.report().motions; - cancel.store(true, std::sync::atomic::Ordering::Relaxed); - assert!(plan.next_motion_with_stock(&stock, &cancel).is_err()); - assert_eq!(plan.report().motions, before); - cancel.store(false, std::sync::atomic::Ordering::Relaxed); - } - } - plan.finish_report(&cancel).unwrap(); - assert!(checked_cancel); - assert_eq!(depths, [9., 8.]); - assert_eq!(plan.report().seed_orbits, 2); - assert!(plan.report().max_bounded_engagement_deg <= 90.); - for min in [0., -1., 2., f64::NAN] { - let mut bad = operation(); - bad.min_orbit_radius_mm = Some(min); - assert!( - AdaptivePlan::prepare( - bad, - &m.tools[0], - m.stock.height().unwrap(), - m.initial_position_mm, - 1, - &cancel - ) - .is_err() - ); - } -} - -#[test] -fn stock_front_completes_connected_cad_passage_with_source_and_stock_checks() { - check_front_passage(fixture()); -} -#[test] -fn stock_front_completes_tapered_cad_passage_with_source_and_stock_checks() { - check_front_passage(tapered_fixture()); -} -fn check_front_passage(m: StreamManifest) { - let Operation::AdaptivePocket(mut op) = m.operations[0].clone() else { - panic!("fixture") - }; - op.path_strategy = AdaptivePathStrategy::StockFront; - let poly: Vec<_> = op.pocket.region.components[0] - .outer - .vertices - .iter() - .map(|v| [v[0], v[1]]) - .collect(); - let radius = m.tools[0].cutter.diameter_mm / 2.; - let mut plan = AdaptivePlan::prepare( - op, - &m.tools[0], - m.stock.height().unwrap(), - m.initial_position_mm, - 1, - &|| false, - ) - .unwrap(); - let tool = m.tools[0].prepare().unwrap(); - let mut stock = Stock::new(m.stock.height().unwrap().clone()).unwrap(); - let mut curves = vec![]; - let mut position = m.initial_position_mm; - let mut checked_link_receipt = false; - let mut link_count = 0; - loop { - let result = plan.next_motion_with_stock(&stock, &|| false); - let motion = result.unwrap_or_else(|error| { - panic!( - "failed after {}motions at {position:?}: {error}; {:?}; last curves {:?}", - curves.len(), - plan.report().front, - &curves[curves.len().saturating_sub(8)..] - ) - }); - let Some(motion) = motion else { break }; - assert_eq!(motion.curve.start(), position); - let links = plan - .report() - .front - .as_ref() - .map_or(0, |r| r.cleared_reentry_links); - if links > link_count && !checked_link_receipt { - assert_eq!(motion.kind, MoveKind::Link); - let mut partial_stock = stock.clone(); - let partial = partial_stock - .preview_sweep(&tool, &motion, 0.5, m.sweep, &|| false) - .unwrap(); - partial_stock.apply_delta(&partial).unwrap(); - assert!( - plan.next_motion_with_stock(&partial_stock, &|| false) - .is_err() - ); - checked_link_receipt = true; - } - link_count = links; - if motion.kind != MoveKind::Rapid { - let start = motion.curve.start(); - assert!(source_clearance([start[0], start[1]], &poly) >= radius - 1e-7); - for (&a, &b) in poly - .iter() - .zip(poly.iter().cycle().skip(1)) - .take(poly.len()) - { - assert!( - path_segment(&motion.curve, a, b) >= radius - 1e-7, - "source crossed: {motion:?}" - ); - } - } - let delta = stock - .preview_sweep(&tool, &motion, 1., m.sweep, &|| false) - .unwrap(); - stock.apply_delta(&delta).unwrap(); - position = motion.curve.end(); - curves.push(motion.curve); - } - plan.finish_report(&|| false).unwrap(); - let front = plan.report().front.as_ref().unwrap(); - assert!(front.coverage_complete && checked_link_receipt); - assert!(front.max_bounded_engagement_deg <= 90.); - assert!(front.cleared_reentry_links > 0); - assert!(front.reentries - front.cleared_reentry_links < 400); - // Unchanged inputs used 4,149 and 4,157 moves before goal steering and - // segment re-entry/cleared links. Keep at least a 10% whole-job reduction. - assert!(curves.len() < 3734); - for (i, h) in stock.cells().iter().enumerate() { - let xy = stock.cell_center(i).unwrap(); - let actual = curves - .iter() - .filter(|c| path_distance(c, xy, false) <= radius + 1e-10) - .map(|c| c.start()[2].min(c.end()[2])) - .fold(10f64, f64::min); - assert!( - h.lower_mm <= actual + 1e-6 && h.upper_mm >= actual - 1e-6, - "cell{xy:?}: {h:?} vs {actual}" - ); - if source_clearance(xy, &poly) > 2.27 { - assert!(actual <= 9. + 1e-7, "uncut reachable core {xy:?}"); - } - if source_clearance(xy, &poly) < -1e-7 { - assert_eq!(actual, 10.); - } - } - eprintln!( - "passage complete: {}motions; {:?}", - curves.len(), - plan.report().front - ); -} diff --git a/tests/adaptive_front_complete.rs b/tests/adaptive_front_complete.rs index 36a19345..0866cd48 100644 --- a/tests/adaptive_front_complete.rs +++ b/tests/adaptive_front_complete.rs @@ -1,4 +1,6 @@ -//! Full-operation regression for the frozen real CAD case. Independent prism +//! Full-operation regression for the frozen real CAD case, planned by the +//! engagement front (the stock_front planner it was saved from was removed +//! in #190). Independent prism //! checks are continuous; point/angular probes are explicitly corroboration. use camlib::{ motion::{Curve, Motion, MoveKind, WorkFrame}, @@ -188,6 +190,10 @@ fn saved_real_cad_case(conventional: bool, rotated: bool) { let verifier = geometry .prepare(Options { spatial_resolution_mm: 1e-5, + // The wall pass runs at the walls' exact offset: resolving it at + // 10 micron takes more work than the default budget. + max_nodes: 1_000_000, + max_boundary_tests: 100_000_000, ..Default::default() }) .unwrap(); @@ -249,11 +255,15 @@ fn saved_real_cad_case(conventional: bool, rotated: bool) { } } } + // The sides of a cutting pass. Entry moves (at the entry feed) are + // a full-width bore or slot, and stay-down links may graze stock on + // either side; neither has a material side. if count > 4 && count % 97 == 0 && motion.curve.start()[2] == 9. && motion.curve.end()[2] == 9. - && matches!(motion.kind, MoveKind::Cut | MoveKind::Link) + && motion.kind == MoveKind::Cut + && motion.feed_mm_min == Some(600.) { let path = motion.curve.prepare(1e-5).unwrap(); for i in 0..=4 { @@ -273,19 +283,50 @@ fn saved_real_cad_case(conventional: bool, rotated: bool) { } _ => unreachable!(), }; + // The move's own sweep up to here is cut too (a tight turn + // arc clears the inside of its turn). + let prefix = match motion.curve { + Curve::Line { start, .. } => Curve::Line { start, end: p }, + Curve::Arc { + start, + center, + plane, + sweep_rad, + .. + } => Curve::Arc { + start, + end: p, + center, + plane, + sweep_rad: f * sweep_rad, + }, + _ => unreachable!(), + }; let mut contact = 0; for j in 0..720 { let a = TAU * (j as f64 + 0.5) / 720.; let q = [p[0] + r * a.cos(), p[1] + r * a.sin()]; - if !known_empty(&history, q, 9., r) { + if !known_empty(&history, q, 9., r) && distance(&prefix, q) >= r - 1e-6 { contact += 1; + // The material side of a pass: lines, and arcs that + // turn no tighter than the cutter. On a tighter turn + // arc between passes (0.27 mm radius here, cutter + // 2 mm) the contact can reach a few degrees past the + // cutter's front; the contact bound below still holds. + let sided = match motion.curve { + Curve::Arc { start, center, .. } => { + dist([start[0], start[1]], [center[0], center[1]]) >= r + } + _ => true, + }; assert!( - if conventional { - (a - heading).sin() >= -1e-7 - } else { - (a - heading).sin() <= 1e-7 - }, - "sampled material on wrong side at{q:?}" + !sided + || if conventional { + (a - heading).sin() >= -1e-7 + } else { + (a - heading).sin() <= 1e-7 + }, + "sampled material on wrong side at{q:?} of motion {count}: {motion:?}" ); } } @@ -306,15 +347,19 @@ fn saved_real_cad_case(conventional: bool, rotated: bool) { eprintln!( "complete CAD front conventional={conventional},rotated={rotated}, {count} motions: {report}" ); - assert_eq!(report["front"]["coverage_complete"], true); - assert_eq!(report["geometric_residual_status"], "estimated"); - assert!( - report["front"]["max_bounded_engagement_deg"] - .as_f64() - .unwrap() - <= 90. + assert_eq!( + report["completed_layers"].as_u64().unwrap() as usize, + report["layers"].as_array().unwrap().len() ); - assert_eq!(report["seed_orbits"], 1); + assert_eq!(report["geometric_residual_status"], "estimated"); + for layer in report["layers"].as_array().unwrap() { + assert!( + layer["clearing"]["proven_max_engagement_deg"] + .as_f64() + .unwrap() + <= report["max_engagement_deg"].as_f64().unwrap() + 1e-9 + ); + } assert_eq!(report["helical_entries"], 1); assert!( reentry_descents > 0, @@ -348,7 +393,7 @@ fn saved_real_cad_case(conventional: bool, rotated: bool) { // Small independent rectilinear corpus exercises real component/depth resets. // The full L cases above cover concavity and both material sides. #[test] -fn stock_front_completes_disconnected_components_at_two_depths() { +fn adaptive_pocket_completes_disconnected_components_at_two_depths() { let saved: serde_json::Value = serde_json::from_str(include_str!( "../fixtures/regressions/disconnected-pocket.json" )) @@ -393,6 +438,8 @@ fn stock_front_completes_disconnected_components_at_two_depths() { let verifier = geometry .prepare(Options { spatial_resolution_mm: 1e-5, + max_nodes: 1_000_000, + max_boundary_tests: 100_000_000, // Explicit 10micron machining tolerance; fixtures/noncutting parts // and all side/bottom boundaries below the top cap remain strict. target_floor_tolerance_mm: Some(0.01), @@ -446,13 +493,10 @@ fn stock_front_completes_disconnected_components_at_two_depths() { eprintln!( "complete disconnected/depth {} motions: {}", history.len(), - report["front"] + report ); - assert_eq!(report["front"]["completed_components"], 4); - assert_eq!(report["front"]["coverage_complete"], true); assert_eq!(report["geometric_residual_status"], "estimated"); - assert_eq!(report["depth_passes"], 2); - assert_eq!(report["seed_orbits"], 4); + assert_eq!(report["completed_layers"], 2); assert_eq!(floors, std::collections::BTreeSet::from([8, 9])); assert!(stock.volume().removed_lower_mm3 > 300.); // Analytic reachable C for each 10mm square is its radius3 inset. diff --git a/tests/helical_entry.rs b/tests/helical_entry.rs index 3dc1be0d..f1e2e3b2 100644 --- a/tests/helical_entry.rs +++ b/tests/helical_entry.rs @@ -51,43 +51,6 @@ fn circular(c: &Curve) -> Option<(Vec3, Vec3, Vec3, f64)> { _ => None, } } -fn point(c: &Curve, f: f64) -> Vec3 { - let a = c.start(); - let b = c.end(); - if f == 0. { - return a; - } - if f == 1. { - return b; - } - if let Some((_, _, o, s)) = circular(c) { - let r = distance([a[0], a[1]], [o[0], o[1]]); - let t = (a[1] - o[1]).atan2(a[0] - o[0]) + s * f; - [ - o[0] + r * t.cos(), - o[1] + r * t.sin(), - a[2] + (b[2] - a[2]) * f, - ] - } else { - std::array::from_fn(|k| a[k] + (b[k] - a[k]) * f) - } -} -fn part(c: &Curve, a: f64, b: f64) -> Curve { - let start = point(c, a); - let end = point(c, b); - if let Some((_, _, mut center, s)) = circular(c) { - center[2] = start[2]; - Curve::Arc { - start, - end, - center, - plane: Plane::Xy, - sweep_rad: s * (b - a), - } - } else { - Curve::Line { start, end } - } -} fn axis_distance(c: &Curve, p: [f64; 2], maximum: bool) -> f64 { let a = c.start(); let b = c.end(); @@ -209,42 +172,12 @@ fn exact_height(c: &Curve, p: [f64; 2]) -> f64 { } } } -fn exposure(q: f64, a: f64) -> f64 { - if q + 2. <= a { - 0. - } else if q >= a + 2. { - 360. - } else { - 2. * ((a * a - q * q - 4.) / (4. * q)) - .clamp(-1., 1.) - .acos() - .to_degrees() - } -} -fn certify(c: &Curve, disks: &[([f64; 2], f64)]) { - let mut stack = vec![(0., 1., 0)]; - let mut work = 0; - while let Some((a, b, depth)) = stack.pop() { - let sub = part(c, a, b); - let mut clear = false; - for &(center, radius) in disks.iter().rev() { - work += 1; - if exposure(axis_distance(&sub, center, true), radius) <= 90. + 1e-6 { - clear = true; - break; - } - } - if !clear { - assert!(depth < 24 && work < 50_000_000, "uncertified exposure{c:?}"); - let mid = (a + b) / 2.; - stack.extend([(a, mid, depth + 1), (mid, b, depth + 1)]); - } - } -} // Independent complete disk coverage from previously emitted horizontal sweeps. // Distance to a closed curve is 1-Lipschitz: center distance + box half diagonal // bounds EVERY point in each tile. A sample alone never certifies a tile. -fn certify_air_entry(c: &Curve, history: &[Curve]) { +/// `at_floor`: a sweep at the descent's own end height also clears it (a +/// descent that stops on a floor already cut). +fn certify_air_entry(c: &Curve, history: &[Curve], at_floor: bool) { let p = [c.end()[0], c.end()[1]]; assert_eq!(&c.start()[..2], &c.end()[..2]); let mut stack = vec![([p[0] - 2., p[1] - 2.], [p[0] + 2., p[1] + 2.], 0)]; @@ -259,7 +192,7 @@ fn certify_air_entry(c: &Curve, history: &[Curve]) { let clear = history.iter().any(|old| { work += 1; old.start()[2] == old.end()[2] - && old.start()[2] < c.end()[2] + && (old.start()[2] < c.end()[2] || at_floor && old.start()[2] == c.end()[2]) && axis_distance(old, mid, false) + extent < 2. - 1e-7 }); if !clear { @@ -278,8 +211,14 @@ fn certify_air_entry(c: &Curve, history: &[Curve]) { } } fn check(mut m: StreamManifest, clockwise: bool, radius: Option, all_cells: bool) { + // An adaptive pocket's direction is its cutting sense: with the + // clockwise spindle, climb clears counter-clockwise. if let Operation::AdaptivePocket(op) = &mut m.operations[0] { - op.clockwise = clockwise; + op.cutting_sense = Some(if clockwise { + camlib::adaptive::CuttingSense::Conventional + } else { + camlib::adaptive::CuttingSense::Climb + }); } let p = pocket(&mut m); p.boundary_clockwise = Some(clockwise); @@ -302,7 +241,6 @@ fn check(mut m: StreamManifest, clockwise: bool, radius: Option, all_cells: let mut stock = Stock::new(m.stock.height().unwrap().clone()).unwrap(); let adaptive = matches!(m.operations[0], Operation::AdaptivePocket(_)); let mut curves = vec![]; - let mut disks = vec![]; let mut helices = 0; // Entries are emitted one full turn per helix motion; consecutive turns // of one descent share endpoints. @@ -317,7 +255,7 @@ fn check(mut m: StreamManifest, clockwise: bool, radius: Option, all_cells: source_tube(c); } if motion.kind == MoveKind::Link && c.start()[2] > c.end()[2] { - certify_air_entry(c, &curves); + certify_air_entry(c, &curves, false); air_entries += 1; } if let Some((_, _, center, sweep)) = circular(c) { @@ -328,8 +266,24 @@ fn check(mut m: StreamManifest, clockwise: bool, radius: Option, all_cells: if !continuation { assert!(floor_circle.is_none()); helices += 1; - disks.clear(); - if adaptive || helices == 1 { + if adaptive { + // The engagement front starts each helix on the + // material its bore meets (ramp_clearance_mm unset): + // at the stock's top there, never inside it. + let bore = r + 2.; + let mut top = f64::NEG_INFINITY; + for (i, cell) in stock.cells().iter().enumerate() { + let p = stock.cell_center(i).unwrap(); + if distance(p, [center[0], center[1]]) <= bore { + top = top.max(cell.upper_mm); + } + } + assert!( + c.start()[2] >= top - 1e-6 && c.start()[2] <= top + 0.011, + "helix {helices} starts at Z{} on stock at Z{top}", + c.start()[2] + ); + } else if helices == 1 { assert_eq!(c.start()[2], 10.); } else { assert!( @@ -350,7 +304,10 @@ fn check(mut m: StreamManifest, clockwise: bool, radius: Option, all_cells: assert_eq!(sweep < 0., clockwise); assert_eq!(motion.feed_mm_min, Some(150.)); turns += n.round() as usize; - floor_circle = Some((center, r, c.end()[2])); + // A Pocket's helix ends with a full circle at its floor. + if !adaptive { + floor_circle = Some((center, r, c.end()[2])); + } } else if let Some((origin, radius, z)) = floor_circle.take() { assert_eq!(center[0], origin[0]); assert_eq!(center[1], origin[1]); @@ -358,19 +315,12 @@ fn check(mut m: StreamManifest, clockwise: bool, radius: Option, all_cells: assert_eq!(c.start()[2], z); assert!((sweep.abs() - TAU).abs() < 1e-9); } - } else if motion.kind == MoveKind::Plunge { - assert!(c.end()[2] >= 10., "straight plunge into virgin material"); - } - if adaptive && matches!(motion.kind, MoveKind::Cut | MoveKind::Link) && !disks.is_empty() { - certify(c, &disks); - } - if adaptive && motion.kind == MoveKind::Cut { - let (_, _, o, sweep) = circular(c).unwrap(); - assert!((sweep.abs() - TAU).abs() < 1e-9); - disks.push(( - [o[0], o[1]], - 2. + distance([c.start()[0], c.start()[1]], [o[0], o[1]]), - )); + } else if motion.kind == MoveKind::Plunge && c.end()[2] < 10. { + // A Pocket plunges only in air. The engagement front also feeds + // down into a column its earlier sweeps cleared: the whole + // cutter disk there was swept at or below the plunge's end. + assert!(adaptive, "straight plunge into virgin material"); + certify_air_entry(c, &curves, true); } let d = stock .preview_sweep(&t, &motion, 1., m.sweep, &cancel) @@ -380,15 +330,27 @@ fn check(mut m: StreamManifest, clockwise: bool, radius: Option, all_cells: } plan.finish_report(&cancel).unwrap(); let report = serde_json::to_value(plan.report()).unwrap(); - assert_eq!(helices, 2); - assert_eq!(air_entries, usize::from(!adaptive)); assert!(floor_circle.is_none()); - assert_eq!(report["helical_entries"], 2); - assert_eq!(report["entry_turns"].as_u64().unwrap(), turns as u64); - assert!(report["entry_geometry_work"].as_u64().unwrap() > 0); if adaptive { - assert_eq!(report["seed_orbits"], 2); - assert!(report["max_bounded_engagement_deg"].as_f64().unwrap() <= 90.); + // At least one helix a level (this ring around an island takes four + // in all), counted here independently of the report. + assert!(helices >= 2); + assert_eq!(report["helical_entries"], helices); + // Each level's engagement is proven against its limit. + for layer in report["layers"].as_array().unwrap() { + assert!( + layer["clearing"]["proven_max_engagement_deg"] + .as_f64() + .unwrap() + <= report["max_engagement_deg"].as_f64().unwrap() + 1e-9 + ); + } + } else { + assert_eq!(helices, 2); + assert_eq!(air_entries, 1); + assert_eq!(report["helical_entries"], 2); + assert_eq!(report["entry_turns"].as_u64().unwrap(), turns as u64); + assert!(report["entry_geometry_work"].as_u64().unwrap() > 0); } if all_cells { for (i, h) in stock.cells().iter().enumerate() { @@ -424,9 +386,31 @@ fn real_cad_helix_entries_preserve_whole_source_stock_and_adaptive_exposure() { } #[test] fn explicit_entry_radius_uses_a_bounded_adaptive_approach_and_growth() { - for radius in [0.5, 0.1] { - check(fixture(true), true, Some(radius), false); - } + check(fixture(true), true, Some(0.5), false); + // A 0.1 mm helix is narrower than the engagement front works from: the + // level is refused when it starts, before any motion, naming the radii. + let mut m = fixture(true); + let Some(PocketEntry::Helix(h)) = &mut pocket(&mut m).entry else { + panic!("entry"); + }; + h.radius_mm = Some(0.1); + let mut plan = OperationPlan::prepare( + m.operations[0].clone(), + &m.tools[0], + m.stock.height().unwrap(), + m.initial_position_mm, + 1, + &AtomicBool::new(false), + ) + .unwrap(); + let stock = Stock::new(m.stock.height().unwrap().clone()).unwrap(); + let error = plan + .next_motion_with_stock(&stock, &AtomicBool::new(false)) + .unwrap_err(); + assert!( + error.contains("no helix fits") && error.contains("[0.1] mm"), + "{error}" + ); } #[test] fn no_fit_bad_parameters_and_turn_limit_fail_before_any_motion() { @@ -447,17 +431,23 @@ fn no_fit_bad_parameters_and_turn_limit_fail_before_any_motion() { "radius" => h.radius_mm = Some(value), _ => h.feed_mm_min = Some(value), } - assert!( - OperationPlan::prepare( - m.operations[0].clone(), - &m.tools[0], - m.stock.height().unwrap(), - m.initial_position_mm, - 1, - &AtomicBool::new(false) - ) - .is_err() - ); + // Refused before any motion: when prepared, or (the adaptive + // pocket plans each level from the stock) when its first level + // starts. + let refused = OperationPlan::prepare( + m.operations[0].clone(), + &m.tools[0], + m.stock.height().unwrap(), + m.initial_position_mm, + 1, + &AtomicBool::new(false), + ) + .and_then(|mut plan| { + let stock = Stock::new(m.stock.height().unwrap().clone())?; + plan.next_motion_with_stock(&stock, &AtomicBool::new(false)) + }) + .is_err(); + assert!(refused, "adaptive={adaptive} {field}={value}"); } } for (width, radius, success) in [(4.15, None, false), (5., Some(1.), false), (5., None, true)] { diff --git a/tests/main.rs b/tests/main.rs index 1a4651db..016238e8 100644 --- a/tests/main.rs +++ b/tests/main.rs @@ -20,7 +20,6 @@ macro_rules! modules { modules! { adaptive, - adaptive_connected, adaptive_front_complete, assembly_reach, chamfer, diff --git a/tests/no_entry.rs b/tests/no_entry.rs index 1545f33f..e0cf391f 100644 --- a/tests/no_entry.rs +++ b/tests/no_entry.rs @@ -25,13 +25,11 @@ const FLOOR: f64 = 8.; fn fixture() -> StreamManifest { serde_json::from_str(include_str!("../fixtures/operations/adaptive-pocket.json")).unwrap() } -/// The fixture's adaptive pocket, planned by the engagement front (the -/// Python API's default; a manifest without `path_strategy` is disk_front). +/// The fixture's adaptive pocket, planned by the engagement front. fn adaptive(m: &StreamManifest) -> AdaptivePocketOperation { - let Operation::AdaptivePocket(mut op) = m.operations[0].clone() else { + let Operation::AdaptivePocket(op) = m.operations[0].clone() else { panic!("fixture") }; - op.path_strategy = AdaptivePathStrategy::EngagementFront; op } type Rect = [[f64; 2]; 2]; @@ -468,27 +466,15 @@ fn no_pocket_strategy_plans_nothing_in_a_slot_the_cutter_fits() { // engagement front plans in. for width in [5., 4.5, 4.2] { let slot = slot_rect(width); - for strategy in [ - AdaptivePathStrategy::EngagementFront, - AdaptivePathStrategy::DiskFront, - AdaptivePathStrategy::StockFront, - ] { - for entry in [None, helix(), ramp(4.)] { - let front = strategy == AdaptivePathStrategy::EngagementFront; - if !front && entry.as_ref().is_some_and(|e| matches!(e, PocketEntry::Ramp(_))) { - // Refused by name before planning (#219). - continue; - } - let mut op = adaptive(&m); - set_region(&mut op.pocket, rectangle(slot)); - op.path_strategy = strategy; - op.pocket.entry = entry.clone(); - check( - format!("adaptive {strategy:?} {width} mm {entry:?}"), - slot, - run(&m, Operation::AdaptivePocket(op)), - ); - } + for entry in [None, helix(), ramp(4.)] { + let mut op = adaptive(&m); + set_region(&mut op.pocket, rectangle(slot)); + op.pocket.entry = entry.clone(); + check( + format!("adaptive EngagementFront {width} mm {entry:?}"), + slot, + run(&m, Operation::AdaptivePocket(op)), + ); } for rest in [None, Some(0.01)] { for entry in [None, helix(), ramp(4.)] { @@ -540,21 +526,6 @@ fn no_pocket_strategy_plans_nothing_in_a_slot_the_cutter_fits() { outcome(&format!("pocket rest=None 4.2 mm {:?}", None::)), None ); - // The orbit strategies sweep a disk of radius 3 (cutter 2 + orbit 1): - // none fits a 5 mm slot, and that is refused with the sweep's size. - for strategy in ["DiskFront", "StockFront"] { - let error = outcome(&format!("adaptive {strategy} 5 mm None")).unwrap(); - for part in [ - "adaptive pocket adaptive: no orbit fits the area at (", - "sweep a disk of radius 3 mm (cutter radius 2 + orbit radius 1)", - "though the cutter fits it", - "path_strategy engagement_front", - "a smaller orbit_radius_mm", - ] { - assert!(error.contains(part), "{part:?} not in: {error}"); - } - assert!(inside(named_point(&error), slot_rect(5.)), "{error}"); - } // A helix radius that does not fit is refused before any motion, naming // what, where, what was tried and the options. The `Pocket` says it as // its entry fit (#250); the engagement front lists the area itself, @@ -604,30 +575,14 @@ fn no_pocket_strategy_plans_nothing_in_a_slot_the_cutter_fits() { } assert!(inside(named_point(&error), slot_rect(5.)), "{error}"); } - // A smaller orbit, as that message says, does fit and cut the slot. - let slot = slot_rect(5.); - let mut op = adaptive(&m); - set_region(&mut op.pocket, rectangle(slot)); - op.path_strategy = AdaptivePathStrategy::DiskFront; - op.orbit_radius_mm = Some(0.25); - let seen = run(&m, Operation::AdaptivePocket(op)); - assert_eq!(seen.error, None); - assert!(cut_to(&seen.stock, slot, FLOOR)); // A region the cutter fits nowhere in (3 mm for a 4 mm cutter): the // operation can do nothing it was asked to, and every pocket operation // says so before any motion. let narrow = slot_rect(3.); let mut ops = vec![]; - for strategy in [ - AdaptivePathStrategy::EngagementFront, - AdaptivePathStrategy::DiskFront, - AdaptivePathStrategy::StockFront, - ] { - let mut op = adaptive(&m); - set_region(&mut op.pocket, rectangle(narrow)); - op.path_strategy = strategy; - ops.push(("adaptive pocket adaptive", Operation::AdaptivePocket(op))); - } + let mut op = adaptive(&m); + set_region(&mut op.pocket, rectangle(narrow)); + ops.push(("adaptive pocket adaptive", Operation::AdaptivePocket(op))); for rest in [None, Some(0.01)] { let mut op = adaptive(&m).pocket; set_region(&mut op, rectangle(narrow)); @@ -697,9 +652,7 @@ fn roughing_refuses_an_enclosed_slot_no_entry_fits() { let front = || { serde_json::json!({ "kind": "adaptive", "path_strategy": "engagement_front", - "max_radial_engagement_mm": 0.5, "orbit_radius_mm": null, - "min_orbit_radius_mm": null, "local_orbit_tolerance_mm": null, - "boundary_tolerance_mm": 0.01, + "max_radial_engagement_mm": 0.5, }) }; let stock_edge_or_helix = @@ -869,40 +822,6 @@ fn roughing_refuses_an_enclosed_slot_no_entry_fits() { // The slot's stock within the cutter's reach: about 12 x 2 mm. assert!(unresolved(layer) > unresolved(cut) + 15., "{layer}"); } - // stock_front, whose orbits sweep more than the cutter (radius 1 + 0.5 - // orbit, 0.1 off the walls: 3.2 mm, in a 2.8 mm slot): the layer lists - // the slot as an area no orbit fits in. - let orbits = serde_json::json!({ - "kind": "adaptive", "path_strategy": "stock_front", - "max_radial_engagement_mm": 0.5, "orbit_radius_mm": null, - "min_orbit_radius_mm": null, "local_orbit_tolerance_mm": null, - "boundary_tolerance_mm": 0.01, - }); - let m = roughing_from(1.5, orbits, stock_edge_or_helix(), NARROW); - let plan = OperationPlan::prepare( - m.operations[0].clone(), - &m.tools[0], - m.stock.height().unwrap(), - m.initial_position_mm, - 1, - &AtomicBool::new(false), - ) - .unwrap(); - let report = serde_json::to_value(plan.report()).unwrap(); - for layer in report["layers"].as_array().unwrap() { - let areas = layer["clearing"]["unentered_areas"].as_array().unwrap(); - assert_eq!(areas.len(), 1, "{layer}"); - assert_eq!(areas[0]["reason"], "no_orbit_fits"); - assert_eq!(areas[0]["needed_mm"], 0.5); - let at = areas[0]["at_mm"].as_array().unwrap(); - assert!( - inside( - [at[0].as_f64().unwrap(), at[1].as_f64().unwrap()], - slot(NARROW) - ), - "{layer}" - ); - } // Raster and offset layers fit their entries before any motion: refused // there, or cut. for clearing in [ @@ -934,9 +853,7 @@ fn roughing_lists_an_area_whose_only_entry_is_a_forbidden_helix() { let front = || { serde_json::json!({ "kind": "adaptive", "path_strategy": "engagement_front", - "max_radial_engagement_mm": 0.5, "orbit_radius_mm": null, - "min_orbit_radius_mm": null, "local_orbit_tolerance_mm": null, - "boundary_tolerance_mm": 0.01, + "max_radial_engagement_mm": 0.5, }) }; let stock_edge = diff --git a/tests/pocket_top.rs b/tests/pocket_top.rs index 6180e41f..7d40edcc 100644 --- a/tests/pocket_top.rs +++ b/tests/pocket_top.rs @@ -55,14 +55,9 @@ fn operation(top: f64, adaptive: bool) -> Operation { if adaptive { Operation::AdaptivePocket(AdaptivePocketOperation { pocket, - path_strategy: AdaptivePathStrategy::DiskFront, + path_strategy: AdaptivePathStrategy::EngagementFront, cutting_sense: None, - orbit_radius_mm: Some(1.), - min_orbit_radius_mm: None, - local_orbit_tolerance_mm: None, max_engagement_deg: 90., - boundary_tolerance_mm: 0.01, - clockwise: true, rapid_descent_clearance_mm: None, ramp_clearance_mm: None, link_feed_mm_min: None, @@ -125,8 +120,14 @@ fn pocket_and_adaptive_use_faced_stock_top_without_resetting_stock_or_extra_dept .unwrap(); let report = serde_json::to_value(plan.report()).unwrap(); if top == 8. { - assert_eq!(report["stock_top"]["generation"], current.generation()); - assert_eq!(report["depth_passes"], 2); + if adaptive { + // The engagement front plans each level from the + // committed stock; it has no stock-top bound to report. + assert_eq!(report["layers"].as_array().unwrap().len(), 2); + } else { + assert_eq!(report["stock_top"]["generation"], current.generation()); + assert_eq!(report["depth_passes"], 2); + } } let mut count = 0; while let Some(motion) = plan.next_motion_with_stock(¤t, &|| false).unwrap() { @@ -139,10 +140,21 @@ fn pocket_and_adaptive_use_faced_stock_top_without_resetting_stock_or_extra_dept assert_eq!(current.spec(), m.stock.height().unwrap()); results.push((count, current)); } - assert!( - results[1].0 < results[0].0, - "the extra air depth must disappear" - ); + // The extra air depth must disappear: a Pocket plans one depth pass + // fewer; the engagement front plans each level from the stock, so + // its level in the air above the faced top makes no move. + if adaptive { + assert_eq!( + results[1].0, results[0].0, + "a move in the air depth: {} / {}", + results[1].0, results[0].0 + ); + } else { + assert!( + results[1].0 < results[0].0, + "the extra air depth must disappear" + ); + } for (a, b) in results[0].1.cells().iter().zip(results[1].1.cells()) { assert!((a.lower_mm - b.lower_mm).abs() < 1e-9); assert!((a.upper_mm - b.upper_mm).abs() < 1e-9); @@ -153,7 +165,11 @@ fn pocket_and_adaptive_use_faced_stock_top_without_resetting_stock_or_extra_dept #[test] fn lower_top_rejects_uncut_and_same_generation_foreign_stock_but_accepts_restored_faced_stock() { let m = fixture(); - for adaptive in [false, true] { + // Pocket only: AdaptivePocket's engagement front does not check the + // stock against top_z_mm (it plans its first level from the stock top). + // The removed orbit planner did; see the #190 pull request. + let adaptive = false; + { let original = Stock::new(m.stock.height().unwrap().clone()).unwrap(); assert!( OperationPlan::prepare_with_stock( diff --git a/tests/ramp_entry.rs b/tests/ramp_entry.rs index 9bd66e0a..1eb474cb 100644 --- a/tests/ramp_entry.rs +++ b/tests/ramp_entry.rs @@ -953,28 +953,10 @@ fn contour_ramp_refusals_and_default_serialisation() { } #[test] -fn roughing_and_adaptive_refuse_a_ramp_entry_by_name() { +fn roughing_refuses_a_ramp_entry_by_name() { + // AdaptivePocket ramps into enclosed material since its orbit planner + // was removed (#190); tests/ramp_entry_front.rs covers it. let cancel = AtomicBool::new(false); - let mut m: StreamManifest = - serde_json::from_str(include_str!("../fixtures/operations/helical-adaptive.json")).unwrap(); - let Operation::AdaptivePocket(a) = &mut m.operations[0] else { - panic!("fixture"); - }; - a.pocket.entry = Some(PocketEntry::Ramp(ramp(3.))); - let error = OperationPlan::prepare( - m.operations[0].clone(), - &m.tools[0], - m.stock.height().unwrap(), - m.initial_position_mm, - 1, - &cancel, - ) - .map(|_| ()) - .unwrap_err(); - assert!( - error.contains("RampEntry is not supported") && error.contains("HelicalEntry"), - "{error}" - ); let mut m: StreamManifest = serde_json::from_str(include_str!("../fixtures/operations/roughing.json")).unwrap(); let Operation::Roughing(r) = &mut m.operations[0] else { diff --git a/tests/ramp_entry_front.rs b/tests/ramp_entry_front.rs index b558daaa..4a84baa7 100644 --- a/tests/ramp_entry_front.rs +++ b/tests/ramp_entry_front.rs @@ -127,7 +127,6 @@ fn run_with( let Operation::AdaptivePocket(mut op) = m.operations[0].clone() else { panic!("fixture") }; - op.path_strategy = AdaptivePathStrategy::EngagementFront; edit(&mut op); // The wire format round-trips the entry. let wire = serde_json::to_value(&op).unwrap(); @@ -351,10 +350,9 @@ fn adaptive_pocket_ramps_into_enclosed_material_and_proves_every_cut_after_it() } // A job that asks for no ramp reports none: its report has no new field. let m = fixture(); - let Operation::AdaptivePocket(mut op) = m.operations[0].clone() else { + let Operation::AdaptivePocket(op) = m.operations[0].clone() else { panic!("fixture") }; - op.path_strategy = AdaptivePathStrategy::EngagementFront; let plan = OperationPlan::prepare( Operation::AdaptivePocket(op), &m.tools[0], @@ -483,25 +481,6 @@ fn adaptive_pocket_ramps_along_a_slot_no_helix_fits() { #[test] fn adaptive_ramp_refusals_name_the_reason() { - // The orbit strategies start from a fitted seed circle. - for strategy in [ - AdaptivePathStrategy::DiskFront, - AdaptivePathStrategy::StockFront, - ] { - let error = run(4., |op| { - op.pocket.entry = Some(ramp(4., Some(2.))); - op.path_strategy = strategy; - }) - .err() - .unwrap(); - for part in [ - "RampEntry is not supported here", - "seed circle", - "engagement_front", - ] { - assert!(error.contains(part), "{error}"); - } - } // An invalid ramp is refused before planning. let error = run(4., |op| op.pocket.entry = Some(ramp(0., None))) .err() @@ -514,7 +493,6 @@ fn adaptive_ramp_refusals_name_the_reason() { let Operation::AdaptivePocket(op) = &mut m.operations[0] else { panic!("fixture") }; - op.path_strategy = AdaptivePathStrategy::EngagementFront; op.pocket.entry = Some(ramp(4., None)); let error = OperationPlan::prepare( m.operations[0].clone(), diff --git a/tests/roughing.rs b/tests/roughing.rs index 0105109c..4d62e319 100644 --- a/tests/roughing.rs +++ b/tests/roughing.rs @@ -1062,353 +1062,6 @@ fn real_cad_roughing_streams_both_entries_and_preserves_whole_columns_and_every_ } } -/// SAME frozen physical input as the historical 90651-motion adaptive job. -/// Complete operation/quality regression, not a production latency benchmark. -#[test] -fn stock_front_bulk_contours_need_full_native_commits_and_remove_actual_stock() { - for sense in ["climb", "conventional"] { - let saved: serde_json::Value = - serde_json::from_str(include_str!("../fixtures/regressions/retained-body.json")) - .unwrap(); - let mut selected = - saved["cases"]["adaptive"]["policies"]["omit_proven_empty"]["input"].clone(); - selected["operations"][0]["clearing"]["path_strategy"] = "stock_front".into(); - selected["operations"][0]["clearing"]["cutting_sense"] = sense.into(); - let m: StreamManifest = serde_json::from_value(selected).unwrap(); - 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( - m.operations[0].clone(), - &m.tools[0], - &stock, - m.initial_position_mm, - 1, - &|| false, - ) - .unwrap(); - let front = |plan: &OperationPlan| { - serde_json::to_value(plan.report()).unwrap()["layers"][0]["clearing"]["front"].clone() - }; - let mut history: Vec = vec![]; - let mut tested_refusal = false; - let tangent = |curve: &Curve, end: bool| { - let a = if end { curve.end() } else { curve.start() }; - let v = match *curve { - Curve::Line { start, end } => [end[0] - start[0], end[1] - start[1]], - Curve::Arc { - center, sweep_rad, .. - } => [ - -(a[1] - center[1]) * sweep_rad.signum(), - (a[0] - center[0]) * sweep_rad.signum(), - ], - _ => panic!("flat contour expected"), - }; - let norm = v[0].hypot(v[1]); - [v[0] / norm, v[1] / norm] - }; - for _ in 0..120 { - let motion = plan - .next_motion_with_stock(&stock, &|| false) - .unwrap() - .unwrap(); - assert_eq!(motion.id, history.len() as u64 + 1); - assert_eq!( - motion.curve.start(), - history - .last() - .map_or(m.initial_position_mm, |old| old.curve.end()) - ); - certify_part(&motion.curve); - if let Some(old) = history.last() - && matches!(old.kind, MoveKind::Cut | MoveKind::Lead) - && matches!(motion.kind, MoveKind::Cut | MoveKind::Lead) - && old.curve.start()[2] == old.curve.end()[2] - && motion.curve.start()[2] == motion.curve.end()[2] - { - let a = tangent(&old.curve, true); - let b = tangent(&motion.curve, false); - assert!( - a[0] * b[0] + a[1] * b[1] >= 1. - 1e-9, - "bulk G1 discontinuity" - ); - } - let r = front(&plan); - let last_first_contour = - !tested_refusal && r["bulk_contours"] == 0 && r["bulk_committed_moves"] == 10; - if last_first_contour { - let partial = stock - .preview_sweep(&tool, &motion, 0.5, m.sweep, &|| false) - .unwrap(); - let mut fractional = stock.clone(); - fractional.apply_delta(&partial).unwrap(); - assert!(plan.next_motion_with_stock(&fractional, &|| false).is_err()); - assert_eq!(front(&plan)["bulk_contours"], 0); - assert!(front(&plan)["bulk_material_bounds_mm"].is_null()); - let full = stock - .preview_sweep(&tool, &motion, 1., m.sweep, &|| false) - .unwrap(); - let mut restored = stock.clone(); - restored.apply_delta(&full).unwrap(); - let restored = Stock::from_snapshot(restored.snapshot()).unwrap(); - assert!(plan.next_motion_with_stock(&restored, &|| false).is_err()); - assert_eq!(front(&plan)["bulk_contours"], 0); - } - let delta = stock - .preview_sweep(&tool, &motion, 1., m.sweep, &|| false) - .unwrap(); - stock.apply_delta(&delta).unwrap(); - history.push(motion); - if last_first_contour { - assert!( - plan.next_motion_with_stock(&stock, &|| true) - .unwrap_err() - .contains("cancelled") - ); - assert_eq!(front(&plan)["bulk_contours"], 0); - tested_refusal = true; - } - if front(&plan)["bulk_contours"].as_u64().unwrap() >= 2 { - break; - } - } - let report = front(&plan); - eprintln!( - "bulk {sense}: {} motions, lower removal={}, {report}", - history.len(), - stock.volume().removed_lower_mm3 - ); - assert!(tested_refusal); - assert_eq!(report["bulk_contours"], 2); - assert_eq!(report["bulk_abandoned"], 0); - assert!(stock.volume().removed_lower_mm3 > 50.); - assert!( - report["max_bounded_engagement_deg"].as_f64().unwrap() - <= 2. * 0.75f64.acos().to_degrees() - ); - let b: [[f64; 2]; 2] = - serde_json::from_value(report["bulk_material_bounds_mm"].clone()).unwrap(); - for i in 0..stock.cells().len() { - let p = stock.cell_center(i).unwrap(); - if (0..2).any(|k| p[k] < b[0][k] || p[k] > b[1][k]) { - let height = history - .iter() - .filter(|m| m.kind != MoveKind::Rapid) - .map(|m| exact_height(&m.curve, p)) - .fold(10f64, f64::min); - assert!( - height <= 8. + 1e-6, - "claimed shell contains untouched stock at {p:?}: {height}" - ); - } - } - assert_eq!(stock.spec(), m.stock.height().unwrap()); - } -} - -#[test] -fn stock_front_saved_frustum_completes_all_layers_with_checked_stock_and_quality() { - let saved: serde_json::Value = - serde_json::from_str(include_str!("../fixtures/regressions/retained-body.json")).unwrap(); - let original = saved["cases"]["adaptive"]["policies"]["omit_proven_empty"]["input"].clone(); - let mut selected = original.clone(); - selected["operations"][0]["clearing"]["path_strategy"] = "stock_front".into(); - // The selector is the sole changed input: no wider engagement, altered - // cutter, simpler CAD, stock spacing, allowances, feeds or new seed policy. - let mut restored = selected.clone(); - restored["operations"][0]["clearing"] - .as_object_mut() - .unwrap() - .remove("path_strategy"); - assert_eq!(restored, original); - let m: StreamManifest = serde_json::from_value(selected).unwrap(); - m.validate().unwrap(); - assert_eq!(m.tools[0].cutter.diameter_mm, 2.); - 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( - m.operations[0].clone(), - &m.tools[0], - &stock, - m.initial_position_mm, - 1, - &|| false, - ) - .unwrap(); - let mut history: Vec = Vec::new(); - let mut current = m.initial_position_mm; - let mut nominal = 0.; - let started = std::time::Instant::now(); - let summary = |report: serde_json::Value| { - serde_json::json!({ - "completed_layers":report["completed_layers"], "active_layer":report["active_layer"], - "motions":report["motions"], "max_engagement_deg":report["max_engagement_deg"], - "layers":report["layers"].as_array().unwrap().iter().map(|layer| serde_json::json!({ - "z":layer["tip_z_mm"], "front":layer["clearing"]["front"], - "motions":layer["clearing"]["motions"] - })).collect::>() - }) - }; - loop { - let motion = match plan.next_motion_with_stock(&stock, &|| false) { - Ok(Some(motion)) => motion, - Ok(None) => break, - Err(error) => { - if let Some(path) = std::env::var_os("CAMLIB_FRUSTUM_FAILURE_TRACE") { - let trace = serde_json::json!({ - "complete": false, - "error": error, - "manifest": m, - "motions": history, - "stock": stock.snapshot(), - "report": plan.report(), - }); - std::fs::write(path, serde_json::to_vec(&trace).unwrap()).unwrap(); - } - panic!( - "frustum incomplete after {} motions at {current:?}: {error}; last={:?}; {}", - history.len(), - history.last(), - summary(serde_json::to_value(plan.report()).unwrap()) - ) - } - }; - assert!( - history.len() < 100000, - "frustum exceeded bounded diagnostic work without completing" - ); - assert_eq!(motion.id, history.len() as u64 + 1); - assert_eq!(motion.curve.start(), current); - assert_eq!(motion.tool, "t1"); - assert_eq!(motion.operation, "rough"); - current = motion.curve.end(); - if motion.kind == MoveKind::Rapid { - assert!(motion.curve.start()[2] >= 12. && current[2] >= 12.); - } - // Continuous extrema/subdivision proof against the analytic retained - // solid, independent of mesh clipping, source offsets and stock sweeps. - certify_part(&motion.curve); - if motion.kind == MoveKind::Plunge - && current[2] < 10. - && box_distance(bounds(&motion.curve, 0., 1.), [[0., 0.], [32., 28.]]) < 1. - { - // Corroborate noncutting inside-stock descents from independently - // reconstructed full-motion heights. This is NOT a sweep proof; - // the production reentry disk requires whole-region clearance. - for radial in [0., 0.5, 1.] { - for i in 0..16 { - let angle = TAU * i as f64 / 16.; - let p = [ - current[0] + radial * angle.cos(), - current[1] + radial * angle.sin(), - ]; - if p[0] < 0. || p[0] > 32. || p[1] < 0. || p[1] > 28. { - continue; - } - let height = history - .iter() - .filter(|old| old.kind != MoveKind::Rapid) - .map(|old| exact_height(&old.curve, p)) - .fold(10f64, f64::min); - assert!( - height <= current[2] + 1e-6, - "descent into material at{p:?}: {height} > {}", - current[2] - ); - } - } - } - nominal += motion - .curve - .prepare(m.sweep.tolerance_mm) - .unwrap() - .length_mm() - / motion.feed_mm_min.unwrap_or(6000.) - * 60.; - let delta = stock - .preview_sweep(&tool, &motion, 1., m.sweep, &|| false) - .unwrap(); - stock.apply_delta(&delta).unwrap(); - history.push(motion); - if history.len().is_multiple_of(256) { - eprintln!( - "frustum {} motions {:?} nominal={nominal}s lower={} {}", - history.len(), - started.elapsed(), - stock.volume().removed_lower_mm3, - summary(serde_json::to_value(plan.report()).unwrap()) - ); - } - } - plan.finish_report(&|| false).unwrap(); - let report = serde_json::to_value(plan.report()).unwrap(); - eprintln!( - "frustum COMPLETE {}motions nominal={nominal}s {}", - history.len(), - summary(report.clone()) - ); - assert_eq!(report["completed_layers"], 4); - let angle = 2. * 0.75f64.acos().to_degrees(); - for layer in report["layers"].as_array().unwrap() { - let clearing = &layer["clearing"]; - assert_eq!(clearing["front"]["coverage_complete"], true); - assert!(clearing["front"]["completed_components"].as_u64().unwrap() > 0); - // Exterior convex material exclusion and completed enclosed fan. - assert_eq!(clearing["front"]["coverage_envelopes"], 2); - // This case completes through fixed recipes. Candidate-potential - // counters must not imply productive or empty material along them. - assert_eq!(clearing["front"]["productive_candidates"], 0); - assert_eq!(clearing["front"]["navigation_moves"], 0); - assert_eq!( - clearing["front"]["unranked_contour_moves"], - clearing["front"]["front_moves"] - ); - assert!( - clearing["front"]["unranked_contour_moves"] - .as_u64() - .unwrap() - > 0 - ); - assert!(clearing["max_bounded_engagement_deg"].as_f64().unwrap() <= angle); - assert_eq!( - clearing["max_bounded_engagement_deg"], - clearing["front"]["max_bounded_engagement_deg"] - ); - } - let floor = report["target_z_mm"].as_f64().unwrap(); - for (i, cell) in stock.cells().iter().enumerate() { - let p = stock.cell_center(i).unwrap(); - let height = history - .iter() - .filter(|m| m.kind != MoveKind::Rapid) - .map(|m| exact_height(&m.curve, p)) - .fold(10f64, f64::min); - assert!( - cell.lower_mm <= height + 1e-6 && cell.upper_mm >= height - 1e-6, - "{p:?}: {cell:?} misses independent exact height {height}" - ); - if p[0] < 5. - || p[0] > 27. - || p[1] < 5. - || p[1] > 23. - || (p[0] > 15.4 && p[0] < 16.6 && p[1] > 13.4 && p[1] < 14.6) - { - assert!( - height <= floor + 1e-6, - "uncut reachable floor{p:?}: {height}" - ); - } - } - assert!( - history.len() <= 10000, - "complete frustum path quality: {} >10000 motions", - history.len() - ); - assert!( - nominal <= 3000., - "complete frustum nominal cycle quality: {nominal} >3000s" - ); -} - fn engagement_front_frustum() -> StreamManifest { let saved: serde_json::Value = serde_json::from_str(include_str!("../fixtures/regressions/retained-body.json")).unwrap(); @@ -1416,13 +1069,6 @@ fn engagement_front_frustum() -> StreamManifest { let op = &mut input["operations"][0]; op["omit_empty_cuts"] = false.into(); let clearing = op["clearing"].as_object_mut().unwrap(); - for key in [ - "orbit_radius_mm", - "min_orbit_radius_mm", - "local_orbit_tolerance_mm", - ] { - clearing.remove(key); - } clearing.insert("path_strategy".into(), "engagement_front".into()); serde_json::from_value(input).unwrap() } @@ -1880,30 +1526,20 @@ fn issue_167_open_block_is_cleared_from_the_stock_edge_within_its_engagement() { } // Allowing a helix changes nothing where none is needed. assert_eq!(paths[0], paths[1]); - // The old default is refused, with the reason. - let mut m = base.clone(); - let Operation::Roughing(op) = &mut m.operations[0] else { - panic!("fixture") - }; - let camlib::roughing::RoughingClearing::Adaptive { path_strategy, .. } = &mut op.clearing - else { - panic!("clearing") - }; - *path_strategy = camlib::adaptive::AdaptivePathStrategy::DiskFront; - let error = OperationPlan::prepare( - m.operations[0].clone(), - &m.tools[0], - m.stock.height().unwrap(), - m.initial_position_mm, - 1, - &AtomicBool::new(false), - ) - .err() - .unwrap(); - assert!( - error.contains("disk_front") && error.contains("engagement_front"), - "{error}" - ); + // The removed orbit planners (#190) are refused when a program is read, + // with the name that is not known. + for removed in ["disk_front", "stock_front"] { + let mut value = serde_json::to_value(&base).unwrap(); + value["operations"][0]["clearing"]["path_strategy"] = removed.into(); + let error = serde_json::from_value::(value) + .err() + .unwrap() + .to_string(); + assert!( + error.contains(removed) && error.contains("engagement_front"), + "{error}" + ); + } } #[test] @@ -2083,8 +1719,15 @@ fn engagement_front_refuses_orbits_empty_cut_omission_and_helix_only_entry() { f(&mut v["operations"][0]); serde_json::from_value::(v).unwrap() }; - let orbit = edit(&|op| op["clearing"]["orbit_radius_mm"] = 0.5.into()); - assert!(prepare(&orbit).contains("does not use orbits")); + // The orbit options were removed with the orbit planners (#190): a + // program that still sets one is refused when it is read. + let mut orbit = serde_json::to_value(&base).unwrap(); + orbit["operations"][0]["clearing"]["orbit_radius_mm"] = 0.5.into(); + let error = serde_json::from_value::(orbit) + .err() + .unwrap() + .to_string(); + assert!(error.contains("unknown field `orbit_radius_mm`"), "{error}"); let omit = edit(&|op| op["omit_empty_cuts"] = true.into()); assert!(prepare(&omit).contains("omit_empty_cuts")); let helix = edit(&|op| op["entry"]["kind"] = "helix".into()); @@ -3404,39 +3047,6 @@ fn empty_roughing_still_validates_tool_source_pose_setup_entry_and_all_strategy_ ); let variants: Vec = if adaptive { let mutations: &[fn(&mut RoughingClearing)] = &[ - |c| { - if let RoughingClearing::Adaptive { - orbit_radius_mm, .. - } = c - { - *orbit_radius_mm = Some(f64::NAN) - } - }, - |c| { - if let RoughingClearing::Adaptive { - min_orbit_radius_mm, - .. - } = c - { - *min_orbit_radius_mm = Some(0.) - } - }, - |c| { - if let RoughingClearing::Adaptive { - local_orbit_tolerance_mm, - .. - } = c - { - *local_orbit_tolerance_mm = Some(1e-8) - } - }, - |c| { - // #167: disk_front never reads the stock; Roughing - // refuses it. - if let RoughingClearing::Adaptive { path_strategy, .. } = c { - *path_strategy = camlib::adaptive::AdaptivePathStrategy::DiskFront - } - }, |c| { if let RoughingClearing::Adaptive { max_radial_engagement_mm, @@ -3502,141 +3112,6 @@ fn empty_roughing_still_validates_tool_source_pose_setup_entry_and_all_strategy_ } } -#[test] -fn stock_front_convex_contour_requires_complete_native_receipts() { - check_stock_front_contour_receipts("convex_contour", "convex_contours"); -} - -#[test] -fn stock_front_enclosed_contour_requires_complete_native_receipts() { - check_stock_front_contour_receipts("enclosed_contour", "enclosed_contours"); -} - -fn check_stock_front_contour_receipts(status: &str, counter: &str) { - let m: StreamManifest = - serde_json::from_str(include_str!("../fixtures/regressions/stock-front.json")).unwrap(); - 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( - m.operations[0].clone(), - &m.tools[0], - &stock, - m.initial_position_mm, - 1, - &|| false, - ) - .unwrap(); - let mut checked = false; - for _ in 0..10000 { - let motion = plan - .next_motion_with_stock(&stock, &|| false) - .unwrap() - .expect("must reach the selected contour transition"); - let report = serde_json::to_value(plan.report()).unwrap(); - let convex = report["layers"][0]["clearing"]["front"]["status"] == status; - let delta = stock - .preview_sweep(&tool, &motion, 1., m.sweep, &|| false) - .unwrap(); - if convex && motion.kind == MoveKind::Cut { - assert_eq!(report["layers"][0]["clearing"]["front"][counter], 0); - assert_eq!( - report["layers"][0]["clearing"]["front"]["coverage_envelopes"], - usize::from(status == "enclosed_contour") - ); - let mut invalid = Vec::new(); - let mut partial = stock.clone(); - partial - .apply_delta( - &stock - .preview_sweep(&tool, &motion, 0.5, m.sweep, &|| false) - .unwrap(), - ) - .unwrap(); - invalid.push(partial); - let mut altered = motion.clone(); - altered.id += 1; - let mut wrong_motion = stock.clone(); - wrong_motion - .apply_delta( - &stock - .preview_sweep(&tool, &altered, 1., m.sweep, &|| false) - .unwrap(), - ) - .unwrap(); - invalid.push(wrong_motion); - let wire: camlib::stock::StockDelta = - serde_json::from_value(serde_json::to_value(&delta).unwrap()).unwrap(); - let mut replayed = stock.clone(); - replayed.apply_delta(&wire).unwrap(); - invalid.push(replayed); - let mut restored = stock.clone(); - restored.apply_delta(&delta).unwrap(); - invalid.push(Stock::from_snapshot(restored.snapshot()).unwrap()); - let mut undone = stock.clone(); - undone.apply_delta(&delta).unwrap(); - undone.undo_delta(&delta).unwrap(); - undone.apply_delta(&delta).unwrap(); - invalid.push(undone); - let mut coarse = m.sweep; - coarse.tolerance_mm *= 2.; - let mut inaccurate = stock.clone(); - inaccurate - .apply_delta( - &stock - .preview_sweep(&tool, &motion, 1., coarse, &|| false) - .unwrap(), - ) - .unwrap(); - invalid.push(inaccurate); - let mut changed_tool = m.tools[0].clone(); - changed_tool.cutter.diameter_mm *= 0.9; - let mut other_tool = stock.clone(); - other_tool - .apply_delta( - &stock - .preview_sweep( - &changed_tool.prepare().unwrap(), - &motion, - 1., - m.sweep, - &|| false, - ) - .unwrap(), - ) - .unwrap(); - invalid.push(other_tool); - for invalid_stock in invalid { - assert!( - plan.next_motion_with_stock(&invalid_stock, &|| false) - .is_err() - ); - } - stock.apply_delta(&delta).unwrap(); - assert!(plan.next_motion_with_stock(&stock, &|| true).is_err()); - let next = plan - .next_motion_with_stock(&stock, &|| false) - .unwrap() - .unwrap(); - assert_eq!(next.id, motion.id + 1); - assert_eq!(next.curve.start(), motion.curve.end()); - let report = serde_json::to_value(plan.report()).unwrap(); - assert_eq!( - report["layers"][0]["clearing"]["front"][counter], 0, - "one cut cannot certify the complete contour" - ); - assert_eq!( - report["layers"][0]["clearing"]["front"]["coverage_envelopes"], - usize::from(status == "enclosed_contour"), - "partial/refused receipts must not publish new coverage" - ); - checked = true; - break; - } - stock.apply_delta(&delta).unwrap(); - } - assert!(checked, "test must exercise an actual selected contour"); -} - #[test] fn smaller_raster_rest_rougher_uses_committed_multilevel_stock_with_column_protection() { smaller_rest_rougher(false, false); @@ -3844,7 +3319,7 @@ fn smaller_rest_rougher(offset: bool, clockwise: bool) { #[test] fn roughing_reports_preserve_progress_across_reads_rejections_and_finalization() { let mut m: StreamManifest = - serde_json::from_str(include_str!("../fixtures/regressions/stock-front.json")).unwrap(); + serde_json::from_str(include_str!("../fixtures/regressions/adaptive-roughing-layers.json")).unwrap(); // The golden counts below were taken with the exact shadow. if let Operation::Roughing(op) = &mut m.operations[0] { op.contour_tolerance_mm = Some(0.); @@ -3874,19 +3349,20 @@ fn roughing_reports_preserve_progress_across_reads_rejections_and_finalization() let before = serde_json::to_value(plan.report()).unwrap(); assert_eq!(before["motions"], count); let layers = before["layers"].as_array().unwrap(); - assert_eq!( - layers - .iter() - .map(|l| l["clearing"]["motions"].as_u64().unwrap()) - .sum::(), - count - ); let active = before["active_layer"].as_u64().unwrap(); observed_layers.insert(active); assert_eq!(before["completed_layers"], active); + // A layer's report is written when the layer completes (the + // engagement front reports no partial layer): the completed + // layers hold every motion before the active one's. + let completed = layers + .iter() + .take(active as usize) + .map(|l| l["clearing"]["motions"].as_u64().unwrap()) + .sum::(); + assert!(completed < count, "{completed} >= {count}"); for layer in layers.iter().take(active as usize) { assert_eq!(layer["clearing"]["geometric_residual_status"], "estimated"); - assert_eq!(layer["clearing"]["front"]["coverage_complete"], true); } assert_eq!(serde_json::to_value(plan.report()).unwrap(), before); assert!(plan.next_motion_with_stock(&stock, &|| true).is_err()); @@ -3901,12 +3377,23 @@ fn roughing_reports_preserve_progress_across_reads_rejections_and_finalization() .unwrap(); stock.apply_delta(&delta).unwrap(); } - // Golden count from before entry helices were split one turn per motion. - assert_eq!(count - continued_entry_turns(&curves) as u64, 5366); + // Golden count, with continued entry-helix turns counted as one motion. + // Measured with the engagement front (#190; the removed stock_front + // planner made 5366 on this input). + assert_eq!(count - continued_entry_turns(&curves) as u64, 5021); assert_eq!(observed_layers.len(), 4); let drained = serde_json::to_value(plan.report()).unwrap(); assert_eq!(drained["motions"], count); assert_eq!(drained["completed_layers"], 4); + assert_eq!( + drained["layers"] + .as_array() + .unwrap() + .iter() + .map(|l| l["clearing"]["motions"].as_u64().unwrap()) + .sum::(), + count + ); assert_eq!(drained["geometric_residual_status"], "pending"); assert!(plan.finish_report(&|| true).is_err()); assert_eq!(serde_json::to_value(plan.report()).unwrap(), drained); @@ -4727,13 +4214,6 @@ fn bar_input(top_z: f64, ends: bool) -> serde_json::Value { "source": null, }); let clearing = op["clearing"].as_object_mut().unwrap(); - for key in [ - "orbit_radius_mm", - "min_orbit_radius_mm", - "local_orbit_tolerance_mm", - ] { - clearing.remove(key); - } clearing.insert("path_strategy".into(), "engagement_front".into()); clearing.insert("max_radial_engagement_mm".into(), 0.6.into()); input From 3b00550b049b3a515f824eb24cff6e885cb0d066 Mon Sep 17 00:00:00 2001 From: Wookie1 <6943491+Wookie1@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:56:49 +0000 Subject: [PATCH 03/17] AdaptivePocket: check the stock against top_z_mm (#344) The engagement front planned its first level from the stock's top, so with uncut stock above a lower top_z_mm that level was deeper than stepdown_mm and nothing refused it. AdaptivePocket now runs Pocket's stock-top proof (StockTop) before any motion, plans its levels from top_z_mm, rescans stock it did not see committed, admits each motion against stock left beside the region, and reports stock_top. Without committed stock a lower top is refused. --- docs/operations.md | 7 ++++-- src/pocket_front.rs | 54 ++++++++++++++++++++++++++++++++++++++++++++- tests/pocket_top.rs | 42 +++++++++++++++++++++++------------ 3 files changed, 86 insertions(+), 17 deletions(-) diff --git a/docs/operations.md b/docs/operations.md index 3e0c9ec9..2e4807a9 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -178,8 +178,11 @@ without a word: **A top below the remaining stock** (`Pocket` and `AdaptivePocket`, issue #129). `top_z_mm` may be below the stock's original top when earlier operations removed the material: the depth (and the cutting-length check) is -then measured from `top_z_mm`. Every stock cell meeting the `region` must be at -or below it. Stock may stand higher outside the region, for example a low +then measured from `top_z_mm`, and an `AdaptivePocket` plans its first level +from it (#344), so no level is deeper than `stepdown_mm`. Every stock cell +meeting the `region` must be at or below it; the run checks this against the +committed stock, so a lower top needs the stock (an `AdaptivePocket` planned +without it is refused). Stock may stand higher outside the region, for example a low pocket beside a tall wall, when the tool assembly clears it: - Before any motion, the neck, shank and every holder section are checked diff --git a/src/pocket_front.rs b/src/pocket_front.rs index 0381312d..117cae5c 100644 --- a/src/pocket_front.rs +++ b/src/pocket_front.rs @@ -50,6 +50,10 @@ pub struct PocketFrontReport { pub max_ramp_angle_deg: Option, pub geometric_residual_status: ResidualStatus, pub diagnostics: Vec, + /// A `top_z_mm` below the stock's top, proven against the committed + /// stock as for `Pocket` (`crate::pocket::StockTop`). + #[serde(skip_serializing_if = "Option::is_none")] + pub stock_top: Option, } #[derive(Clone, Debug, Serialize)] pub struct PocketFrontLayer { @@ -66,6 +70,9 @@ pub struct PocketFrontPlan { next_id: u64, generation: Option, spec: StockSpec, + /// A lower top's proof: checked before any motion, rescanned on stock + /// it did not see committed, and each motion admitted against it. + stock_top: Option, report: PocketFrontReport, } @@ -107,6 +114,16 @@ impl PocketFrontPlan { pocket.id )); } + // A top below the stock's top is only proven against committed + // stock (`prepare_with_stock`); here the stock is the whole blank, so + // its first level would cut from the blank's top, deeper than a + // stepdown (#190 follow-up). Refused, as `Pocket` refuses it. + if pocket.top_z_mm < spec.max_mm[2] { + return Err(format!( + "adaptive pocket {}: top_z_mm {} is below the stock top {}; plan it against the committed stock after the operation that removed the stock above it, or raise the operation top", + pocket.id, pocket.top_z_mm, spec.max_mm[2] + )); + } let floor = pocket.floor_z_mm + pocket.bottom_allowance_mm; if !(pocket.stepdown_mm.is_finite() && pocket.stepdown_mm > 0.) || floor >= pocket.top_z_mm { @@ -218,6 +235,7 @@ impl PocketFrontPlan { next_id: first_id, generation: None, spec: spec.clone(), + stock_top: None, report: PocketFrontReport { strategy: "adaptive_pocket", clearing: "engagement_front", @@ -233,6 +251,7 @@ impl PocketFrontPlan { ramp_entries: 0, max_ramp_angle_deg: None, geometric_residual_status: ResidualStatus::Pending, + stock_top: None, diagnostics: vec![ "Each depth level follows the boundary between cut and uncut stock inside the pocket region; every cutting stroke is proven within max_engagement_deg = acos(1 - stepover/r) against the committed cleared sweeps".into(), ], @@ -247,7 +266,34 @@ impl PocketFrontPlan { first_id: u64, cancel: &impl CancelSignal, ) -> Result { - Self::prepare(op, tool, stock.spec(), initial, first_id, cancel) + // A top below the stock's top is the caller's statement that + // earlier operations removed the stock above it: proven here, as + // for `Pocket` (#129), before any motion. The levels are then + // planned from that top, each at most a stepdown deep. + let pocket = &op.pocket; + let scope = crate::pocket::ReachScope { + operation: &pocket.id, + tool, + region: &pocket.region, + lowest_tip_z: pocket.floor_z_mm + pocket.bottom_allowance_mm, + clearance_z: pocket.clearance_z_mm, + boundary_slack_mm: 0., + }; + let (envelope, bound) = crate::pocket::StockTop::prepare( + stock, + pocket.top_z_mm, + pocket.tolerance_mm, + &scope, + cancel, + ) + .map_err(|e| format!("adaptive {e}"))?; + let mut plan = Self::prepare(op, tool, &envelope, initial, first_id, cancel)?; + plan.spec = stock.spec().clone(); + if let Some(bound) = bound { + plan.report.stock_top = Some(bound.report.clone()); + plan.stock_top = Some(bound); + } + Ok(plan) } pub fn report(&self) -> &PocketFrontReport { &self.report @@ -283,6 +329,9 @@ impl PocketFrontPlan { "commit preceding adaptive pocket motion to matching stock before planning".into(), ); } + if let Some(bound) = &mut self.stock_top { + bound.validate(stock, cancel)?; + } loop { let Some(plan) = self.plans.front_mut() else { return Ok(None); @@ -314,6 +363,9 @@ impl PocketFrontPlan { .map_or(angle, |a| a.max(angle)), ); } + if let Some(bound) = &self.stock_top { + bound.admit(&m)?; + } self.position = m.curve.end(); self.next_id = m.id + 1; self.generation = Some(stock.generation() + 1); diff --git a/tests/pocket_top.rs b/tests/pocket_top.rs index 7d40edcc..556b0c03 100644 --- a/tests/pocket_top.rs +++ b/tests/pocket_top.rs @@ -120,12 +120,17 @@ fn pocket_and_adaptive_use_faced_stock_top_without_resetting_stock_or_extra_dept .unwrap(); let report = serde_json::to_value(plan.report()).unwrap(); if top == 8. { + assert_eq!(report["stock_top"]["generation"], current.generation()); if adaptive { - // The engagement front plans each level from the - // committed stock; it has no stock-top bound to report. - assert_eq!(report["layers"].as_array().unwrap().len(), 2); + // Levels from the operation top, a stepdown apart. + let tips: Vec = report["layers"] + .as_array() + .unwrap() + .iter() + .map(|l| l["tip_z_mm"].as_f64().unwrap()) + .collect(); + assert_eq!(tips, [6., 5.]); } else { - assert_eq!(report["stock_top"]["generation"], current.generation()); assert_eq!(report["depth_passes"], 2); } } @@ -144,10 +149,11 @@ fn pocket_and_adaptive_use_faced_stock_top_without_resetting_stock_or_extra_dept // fewer; the engagement front plans each level from the stock, so // its level in the air above the faced top makes no move. if adaptive { - assert_eq!( - results[1].0, results[0].0, + assert!( + results[1].0 <= results[0].0, "a move in the air depth: {} / {}", - results[1].0, results[0].0 + results[1].0, + results[0].0 ); } else { assert!( @@ -165,17 +171,25 @@ fn pocket_and_adaptive_use_faced_stock_top_without_resetting_stock_or_extra_dept #[test] fn lower_top_rejects_uncut_and_same_generation_foreign_stock_but_accepts_restored_faced_stock() { let m = fixture(); - // Pocket only: AdaptivePocket's engagement front does not check the - // stock against top_z_mm (it plans its first level from the stock top). - // The removed orbit planner did; see the #190 pull request. - let adaptive = false; - { + for adaptive in [false, true] { let original = Stock::new(m.stock.height().unwrap().clone()).unwrap(); + let error = OperationPlan::prepare_with_stock( + operation(8., adaptive), + &m.tools[0], + &original, + m.initial_position_mm, + 1, + &|| false, + ) + .err() + .unwrap(); + assert!(error.contains("raise the operation top"), "{error}"); + // Without committed stock a lower top cannot be proven. assert!( - OperationPlan::prepare_with_stock( + OperationPlan::prepare( operation(8., adaptive), &m.tools[0], - &original, + m.stock.height().unwrap(), m.initial_position_mm, 1, &|| false From 29c7dbddecd3fbeec02482a211fdf0d3e06976a2 Mon Sep 17 00:00:00 2001 From: Wookie1 <6943491+Wookie1@users.noreply.github.com> Date: Thu, 19 Nov 2026 04:24:39 +0000 Subject: [PATCH 04/17] Place the depths from stock the top accepts within the band (#344) A top up to 16 x tolerance_mm below the stock is accepted as the stock model's band, but Pocket and AdaptivePocket then placed their first depth from the authored top: with tolerance 0.01 and a top 0.1 mm below uncut stock the first motion removed 1.1 mm with a 1 mm stepdown. StockTop now reports the highest such stock the cutter can reach, and both plan their depths from it. Regression measures the depth each motion removes from the stock. --- docs/operations.md | 10 +++++++--- src/pocket.rs | 43 +++++++++++++++++++++++++++++++++++------ src/pocket_front.rs | 11 +++++++++++ tests/pocket_top.rs | 47 ++++++++++++++++++++++++++++++++++++++++++++- 4 files changed, 101 insertions(+), 10 deletions(-) diff --git a/docs/operations.md b/docs/operations.md index 2e4807a9..e501d949 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -180,9 +180,13 @@ without a word: operations removed the material: the depth (and the cutting-length check) is then measured from `top_z_mm`, and an `AdaptivePocket` plans its first level from it (#344), so no level is deeper than `stepdown_mm`. Every stock cell -meeting the `region` must be at or below it; the run checks this against the -committed stock, so a lower top needs the stock (an `AdaptivePocket` planned -without it is refused). Stock may stand higher outside the region, for example a low +meeting the `region` must be at or below it, within the stock model's band +of 16 x `tolerance_mm`; the run checks this against the committed stock, so a +lower top needs the stock (an `AdaptivePocket` planned without it is refused). +Where stock inside that band stands above `top_z_mm` within the cutter's reach, +the depths are measured from the highest of it instead, so the first is still no +deeper than `stepdown_mm` below the stock it meets +(`stock_top.reachable_upper_z_mm` in the report, #344). Stock may stand higher outside the region, for example a low pocket beside a tall wall, when the tool assembly clears it: - Before any motion, the neck, shank and every holder section are checked diff --git a/src/pocket.rs b/src/pocket.rs index 64224e1f..2eb51341 100644 --- a/src/pocket.rs +++ b/src/pocket.rs @@ -578,6 +578,11 @@ pub struct StockTopReport { /// Stock cells above the top that the assembly proof examined. #[serde(skip_serializing_if = "Option::is_none")] pub assembly_checked_cells: Option, + /// Highest stock above the authored top, within the stock model's band + /// (16 x tolerance_mm), where the cutter can reach it. The depth levels + /// are placed from it, so no level cuts deeper than a stepdown (#344). + #[serde(skip_serializing_if = "Option::is_none")] + pub reachable_upper_z_mm: Option, } /// What a lower top needs to know about the operation, to judge stock left @@ -719,7 +724,8 @@ impl StockTop { } let ceiling = top + 16. * tolerance; let mut outside = Outside::new(scope, tolerance)?; - let (maximum, examined) = Self::scan(stock, top, ceiling, &mut outside, cancel)?; + let (maximum, examined, reachable) = + Self::scan(stock, top, ceiling, &mut outside, cancel)?; spec.max_mm[2] = top; stock.request_sweep_receipts(); let tall = outside.highest; @@ -736,18 +742,21 @@ impl StockTop { generation: stock.generation(), outside_upper_z_mm: tall, assembly_checked_cells: tall.map(|_| examined), + reachable_upper_z_mm: reachable, }, }), )) } - /// The highest stock, and how many cells above the top were examined. + /// The highest stock, how many cells above the ceiling were examined, + /// and the highest stock above the top (up to the ceiling) that the + /// cutter can reach. fn scan( stock: &Stock, top: f64, ceiling: f64, outside: &mut Outside, cancel: &impl CancelSignal, - ) -> Result<(f64, usize), String> { + ) -> Result<(f64, usize, Option), String> { let mut maximum = f64::NEG_INFINITY; let [dx, dy] = stock.cell_widths_mm(); let half = dx.hypot(dy) / 2.; @@ -760,12 +769,26 @@ impl StockTop { // Per section, the highest obstruction within its radius. let mut blocked = vec![None::; o.sections.len()]; let mut examined = 0; + let mut reachable = None; for (i, cell) in stock.cells().iter().enumerate() { if i.is_multiple_of(1024) && cancel.is_cancelled() { return Err("pocket stock-top inspection cancelled".into()); } maximum = maximum.max(cell.upper_mm); + if cell.upper_mm <= top { + continue; + } if cell.upper_mm <= ceiling { + // Within the band the top is accepted, but the cutter meets + // this stock where it can reach it: the levels start from it. + let p = stock.cell_center(i).ok_or("stock cell outside the grid")?; + let b = o.region_bounds; + let far = ((b[0] - p[0]).max(p[0] - b[2]).max(0.)) + .hypot((b[1] - p[1]).max(p[1] - b[3]).max(0.)) + - half; + if far <= o.cutter_radius + o.guard + o.slack { + reachable = Some(reachable.map_or(cell.upper_mm, |h: f64| h.max(cell.upper_mm))); + } continue; } let refuse = || { @@ -843,7 +866,7 @@ impl StockTop { )); } outside.highest = tall; - Ok((maximum, examined)) + Ok((maximum, examined, reachable)) } pub(crate) fn validate( &mut self, @@ -857,7 +880,7 @@ impl StockTop { .last_sweep_receipt() .is_some_and(|r| r.base_identity == self.identity) { - let (_, _) = Self::scan( + let _ = Self::scan( stock, self.report.authored_top_z_mm, self.ceiling, @@ -1399,8 +1422,16 @@ impl PocketPlan { clearance_z: op.clearance_z_mm, boundary_slack_mm: 0., }; - let (envelope, bound) = + let (mut envelope, bound) = StockTop::prepare(stock, op.top_z_mm, op.tolerance_mm, &scope, cancel)?; + // Stock the top accepts within the model's band still stands above + // it where the cutter reaches: the depth passes start from that + // stock, so the first is no deeper than a stepdown below it (#344). + let mut op = op; + if let Some(h) = bound.as_ref().and_then(|b| b.report.reachable_upper_z_mm) { + op.top_z_mm = h; + envelope.max_mm[2] = h; + } let mut plan = Self::prepare(op, assembly, &envelope, initial, first_motion_id, cancel)?; if let Some(bound) = bound { plan.activate_layer(initial, first_motion_id, stock.spec())?; diff --git a/src/pocket_front.rs b/src/pocket_front.rs index 117cae5c..bea12a3a 100644 --- a/src/pocket_front.rs +++ b/src/pocket_front.rs @@ -287,6 +287,17 @@ impl PocketFrontPlan { cancel, ) .map_err(|e| format!("adaptive {e}"))?; + // Stock the top accepts within the model's band still stands above + // it where the cutter reaches: the levels start from that stock, so + // the first is no deeper than a stepdown below it (#344). + let (mut op, mut envelope) = (op, envelope); + if let Some(h) = bound + .as_ref() + .and_then(|b| b.report.reachable_upper_z_mm) + { + op.pocket.top_z_mm = h; + envelope.max_mm[2] = h; + } let mut plan = Self::prepare(op, tool, &envelope, initial, first_id, cancel)?; plan.spec = stock.spec().clone(); if let Some(bound) = bound { diff --git a/tests/pocket_top.rs b/tests/pocket_top.rs index 556b0c03..04c4b038 100644 --- a/tests/pocket_top.rs +++ b/tests/pocket_top.rs @@ -129,7 +129,10 @@ fn pocket_and_adaptive_use_faced_stock_top_without_resetting_stock_or_extra_dept .iter() .map(|l| l["tip_z_mm"].as_f64().unwrap()) .collect(); - assert_eq!(tips, [6., 5.]); + // The faced stock model stands up to 16 x tolerance + // above Z8 (see `faced`); levels start from it (#344). + assert!(tips.len() == 2 && tips[1] == 5., "{tips:?}"); + assert!((6. ..=6. + 16. * 1e-5).contains(&tips[0]), "{tips:?}"); } else { assert_eq!(report["depth_passes"], 2); } @@ -272,3 +275,45 @@ fn cancelled_faced_stock_inspection_does_not_change_stock() { assert_eq!(stock.generation(), before.generation); assert_eq!(stock.cells(), before.cells); } + +/// A top within the stock-model band below uncut stock is accepted as the +/// stock top, but the first level must still be at most a stepdown below the +/// stock it meets (#344 review): measured on the stock each motion removes. +#[test] +fn top_inside_the_tolerance_band_never_cuts_deeper_than_a_stepdown() { + let m = fixture(); + for adaptive in [false, true] { + let mut op = operation(9.9, adaptive); + let pocket = match &mut op { + Operation::Pocket(p) => p, + Operation::AdaptivePocket(a) => &mut a.pocket, + _ => unreachable!(), + }; + pocket.tolerance_mm = 0.01; + pocket.stepdown_mm = 1.; + pocket.floor_z_mm = 7.; + let stepdown = pocket.stepdown_mm; + let mut stock = Stock::new(m.stock.height().unwrap().clone()).unwrap(); + let mut plan = OperationPlan::prepare_with_stock( + op, + &m.tools[0], + &stock, + m.initial_position_mm, + 1, + &|| false, + ) + .unwrap(); + let mut deepest: f64 = 0.; + while let Some(motion) = plan.next_motion_with_stock(&stock, &|| false).unwrap() { + let before: Vec = stock.cells().iter().map(|c| c.upper_mm).collect(); + commit(&mut stock, &motion, &m); + for (b, a) in before.iter().zip(stock.cells()) { + deepest = deepest.max(b - a.upper_mm); + } + } + assert!( + deepest <= stepdown + 1e-6, + "adaptive {adaptive}: one motion removed {deepest} mm of stock depth, more than the stepdown {stepdown}" + ); + } +} From 7178286a244314b93f929eeb86fc266e20adc5b9 Mon Sep 17 00:00:00 2001 From: Wookie1 <6943491+Wookie1@users.noreply.github.com> Date: Thu, 19 Nov 2026 04:26:25 +0000 Subject: [PATCH 05/17] Read saved engagement_front programs without the removed orbit fields (#190) The earlier serializers wrote orbit_radius_mm and its siblings (null) and boundary_tolerance_mm, and an adaptive pocket's clockwise, for every strategy; engagement_front never used them. A program that chose engagement_front is read without them. One without a path_strategy was planned by the old default, disk_front, and is refused with that reason instead of being read as engagement_front. The regression reads the unchanged roughing-open-block.json from before the removal. --- docs/operations.md | 8 +- .../saved-engagement-front-roughing.json | 323 ++++++++++++++++++ src/adaptive.rs | 54 +++ src/roughing.rs | 16 + tests/roughing.rs | 69 +++- 5 files changed, 468 insertions(+), 2 deletions(-) create mode 100644 fixtures/regressions/saved-engagement-front-roughing.json diff --git a/docs/operations.md b/docs/operations.md index 3e0c9ec9..e228a957 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -403,7 +403,13 @@ no full-width slotting, for hard materials and high-speed toolpaths. - **It follows the stock** (`path_strategy="engagement_front"`, the only planner; the orbit planners `disk_front` and `stock_front` were removed in - #190 and their names are refused): + #190 and their names are refused. A program saved earlier that chose + `engagement_front` still reads: the orbit fields the earlier serializers + wrote with it (`orbit_radius_mm` and its siblings as null, + `boundary_tolerance_mm`, and an adaptive pocket's `clockwise`) are dropped, + since the engagement front never used them. One saved without a + `path_strategy` was planned by the old default, `disk_front`, and is refused + with that reason): one depth level at a time, each pass runs along the boundary between cut and uncut stock inside the region, so nothing is cut twice. The region's boundary is a wall. diff --git a/fixtures/regressions/saved-engagement-front-roughing.json b/fixtures/regressions/saved-engagement-front-roughing.json new file mode 100644 index 00000000..5d0c66be --- /dev/null +++ b/fixtures/regressions/saved-engagement-front-roughing.json @@ -0,0 +1,323 @@ +{ + "version": 1, + "run": { + "id": "roughing-open-block", + "revision": "issue-167" + }, + "stock": { + "version": 1, + "units": "mm", + "min_mm": [ + -15.0, + -15.0, + 0.0 + ], + "max_mm": [ + 115.0, + 75.0, + 21.0 + ], + "cell_size_mm": 0.5, + "max_cells": 4294967295 + }, + "tools": [ + { + "id": "mill10", + "cutter": { + "id": "em10", + "name": "em10", + "shape": { + "kind": "flat" + }, + "diameter_mm": 10.0, + "cutting_length_mm": 30.0, + "overall_length_mm": 75.0, + "shank_diameter_mm": 10.0, + "flutes": 3, + "center_cutting": true, + "material": "carbide", + "neck": null + }, + "stickout_mm": 45.0, + "gauge_length_mm": 115.0, + "holders": [ + { + "z_min_mm": 45.0, + "z_max_mm": 115.0, + "radius_min_mm": 20.0, + "radius_max_mm": 20.0 + } + ] + } + ], + "initial_position_mm": [ + 0.0, + 0.0, + 60.0 + ], + "sweep": { + "tolerance_mm": 1e-05, + "chord_error_mm": 0.002, + "max_tip_step_mm": 0.1, + "max_segments": 100000, + "max_scratch_cells": 4294967295, + "max_changed_cells": 4294967295, + "max_cell_visits": 100000000 + }, + "operations": [ + { + "kind": "roughing", + "id": "rough", + "tool": "mill10", + "target": { + "version": 1, + "units": "mm", + "surface_error_mm": 2.0099999999999999e-07, + "source": { + "adapter": "planar_cad_solid_facets_v1", + "cadquery_version": "2.9.0.dev0", + "error_basis": "planar faces, straight trim edges, twice CAD topology tolerance plus numerical guard", + "extraction_ms": 8.970487979240716, + "faces": 6, + "ocp_version": "8.0.1.1", + "triangle_count": 12 + }, + "triangles": [ + [ + [ + 0.0, + 60.0, + 0.0 + ], + [ + 0.0, + 0.0, + 0.0 + ], + [ + 0.0, + 60.0, + 20.0 + ] + ], + [ + [ + 0.0, + 0.0, + 0.0 + ], + [ + 0.0, + 0.0, + 20.0 + ], + [ + 0.0, + 60.0, + 20.0 + ] + ], + [ + [ + 100.0, + 60.0, + 0.0 + ], + [ + 100.0, + 60.0, + 20.0 + ], + [ + 100.0, + 0.0, + 0.0 + ] + ], + [ + [ + 100.0, + 0.0, + 0.0 + ], + [ + 100.0, + 60.0, + 20.0 + ], + [ + 100.0, + 0.0, + 20.0 + ] + ], + [ + [ + 100.0, + 0.0, + 20.0 + ], + [ + 0.0, + 0.0, + 20.0 + ], + [ + 100.0, + 0.0, + 0.0 + ] + ], + [ + [ + 0.0, + 0.0, + 20.0 + ], + [ + 0.0, + 0.0, + 0.0 + ], + [ + 100.0, + 0.0, + 0.0 + ] + ], + [ + [ + 100.0, + 60.0, + 20.0 + ], + [ + 100.0, + 60.0, + 0.0 + ], + [ + 0.0, + 60.0, + 20.0 + ] + ], + [ + [ + 0.0, + 60.0, + 20.0 + ], + [ + 100.0, + 60.0, + 0.0 + ], + [ + 0.0, + 60.0, + 0.0 + ] + ], + [ + [ + 100.0, + 0.0, + 0.0 + ], + [ + 0.0, + 0.0, + 0.0 + ], + [ + 0.0, + 60.0, + 0.0 + ] + ], + [ + [ + 100.0, + 0.0, + 0.0 + ], + [ + 0.0, + 60.0, + 0.0 + ], + [ + 100.0, + 60.0, + 0.0 + ] + ], + [ + [ + 100.0, + 0.0, + 20.0 + ], + [ + 0.0, + 60.0, + 20.0 + ], + [ + 0.0, + 0.0, + 20.0 + ] + ], + [ + [ + 100.0, + 0.0, + 20.0 + ], + [ + 100.0, + 60.0, + 20.0 + ], + [ + 0.0, + 60.0, + 20.0 + ] + ] + ] + }, + "clearing": { + "kind": "adaptive", + "path_strategy": "engagement_front", + "max_radial_engagement_mm": 3.0, + "orbit_radius_mm": null, + "min_orbit_radius_mm": null, + "local_orbit_tolerance_mm": null, + "boundary_tolerance_mm": 0.01 + }, + "top_z_mm": 21.0, + "floor_z_mm": 14.0, + "stepdown_mm": 7.0, + "clearance_z_mm": 30.0, + "feed_mm_min": 1000.0, + "plunge_mm_min": 300.0, + "radial_allowance_mm": 0.3, + "bottom_allowance_mm": 0.0, + "tolerance_mm": 1e-05, + "spindle_rpm": 9000.0, + "work_offset": 1, + "tool_number": 1, + "length_register": 1, + "coolant": "off", + "clockwise": false, + "entry": { + "kind": "stock_edge", + "angle_rad": 0.05235987755982988 + } + } + ], + "rapid_retracts": true +} diff --git a/src/adaptive.rs b/src/adaptive.rs index d4ce24d9..68c6b738 100644 --- a/src/adaptive.rs +++ b/src/adaptive.rs @@ -60,12 +60,66 @@ impl AdaptivePocketOperation { } } } +/// Fields the removed orbit planners (#190) wrote. Saved programs that chose +/// `engagement_front` still carry them: the earlier serializers wrote +/// `boundary_tolerance_mm` (and, for an adaptive pocket, `clockwise`) for every +/// strategy and the orbit sizes as null, and the engagement front never read +/// them. Such a program is read without them. A program without a +/// `path_strategy` was planned by the old default, disk_front, and is refused: +/// reading it as engagement_front would silently plan a different path. +pub(crate) fn drop_removed_orbit_fields( + fields: &mut serde_json::Map, + owner: &str, + extra: &[&str], +) -> Result<(), String> { + const ORBITS: [&str; 3] = [ + "orbit_radius_mm", + "min_orbit_radius_mm", + "local_orbit_tolerance_mm", + ]; + let present: Vec<&str> = ORBITS + .iter() + .chain(["boundary_tolerance_mm"].iter()) + .chain(extra) + .copied() + .filter(|name| fields.contains_key(*name)) + .collect(); + let Some(first) = present.first() else { + return Ok(()); + }; + match fields.get("path_strategy") { + Some(serde_json::Value::String(s)) if s == "engagement_front" => {} + Some(_) => return Ok(()), // the strategy itself is refused by name + None => { + return Err(format!( + "{owner}: `{first}` without a path_strategy is a program saved for disk_front, the earlier default planner, which was removed (#190); set path_strategy \"engagement_front\" and remove the orbit fields to plan it with the engagement front" + )); + } + } + for name in present { + let value = fields.remove(name).expect("present"); + let ok = if ORBITS.contains(&name) { + value.is_null() + } else if name == "boundary_tolerance_mm" { + value.as_f64().is_some_and(f64::is_finite) + } else { + value.is_boolean() + }; + if !ok { + return Err(format!( + "{owner}: {name} {value} belongs to the removed orbit planners (#190) and engagement_front does not use it; remove it" + )); + } + } + Ok(()) +} impl TryFrom for AdaptivePocketOperation { type Error = String; fn try_from(value: serde_json::Value) -> Result { let serde_json::Value::Object(mut fields) = value else { return Err("adaptive operation must be an object".into()); }; + drop_removed_orbit_fields(&mut fields, "adaptive pocket", &["clockwise"])?; let path_strategy = serde_json::from_value( fields .remove("path_strategy") diff --git a/src/roughing.rs b/src/roughing.rs index c931cf74..bf5640f2 100644 --- a/src/roughing.rs +++ b/src/roughing.rs @@ -662,6 +662,21 @@ pub enum RoughingClearing { max_radial_engagement_mm: f64, }, } +/// Reads a saved clearing, without the fields the removed orbit planners +/// wrote into adaptive clearing that chose engagement_front (#190). +fn clearing_from_saved<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result { + use serde::de::Error; + let mut value = serde_json::Value::deserialize(deserializer)?; + if let Some(fields) = value.as_object_mut() + && fields.get("kind").and_then(|k| k.as_str()) == Some("adaptive") + { + crate::adaptive::drop_removed_orbit_fields(fields, "adaptive clearing", &[]) + .map_err(D::Error::custom)?; + } + serde_json::from_value(value).map_err(D::Error::custom) +} fn default_coverage_margin() -> f64 { 0.01 } @@ -725,6 +740,7 @@ pub struct RoughingOperation { pub id: String, pub tool: String, pub target: G, + #[serde(deserialize_with = "clearing_from_saved")] pub clearing: RoughingClearing, pub top_z_mm: f64, pub floor_z_mm: f64, diff --git a/tests/roughing.rs b/tests/roughing.rs index 4d62e319..246eda24 100644 --- a/tests/roughing.rs +++ b/tests/roughing.rs @@ -1727,7 +1727,10 @@ fn engagement_front_refuses_orbits_empty_cut_omission_and_helix_only_entry() { .err() .unwrap() .to_string(); - assert!(error.contains("unknown field `orbit_radius_mm`"), "{error}"); + assert!( + error.contains("orbit_radius_mm") && error.contains("removed orbit planners"), + "{error}" + ); let omit = edit(&|op| op["omit_empty_cuts"] = true.into()); assert!(prepare(&omit).contains("omit_empty_cuts")); let helix = edit(&|op| op["entry"]["kind"] = "helix".into()); @@ -4857,3 +4860,67 @@ fn bounded_front_on_large_blank_keeps_independent_pocket_engagement_and_stock_ch assert_eq!(report["completed_layers"], 1); assert!(report["layers"][0]["clearing"]["certified_strokes"].as_u64().unwrap() > 0); } + +/// Programs saved before the orbit planners were removed (#190) that chose +/// engagement_front still read: the earlier serializers wrote the orbit +/// fields (null) and `boundary_tolerance_mm` for every strategy, and the +/// engagement front never used them. A program saved for the old default, +/// disk_front (no path_strategy), is refused rather than replanned. +#[test] +fn saved_engagement_front_programs_read_without_the_removed_orbit_fields() { + let saved: serde_json::Value = serde_json::from_str(include_str!( + "../fixtures/regressions/saved-engagement-front-roughing.json" + )) + .unwrap(); + let current: serde_json::Value = + serde_json::from_str(include_str!("../fixtures/operations/roughing-open-block.json")) + .unwrap(); + let read = |v: &serde_json::Value| { + serde_json::to_value(serde_json::from_value::(v.clone()).unwrap()).unwrap() + }; + assert_eq!(read(&saved), read(¤t)); + // The old default strategy: no path_strategy, with the orbit fields. + let mut disk = saved.clone(); + disk["operations"][0]["clearing"] + .as_object_mut() + .unwrap() + .remove("path_strategy"); + let error = serde_json::from_value::(disk) + .err() + .unwrap() + .to_string(); + assert!(error.contains("disk_front") && error.contains("path_strategy"), "{error}"); + + // An adaptive pocket as the earlier serializer wrote it for + // engagement_front: orbit sizes null, boundary_tolerance_mm and clockwise. + let pocket: serde_json::Value = + serde_json::from_str(include_str!("../fixtures/operations/adaptive-pocket.json")).unwrap(); + let mut old = pocket.clone(); + let op = old["operations"][0].as_object_mut().unwrap(); + op.insert("path_strategy".into(), "engagement_front".into()); + for name in ["orbit_radius_mm", "min_orbit_radius_mm", "local_orbit_tolerance_mm"] { + op.insert(name.into(), serde_json::Value::Null); + } + op.insert("boundary_tolerance_mm".into(), 0.01.into()); + op.insert("clockwise".into(), true.into()); + assert_eq!(read(&old), read(&pocket)); + // A set orbit size was refused by engagement_front before, and still is. + let mut sized = old.clone(); + sized["operations"][0]["orbit_radius_mm"] = 1.into(); + let error = serde_json::from_value::(sized) + .err() + .unwrap() + .to_string(); + assert!(error.contains("orbit_radius_mm") && error.contains("#190"), "{error}"); + // Saved for disk_front (the old default): refused. + let mut disk = old; + disk["operations"][0] + .as_object_mut() + .unwrap() + .remove("path_strategy"); + let error = serde_json::from_value::(disk) + .err() + .unwrap() + .to_string(); + assert!(error.contains("disk_front"), "{error}"); +} 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 06/17] 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 66f0ac96edeac88c9a583fdf84666940add9bf3d 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 07/17] Move the depths only for stock more than the tolerance above the top (#344) Measuring the depths from any stock in the band moved them by a faced top's sweep error (1e-5 mm) and added a redundant last pass where the depth was an exact number of stepdowns (standalone rest example). The depths now move only when the reachable stock is more than tolerance_mm above the top; within it they stay where they were, and the first cut is at most a stepdown plus that tolerance. --- docs/operations.md | 9 +++++---- src/pocket.rs | 18 ++++++++++++------ src/pocket_front.rs | 8 ++++++-- tests/pocket_top.rs | 5 +---- 4 files changed, 24 insertions(+), 16 deletions(-) diff --git a/docs/operations.md b/docs/operations.md index c10df700..4e388e76 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -183,10 +183,11 @@ from it (#344), so no level is deeper than `stepdown_mm`. Every stock cell meeting the `region` must be at or below it, within the stock model's band of 16 x `tolerance_mm`; the run checks this against the committed stock, so a lower top needs the stock (an `AdaptivePocket` planned without it is refused). -Where stock inside that band stands above `top_z_mm` within the cutter's reach, -the depths are measured from the highest of it instead, so the first is still no -deeper than `stepdown_mm` below the stock it meets -(`stock_top.reachable_upper_z_mm` in the report, #344). Stock may stand higher outside the region, for example a low +Where stock inside that band stands more than `tolerance_mm` above `top_z_mm` +within the cutter's reach, the depths are measured from the highest of it +instead, so the first is still no deeper than `stepdown_mm` below the stock it +meets (`stock_top.reachable_upper_z_mm` in the report, #344). Within +`tolerance_mm` (a faced top's own sweep error) they stay where they were. Stock may stand higher outside the region, for example a low pocket beside a tall wall, when the tool assembly clears it: - Before any motion, the neck, shank and every holder section are checked diff --git a/src/pocket.rs b/src/pocket.rs index 3a8f6619..19e04895 100644 --- a/src/pocket.rs +++ b/src/pocket.rs @@ -726,8 +726,7 @@ impl StockTop { } let ceiling = top + 16. * tolerance; let mut outside = Outside::new(scope, tolerance)?; - let (maximum, examined, reachable) = - Self::scan(stock, top, ceiling, &mut outside, cancel)?; + let (maximum, examined, reachable) = Self::scan(stock, top, ceiling, &mut outside, cancel)?; spec.max_mm[2] = top; stock.request_sweep_receipts(); let tall = outside.highest; @@ -789,7 +788,8 @@ impl StockTop { .hypot((b[1] - p[1]).max(p[1] - b[3]).max(0.)) - half; if far <= o.cutter_radius + o.guard + o.slack { - reachable = Some(reachable.map_or(cell.upper_mm, |h: f64| h.max(cell.upper_mm))); + reachable = + Some(reachable.map_or(cell.upper_mm, |h: f64| h.max(cell.upper_mm))); } continue; } @@ -1428,10 +1428,16 @@ impl PocketPlan { let (mut envelope, bound) = StockTop::prepare(stock, op.top_z_mm, op.tolerance_mm, &scope, cancel)?; // Stock the top accepts within the model's band still stands above - // it where the cutter reaches: the depth passes start from that - // stock, so the first is no deeper than a stepdown below it (#344). + // it where the cutter reaches: when it is higher than the operation's + // own tolerance, the depth passes start from that stock, so the first + // is no deeper than a stepdown below it (#344). Within the tolerance + // (a faced top's sweep error) the passes stay where they were. let mut op = op; - if let Some(h) = bound.as_ref().and_then(|b| b.report.reachable_upper_z_mm) { + if let Some(h) = bound + .as_ref() + .and_then(|b| b.report.reachable_upper_z_mm) + .filter(|h| *h > op.top_z_mm + op.tolerance_mm + 1e-9) + { op.top_z_mm = h; envelope.max_mm[2] = h; } diff --git a/src/pocket_front.rs b/src/pocket_front.rs index bea12a3a..1d06f64f 100644 --- a/src/pocket_front.rs +++ b/src/pocket_front.rs @@ -288,12 +288,16 @@ impl PocketFrontPlan { ) .map_err(|e| format!("adaptive {e}"))?; // Stock the top accepts within the model's band still stands above - // it where the cutter reaches: the levels start from that stock, so - // the first is no deeper than a stepdown below it (#344). + // it where the cutter reaches: when it is higher than the operation's + // own tolerance, the levels start from that stock, so the first is no + // deeper than a stepdown below it (#344). Within the tolerance (a + // faced top's sweep error) the levels stay where they were. + let within = pocket.top_z_mm + pocket.tolerance_mm + 1e-9; let (mut op, mut envelope) = (op, envelope); if let Some(h) = bound .as_ref() .and_then(|b| b.report.reachable_upper_z_mm) + .filter(|h| *h > within) { op.pocket.top_z_mm = h; envelope.max_mm[2] = h; diff --git a/tests/pocket_top.rs b/tests/pocket_top.rs index 04c4b038..7e3a1fc0 100644 --- a/tests/pocket_top.rs +++ b/tests/pocket_top.rs @@ -129,10 +129,7 @@ fn pocket_and_adaptive_use_faced_stock_top_without_resetting_stock_or_extra_dept .iter() .map(|l| l["tip_z_mm"].as_f64().unwrap()) .collect(); - // The faced stock model stands up to 16 x tolerance - // above Z8 (see `faced`); levels start from it (#344). - assert!(tips.len() == 2 && tips[1] == 5., "{tips:?}"); - assert!((6. ..=6. + 16. * 1e-5).contains(&tips[0]), "{tips:?}"); + assert_eq!(tips, [6., 5.]); } else { assert_eq!(report["depth_passes"], 2); } 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 08/17] 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 cb7769c440dc43fbb5a9210667685a12d6d54f46 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 09/17] Make stepdown a strict maximum; refuse stock that changes after planning (#344) Depths are planned from any reachable stock above the top inside the band: the stock model cannot tell a faced top's sweep error from material, so no depth of cut exceeds stepdown_mm below it. A faced top can therefore gain a last, nearly empty pass (the standalone rest example's golden program does, regenerated). A rescan that finds stock above the top the depths were planned from refuses before the next motion, and the floor is checked against the authored top before a higher planning top is used. --- docs/operations.md | 15 +++-- fixtures/posts/rust/standalone-rest.nc | 56 ++++++++++++++++++ src/pocket.rs | 55 +++++++++++++----- src/pocket_front.rs | 18 ++---- tests/pocket_top.rs | 78 +++++++++++++++++++++++++- tests/ramp_entry.rs | 6 +- tests/supplied.rs | 11 +++- 7 files changed, 199 insertions(+), 40 deletions(-) diff --git a/docs/operations.md b/docs/operations.md index 4e388e76..f74f2b8f 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -183,11 +183,16 @@ from it (#344), so no level is deeper than `stepdown_mm`. Every stock cell meeting the `region` must be at or below it, within the stock model's band of 16 x `tolerance_mm`; the run checks this against the committed stock, so a lower top needs the stock (an `AdaptivePocket` planned without it is refused). -Where stock inside that band stands more than `tolerance_mm` above `top_z_mm` -within the cutter's reach, the depths are measured from the highest of it -instead, so the first is still no deeper than `stepdown_mm` below the stock it -meets (`stock_top.reachable_upper_z_mm` in the report, #344). Within -`tolerance_mm` (a faced top's own sweep error) they stay where they were. Stock may stand higher outside the region, for example a low +Where stock inside that band stands above `top_z_mm` within the cutter's reach, +the depths are measured from the highest of it instead +(`stock_top.reachable_upper_z_mm` in the report, #344): `stepdown_mm` is a +strict maximum below the stock model. The model cannot tell a faced top's +sweep error from material, so a top faced to exactly `top_z_mm` can gain a last, +nearly empty depth when the depth is a whole number of stepdowns. The floor is +checked against the authored top first. If the stock changes after planning and +stands higher than the top the depths were planned from, where the cutter +reaches, the run refuses before the next motion; plan the operation again +against that stock. Stock may stand higher outside the region, for example a low pocket beside a tall wall, when the tool assembly clears it: - Before any motion, the neck, shank and every holder section are checked diff --git a/fixtures/posts/rust/standalone-rest.nc b/fixtures/posts/rust/standalone-rest.nc index b4b73579..9f10b8a6 100644 --- a/fixtures/posts/rust/standalone-rest.nc +++ b/fixtures/posts/rust/standalone-rest.nc @@ -65,6 +65,21 @@ G1 X12 Y10 Z3 F600 G1 X6 Y10 Z3 F600 G1 X6 Y6 Z3 F600 G0 X6 Y6 Z8 +G0 X6 Y6.667 Z8 +G1 X6 Y6.667 Z3 F150 +G1 X12 Y6.667 Z3 F600 +G1 X12 Y8 Z3 F600 +G1 X6 Y8 Z3 F600 +G1 X6 Y9.333 Z3 F600 +G1 X12 Y9.333 Z3 F600 +G0 X12 Y9.333 Z8 +G0 X6 Y6 Z8 +G1 X6 Y6 Z3 F150 +G1 X12 Y6 Z3 F600 +G1 X12 Y10 Z3 F600 +G1 X6 Y10 Z3 F600 +G1 X6 Y6 Z3 F600 +G0 X6 Y6 Z8 M9 M5 G54 @@ -155,6 +170,47 @@ G1 X5 Y11 Z3 F600 G1 X5 Y5 Z3 F600 G0 X5 Y5 Z6.5 G0 X5 Y5 Z8 +G0 X5 Y5.375 Z8 +G0 X5 Y5.375 Z6.5 +G1 X5 Y5.375 Z3 F150 +G1 X13 Y5.375 Z3 F600 +G1 X13 Y6.125 Z3 F600 +G1 X12 Y6.125 Z3 F600 +G1 X6 Y6.125 Z3 F600 +G1 X5 Y6.125 Z3 F600 +G1 X5 Y6.875 Z3 F600 +G1 X6 Y6.875 Z3 F600 +G1 X12 Y6.875 Z3 F600 +G1 X13 Y6.875 Z3 F600 +G1 X13 Y7.625 Z3 F600 +G1 X12 Y7.625 Z3 F600 +G1 X6 Y7.625 Z3 F600 +G1 X5 Y7.625 Z3 F600 +G1 X5 Y8.375 Z3 F600 +G1 X6 Y8.375 Z3 F600 +G1 X12 Y8.375 Z3 F600 +G1 X13 Y8.375 Z3 F600 +G1 X13 Y9.125 Z3 F600 +G1 X12 Y9.125 Z3 F600 +G1 X6 Y9.125 Z3 F600 +G1 X5 Y9.125 Z3 F600 +G1 X5 Y9.875 Z3 F600 +G1 X6 Y9.875 Z3 F600 +G1 X12 Y9.875 Z3 F600 +G1 X13 Y9.875 Z3 F600 +G1 X13 Y10.625 Z3 F600 +G1 X5 Y10.625 Z3 F600 +G0 X5 Y10.625 Z6.5 +G0 X5 Y10.625 Z8 +G0 X5 Y5 Z8 +G0 X5 Y5 Z6.5 +G1 X5 Y5 Z3 F150 +G1 X13 Y5 Z3 F600 +G1 X13 Y11 Z3 F600 +G1 X5 Y11 Z3 F600 +G1 X5 Y5 Z3 F600 +G0 X5 Y5 Z6.5 +G0 X5 Y5 Z8 M9 M5 G49 diff --git a/src/pocket.rs b/src/pocket.rs index 19e04895..d03ee63c 100644 --- a/src/pocket.rs +++ b/src/pocket.rs @@ -705,6 +705,8 @@ impl Outside { /// judged by the tool assembly (`Outside`). pub(crate) struct StockTop { ceiling: f64, + /// The top the depths are planned from (`planning_top`). + planned: f64, identity: u64, outside: Outside, pub(crate) report: StockTopReport, @@ -724,16 +726,26 @@ impl StockTop { if !tolerance.is_finite() || !(1e-7..=0.01).contains(&tolerance) { return Err("pocket tolerance_mm must be finite in [1e-7, 0.01]".into()); } + // Checked here, against the authored top, because the depths may be + // planned from a higher one (below) that would hide it (#344). + if scope.lowest_tip_z >= top { + return Err(format!( + "operation {}: floor_z_mm plus bottom allowance (Z{}) must be below top_z_mm {top}", + scope.operation, scope.lowest_tip_z + )); + } let ceiling = top + 16. * tolerance; let mut outside = Outside::new(scope, tolerance)?; let (maximum, examined, reachable) = Self::scan(stock, top, ceiling, &mut outside, cancel)?; - spec.max_mm[2] = top; + let planned = Self::planning_top(top, reachable); + spec.max_mm[2] = planned; stock.request_sweep_receipts(); let tall = outside.highest; Ok(( spec, Some(Self { ceiling, + planned, identity: stock.identity(), outside, report: StockTopReport { @@ -748,6 +760,18 @@ impl StockTop { }), )) } + /// The top the depths are planned from. Stock the top accepts within + /// the model's band may still stand above it where the cutter reaches: + /// the depths then start from the highest of it, so no depth of cut is + /// deeper than `stepdown_mm` below the stock model (#344). `stepdown_mm` + /// is a strict maximum: the model cannot tell a faced top's sweep error + /// from material, so that error is treated as material too. + fn planning_top(top: f64, reachable: Option) -> f64 { + reachable.filter(|h| *h > top).unwrap_or(top) + } + pub(crate) fn planned_top(&self) -> f64 { + self.planned + } /// The highest stock, how many cells above the ceiling were examined, /// and the highest stock above the top (up to the ceiling) that the /// cutter can reach. @@ -882,13 +906,23 @@ impl StockTop { .last_sweep_receipt() .is_some_and(|r| r.base_identity == self.identity) { - let _ = Self::scan( + let (_, _, reachable) = Self::scan( stock, self.report.authored_top_z_mm, self.ceiling, &mut self.outside, cancel, )?; + // The depths were planned from `planned`: stock that now + // stands higher where the cutter reaches would make the + // next cut deeper than a stepdown (#344 review). + let needed = Self::planning_top(self.report.authored_top_z_mm, reachable); + if needed > self.planned { + return Err(format!( + "operation {}: the stock changed after planning: stock up to Z{needed} where the cutter reaches stands above Z{}, the top the depths were planned from; plan the operation again against this stock", + self.outside.operation, self.planned + )); + } } self.identity = stock.identity(); } @@ -1425,21 +1459,12 @@ impl PocketPlan { clearance_z: op.clearance_z_mm, boundary_slack_mm: 0., }; - let (mut envelope, bound) = + let (envelope, bound) = StockTop::prepare(stock, op.top_z_mm, op.tolerance_mm, &scope, cancel)?; - // Stock the top accepts within the model's band still stands above - // it where the cutter reaches: when it is higher than the operation's - // own tolerance, the depth passes start from that stock, so the first - // is no deeper than a stepdown below it (#344). Within the tolerance - // (a faced top's sweep error) the passes stay where they were. + // The depths start from the top `StockTop` planned (#344). let mut op = op; - if let Some(h) = bound - .as_ref() - .and_then(|b| b.report.reachable_upper_z_mm) - .filter(|h| *h > op.top_z_mm + op.tolerance_mm + 1e-9) - { - op.top_z_mm = h; - envelope.max_mm[2] = h; + if let Some(b) = &bound { + op.top_z_mm = b.planned_top(); } let mut plan = Self::prepare(op, assembly, &envelope, initial, first_motion_id, cancel)?; if let Some(bound) = bound { diff --git a/src/pocket_front.rs b/src/pocket_front.rs index 1d06f64f..ad43c3b1 100644 --- a/src/pocket_front.rs +++ b/src/pocket_front.rs @@ -287,20 +287,10 @@ impl PocketFrontPlan { cancel, ) .map_err(|e| format!("adaptive {e}"))?; - // Stock the top accepts within the model's band still stands above - // it where the cutter reaches: when it is higher than the operation's - // own tolerance, the levels start from that stock, so the first is no - // deeper than a stepdown below it (#344). Within the tolerance (a - // faced top's sweep error) the levels stay where they were. - let within = pocket.top_z_mm + pocket.tolerance_mm + 1e-9; - let (mut op, mut envelope) = (op, envelope); - if let Some(h) = bound - .as_ref() - .and_then(|b| b.report.reachable_upper_z_mm) - .filter(|h| *h > within) - { - op.pocket.top_z_mm = h; - envelope.max_mm[2] = h; + // The levels start from the top `StockTop` planned (#344). + let mut op = op; + if let Some(b) = &bound { + op.pocket.top_z_mm = b.planned_top(); } let mut plan = Self::prepare(op, tool, &envelope, initial, first_id, cancel)?; plan.spec = stock.spec().clone(); diff --git a/tests/pocket_top.rs b/tests/pocket_top.rs index 7e3a1fc0..43215f3c 100644 --- a/tests/pocket_top.rs +++ b/tests/pocket_top.rs @@ -129,7 +129,11 @@ fn pocket_and_adaptive_use_faced_stock_top_without_resetting_stock_or_extra_dept .iter() .map(|l| l["tip_z_mm"].as_f64().unwrap()) .collect(); - assert_eq!(tips, [6., 5.]); + // From the faced stock model, which stands up to + // 16 x tolerance above Z8 (see `faced`): stepdown_mm is + // a strict maximum below it (#344). + assert!(tips.len() == 2 && tips[1] == 5., "{tips:?}"); + assert!((6. ..=6. + 16. * 1e-5).contains(&tips[0]), "{tips:?}"); } else { assert_eq!(report["depth_passes"], 2); } @@ -314,3 +318,75 @@ fn top_inside_the_tolerance_band_never_cuts_deeper_than_a_stepdown() { ); } } + +fn band_operation(top: f64, adaptive: bool, edit: impl Fn(&mut PocketOperation)) -> Operation { + let mut op = operation(top, adaptive); + let pocket = match &mut op { + Operation::Pocket(p) => p, + Operation::AdaptivePocket(a) => &mut a.pocket, + _ => unreachable!(), + }; + pocket.tolerance_mm = 0.01; + pocket.stepdown_mm = 1.; + pocket.floor_z_mm = 7.; + edit(pocket); + op +} + +/// #344 review: the depths are planned from the stock seen at preparation. +/// Stock supplied later that stands higher within the band, where the cutter +/// reaches, would make the next cut deeper than a stepdown: refused on the +/// rescan, before any motion. +#[test] +fn a_rescan_refuses_stock_above_the_top_the_depths_were_planned_from() { + let m = fixture(); + for adaptive in [false, true] { + let blank = Stock::new(m.stock.height().unwrap().clone()).unwrap(); + let mut lower = blank.snapshot(); + for cell in &mut lower.cells { + cell.lower_mm = 9.9; + cell.upper_mm = 9.9; + } + let lower = Stock::from_snapshot(lower).unwrap(); + let mut plan = OperationPlan::prepare_with_stock( + band_operation(9.9, adaptive, |_| ()), + &m.tools[0], + &lower, + m.initial_position_mm, + 1, + &|| false, + ) + .unwrap(); + let error = plan + .next_motion_with_stock(&blank, &|| false) + .unwrap_err(); + assert!( + error.contains("stock changed after planning") && error.contains("Z10"), + "adaptive {adaptive}: {error}" + ); + } +} + +/// #344 review: a floor above the authored top is refused even where the +/// depths would be planned from higher stock. +#[test] +fn a_floor_above_the_authored_top_is_refused_on_stock_in_the_band() { + let m = fixture(); + for adaptive in [false, true] { + let blank = Stock::new(m.stock.height().unwrap().clone()).unwrap(); + let error = OperationPlan::prepare_with_stock( + band_operation(9.9, adaptive, |p| p.floor_z_mm = 9.92), + &m.tools[0], + &blank, + m.initial_position_mm, + 1, + &|| false, + ) + .err() + .unwrap(); + assert!( + error.contains("must be below top_z_mm 9.9"), + "adaptive {adaptive}: {error}" + ); + } +} diff --git a/tests/ramp_entry.rs b/tests/ramp_entry.rs index 1eb474cb..ccd8579e 100644 --- a/tests/ramp_entry.rs +++ b/tests/ramp_entry.rs @@ -560,7 +560,7 @@ fn pocket_ramp_on_uneven_stock_descends_straight_only_through_air() { #[test] fn pocket_ramp_below_a_lower_authored_top_starts_at_that_top() { // A wider pocket has taken the top 2 mm; the slot starts at Z8 inside - // it. The first ramp starts at Z8, in air above the earlier floor. + // it. The first ramp starts at Z8 (the stock model's floor), in air above it. let (stock, heights) = precut([[2., 8.], [30., 16.]], 8.); let mut m = pocket_manifest(SLOT, Some(PocketEntry::Ramp(zigzag(4., 2.)))); let Operation::Pocket(p) = &mut m.operations[0] else { @@ -577,7 +577,9 @@ fn pocket_ramp_below_a_lower_authored_top_starts_at_that_top() { .filter(|m| m.curve.end()[2] < m.curve.start()[2] && horizontal(&m.curve) > 0.) .map(|m| m.curve.start()[2]) .fold(f64::NEG_INFINITY, f64::max); - assert_eq!(sloped_top, 8.); + // At the earlier floor as the stock model holds it: up to its sweep + // tolerance above Z8, where the depths are planned from (#344). + assert!((8. ..=8. + 1e-4).contains(&sloped_top), "{sloped_top}"); check_slot(&seen, &stock, true, 4., None); } diff --git a/tests/supplied.rs b/tests/supplied.rs index 9356b870..c3f05790 100644 --- a/tests/supplied.rs +++ b/tests/supplied.rs @@ -155,7 +155,11 @@ fn cut_length_at(run: &Run, operation: &str, z: f64) -> f64 { .iter() .filter(|m| m.operation == operation && m.kind == MoveKind::Cut) .filter_map(|m| match m.curve { - Curve::Line { start, end } if start[2] == z && end[2] == z => { + // Within the sweep tolerance: a level planned from the faced + // stock model sits up to 1e-5 above the nominal Z (#344). + Curve::Line { start, end } + if (start[2] - z).abs() <= 1e-4 && (end[2] - z).abs() <= 1e-4 => + { Some((end[0] - start[0]).hypot(end[1] - start[1])) } _ => None, @@ -261,8 +265,9 @@ fn the_stock_a_supplied_toolpath_leaves_is_what_the_next_operation_sees() { assert!(near(upper_at(cut, 9., y), 4.), "{}", upper_at(cut, 9., y)); assert!(upper_at(cut, 6., y) < 4. && upper_at(cut, 6., y) >= 3.5); assert!(near(upper_at(cut, 20., 2.), 5.)); - // The rest pocket (floor Z 3, in 1 mm steps: levels 4 and 3) plans from - // that stock: at Z 4 it no longer cuts along the supplied slot. + // The rest pocket (floor Z 3, in 1 mm steps from the faced stock model: + // levels near 4 and 3) plans from that stock: at Z 4 it no longer cuts + // along the supplied slot. let (after_slot, from_faced) = ( cut_length_at(&with, "rest", 4.), cut_length_at(&without, "rest", 4.), 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 10/17] 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 11/17] 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 ab13af22334e7be257be944ab3dbf377462262ca Mon Sep 17 00:00:00 2001 From: James Date: Fri, 20 Nov 2026 08:18:43 -0700 Subject: [PATCH 12/17] Reject duplicate fields in saved roughing clearing (#190) --- src/roughing.rs | 30 ++++++++++++++++++++++-------- tests/roughing.rs | 13 +++++++++---- 2 files changed, 31 insertions(+), 12 deletions(-) diff --git a/src/roughing.rs b/src/roughing.rs index 8114d11b..7143adc8 100644 --- a/src/roughing.rs +++ b/src/roughing.rs @@ -667,15 +667,29 @@ pub enum RoughingClearing { fn clearing_from_saved<'de, D: serde::Deserializer<'de>>( deserializer: D, ) -> Result { - use serde::de::Error; - let mut value = serde_json::Value::deserialize(deserializer)?; - if let Some(fields) = value.as_object_mut() - && fields.get("kind").and_then(|k| k.as_str()) == Some("adaptive") - { - crate::adaptive::drop_removed_orbit_fields(fields, "adaptive clearing", &[]) - .map_err(D::Error::custom)?; + use serde::de::{Error, MapAccess, Visitor}; + struct ClearingVisitor; + impl<'de> Visitor<'de> for ClearingVisitor { + type Value = RoughingClearing; + fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("a roughing clearing object") + } + fn visit_map>(self, mut map: M) -> Result { + let mut fields = serde_json::Map::new(); + while let Some(key) = map.next_key::()? { + if fields.contains_key(&key) { + return Err(M::Error::custom(format!("duplicate field `{key}`"))); + } + fields.insert(key, map.next_value()?); + } + if fields.get("kind").and_then(|k| k.as_str()) == Some("adaptive") { + crate::adaptive::drop_removed_orbit_fields(&mut fields, "adaptive clearing", &[]) + .map_err(M::Error::custom)?; + } + serde_json::from_value(serde_json::Value::Object(fields)).map_err(M::Error::custom) + } } - serde_json::from_value(value).map_err(D::Error::custom) + deserializer.deserialize_map(ClearingVisitor) } fn default_coverage_margin() -> f64 { 0.01 diff --git a/tests/roughing.rs b/tests/roughing.rs index fa3e40f9..02e286a2 100644 --- a/tests/roughing.rs +++ b/tests/roughing.rs @@ -5038,10 +5038,8 @@ fn bounded_front_on_large_blank_keeps_independent_pocket_engagement_and_stock_ch /// disk_front (no path_strategy), is refused rather than replanned. #[test] fn saved_engagement_front_programs_read_without_the_removed_orbit_fields() { - let saved: serde_json::Value = serde_json::from_str(include_str!( - "../fixtures/regressions/saved-engagement-front-roughing.json" - )) - .unwrap(); + let saved_wire = include_str!("../fixtures/regressions/saved-engagement-front-roughing.json"); + let saved: serde_json::Value = serde_json::from_str(saved_wire).unwrap(); let current: serde_json::Value = serde_json::from_str(include_str!("../fixtures/operations/roughing-open-block.json")) .unwrap(); @@ -5049,6 +5047,13 @@ fn saved_engagement_front_programs_read_without_the_removed_orbit_fields() { serde_json::to_value(serde_json::from_value::(v.clone()).unwrap()).unwrap() }; assert_eq!(read(&saved), read(¤t)); + // Read the raw wire here: a Value would already have discarded the duplicate. + let key = "\"max_radial_engagement_mm\":"; + let duplicate = saved_wire.replacen(key, &format!("{key} 0.01, {key}"), 1); + let error = serde_json::from_str::(&duplicate) + .unwrap_err() + .to_string(); + assert!(error.contains("duplicate field `max_radial_engagement_mm`"), "{error}"); // The old default strategy: no path_strategy, with the orbit fields. let mut disk = saved.clone(); disk["operations"][0]["clearing"] From f227e316c835239f516e072b80df45b13dc504f4 Mon Sep 17 00:00:00 2001 From: James Date: Fri, 20 Nov 2026 08:18:43 -0700 Subject: [PATCH 13/17] Reject duplicate fields in saved roughing clearing (#190) --- src/roughing.rs | 30 ++++++++++++++++++++++-------- tests/roughing.rs | 13 +++++++++---- 2 files changed, 31 insertions(+), 12 deletions(-) diff --git a/src/roughing.rs b/src/roughing.rs index 8114d11b..7143adc8 100644 --- a/src/roughing.rs +++ b/src/roughing.rs @@ -667,15 +667,29 @@ pub enum RoughingClearing { fn clearing_from_saved<'de, D: serde::Deserializer<'de>>( deserializer: D, ) -> Result { - use serde::de::Error; - let mut value = serde_json::Value::deserialize(deserializer)?; - if let Some(fields) = value.as_object_mut() - && fields.get("kind").and_then(|k| k.as_str()) == Some("adaptive") - { - crate::adaptive::drop_removed_orbit_fields(fields, "adaptive clearing", &[]) - .map_err(D::Error::custom)?; + use serde::de::{Error, MapAccess, Visitor}; + struct ClearingVisitor; + impl<'de> Visitor<'de> for ClearingVisitor { + type Value = RoughingClearing; + fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("a roughing clearing object") + } + fn visit_map>(self, mut map: M) -> Result { + let mut fields = serde_json::Map::new(); + while let Some(key) = map.next_key::()? { + if fields.contains_key(&key) { + return Err(M::Error::custom(format!("duplicate field `{key}`"))); + } + fields.insert(key, map.next_value()?); + } + if fields.get("kind").and_then(|k| k.as_str()) == Some("adaptive") { + crate::adaptive::drop_removed_orbit_fields(&mut fields, "adaptive clearing", &[]) + .map_err(M::Error::custom)?; + } + serde_json::from_value(serde_json::Value::Object(fields)).map_err(M::Error::custom) + } } - serde_json::from_value(value).map_err(D::Error::custom) + deserializer.deserialize_map(ClearingVisitor) } fn default_coverage_margin() -> f64 { 0.01 diff --git a/tests/roughing.rs b/tests/roughing.rs index fa3e40f9..02e286a2 100644 --- a/tests/roughing.rs +++ b/tests/roughing.rs @@ -5038,10 +5038,8 @@ fn bounded_front_on_large_blank_keeps_independent_pocket_engagement_and_stock_ch /// disk_front (no path_strategy), is refused rather than replanned. #[test] fn saved_engagement_front_programs_read_without_the_removed_orbit_fields() { - let saved: serde_json::Value = serde_json::from_str(include_str!( - "../fixtures/regressions/saved-engagement-front-roughing.json" - )) - .unwrap(); + let saved_wire = include_str!("../fixtures/regressions/saved-engagement-front-roughing.json"); + let saved: serde_json::Value = serde_json::from_str(saved_wire).unwrap(); let current: serde_json::Value = serde_json::from_str(include_str!("../fixtures/operations/roughing-open-block.json")) .unwrap(); @@ -5049,6 +5047,13 @@ fn saved_engagement_front_programs_read_without_the_removed_orbit_fields() { serde_json::to_value(serde_json::from_value::(v.clone()).unwrap()).unwrap() }; assert_eq!(read(&saved), read(¤t)); + // Read the raw wire here: a Value would already have discarded the duplicate. + let key = "\"max_radial_engagement_mm\":"; + let duplicate = saved_wire.replacen(key, &format!("{key} 0.01, {key}"), 1); + let error = serde_json::from_str::(&duplicate) + .unwrap_err() + .to_string(); + assert!(error.contains("duplicate field `max_radial_engagement_mm`"), "{error}"); // The old default strategy: no path_strategy, with the orbit fields. let mut disk = saved.clone(); disk["operations"][0]["clearing"] From 3184ff569add8aafd9b551a1add3c4179b256e63 Mon Sep 17 00:00:00 2001 From: James Date: Fri, 20 Nov 2026 08:18:43 -0700 Subject: [PATCH 14/17] Bind lower-top pocket plans to committed stock (#344) --- docs/operations.md | 9 ++- src/pocket.rs | 179 ++++++++++++++++++++++++++++++-------------- src/pocket_front.rs | 7 +- tests/pocket_top.rs | 77 +++++++++++++++++++ 4 files changed, 209 insertions(+), 63 deletions(-) diff --git a/docs/operations.md b/docs/operations.md index f74f2b8f..8bdab2ca 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -189,10 +189,13 @@ the depths are measured from the highest of it instead strict maximum below the stock model. The model cannot tell a faced top's sweep error from material, so a top faced to exactly `top_z_mm` can gain a last, nearly empty depth when the depth is a whole number of stepdowns. The floor is -checked against the authored top first. If the stock changes after planning and +checked against the authored top first. If the stock changes before the first motion and stands higher than the top the depths were planned from, where the cutter -reaches, the run refuses before the next motion; plan the operation again -against that stock. Stock may stand higher outside the region, for example a low +reaches, the run refuses. After the first motion, the next move requires the +complete preceding sweep to have been committed with the matching tool and +stock. A replacement stock may have refilled earlier levels even if its top +and generation still match; plan the operation again against that stock. +Stock may stand higher outside the region, for example a low pocket beside a tall wall, when the tool assembly clears it: - Before any motion, the neck, shank and every holder section are checked diff --git a/src/pocket.rs b/src/pocket.rs index d03ee63c..cb8152a0 100644 --- a/src/pocket.rs +++ b/src/pocket.rs @@ -708,9 +708,18 @@ pub(crate) struct StockTop { /// The top the depths are planned from (`planning_top`). planned: f64, identity: u64, + tool: ToolAssembly, + pending: Option, + started: bool, outside: Outside, pub(crate) report: StockTopReport, } +struct StockTopScan { + maximum: f64, + examined: usize, + reachable: Option, + tall: Option, +} impl StockTop { pub(crate) fn prepare( stock: &Stock, @@ -736,26 +745,29 @@ impl StockTop { } let ceiling = top + 16. * tolerance; let mut outside = Outside::new(scope, tolerance)?; - let (maximum, examined, reachable) = Self::scan(stock, top, ceiling, &mut outside, cancel)?; - let planned = Self::planning_top(top, reachable); + let scan = Self::scan(stock, top, ceiling, &outside, cancel)?; + let planned = Self::planning_top(top, scan.reachable); spec.max_mm[2] = planned; stock.request_sweep_receipts(); - let tall = outside.highest; + outside.highest = scan.tall; Ok(( spec, Some(Self { ceiling, planned, identity: stock.identity(), + tool: scope.tool.clone(), + pending: None, + started: false, outside, report: StockTopReport { authored_top_z_mm: top, - maximum_upper_z_mm: maximum, + maximum_upper_z_mm: scan.maximum, checked_cells: stock.cells().len(), generation: stock.generation(), - outside_upper_z_mm: tall, - assembly_checked_cells: tall.map(|_| examined), - reachable_upper_z_mm: reachable, + outside_upper_z_mm: scan.tall, + assembly_checked_cells: scan.tall.map(|_| scan.examined), + reachable_upper_z_mm: scan.reachable, }, }), )) @@ -779,13 +791,12 @@ impl StockTop { stock: &Stock, top: f64, ceiling: f64, - outside: &mut Outside, + o: &Outside, cancel: &impl CancelSignal, - ) -> Result<(f64, usize, Option), String> { + ) -> Result { let mut maximum = f64::NEG_INFINITY; let [dx, dy] = stock.cell_widths_mm(); let half = dx.hypot(dy) / 2.; - let o = &*outside; let reach = o .sections .iter() @@ -803,15 +814,20 @@ impl StockTop { if cell.upper_mm <= top { continue; } + let p = stock.cell_center(i).ok_or("stock cell outside the grid")?; + // The distance from this cell to the region's bounding box bounds + // its distance to the region from below: far cells need no query. + let b = o.region_bounds; + let far = ((b[0] - p[0]).max(p[0] - b[2]).max(0.)) + .hypot((b[1] - p[1]).max(p[1] - b[3]).max(0.)) + - half; if cell.upper_mm <= ceiling { - // Within the band the top is accepted, but the cutter meets - // this stock where it can reach it: the levels start from it. - let p = stock.cell_center(i).ok_or("stock cell outside the grid")?; - let b = o.region_bounds; - let far = ((b[0] - p[0]).max(p[0] - b[2]).max(0.)) - .hypot((b[1] - p[1]).max(p[1] - b[3]).max(0.)) - - half; - if far <= o.cutter_radius + o.guard + o.slack { + // A centre in the proven centre set has clearance >= r - slack, + // so its cutter cannot reach outside the region by more + // than slack (plus the numerical guard). + if far <= o.guard + o.slack + && o.upper_clearance_at(p)? + half + o.guard + o.slack >= 0. + { reachable = Some(reachable.map_or(cell.upper_mm, |h: f64| h.max(cell.upper_mm))); } @@ -823,14 +839,7 @@ impl StockTop { cell.upper_mm ) }; - let p = stock.cell_center(i).ok_or("stock cell outside the grid")?; examined += 1; - // The distance from this cell to the region's bounding box bounds - // its distance to the region from below: far cells need no query. - let b = o.region_bounds; - let far = ((b[0] - p[0]).max(p[0] - b[2]).max(0.)) - .hypot((b[1] - p[1]).max(p[1] - b[3]).max(0.)) - - half; if far > reach + o.guard + o.slack { continue; } @@ -891,44 +900,67 @@ impl StockTop { o.operation, o.clearance )); } - outside.highest = tall; - Ok((maximum, examined, reachable)) + Ok(StockTopScan { + maximum, + examined, + reachable, + tall, + }) } pub(crate) fn validate( &mut self, stock: &Stock, cancel: &impl CancelSignal, ) -> Result<(), String> { - if stock.identity() != self.identity { - // Native monotone commits preserve this height bound. Foreign, - // restored or undone state is assessed afresh instead of trusted. - if !stock - .last_sweep_receipt() - .is_some_and(|r| r.base_identity == self.identity) - { - let (_, _, reachable) = Self::scan( - stock, - self.report.authored_top_z_mm, - self.ceiling, - &mut self.outside, - cancel, - )?; - // The depths were planned from `planned`: stock that now - // stands higher where the cutter reaches would make the - // next cut deeper than a stepdown (#344 review). - let needed = Self::planning_top(self.report.authored_top_z_mm, reachable); - if needed > self.planned { - return Err(format!( - "operation {}: the stock changed after planning: stock up to Z{needed} where the cutter reaches stands above Z{}, the top the depths were planned from; plan the operation again against this stock", - self.outside.operation, self.planned - )); - } + if let Some(pending) = &self.pending { + // Later depths and queued links depend on the *exact* preceding + // sweep. Rescanning the top cannot prove that a cleared layer + // is still clear on foreign or restored stock. + if !stock.last_sweep_receipt().is_some_and(|r| { + r.base_identity == self.identity + && r.motion.commits(pending) + && r.tool == self.tool + && r.fraction == 1. + }) { + return Err(format!( + "operation {}: commit the complete preceding motion with the matching cutter and stock before continuing; replan if the stock was replaced", + self.outside.operation + )); + } + self.pending = None; + } else if stock.identity() != self.identity { + // A preceding commit may already have been acknowledged by a + // call whose planning query was then interrupted. + if self.started { + return Err(format!( + "operation {}: the stock changed during planning; replan against the replacement stock", + self.outside.operation + )); + } + let scan = Self::scan( + stock, + self.report.authored_top_z_mm, + self.ceiling, + &self.outside, + cancel, + )?; + let needed = Self::planning_top(self.report.authored_top_z_mm, scan.reachable); + if needed > self.planned { + return Err(format!( + "operation {}: the stock changed after planning: stock up to Z{needed} where the cutter reaches stands above Z{}, the top the depths were planned from; plan the operation again against this stock", + self.outside.operation, self.planned + )); } - self.identity = stock.identity(); + self.outside.highest = scan.tall; } + self.identity = stock.identity(); stock.request_sweep_receipts(); Ok(()) } + pub(crate) fn expect_commit(&mut self, motion: &Motion) { + self.started = true; + self.pending = Some(motion.clone()); + } /// Refuse a planned motion that leaves the proven centre set below the /// remaining stock (or goes below the operation's lowest tip there). pub(crate) fn admit(&self, motion: &Motion) -> Result<(), String> { @@ -2798,9 +2830,6 @@ impl PocketPlan { // Up to the motion before this one; the call that ends the plan // (it returns no motion) has them all. self.report.entry_proofs_unresolved = self.entry_proofs_unresolved(); - if let Some(bound) = &mut self.stock_top { - bound.validate(stock, cancel)?; - } if self.operation.rest_tolerance_mm.is_some() || self.operation.entry.is_some() || self.report.empty_cuts.is_some() @@ -2823,6 +2852,9 @@ impl PocketPlan { self.report.rest_through_generation = Some(stock.generation()); } } + if let Some(bound) = &mut self.stock_top { + bound.validate(stock, cancel)?; + } if let Some(tool) = &self.rest_tool { // Skipped pieces and queued links assume every preceding emitted // move was fully committed to this stock with this cutter. A mere @@ -2846,8 +2878,9 @@ impl PocketPlan { self.rest_stock_identity.get_or_insert(stock.identity()); } let result = self.next_with_stock(Some(stock), cancel)?; - if let (Some(bound), Some(motion)) = (&self.stock_top, &result) { + if let (Some(bound), Some(motion)) = (&mut self.stock_top, &result) { bound.admit(motion)?; + bound.expect_commit(motion); } if self.rest_tool.is_some() && let Some(motion) = &result @@ -3401,8 +3434,20 @@ mod stock_top_tests { let stock = walled(); let (spec, bound) = StockTop::prepare(&stock, 8., 1e-5, &scope, &|| false).unwrap(); assert_eq!(spec.max_mm[2], 8.); - let bound = bound.unwrap(); + let mut bound = bound.unwrap(); assert_eq!(bound.report.outside_upper_z_mm, Some(60.)); + // A pre-motion replacement with no wall, but reachable stock above + // the planning top, must not erase the original stock's wall guard. + let mut replacement = stock.snapshot(); + for cell in &mut replacement.cells { + cell.lower_mm = 8.; + cell.upper_mm = 8.; + } + replacement.cells[40 * 120 + 30].upper_mm = 8.0001; + let replacement = Stock::from_snapshot(replacement).unwrap(); + let error = bound.validate(&replacement, &|| false).unwrap_err(); + assert!(error.contains("stock changed after planning"), "{error}"); + bound.validate(&stock, &|| false).unwrap(); // Inside the centre set (3 mm in from the edge) at any planned depth. bound .admit(&motion(MoveKind::Cut, [13., 13., 4.], [19., 27., 4.])) @@ -3428,5 +3473,25 @@ mod stock_top_tests { "{error}" ); } + // The caller may be interrupted after validating a full commit, + // but before asking the bound to record the next motion. + let mut stock = stock; + let cut = motion(MoveKind::Cut, [13., 13., 4.], [19., 27., 4.]); + bound.expect_commit(&cut); + let delta = stock + .preview_sweep( + &t.prepare().unwrap(), + &cut, + 1., + crate::stock::SweepOptions::default(), + &|| false, + ) + .unwrap(); + stock.apply_delta(&delta).unwrap(); + bound.validate(&stock, &|| false).unwrap(); + let restored = Stock::from_snapshot(stock.snapshot()).unwrap(); + let error = bound.validate(&restored, &|| false).unwrap_err(); + assert!(error.contains("stock changed during planning"), "{error}"); + bound.validate(&stock, &|| false).unwrap(); } } diff --git a/src/pocket_front.rs b/src/pocket_front.rs index ad43c3b1..5e73a28b 100644 --- a/src/pocket_front.rs +++ b/src/pocket_front.rs @@ -357,6 +357,10 @@ impl PocketFrontPlan { self.report.layers[layer].tip_z_mm ) })? { + if let Some(bound) = &mut self.stock_top { + bound.admit(&m)?; + bound.expect_commit(&m); + } self.report.stock_edge_entries += plan.report().stock_edge_entries - before.0; self.report.helical_entries += plan.report().helical_entries - before.1; self.report.ramp_entries += plan.report().ramp_entries - before.2; @@ -368,9 +372,6 @@ impl PocketFrontPlan { .map_or(angle, |a| a.max(angle)), ); } - if let Some(bound) = &self.stock_top { - bound.admit(&m)?; - } self.position = m.curve.end(); self.next_id = m.id + 1; self.generation = Some(stock.generation() + 1); diff --git a/tests/pocket_top.rs b/tests/pocket_top.rs index 43215f3c..0b8ef3bf 100644 --- a/tests/pocket_top.rs +++ b/tests/pocket_top.rs @@ -390,3 +390,80 @@ fn a_floor_above_the_authored_top_is_refused_on_stock_in_the_band() { ); } } + +#[test] +fn lower_top_requires_the_planned_sweep_before_advancing_to_the_next_layer() { + let m = fixture(); + for adaptive in [false, true] { + let mut stock = Stock::new(m.stock.height().unwrap().clone()).unwrap(); + let blank = stock.snapshot(); + let mut plan = OperationPlan::prepare_with_stock( + band_operation(9.9, adaptive, |_| ()), + &m.tools[0], + &stock, + m.initial_position_mm, + 1, + &|| false, + ) + .unwrap(); + // Stop during the entry into the second level, with moves still queued. + for _ in 0..1000 { + let motion = plan.next_motion_with_stock(&stock, &|| false).unwrap().unwrap(); + let z = motion.curve.end()[2]; + if z < 8.9 && motion.kind.cuts() { + let mut restored = blank.clone(); + restored.generation = stock.generation() + 1; + let foreign = Stock::from_snapshot(restored).unwrap(); + let err = plan.next_motion_with_stock(&foreign, &|| false).unwrap_err(); + assert!(err.contains("commit the complete preceding motion"), "{err}"); + + let mut partial = stock.clone(); + let delta = partial.preview_sweep( + &m.tools[0].prepare().unwrap(), &motion, 0.5, SweepOptions::default(), &|| false, + ).unwrap(); + partial.apply_delta(&delta).unwrap(); + let err = plan.next_motion_with_stock(&partial, &|| false).unwrap_err(); + assert!(err.contains("commit the complete preceding motion"), "{err}"); + + commit(&mut stock, &motion, &m); + assert!(plan.next_motion_with_stock(&stock, &|| false).unwrap().is_some()); + break; + } + commit(&mut stock, &motion, &m); + assert!(motion.id < 1000, "did not reach the second level"); + } + } +} + +#[test] +fn stock_in_the_gap_between_pockets_does_not_raise_the_planning_top() { + let m = fixture(); + let mut low = Stock::new(m.stock.height().unwrap().clone()).unwrap().snapshot(); + for cell in &mut low.cells { + cell.lower_mm = 9.9; + cell.upper_mm = 9.9; + } + let mut raised = low.clone(); + raised.cells[48 * 160 + 80].upper_mm = 10.; + let low = Stock::from_snapshot(low).unwrap(); + let raised = Stock::from_snapshot(raised).unwrap(); + let op = band_operation(9.9, true, |p| { + p.region.components[0].outer.vertices = + vec![[1., 1., 0.], [12., 1., 0.], [12., 22., 0.], [1., 22., 0.]]; + let mut second = p.region.components[0].clone(); + for vertex in &mut second.outer.vertices { + vertex[0] += 26.; + } + p.region.components.push(second); + }); + let prepare = |stock| { + OperationPlan::prepare_with_stock( + op.clone(), &m.tools[0], stock, m.initial_position_mm, 1, &|| false, + ) + .unwrap() + }; + let report = serde_json::to_value(prepare(&raised).report()).unwrap(); + assert_eq!(report["stock_top"]["maximum_upper_z_mm"], 10.); + assert!(report["stock_top"].get("reachable_upper_z_mm").is_none()); + assert!(prepare(&low).next_motion_with_stock(&raised, &|| false).unwrap().is_some()); +} From cd68ed819bd7d9b0fafad52f6e77851303fa31ac Mon Sep 17 00:00:00 2001 From: Wookie1 <6943491+Wookie1@users.noreply.github.com> Date: Fri, 20 Nov 2026 16:04:45 +0000 Subject: [PATCH 15/17] Restore the L-pocket sweep helper the corner-cap test uses (#190) #348's corner-cap test asserts every cut stays inside the L pocket with assert_entire_l_sweep, which this branch had removed with the orbit planner tests. The helper is planner-independent; it is restored as on main. --- tests/adaptive.rs | 69 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/tests/adaptive.rs b/tests/adaptive.rs index 42edd960..5ec6dde9 100644 --- a/tests/adaptive.rs +++ b/tests/adaptive.rs @@ -148,6 +148,75 @@ fn leading_contact_check_reads_a_cut_after_a_lead_whatever_the_lead_split() { } } +fn notch_clearance(p: [f64; 2]) -> f64 { + (11. - p[0]).max(0.).hypot((11. - p[1]).max(0.)) +} +fn l_clearance(p: [f64; 2]) -> f64 { + (p[0] - 3.) + .min(p[1] - 3.) + .min(23. - p[0]) + .min(23. - p[1]) + .min(notch_clearance(p)) +} +fn assert_entire_l_sweep(c: &Curve, r: f64) { + let a = c.start(); + let b = c.end(); + let mut points = vec![[a[0], a[1]], [b[0], b[1]]]; + match *c { + Curve::Line { .. } => { + let d = [b[0] - a[0], b[1] - a[1]]; + let l = d[0] * d[0] + d[1] * d[1]; + let mut ts = vec![]; + if l > 0. { + ts.push(((11. - a[0]) * d[0] + (11. - a[1]) * d[1]) / l); + } + for k in 0..2 { + if d[k] != 0. { + ts.push((11. - a[k]) / d[k]); + } + } + points.extend( + ts.into_iter() + .filter(|t| (0. ..=1.).contains(t)) + .map(|t| [a[0] + t * d[0], a[1] + t * d[1]]), + ); + } + Curve::Arc { + center, sweep_rad, .. + } => { + let rho = dist([a[0], a[1]], [center[0], center[1]]); + let start = (a[1] - center[1]).atan2(a[0] - center[0]); + let mut angles = vec![ + 0., + PI / 2., + PI, + 3. * PI / 2., + (11. - center[1]).atan2(11. - center[0]), + ]; + let x = (11. - center[0]) / rho; + if x.abs() <= 1. { + angles.extend([x.acos(), -x.acos()]); + } + let y = (11. - center[1]) / rho; + if y.abs() <= 1. { + angles.extend([y.asin(), PI - y.asin()]); + } + points.extend( + angles + .into_iter() + .filter(|x| angle_on(*x, start, sweep_rad)) + .map(|x| [center[0] + rho * x.cos(), center[1] + rho * x.sin()]), + ); + } + _ => panic!("unexpected helix"), + } + for p in points { + assert!( + l_clearance(p) >= r - 1e-7, + "whole L sweep exits at{p:?}: {c:?}" + ); + } +} fn dist(a: [f64; 2], b: [f64; 2]) -> f64 { (a[0] - b[0]).hypot(a[1] - b[1]) } 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 16/17] 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) From f9ce3f0544364ce3406f14d6b2f3ff50825b7c94 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 17/17] Reach fractional pocket floors and record faced-stock benchmark depths --- bench/expectations/rest-pocket.json | 44 ++++++++++++++--------------- src/pocket_front.rs | 2 +- tests/pocket_top.rs | 25 ++++++++++++++++ 3 files changed, 48 insertions(+), 23 deletions(-) diff --git a/bench/expectations/rest-pocket.json b/bench/expectations/rest-pocket.json index 300c2aec..93bdbd6b 100644 --- a/bench/expectations/rest-pocket.json +++ b/bench/expectations/rest-pocket.json @@ -14,33 +14,33 @@ "retracts": 1 }, "pocket": { - "air_cut_mm": 7.999, - "cut_mm": 99.328, - "cycle_seconds_exact_stop": 16.66, - "cycle_seconds_tangent": 16.66, - "link_mm": 5.333, - "moves": 30, - "plunges": 4, - "rapid_mm": 44.26, + "air_cut_mm": 11.999, + "cut_mm": 149.991, + "cycle_seconds_exact_stop": 25.322, + "cycle_seconds_tangent": 25.322, + "link_mm": 7.999, + "moves": 45, + "plunges": 6, + "rapid_mm": 61.789, "removed_mm3": 124.0, - "retracts": 4 + "retracts": 6 }, "rest": { - "air_cut_mm": 116.994, - "cut_mm": 206.49, - "cycle_seconds_exact_stop": 26.343, - "cycle_seconds_tangent": 26.103, - "link_mm": 82.496, - "moves": 82, - "plunges": 4, - "rapid_mm": 36.804, + "air_cut_mm": 175.491, + "cut_mm": 310.735, + "cycle_seconds_exact_stop": 39.917, + "cycle_seconds_tangent": 39.557, + "link_mm": 123.743, + "moves": 123, + "plunges": 6, + "rapid_mm": 55.803, "removed_mm3": 2.0, - "retracts": 8 + "retracts": 12 } }, "toolpath": { - "cycle_seconds_exact_stop": 69.862, - "cycle_seconds_tangent": 69.622, + "cycle_seconds_exact_stop": 92.098, + "cycle_seconds_tangent": 91.738, "material": { "leftover_mm3": [ 0.0, @@ -51,8 +51,8 @@ 66.004 ] }, - "moves": 130, + "moves": 186, "post_error": null, - "posted_blocks": 169 + "posted_blocks": 225 } } diff --git a/src/pocket_front.rs b/src/pocket_front.rs index 4764b058..2d9755d3 100644 --- a/src/pocket_front.rs +++ b/src/pocket_front.rs @@ -162,7 +162,7 @@ impl PocketFrontPlan { }); let climb = op.cutting_sense.unwrap_or(CuttingSense::Climb) == CuttingSense::Climb; let guard = 16. * pocket.tolerance_mm; - let levels = ((pocket.top_z_mm - floor) / pocket.stepdown_mm - 1e-9) + let levels = ((pocket.top_z_mm - floor) / pocket.stepdown_mm) .ceil() .max(1.) as usize; let mut plans = VecDeque::new(); diff --git a/tests/pocket_top.rs b/tests/pocket_top.rs index 4ac8f122..4bb1dadc 100644 --- a/tests/pocket_top.rs +++ b/tests/pocket_top.rs @@ -320,6 +320,31 @@ fn top_inside_the_tolerance_band_never_cuts_deeper_than_a_stepdown() { } } +#[test] +fn adaptive_last_level_reaches_the_floor_for_a_fractional_final_step() { + let m = fixture(); + let stock = Stock::new(m.stock.height().unwrap().clone()).unwrap(); + let floor = 8. - 5e-10; + let op = band_operation(10., true, |p| p.floor_z_mm = floor); + let plan = OperationPlan::prepare_with_stock( + op, + &m.tools[0], + &stock, + m.initial_position_mm, + 1, + &|| false, + ) + .unwrap(); + let report = serde_json::to_value(plan.report()).unwrap(); + let tips: Vec<_> = report["layers"] + .as_array() + .unwrap() + .iter() + .map(|layer| layer["tip_z_mm"].as_f64().unwrap()) + .collect(); + assert_eq!(tips, [9., 8., floor]); +} + fn band_operation(top: f64, adaptive: bool, edit: impl Fn(&mut PocketOperation)) -> Operation { let mut op = operation(top, adaptive); let pocket = match &mut op {