1use crate::{KernelRefusal, KernelStage, OrRefuse};
2use super::*;
3
4pub(super) struct RimPiece {
6 pub(super) face_id: u64,
7 pub(super) loop_index: usize,
8 pub(super) window: [f64; 2],
10 pub(super) edge_id: u64,
11}
12
13pub fn blend_smooth_chain(
19 solid: &BrepSolid,
20 seed_edge_id: u64,
21 radius: f64,
22 chamfer: bool,
23 name: Option<&str>,
24) -> Result<BrepSolid, KernelRefusal> {
25 let _operation = crate::blend::BlendOperation::enter();
28 if !(radius > 0.0) || !radius.is_finite() {
29 return Err(KernelRefusal::input(KernelStage::Collect, "radius", "blend: radius must be positive"));
30 }
31 let chain = collect_smooth_chain(solid, seed_edge_id)?;
32 if chain.segments.len() < 2 {
33 return Err(KernelRefusal::internal(KernelStage::Refine, "chain_single_segment", "blend: chain collapsed to a single segment"));
34 }
35 if chain.closed {
36 blend_closed_smooth_chain(solid, &chain.segments, radius, chamfer, name)
37 } else {
38 blend_open_smooth_chain(solid, &chain, radius, chamfer, name)
39 }
40}
41
42pub fn blend_smooth_chain_if_closed(
49 solid: &BrepSolid,
50 seed_edge_id: u64,
51 radius: f64,
52 chamfer: bool,
53 name: Option<&str>,
54) -> Result<BrepSolid, KernelRefusal> {
55 let _operation = crate::blend::BlendOperation::enter();
58 if !(radius > 0.0) || !radius.is_finite() {
59 return Err(KernelRefusal::input(KernelStage::Collect, "radius", "blend: radius must be positive"));
60 }
61 let chain = collect_smooth_chain(solid, seed_edge_id)?;
62 if chain.segments.len() < 2 {
63 return Err(KernelRefusal::internal(KernelStage::Refine, "chain_single_segment", "blend: chain collapsed to a single segment"));
64 }
65 if !chain.closed {
66 return Err(
67 KernelRefusal::unsupported(KernelStage::Classify, "open_tangent_chain", "blend: the edge is one arc of an OPEN tangent chain; the unselected \
68 continuation is capped, not blended"),
69 );
70 }
71 blend_closed_smooth_chain(solid, &chain.segments, radius, chamfer, name)
72}
73
74fn blend_closed_smooth_chain(
85 solid: &BrepSolid,
86 segments: &[ChainSegment<'_>],
87 radius: f64,
88 chamfer: bool,
89 name: Option<&str>,
90) -> Result<BrepSolid, KernelRefusal> {
91 let bar = crate::KernelTolerances::for_solid(solid, 1e-7).intersection_fit;
92 let mut budget = ChainBudget::for_chain(segments, CHAIN_PER_SEGMENT)?;
95 let first = loop {
96 let per_segment = budget.rung;
97 let rung = build_closed_smooth_chain(
98 solid,
99 segments,
100 radius,
101 chamfer,
102 name,
103 &budget,
104 FoldPolicy::Refuse,
105 bar,
106 );
107 match rung {
108 Ok(Rung::TooCoarse { deviation }) => {
109 crate::blend::carve::carve_trace(format_args!(
110 "blend chain: {} leaves the rails \
111 {deviation:.6e} from the rolling ball, against {bar:.3e}",
112 budget.describe()
113 ));
114 if budget.largest() * 2 > CHAIN_CARVE_MAX_PER_SEGMENT {
115 return Err(KernelRefusal::non_convergence(KernelStage::Refine, "chain_ladder_top", format!(
116 "blend: at {per_segment} stations per segment — the top of the chain's \
117 ladder — this collar's fitted rails are still {deviation:.6e} from the \
118 rolling ball's own contacts against a bar of {bar:.3e}, so there is no \
119 wall accurate enough to build"
120 )));
121 }
122 budget = budget.doubled();
123 }
124 Ok(Rung::StationFailed(failure)) => {
129 crate::blend::carve::carve_trace(format_args!(
130 "blend chain: {per_segment} stations per segment: segment {} position {} \
131 (t {:.9}) continued from position {} (t {:.9}, seed {:?}) did not converge: {}",
132 failure.segment, failure.position, failure.t, failure.from_position,
133 failure.from_t, failure.seed_uv, failure.error
134 ));
135 if budget.largest() * 2 > CHAIN_CARVE_MAX_PER_SEGMENT {
136 break Err(failure.error);
137 }
138 budget = budget.doubled();
139 }
140 other => break other,
141 }
142 };
143 if let Err(error) = &first {
144 crate::blend::carve::carve_trace(format_args!(
145 "blend chain: the march at {} refused: {error}", budget.describe()
146 ));
147 }
148 match first {
149 Ok(Rung::Built(built)) => Ok(built),
150 Ok(Rung::TooCoarse { .. }) | Ok(Rung::StationFailed(_)) => {
151 Err(KernelRefusal::internal(KernelStage::Refine, "chain_ladder_rung", "blend: the chain ladder left an accuracy rung unhandled"))
152 }
153 Err(error) if crate::blend::fold::is_rail_fold(&error) => Err(error),
159 Err(error) if crate::blend::is_wall_fold(&error) && !chamfer => {
162 carve_ladder(solid, segments, radius, name, bar)
163 .map_err(|carve_error| {
171 if crate::blend::is_wall_fold(&carve_error) {
172 carve_error
173 } else {
174 crate::blend::fold::wall_fold_refusal(
175 Vec::new(),
176 format!(
177 "{} {} fits this edge: the wall folds, and the fold band could not \
178 be carved — {carve_error}",
179 crate::blend::WALL_FOLDS,
180 radius.abs()
181 ),
182 )
183 }
184 })
185 }
186 Err(error) => Err(error),
187 }
188}
189
190fn carve_ladder(
200 solid: &BrepSolid,
201 segments: &[ChainSegment<'_>],
202 radius: f64,
203 name: Option<&str>,
204 bar: f64,
205) -> Result<BrepSolid, KernelRefusal> {
206 let mut budget = ChainBudget::for_chain(segments, CHAIN_PER_SEGMENT)?;
207 loop {
208 let per_segment = budget.rung;
209 match build_closed_smooth_chain(
210 solid,
211 segments,
212 radius,
213 false,
214 name,
215 &budget,
216 FoldPolicy::Carve,
217 bar,
218 )? {
219 Rung::Built(built) => {
220 crate::blend::carve::carve_trace(format_args!(
221 "blend carve: {} is the first rung inside \
222 {bar:.3e}",
223 budget.describe()
224 ));
225 return Ok(built);
226 }
227 Rung::StationFailed(failure) => return Err(failure.error),
230 Rung::TooCoarse { deviation } => {
231 crate::blend::carve::carve_trace(format_args!(
232 "blend carve: {} leaves the rails \
233 {deviation:.6e} from the rolling ball, against {bar:.3e}",
234 budget.describe()
235 ));
236 if budget.largest() * 2 > CHAIN_CARVE_MAX_PER_SEGMENT {
237 return Err(crate::blend::fold::wall_fold_refusal(
238 Vec::new(),
239 format!(
240 "{} {} fits this edge: the wall folds, and at {per_segment} stations \
241 per segment — the top of the carve's ladder — its fitted rails are \
242 still {deviation:.6e} from the rolling ball's own contacts against a \
243 bar of {bar:.3e}, so there is no wall accurate enough to carve",
244 crate::blend::WALL_FOLDS,
245 radius.abs()
246 ),
247 ));
248 }
249 budget = budget.doubled();
250 }
251 }
252 }
253}
254
255enum Rung {
258 Built(BrepSolid),
259 TooCoarse { deviation: f64 },
260 StationFailed(ChainStationFailure),
263}
264
265fn rail_deviation(
289 samples: &[ChainSample],
290 cr: &NurbsCurve,
291 cs: &NurbsCurve,
292 fit_low: f64,
293 fit_range: f64,
294 budget: &ChainBudget,
295 bar: f64,
296) -> Result<(f64, Vec<usize>), KernelRefusal> {
297 let mut order: Vec<usize> = (0..samples.len())
301 .filter(|&index| (0..=budget.count(samples[index].segment) as isize).contains(&samples[index].position))
302 .collect();
303 order.sort_by(|&a, &b| {
304 let (a, b) = (&samples[a], &samples[b]);
305 a.segment.cmp(&b.segment).then(a.position.cmp(&b.position)).then(a.offset.total_cmp(&b.offset))
306 });
307 let next_of: std::collections::HashMap<usize, f64> = order
308 .windows(2)
309 .filter(|pair| samples[pair[0]].segment == samples[pair[1]].segment)
310 .map(|pair| (pair[0], samples[pair[1]].parameter))
311 .collect();
312 let mut failing = Vec::new();
313 let closest = closest_on_rail;
314 let mut worst: f64 = 0.0;
315 let mut per_segment_worst: Vec<(f64, isize, f64, f64, Vec3, Vec3)> = Vec::new();
318 for &index in &order {
319 let sample = &samples[index];
320 let Some([p1, p2]) = sample.midpoint else {
321 continue;
322 };
323 let Some(&next) = next_of.get(&index) else {
324 continue;
325 };
326 let global = (0.5 * (sample.parameter + next)).rem_euclid(1.0);
327 let seed = (global - fit_low) / fit_range;
328 let reach = (next - sample.parameter).abs() / fit_range;
329 let (miss1, miss2) = (closest(cr, p1, seed, reach)?, closest(cs, p2, seed, reach)?);
330 worst = worst.max(miss1).max(miss2);
331 if miss1.max(miss2) > bar {
332 failing.push(index);
333 }
334 if per_segment_worst.len() <= sample.segment {
335 per_segment_worst.resize(
336 sample.segment + 1,
337 (0.0, 0, 0.0, 0.0, Vec3::default(), Vec3::default()),
338 );
339 }
340 if miss1.max(miss2) >= per_segment_worst[sample.segment].0 {
341 per_segment_worst[sample.segment] = (miss1.max(miss2), sample.position, miss1, miss2, p1, p2);
342 }
343 }
344 for (segment, (miss, position, miss1, miss2, p1, p2)) in per_segment_worst.iter().enumerate() {
345 crate::blend::carve::carve_trace(format_args!(
346 " rail miss segment {segment}: worst {miss:.6e} after station {position} \
347 (cr {miss1:.6e} at ({:.6}, {:.6}, {:.6}), cs {miss2:.6e} at ({:.6}, {:.6}, {:.6}))",
348 p1.x, p1.y, p1.z, p2.x, p2.y, p2.z
349 ));
350 }
351 Ok((worst, failing))
352}
353
354const PIECE_TRACK_CEILING: usize = 4096;
358
359fn closest_on_rail(curve: &NurbsCurve, target: Vec3, seed: f64, reach: f64) -> Result<f64, KernelRefusal> {
362 let [low, high] = curve.domain().or_refuse(KernelStage::Refine, "domain")?;
363 let distance = |u: f64| -> Result<f64, KernelRefusal> {
364 Ok(curve.derivatives_extended(u, 0).or_refuse(KernelStage::Refine, "derivatives_extended")?[0].sub(target).length())
365 };
366 let mut u = seed.clamp(low, high);
367 let mut best = distance(u)?;
368 for _ in 0..40 {
369 let derivatives = curve.derivatives_extended(u, 2).or_refuse(KernelStage::Refine, "derivatives_extended")?;
370 let offset = derivatives[0].sub(target);
371 let slope = offset.dot(derivatives[1]);
372 let curvature = derivatives[1].dot(derivatives[1]) + offset.dot(derivatives[2]);
373 let mut step = if curvature > 0.0 {
376 (slope / curvature).clamp(-reach, reach)
377 } else {
378 reach.copysign(slope)
379 };
380 let mut trial = (u - step).clamp(low, high);
381 let mut trial_distance = distance(trial)?;
382 for _ in 0..30 {
383 if trial_distance < best {
384 break;
385 }
386 step *= 0.5;
387 trial = (u - step).clamp(low, high);
388 trial_distance = distance(trial)?;
389 }
390 if !(trial_distance < best) {
391 break;
392 }
393 let moved = (trial - u).abs();
394 u = trial;
395 best = trial_distance;
396 if moved < 1e-15 {
397 break;
398 }
399 }
400 Ok(best)
401}
402
403pub(super) const LOCAL_RAIL_STENCIL: usize = 16;
406
407fn rail_pair_miss(cr_miss: f64, cs_miss: f64) -> Option<f64> {
411 (cr_miss.is_finite() && cs_miss.is_finite()).then(|| cr_miss.max(cs_miss))
412}
413
414#[allow(clippy::too_many_arguments)]
420pub(super) fn dense_rail_misses(
421 contacts: &crate::blend::chain::DenseContacts,
422 samples: &[ChainSample],
423 cr: &NurbsCurve,
424 cs: &NurbsCurve,
425 low: f64,
426 range: f64,
427 wrap: bool,
428) -> Result<(Vec<(usize, f64)>, Vec<usize>), KernelRefusal> {
429 let mut readable = Vec::with_capacity(contacts.solved.len());
430 let mut unreadable = Vec::new();
431 for (left, next, fraction, p1, p2) in &contacts.solved {
432 let (from, to) = (samples[*left].parameter, samples[*next].parameter);
433 let global = from + fraction * (to - from);
437 let global = if wrap { global.rem_euclid(1.0) } else { global };
438 let seed = (global - low) / range;
439 let reach = (to - from).abs() / range;
440 let cr_miss = closest_on_rail(cr, *p1, seed, reach).unwrap_or(f64::NAN);
443 let cs_miss = closest_on_rail(cs, *p2, seed, reach).unwrap_or(f64::NAN);
444 match rail_pair_miss(cr_miss, cs_miss) {
445 Some(miss) => readable.push((*left, miss)),
446 None => unreadable.push(*left),
447 }
448 }
449 Ok((readable, unreadable))
450}
451
452pub(super) fn combine_rail_verdict(
458 halfway: (f64, Vec<usize>),
459 dense: &[(usize, f64)],
460 unsolved: &[usize],
461 bar: f64,
462) -> (f64, Vec<usize>) {
463 let (mut worst, mut failing) = halfway;
464 for &(left, miss) in dense {
465 if !miss.is_finite() {
466 failing.push(left);
467 continue;
468 }
469 if miss > bar {
470 failing.push(left);
471 }
472 worst = worst.max(miss);
473 }
474 failing.extend_from_slice(unsolved);
475 failing.sort_unstable();
476 failing.dedup();
477 (worst, failing)
478}
479
480pub(super) fn model_rounds_limit() -> usize {
487 REFINE_ROUNDS
488}
489
490pub(super) fn model_request_on() -> bool {
491 wall_verdict_on()
492}
493
494
495pub(super) fn wall_verdict_on() -> bool {
498 true
499}
500
501
502
503
504
505pub(super) const WALL_SECTION_PROBES: usize = 8;
508
509pub(in crate::blend) fn sweep_residual(p: Vec3, nodes: &[Vec3], j: usize, radius: f64) -> Option<f64> {
530 let j = locate_foot(p, nodes, j, radius)?;
531 sweep_residual_on(p, nodes, (j - 1).min(nodes.len() - 4), j, radius)
532}
533
534const FOOT_TRAVEL: usize = 4;
537
538fn locate_foot(p: Vec3, nodes: &[Vec3], j: usize, radius: f64) -> Option<usize> {
548 let n = nodes.len();
549 if n < 4 || j == 0 || j + 1 >= n {
550 return None;
551 }
552 let mut tried: Vec<usize> = Vec::new();
553 let mut at = j;
554 loop {
555 let base = (at - 1).min(n - 4);
556 match stencil_solve(p, nodes, base, at, radius) {
557 Solve::Read(_) => return Some(at),
558 Solve::Unread => return None,
559 Solve::Window(s) => {
560 tried.push(at);
561 let next = (base as f64 + s).round();
562 let next = if next.is_finite() { next.clamp(1.0, (n - 2) as f64) as usize } else { at };
563 if tried.contains(&next) || next.abs_diff(j) > FOOT_TRAVEL {
564 wall_decline(|| format!(
565 "foot search from node {j} of {n}: tried {tried:?}, next {next} ({})",
566 if tried.contains(&next) { "already tried" } else { "beyond FOOT_TRAVEL" }
567 ));
568 return None;
569 }
570 at = next;
571 }
572 }
573 }
574}
575
576fn sweep_residual_on(p: Vec3, nodes: &[Vec3], base: usize, j: usize, radius: f64) -> Option<f64> {
579 match stencil_solve(p, nodes, base, j, radius) {
580 Solve::Read(distance) => Some(distance),
581 Solve::Window(_) | Solve::Unread => None,
582 }
583}
584
585enum Solve {
588 Read(f64),
589 Window(f64),
590 Unread,
591}
592
593thread_local! {
594 static WALL_DECLINES: std::cell::RefCell<Option<Vec<String>>> = const { std::cell::RefCell::new(None) };
599}
600
601fn wall_decline(reason: impl FnOnce() -> String) {
602 WALL_DECLINES.with(|log| {
603 if let Some(lines) = log.borrow_mut().as_mut() {
604 lines.push(reason());
605 }
606 });
607}
608
609pub(in crate::blend) fn declared_wall_probe_why(p: Vec3, fine: &[Vec3], jf: usize, radius: f64) -> Result<(f64, f64), String> {
617 let previous = WALL_DECLINES.with(|log| log.replace(Some(Vec::new())));
618 let read = declared_wall_probe(p, fine, jf, radius);
619 let lines = WALL_DECLINES.with(|log| log.replace(previous)).unwrap_or_default();
620 read.ok_or_else(|| if lines.is_empty() { "declined (no inner cause recorded)".to_string() } else { lines.join(" <- ") })
621}
622
623fn stencil_solve(p: Vec3, nodes: &[Vec3], base: usize, j: usize, radius: f64) -> Solve {
624 let finite = |v: Vec3| v.x.is_finite() && v.y.is_finite() && v.z.is_finite();
625 let n = nodes.len();
626 if n < 4 || j == 0 || j + 1 >= n || base + 4 > n || !radius.is_finite() || !finite(p) || !nodes.iter().all(|&c| finite(c)) {
627 wall_decline(|| format!("stencil {n} nodes base {base} j {j}: unreadable input"));
628 return Solve::Unread;
629 }
630 let [p0, p1, p2, p3] = [nodes[base], nodes[base + 1], nodes[base + 2], nodes[base + 3]];
632 let d1 = p1.sub(p0);
633 let d2 = p2.sub(p1.scale(2.0)).add(p0).scale(0.5);
634 let d3 = p3.sub(p2.scale(3.0)).add(p1.scale(3.0)).sub(p0).scale(1.0 / 6.0);
635 let curve = |s: f64| -> (Vec3, Vec3, Vec3) {
636 let c = p0.add(d1.scale(s)).add(d2.scale(s * (s - 1.0))).add(d3.scale(s * (s - 1.0) * (s - 2.0)));
637 let c1 = d1.add(d2.scale(2.0 * s - 1.0)).add(d3.scale(3.0 * s * s - 6.0 * s + 2.0));
638 let c2 = d2.scale(2.0).add(d3.scale(6.0 * s - 6.0));
639 (c, c1, c2)
640 };
641 let start = j as f64 - base as f64;
642 let mut s = start;
643 let mut converged = false;
644 for _ in 0..50 {
645 let (c, c1, c2) = curve(s);
646 let w = c.sub(p);
647 let (g, slope) = (w.dot(c1), c1.dot(c1) + w.dot(c2));
648 if !(g.is_finite() && slope.is_finite()) || slope == 0.0 {
649 wall_decline(|| format!("stencil {n} nodes base {base} j {j}: slope {slope:e} g {g:e} at s {s}"));
650 return Solve::Unread;
651 }
652 let stationary = g.abs() <= 16.0 * f64::EPSILON * (p.length() + c.length()) * c1.length();
665 if stationary {
666 converged = true;
667 break;
668 }
669 let step = g / slope;
670 let before = s;
671 s -= step;
672 if !((s - start).abs() <= 1.0) {
673 wall_decline(|| {
674 let (c, c1, _) = curve(s);
677 let g_after = c.sub(p).dot(c1);
678 let stationary_after = g_after.abs() <= 16.0 * f64::EPSILON * (p.length() + c.length()) * c1.length();
679 format!(
680 "stencil {n} nodes base {base} j {j}: window exit s {before} -> {s} (start {start}, |s - start| - 1 = {:e}), \
681 g {g:e} -> {g_after:e}, stationary at the overshot s: {stationary_after}",
682 (s - start).abs() - 1.0
683 )
684 });
685 return if s.is_finite() { Solve::Window(s) } else { Solve::Unread };
686 }
687 if step.abs() <= 1e-14 * (1.0 + s.abs()) {
688 converged = true;
689 break;
690 }
691 }
692 if !converged {
693 wall_decline(|| format!("stencil {n} nodes base {base} j {j}: no convergence in 50 steps, s {s}"));
694 return Solve::Unread;
695 }
696 let distance = curve(s).0.sub(p).length() - radius;
697 if distance.is_finite() {
698 Solve::Read(distance)
699 } else {
700 wall_decline(|| format!("stencil {n} nodes base {base} j {j}: non-finite distance at s {s}"));
701 Solve::Unread
702 }
703}
704
705pub(in crate::blend) fn wall_probe_reading(p: Vec3, nodes: &[Vec3], j: usize, radius: f64) -> Option<(f64, f64)> {
714 let n = nodes.len();
715 if n < 5 || j == 0 || j + 1 >= n {
716 return None;
717 }
718 let j = locate_foot(p, nodes, j, radius)?;
719 let first = (j - 1).min(n - 4);
720 let second = if j >= 2 { (j - 2).min(n - 4) } else { j.min(n - 4) };
721 let second = if second == first { if first >= 1 { first - 1 } else { first + 1 } } else { second };
722 let a = sweep_residual_on(p, nodes, first, j, radius)?;
723 let b = sweep_residual_on(p, nodes, second, j, radius)?;
724 Some((a.abs().max(b.abs()), (a - b).abs()))
725}
726
727pub(in crate::blend) fn declared_wall_probe(p: Vec3, fine: &[Vec3], jf: usize, radius: f64) -> Option<(f64, f64)> {
739 if jf % 2 != 0 || fine.len() < 9 || fine.len() % 2 == 0 {
740 wall_decline(|| format!("declared reader: node {jf} of {} not an even node of an odd fine set", fine.len()));
741 return None;
742 }
743 let Some((reading, spread)) = wall_probe_reading(p, fine, jf, radius) else {
744 wall_decline(|| format!("FINE two-stencil reading at node {jf} of {}", fine.len()));
745 return None;
746 };
747 let Some(at_fine) = sweep_residual(p, fine, jf, radius) else {
748 wall_decline(|| format!("FINE sweep at node {jf} of {}", fine.len()));
749 return None;
750 };
751 let coarse: Vec<Vec3> = fine.iter().step_by(2).copied().collect();
752 let Some(at_coarse) = sweep_residual(p, &coarse, jf / 2, radius) else {
753 wall_decline(|| format!("COARSE sweep at node {} of {}", jf / 2, coarse.len()));
754 return None;
755 };
756 let uncertainty = spread.max((at_fine - at_coarse).abs());
757 uncertainty.is_finite().then_some((reading, uncertainty))
758}
759
760pub(in crate::blend) fn centre_path_node(fine: &[Vec3], fraction: f64) -> Option<usize> {
776 let n = fine.len();
777 if n < 7 || !(fraction.is_finite()) {
778 return None;
779 }
780 let mut cumulative = Vec::with_capacity(n);
781 cumulative.push(0.0_f64);
782 for pair in fine.windows(2) {
783 let step = pair[1].sub(pair[0]).length();
784 cumulative.push(cumulative.last().copied().unwrap_or(0.0) + step);
785 }
786 let total = *cumulative.last()?;
787 if !(total.is_finite() && total > 0.0) {
788 return None;
789 }
790 let target = fraction.clamp(0.0, 1.0) * total;
791 let nearest = (0..n).min_by(|&a, &b| (cumulative[a] - target).abs().total_cmp(&(cumulative[b] - target).abs()))?;
792 let even = 2 * ((nearest as f64 / 2.0).round() as usize);
793 Some(even.clamp(2, (n - 3) & !1))
794}
795
796pub(in crate::blend) fn declared_wall_probe_located_why(p: Vec3, fine: &[Vec3], jf: usize, fraction: f64, radius: f64) -> Result<(f64, f64), String> {
803 let first = match declared_wall_probe_why(p, fine, jf, radius) {
804 Ok(read) => return Ok(read),
805 Err(why) => why,
806 };
807 match centre_path_node(fine, fraction) {
808 Some(located) if located != jf => declared_wall_probe_why(p, fine, located, radius)
809 .map_err(|again| format!("{first} -- and from centre-path node {located}: {again}")),
810 _ => Err(first),
811 }
812}
813
814pub(in crate::blend) fn declared_wall_probe_located(p: Vec3, fine: &[Vec3], jf: usize, fraction: f64, radius: f64) -> Option<(f64, f64)> {
816 match declared_wall_probe(p, fine, jf, radius) {
817 Some(read) => Some(read),
818 None => match centre_path_node(fine, fraction) {
819 Some(located) if located != jf => declared_wall_probe(p, fine, located, radius),
820 _ => None,
821 },
822 }
823}
824
825pub(in crate::blend) fn declared_wall_probe_at_why(p: Vec3, fine: &[Vec3], ts: &[f64], jf: usize, radius: f64) -> Result<(f64, f64), String> {
837 if jf % 2 != 0
838 || fine.len() < 9
839 || fine.len() % 2 == 0
840 || ts.len() != fine.len()
841 || !ts.iter().all(|t| t.is_finite())
842 || !ts.windows(2).all(|pair| pair[1] > pair[0])
843 {
844 return Err(format!("native-abscissa reader: node {jf} of {} with {} finite, strictly increasing abscissae required", fine.len(), ts.len()));
845 }
846 let previous = WALL_DECLINES.with(|log| log.replace(Some(Vec::new())));
847 let read = (|| -> Option<(f64, f64)> {
848 let (reading, spread) = wall_probe_reading_at(p, fine, ts, jf, radius).or_else(|| {
849 wall_decline(|| format!("FINE two-stencil reading (native abscissae) at node {jf} of {}", fine.len()));
850 None
851 })?;
852 let at_fine = sweep_residual_at(p, fine, ts, jf, radius).or_else(|| {
853 wall_decline(|| format!("FINE sweep (native abscissae) at node {jf} of {}", fine.len()));
854 None
855 })?;
856 let coarse: Vec<Vec3> = fine.iter().step_by(2).copied().collect();
857 let coarse_ts: Vec<f64> = ts.iter().step_by(2).copied().collect();
858 let at_coarse = sweep_residual_at(p, &coarse, &coarse_ts, jf / 2, radius).or_else(|| {
859 wall_decline(|| format!("COARSE sweep (native abscissae) at node {} of {}", jf / 2, coarse.len()));
860 None
861 })?;
862 let uncertainty = spread.max((at_fine - at_coarse).abs());
863 uncertainty.is_finite().then_some((reading, uncertainty))
864 })();
865 let lines = WALL_DECLINES.with(|log| log.replace(previous)).unwrap_or_default();
866 read.ok_or_else(|| if lines.is_empty() { "declined (no inner cause recorded)".to_string() } else { lines.join(" <- ") })
867}
868
869fn wall_probe_reading_at(p: Vec3, nodes: &[Vec3], ts: &[f64], j: usize, radius: f64) -> Option<(f64, f64)> {
870 let n = nodes.len();
871 if n < 5 || j == 0 || j + 1 >= n {
872 return None;
873 }
874 let j = locate_foot_at(p, nodes, ts, j, radius)?;
875 let first = (j - 1).min(n - 4);
876 let second = if j >= 2 { (j - 2).min(n - 4) } else { j.min(n - 4) };
877 let second = if second == first { if first >= 1 { first - 1 } else { first + 1 } } else { second };
878 let a = match stencil_solve_at(p, nodes, ts, first, j, radius) { Solve::Read(distance) => distance, _ => return None };
879 let b = match stencil_solve_at(p, nodes, ts, second, j, radius) { Solve::Read(distance) => distance, _ => return None };
880 Some((a.abs().max(b.abs()), (a - b).abs()))
881}
882
883fn sweep_residual_at(p: Vec3, nodes: &[Vec3], ts: &[f64], j: usize, radius: f64) -> Option<f64> {
884 let j = locate_foot_at(p, nodes, ts, j, radius)?;
885 match stencil_solve_at(p, nodes, ts, (j - 1).min(nodes.len() - 4), j, radius) {
886 Solve::Read(distance) => Some(distance),
887 Solve::Window(_) | Solve::Unread => None,
888 }
889}
890
891fn locate_foot_at(p: Vec3, nodes: &[Vec3], ts: &[f64], j: usize, radius: f64) -> Option<usize> {
895 let n = nodes.len();
896 if n < 4 || j == 0 || j + 1 >= n {
897 return None;
898 }
899 let mut tried: Vec<usize> = Vec::new();
900 let mut at = j;
901 loop {
902 let base = (at - 1).min(n - 4);
903 match stencil_solve_at(p, nodes, ts, base, at, radius) {
904 Solve::Read(_) => return Some(at),
905 Solve::Unread => return None,
906 Solve::Window(t) => {
907 tried.push(at);
908 let nearest = (0..n).min_by(|&a, &b| (ts[a] - t).abs().total_cmp(&(ts[b] - t).abs())).unwrap_or(at);
909 let next = if t.is_finite() { nearest.clamp(1, n - 2) } else { at };
910 if tried.contains(&next) || next.abs_diff(j) > FOOT_TRAVEL {
911 wall_decline(|| format!(
912 "foot search (native abscissae) from node {j} of {n}: tried {tried:?}, next {next} ({})",
913 if tried.contains(&next) { "already tried" } else { "beyond FOOT_TRAVEL" }
914 ));
915 return None;
916 }
917 at = next;
918 }
919 }
920 }
921}
922
923fn stencil_solve_at(p: Vec3, nodes: &[Vec3], ts: &[f64], base: usize, j: usize, radius: f64) -> Solve {
928 let finite = |v: Vec3| v.x.is_finite() && v.y.is_finite() && v.z.is_finite();
929 let n = nodes.len();
930 if n < 4 || j == 0 || j + 1 >= n || base + 4 > n || ts.len() != n || !radius.is_finite() || !finite(p) || !nodes.iter().all(|&c| finite(c)) {
931 wall_decline(|| format!("native stencil {n} nodes base {base} j {j}: unreadable input"));
932 return Solve::Unread;
933 }
934 let [p0, p1, p2, p3] = [nodes[base], nodes[base + 1], nodes[base + 2], nodes[base + 3]];
935 let [t0, t1, t2, t3] = [ts[base], ts[base + 1], ts[base + 2], ts[base + 3]];
936 let d1 = p1.sub(p0).scale(1.0 / (t1 - t0));
937 let d12 = p2.sub(p1).scale(1.0 / (t2 - t1));
938 let d23 = p3.sub(p2).scale(1.0 / (t3 - t2));
939 let d2 = d12.sub(d1).scale(1.0 / (t2 - t0));
940 let d123 = d23.sub(d12).scale(1.0 / (t3 - t1));
941 let d3 = d123.sub(d2).scale(1.0 / (t3 - t0));
942 let curve = |t: f64| -> (Vec3, Vec3, Vec3) {
943 let (a, b, c) = (t - t0, t - t1, t - t2);
944 let point = p0.add(d1.scale(a)).add(d2.scale(a * b)).add(d3.scale(a * b * c));
945 let first = d1.add(d2.scale(a + b)).add(d3.scale(b * c + a * c + a * b));
946 let second = d2.scale(2.0).add(d3.scale(2.0 * (a + b + c)));
947 (point, first, second)
948 };
949 let (low, high) = (ts[j - 1], ts[j + 1]);
950 let start = ts[j];
951 let mut t = start;
952 let mut converged = false;
953 for _ in 0..50 {
954 let (c, c1, c2) = curve(t);
955 let w = c.sub(p);
956 let (g, slope) = (w.dot(c1), c1.dot(c1) + w.dot(c2));
957 if !(g.is_finite() && slope.is_finite()) || slope == 0.0 {
958 wall_decline(|| format!("native stencil {n} nodes base {base} j {j}: slope {slope:e} g {g:e} at t {t}"));
959 return Solve::Unread;
960 }
961 if g.abs() <= 16.0 * f64::EPSILON * (p.length() + c.length()) * c1.length() {
962 converged = true;
963 break;
964 }
965 let step = g / slope;
966 let before = t;
967 t -= step;
968 if !(t >= low && t <= high) {
969 wall_decline(|| format!("native stencil {n} nodes base {base} j {j}: window exit t {before} -> {t} (window [{low}, {high}])"));
970 return if t.is_finite() { Solve::Window(t) } else { Solve::Unread };
971 }
972 let node = 0.5 * (high - low);
977 if (step / node).abs() <= 1e-14 * (1.0 + ((t - t0) / node).abs()) {
978 converged = true;
979 break;
980 }
981 }
982 if !converged {
983 wall_decline(|| format!("native stencil {n} nodes base {base} j {j}: no convergence in 50 steps, t {t}"));
984 return Solve::Unread;
985 }
986 let distance = curve(t).0.sub(p).length() - radius;
987 if distance.is_finite() {
988 Solve::Read(distance)
989 } else {
990 wall_decline(|| format!("native stencil {n} nodes base {base} j {j}: non-finite distance at t {t}"));
991 Solve::Unread
992 }
993}
994
995pub(in crate::blend) fn wall_model_missing(readings: &[(usize, f64, f64, f64)], model: f64) -> Vec<usize> {
1000 readings.iter().filter(|&&(_, declared, _, _)| !(declared <= model)).map(|&(left, _, _, _)| left).collect()
1001}
1002
1003#[allow(clippy::too_many_arguments)]
1013pub(super) fn wall_interior_misses(
1014 contacts: &crate::blend::chain::DenseContacts,
1015 samples: &[ChainSample],
1016 surface: &crate::NurbsSurface,
1017 low: f64,
1018 range: f64,
1019 radius: f64,
1020 subdivisions: usize,
1021 probes: usize,
1022 wrap: bool,
1023) -> (Vec<(usize, f64, f64, f64)>, Vec<usize>) {
1024 use std::collections::BTreeMap;
1025 let mut nodes: BTreeMap<usize, (usize, Vec<Option<Vec3>>)> = BTreeMap::new();
1028 for (index, (left, next, fraction, _, _)) in contacts.solved.iter().enumerate() {
1029 let entry = nodes.entry(*left).or_insert_with(|| {
1030 let mut row = vec![None; subdivisions + 1];
1031 row[0] = Some(samples[*left].station.center);
1032 row[subdivisions] = Some(samples[*next].station.center);
1033 (*next, row)
1034 });
1035 let step = (fraction * subdivisions as f64).round() as usize;
1036 if (1..subdivisions).contains(&step) {
1037 entry.1[step] = contacts.centers.get(index).copied().flatten();
1038 }
1039 }
1040 let mut readable = Vec::new();
1041 let mut unreadable: Vec<usize> = contacts.unsolved_at.clone();
1042 for (&left, (next, row)) in &nodes {
1043 let Some(centres) = row.iter().copied().collect::<Option<Vec<Vec3>>>() else {
1044 unreadable.push(left);
1045 continue;
1046 };
1047 let (from, to) = (samples[left].parameter, samples[*next].parameter);
1048 let (mut declared, mut worst, mut spread) = (0.0_f64, 0.0_f64, 0.0_f64);
1049 let mut read = true;
1050 'probes: for step in (2..subdivisions).step_by(2) {
1051 let global = from + (step as f64 / subdivisions as f64) * (to - from);
1052 let global = if wrap { global.rem_euclid(1.0) } else { global };
1053 let u = (global - low) / range;
1054 for k in 1..probes {
1055 let v = k as f64 / probes as f64;
1056 let reading = surface.evaluate(u, v).ok().and_then(|p| {
1057 declared_wall_probe_located(p, ¢res, step, step as f64 / subdivisions as f64, radius)
1058 });
1059 match reading {
1060 Some((distance, gap)) => {
1061 declared = declared.max(distance + gap);
1062 worst = worst.max(distance);
1063 spread = spread.max(gap);
1064 }
1065 None => {
1066 read = false;
1067 break 'probes;
1068 }
1069 }
1070 }
1071 }
1072 if read {
1073 readable.push((left, declared, worst, spread));
1074 } else {
1075 unreadable.push(left);
1076 }
1077 }
1078 unreadable.sort_unstable();
1079 unreadable.dedup();
1080 (readable, unreadable)
1081}
1082
1083
1084fn build_closed_smooth_chain(
1085 solid: &BrepSolid,
1086 segments: &[ChainSegment<'_>],
1087 radius: f64,
1088 chamfer: bool,
1089 name: Option<&str>,
1090 budget: &ChainBudget,
1091 fold: FoldPolicy,
1092 bar: f64,
1093) -> Result<Rung, KernelRefusal> {
1094 let samples = match march_chain_typed(segments, radius, false, budget, fold) {
1095 Ok(samples) => samples,
1096 Err(ChainMarchError::Station(failure)) => return Ok(Rung::StationFailed(failure)),
1097 Err(ChainMarchError::Incoherent(failure)) => return Err(failure.error),
1100 Err(ChainMarchError::Other(error)) => return Err(error),
1101 };
1102 CHAIN_DEEPEST_ROUND.with(|deepest| deepest.set(0));
1103 build_closed_chain_from_samples(solid, segments, radius, chamfer, name, budget, fold, bar, samples, 0)
1104}
1105
1106
1107thread_local! {
1108 static CHAIN_DEEPEST_ROUND: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1112}
1113
1114#[allow(clippy::too_many_arguments)]
1123fn build_closed_chain_from_samples(
1124 solid: &BrepSolid,
1125 segments: &[ChainSegment<'_>],
1126 radius: f64,
1127 chamfer: bool,
1128 name: Option<&str>,
1129 budget: &ChainBudget,
1130 fold: FoldPolicy,
1131 bar: f64,
1132 mut samples: Vec<ChainSample>,
1133 round: usize,
1134) -> Result<Rung, KernelRefusal> {
1135 let per_segment = budget.rung;
1138 CHAIN_DEEPEST_ROUND.with(|deepest| deepest.set(deepest.get().max(round)));
1139
1140 let mut global: Vec<(f64, &ChainSample)> = samples
1142 .iter()
1143 .filter(|sample| (0..budget.count(sample.segment) as isize).contains(&sample.position))
1144 .map(|sample| (sample.parameter.rem_euclid(1.0), sample))
1145 .collect();
1146 global.sort_by(|a, b| a.0.total_cmp(&b.0));
1147 let count = global.len();
1148 let degree = FIT_DEGREE;
1149 let mut extended_params = Vec::new();
1150 let mut samples_cr = Vec::new();
1151 let mut samples_mid = Vec::new();
1152 let mut samples_cs = Vec::new();
1153 let mut push = |station: &Station, parameter: f64| {
1154 extended_params.push(parameter);
1155 samples_cr.push(Vec4::from_point(station.p1, 1.0));
1156 samples_cs.push(Vec4::from_point(station.p2, 1.0));
1157 samples_mid.push(Vec4 {
1158 x: station.apex.x * station.weight,
1159 y: station.apex.y * station.weight,
1160 z: station.apex.z * station.weight,
1161 w: station.weight,
1162 });
1163 };
1164 for offset in (1..=degree).rev() {
1165 let (parameter, sample) = &global[count - offset];
1166 push(&sample.station, parameter - 1.0);
1167 }
1168 for (parameter, sample) in &global {
1169 push(&sample.station, *parameter);
1170 }
1171 push(&global[0].1.station, global[0].0 + 1.0);
1174 for offset in 1..=degree {
1175 let (parameter, sample) = &global[offset];
1176 push(&sample.station, parameter + 1.0);
1177 }
1178 let low = extended_params[0];
1179 let high = *extended_params.last().unwrap();
1180 let range = high - low;
1181 let normalized: Vec<f64> = extended_params
1182 .iter()
1183 .map(|parameter| (parameter - low) / range)
1184 .collect();
1185 let seam_low = (0.0 - low) / range;
1186 let seam_high = (1.0 - low) / range;
1187 let fit_row = |row: &[Vec4]| -> Result<NurbsCurve, KernelRefusal> {
1188 let curve = fit::interpolate_homogeneous(row, degree, &normalized).or_refuse(KernelStage::Refine, "interpolate_homogeneous")?;
1189 let (_, tail) = curve.split(seam_low).or_refuse(KernelStage::Refine, "split")?;
1190 let (middle, _) = tail.split(seam_high).or_refuse(KernelStage::Refine, "split")?;
1191 Ok(middle)
1192 };
1193 let cr = fit_row(&samples_cr)?;
1194 let cs = fit_row(&samples_cs)?;
1195 let mid = if chamfer {
1196 None
1197 } else {
1198 Some(fit_row(&samples_mid)?)
1199 };
1200 let u_domain = cr.domain().or_refuse(KernelStage::Refine, "domain")?;
1201 let surface = crate::blend::rows::surface_from_rows(degree, &cr, &cs, mid.as_ref(), true)?;
1202
1203 let (halfway, halfway_failing) = rail_deviation(&samples, &cr, &cs, low, range, budget, bar)?;
1216 let stencil = if round > 0 {
1228 Some(crate::blend::chain::chain_dense_contacts(segments, radius, budget, &samples, LOCAL_RAIL_STENCIL)?)
1229 } else {
1230 None
1231 };
1232 let wall_stencil = if !chamfer && wall_verdict_on() {
1237 Some(crate::blend::chain::chain_dense_contacts(segments, radius, budget, &samples, 2 * LOCAL_RAIL_STENCIL)?)
1238 } else {
1239 None
1240 };
1241 let (mut deviation, mut failing, _stencil_reads) = if round > 0 {
1242 let contacts = stencil.as_ref().expect("the local path solves the stencil");
1243 let (dense, unreadable) = dense_rail_misses(contacts, &samples, &cr, &cs, low, range, true)?;
1244 let reads = dense.len() + unreadable.len() + contacts.unsolved;
1245 let failed_to_read: Vec<usize> = contacts.unsolved_at.iter().chain(&unreadable).copied().collect();
1246 let verdict = combine_rail_verdict((halfway, halfway_failing), &dense, &failed_to_read, bar);
1247 crate::blend::carve::carve_trace(format_args!(
1248 "blend chain local rails: rung {per_segment} round {round}: stencil verdict {:.9e} (halfway {halfway:.9e}), \
1249 {} failing interval(s), {} unsolved contact(s)",
1250 verdict.0, verdict.1.len(), contacts.unsolved
1251 ));
1252 (verdict.0, verdict.1, reads)
1253 } else {
1254 (halfway, halfway_failing, 0)
1255 };
1256 let mut _wall_worst = 0.0_f64;
1262 let mut _wall_spread = 0.0_f64;
1263 let mut wall_readings: Vec<(usize, f64, f64, f64)> = Vec::new();
1264 if let Some(contacts) = wall_stencil.as_ref() {
1265 let (wall, unreadable) =
1266 wall_interior_misses(contacts, &samples, &surface, low, range, radius, 2 * LOCAL_RAIL_STENCIL, WALL_SECTION_PROBES, true);
1267 wall_readings = wall.clone();
1268 for &(left, declared, _, uncertainty) in &wall {
1270 if declared > bar {
1271 failing.push(left);
1272 }
1273 _wall_worst = _wall_worst.max(declared);
1274 _wall_spread = _wall_spread.max(uncertainty);
1275 }
1276 failing.extend_from_slice(&unreadable);
1277 failing.sort_unstable();
1278 failing.dedup();
1279 deviation = deviation.max(_wall_worst);
1280 crate::blend::carve::carve_trace(format_args!(
1281 "blend chain wall: rung {per_segment} round {round}: wall interior worst {_wall_worst:.9e} over {} \
1282 interval(s), {} unreadable, bar {bar:.3e}",
1283 wall.len(),
1284 unreadable.len()
1285 ));
1286 }
1287 if deviation > bar || !failing.is_empty() {
1288 let in_segment = |segment: usize| {
1289 samples
1290 .iter()
1291 .filter(|sample| sample.segment == segment && (0..budget.count(segment) as isize).contains(&sample.position))
1292 .count()
1293 };
1294 let within_ceiling = (0..segments.len()).all(|segment| {
1295 in_segment(segment) + failing.iter().filter(|&&index| samples[index].segment == segment).count()
1296 <= CHAIN_CARVE_MAX_PER_SEGMENT
1297 });
1298 crate::blend::carve::carve_trace(format_args!(
1299 "blend chain local rails: rung {per_segment} round {round} stations {} failing {} \
1300 worst {deviation:.9e} bar {bar:.9e} ceiling {}",
1301 samples.len(),
1302 failing.len(),
1303 if within_ceiling { "ok" } else { "reached" }
1304 ));
1305 if fold != FoldPolicy::Refuse || round >= REFINE_ROUNDS || !within_ceiling {
1306 return Ok(Rung::TooCoarse { deviation });
1307 }
1308 CHAIN_DEEPEST_ROUND.with(|deepest| deepest.set(deepest.get().max(round + 1)));
1310 match insert_chain_stations(segments, radius, budget, &mut samples, &failing) {
1311 Ok(()) => {}
1312 Err(ChainMarchError::Station(failure)) => return Ok(Rung::StationFailed(failure)),
1313 Err(ChainMarchError::Incoherent(failure)) => {
1317 crate::blend::carve::carve_trace(format_args!(
1318 "blend chain local rails: rung {per_segment} round {round}: segment {} station \
1319 at t {:.9} does not reach its retained right neighbour: {}",
1320 failure.segment, failure.t, failure.error
1321 ));
1322 return Ok(Rung::TooCoarse { deviation });
1323 }
1324 Err(ChainMarchError::Other(error)) => return Err(error),
1325 }
1326 assign_chain_parameters(&mut samples, segments.len(), budget, false);
1327 return build_closed_chain_from_samples(
1328 solid, segments, radius, chamfer, name, budget, fold, bar, samples, round + 1,
1329 );
1330 }
1331 crate::blend::carve::carve_trace(format_args!(
1332 "blend chain: {per_segment} stations per segment leaves the rails {deviation:.6e} \
1333 from the rolling ball, inside {bar:.3e}"
1334 ));
1335 let model = crate::KernelTolerances::for_solid(solid, 1e-7).model;
1349 let stations_now = (0..segments.len())
1350 .map(|segment| {
1351 samples
1352 .iter()
1353 .filter(|sample| sample.segment == segment && (0..budget.count(segment) as isize).contains(&sample.position))
1354 .count()
1355 })
1356 .max()
1357 .unwrap_or(0);
1358 let mut unmet: Option<(f64, crate::BudgetReason)> = None;
1359 let mut request_detail: Option<String> = None;
1363 let mut request_component = crate::MeasuredComponent::Wall;
1364 let mut request_unread = 0usize;
1365 if !chamfer && fold == FoldPolicy::Refuse && model_request_on() {
1366 let wall_missing = wall_model_missing(&wall_readings, model);
1367 let (rail_dense, rail_unread) = match wall_stencil.as_ref() {
1375 Some(contacts) => dense_rail_misses(contacts, &samples, &cr, &cs, low, range, true)?,
1376 None => (Vec::new(), Vec::new()),
1377 };
1378 let rail_over: std::collections::BTreeSet<usize> =
1380 rail_dense.iter().filter(|&&(_, miss)| !(miss <= model)).map(|&(left, _)| left).collect();
1381 let rail_unread_intervals: std::collections::BTreeSet<usize> = rail_unread.iter().copied().collect();
1382 let rail_missing: Vec<usize> = rail_over.union(&rail_unread_intervals).copied().collect();
1383 let mut missing: Vec<usize> = wall_missing.iter().chain(&rail_missing).copied().collect();
1384 missing.sort_unstable();
1385 missing.dedup();
1386 if !missing.is_empty() {
1387 let wall_short = wall_readings
1389 .iter()
1390 .filter(|reading| wall_missing.contains(&reading.0))
1391 .map(|&(_, declared, _, _)| declared)
1392 .fold(0.0_f64, f64::max);
1393 let rail_short = rail_dense.iter().filter(|&&(_, miss)| !(miss <= model)).map(|&(_, miss)| miss).fold(0.0_f64, f64::max);
1394 let short = wall_short.max(rail_short);
1395 request_component = if rail_short > wall_short { crate::MeasuredComponent::Rails } else { crate::MeasuredComponent::Wall };
1396 request_unread = rail_unread_intervals.len();
1397 request_detail = Some(format!(
1398 "short of {model:.3e}: rails {rail_short:.3e} off the exact contacts over {} interval(s) ({} unread), \
1399 wall {wall_short:.3e} over {} interval(s)",
1400 rail_over.len(),
1401 rail_unread_intervals.len(),
1402 wall_missing.len()
1403 ));
1404 let within_ceiling = (0..segments.len()).all(|segment| {
1405 let present = samples
1406 .iter()
1407 .filter(|sample| sample.segment == segment && (0..budget.count(segment) as isize).contains(&sample.position))
1408 .count();
1409 present + missing.iter().filter(|&&index| samples[index].segment == segment).count()
1410 <= CHAIN_CARVE_MAX_PER_SEGMENT
1411 });
1412 crate::blend::carve::carve_trace(format_args!(
1413 "blend chain wall model: rung {per_segment} round {round}: {} interval(s) short of {model:.3e} \
1414 (worst reading + spread {short:.3e}), ceiling {}",
1415 missing.len(),
1416 if within_ceiling { "ok" } else { "reached" }
1417 ));
1418 unmet = if round >= model_rounds_limit() {
1419 Some((short, crate::BudgetReason::RoundsSpent))
1420 } else if !within_ceiling {
1421 Some((short, crate::BudgetReason::StationCeiling))
1422 } else {
1423 let mut refined = samples.clone();
1424 CHAIN_DEEPEST_ROUND.with(|deepest| deepest.set(deepest.get().max(round + 1)));
1426 match insert_chain_stations(segments, radius, budget, &mut refined, &missing) {
1427 Ok(()) => {
1428 assign_chain_parameters(&mut refined, segments.len(), budget, false);
1429 match build_closed_chain_from_samples(
1430 solid, segments, radius, chamfer, name, budget, fold, bar, refined, round + 1,
1431 ) {
1432 Ok(Rung::Built(built)) => return Ok(Rung::Built(built)),
1433 _ => Some((short, crate::BudgetReason::Rejected)),
1434 }
1435 }
1436 Err(_) => {
1437 CHAIN_DEEPEST_ROUND.with(|deepest| deepest.set(deepest.get().max(round + 1)));
1439 Some((short, crate::BudgetReason::Incoherent))
1440 }
1441 }
1442 };
1443 }
1444 }
1445 if let Some(subdivisions) = std::env::var("BREP_DEBUG_CHAIN_DENSE_RAILS").ok().and_then(|value| value.parse::<usize>().ok()) {
1450 let contacts = crate::blend::chain::chain_dense_contacts(segments, radius, budget, &samples, subdivisions.max(2))?;
1451 let mut worst = (0.0_f64, 0usize, 0isize, 0.0_f64);
1452 let mut unreadable = 0usize;
1453 for (left, next, fraction, p1, p2) in &contacts.solved {
1454 let (from, to) = (samples[*left].parameter, samples[*next].parameter);
1455 let global = (from + fraction * (to - from)).rem_euclid(1.0);
1456 let seed = (global - low) / range;
1457 let reach = (to - from).abs() / range;
1458 match rail_pair_miss(closest_on_rail(&cr, *p1, seed, reach).unwrap_or(f64::NAN), closest_on_rail(&cs, *p2, seed, reach).unwrap_or(f64::NAN)) {
1459 Some(miss) if miss > worst.0 => worst = (miss, samples[*left].segment, samples[*left].position, *fraction),
1460 Some(_) => {}
1461 None => unreadable += 1,
1462 }
1463 }
1464 eprintln!(
1465 "blend chain dense rails: rung {per_segment} round {round}: {} contacts at {subdivisions} per interval, \
1466 worst {:.9e} (halfway reading {halfway:.9e}, bar {bar:.3e}) at segment {} position {} fraction {:.4}; {} unsolved, {unreadable} unreadable",
1467 contacts.solved.len(), worst.0, worst.1, worst.2, worst.3, contacts.unsolved
1468 );
1469 }
1470 let crease = if fold == FoldPolicy::Carve {
1471 let bar = crate::KernelTolerances::for_solid(solid, 1e-7).pcurve_consistency;
1481 let Some(carved) = crate::blend::carve::trace_wall_crease(&surface, radius.abs())? else {
1482 return Err(KernelRefusal::internal(KernelStage::Refine, "carve_no_fold", format!(
1483 "blend carve: the wall re-marched at {per_segment} stations per segment carries no fold to carve, but the march at {CHAIN_PER_SEGMENT} refused one"
1484 )));
1485 };
1486 Some(crate::blend::carve::fit_crease(&surface, &carved, bar)?)
1487 } else {
1488 None
1489 };
1490
1491 let single_face = |side: usize| -> bool {
1495 let first_id = segments[0].mate(side).face.id;
1496 segments
1497 .iter()
1498 .all(|segment| segment.mate(side).face.id == first_id)
1499 };
1500 let mut whole_pcurves: [Option<NurbsCurve>; 2] = [None, None];
1501 for side in 0..2 {
1502 if !single_face(side) {
1503 continue;
1504 }
1505 let mut row = Vec::new();
1506 let select = |station: &Station| -> [f64; 2] {
1507 if side == 0 {
1508 station.uv1
1509 } else {
1510 station.uv2
1511 }
1512 };
1513 let mut push_uv = |station: &Station| {
1514 let uv = select(station);
1515 row.push(Vec4::from_point(Vec3::new(uv[0], uv[1], 0.0), 1.0));
1516 };
1517 for offset in (1..=degree).rev() {
1518 push_uv(&global[count - offset].1.station);
1519 }
1520 for (_, sample) in &global {
1521 push_uv(&sample.station);
1522 }
1523 push_uv(&global[0].1.station);
1524 for offset in 1..=degree {
1525 push_uv(&global[offset].1.station);
1526 }
1527 whole_pcurves[side] = Some(fit_row(&row)?);
1528 }
1529
1530 let mut pcurves1 = Vec::with_capacity(segments.len());
1533 let mut pcurves2 = Vec::with_capacity(segments.len());
1534 for segment in 0..segments.len() {
1535 let mut window: Vec<&ChainSample> = samples
1536 .iter()
1537 .filter(|sample| sample.segment == segment)
1538 .collect();
1539 window.sort_by(|a, b| a.parameter.total_cmp(&b.parameter));
1540 let params: Vec<f64> = window.iter().map(|sample| sample.parameter).collect();
1541 let low = params[0];
1542 let high = *params.last().unwrap();
1543 let normalized: Vec<f64> = params
1544 .iter()
1545 .map(|parameter| (parameter - low) / (high - low))
1546 .collect();
1547 let fit_uv = |select: &dyn Fn(&Station) -> [f64; 2]| -> Result<NurbsCurve, KernelRefusal> {
1548 let points: Vec<Vec4> = window
1549 .iter()
1550 .map(|sample| {
1551 let uv = select(&sample.station);
1552 Vec4::from_point(Vec3::new(uv[0], uv[1], 0.0), 1.0)
1553 })
1554 .collect();
1555 let curve = fit::interpolate_homogeneous(&points, degree, &normalized).or_refuse(KernelStage::Refine, "interpolate_homogeneous")?;
1556 Ok(curve)
1560 };
1561 pcurves1.push((low, high, fit_uv(&|station| station.uv1)?));
1562 pcurves2.push((low, high, fit_uv(&|station| station.uv2)?));
1563 }
1564
1565 let wall_surface = unmet.as_ref().map(|_| surface.clone());
1566 let built = chain_surgery(
1567 solid,
1568 segments,
1569 ChainRows {
1570 surface,
1571 cr,
1572 cs,
1573 u_domain,
1574 fit_low: low,
1575 fit_range: range,
1576 pcurves1,
1577 pcurves2,
1578 whole_pcurves,
1579 crease,
1580 },
1581 name,
1582 )?;
1583 if let (Some((residual, reason)), Some(surface)) = (unmet, wall_surface) {
1584 crate::blend::record_wall_model_report(crate::blend::WallModelReport {
1585 name: name.map(str::to_string),
1586 surface,
1587 request: model,
1588 residual,
1589 detail: request_detail,
1590 budget: crate::ApproximationBudget {
1591 reason,
1592 rounds_used: CHAIN_DEEPEST_ROUND.with(|deepest| deepest.get()).max(round),
1595 rounds_limit: model_rounds_limit(),
1596 stations: stations_now,
1597 station_limit: CHAIN_CARVE_MAX_PER_SEGMENT,
1598 mechanism: crate::BudgetMechanism::LocalRounds,
1599 measured_component: request_component,
1600 unread: request_unread,
1601 },
1602 });
1603 }
1604 Ok(Rung::Built(built))
1605}
1606
1607pub(super) struct ChainRows {
1608 pub(super) surface: NurbsSurface,
1609 pub(super) cr: NurbsCurve,
1610 pub(super) cs: NurbsCurve,
1611 pub(super) u_domain: [f64; 2],
1612 pub(super) fit_low: f64,
1616 pub(super) fit_range: f64,
1617 pub(super) pcurves1: Vec<(f64, f64, NurbsCurve)>,
1620 pub(super) pcurves2: Vec<(f64, f64, NurbsCurve)>,
1621 pub(super) whole_pcurves: [Option<NurbsCurve>; 2],
1623 pub(super) crease: Option<crate::blend::carve::CarvedCrease>,
1626}
1627
1628impl ChainRows {
1629 pub(super) fn to_global(&self, fit_parameter: f64) -> f64 {
1630 self.fit_low + fit_parameter * self.fit_range
1631 }
1632}
1633
1634pub(super) fn pcurve_portion(fitted: &(f64, f64, NurbsCurve), a: f64, b: f64) -> Result<NurbsCurve, KernelRefusal> {
1638 let (low, high, curve) = fitted;
1639 let to_local = |value: f64| {
1642 let mut best = value;
1643 for candidate in [value, value + 1.0, value - 1.0] {
1644 if candidate >= low - 1e-9 && candidate <= high + 1e-9 {
1645 best = candidate;
1646 break;
1647 }
1648 }
1649 ((best - low) / (high - low)).clamp(0.0, 1.0)
1650 };
1651 let mut local_a = to_local(a);
1652 let mut local_b = to_local(b);
1653 if local_a > local_b {
1654 std::mem::swap(&mut local_a, &mut local_b);
1655 }
1656 let epsilon = 1e-9;
1657 let (_, tail) = if local_a > epsilon {
1658 curve.split(local_a).or_refuse(KernelStage::Refine, "split")?
1659 } else {
1660 (curve.clone(), curve.clone())
1661 };
1662 let tail = if local_a > epsilon {
1663 tail
1664 } else {
1665 curve.clone()
1666 };
1667 let portion = if local_b < 1.0 - epsilon {
1668 tail.split(local_b).or_refuse(KernelStage::Refine, "split")?.0
1669 } else {
1670 tail
1671 };
1672 Ok(portion)
1673}
1674
1675pub(super) fn cross_edge_at(
1681 solid: &BrepSolid,
1682 face_before: &FaceRecord,
1683 loop_before: usize,
1684 face_after: &FaceRecord,
1685 loop_after: usize,
1686 vertex: u64,
1687 before_edge: u64,
1688 after_edge: u64,
1689) -> Result<Option<u64>, KernelRefusal> {
1690 let mut found: Option<u64> = None;
1691 let mut consider = |face: &FaceRecord, loop_index: usize| -> Result<(), KernelRefusal> {
1692 for coedge in &face.loops[loop_index].coedges {
1693 if coedge.edge_id == before_edge || coedge.edge_id == after_edge {
1694 continue;
1695 }
1696 let edge = solid
1697 .edges
1698 .iter()
1699 .find(|edge| edge.id == coedge.edge_id)
1700 .ok_or(KernelRefusal::internal(KernelStage::Refine, "missing_edge", "blend: loop references missing edge"))?;
1701 if edge.start_vertex_id == vertex || edge.end_vertex_id == vertex {
1702 if found.is_some() && found != Some(edge.id) {
1703 return Err(KernelRefusal::unsupported(KernelStage::Classify, "chain_cross_edges", "blend: multiple cross edges at a chain vertex"));
1704 }
1705 found = Some(edge.id);
1706 }
1707 }
1708 Ok(())
1709 };
1710 consider(face_before, loop_before)?;
1711 if !(face_after.id == face_before.id && loop_after == loop_before) {
1712 consider(face_after, loop_after)?;
1713 }
1714 Ok(found)
1715}
1716
1717fn nearest_seam_image(value: f64, low: f64, high: f64) -> f64 {
1720 let period = high - low;
1721 low + ((value - low) / period).round() * period
1722}
1723
1724pub(in crate::blend) fn project_piece_pcurve(
1742 piece: &NurbsCurve,
1743 surface: &NurbsSurface,
1744 start_is_crossing: bool,
1745 end_is_crossing: bool,
1746) -> Result<NurbsCurve, KernelRefusal> {
1747 project_piece_pcurve_from(piece, surface, start_is_crossing, end_is_crossing, None)
1748}
1749
1750
1751pub(in crate::blend) fn pcurve_guide<'a>(old: &'a NurbsCurve, surface: &NurbsSurface) -> Result<impl Fn(f64) -> Option<[f64; 2]> + 'a, KernelRefusal> {
1756 let [o0, o1] = old.domain().or_refuse(KernelStage::Refine, "domain")?;
1757 let (closed_u, closed_v) = surface.closed_directions().or_refuse(KernelStage::Refine, "closed_directions")?;
1758 let [u0, u1] = surface.domain_u().or_refuse(KernelStage::Refine, "domain_u")?;
1759 let [v0, v1] = surface.domain_v().or_refuse(KernelStage::Refine, "domain_v")?;
1760 let into = move |value: f64, closed: bool, low: f64, high: f64| {
1761 if closed && high > low {
1762 low + (value - low).rem_euclid(high - low)
1763 } else {
1764 value.clamp(low, high)
1765 }
1766 };
1767 Ok(move |fraction: f64| {
1768 let uv = old.evaluate(o0 + (o1 - o0) * fraction).ok()?;
1769 let seed = [into(uv.x, closed_u, u0, u1), into(uv.y, closed_v, v0, v1)];
1770 seed.iter().all(|value| value.is_finite()).then_some(seed)
1771 })
1772}
1773
1774pub(in crate::blend) fn project_piece_pcurve_from(
1784 piece: &NurbsCurve,
1785 surface: &NurbsSurface,
1786 start_is_crossing: bool,
1787 end_is_crossing: bool,
1788 guide: Option<&dyn Fn(f64) -> Option<[f64; 2]>>,
1789) -> Result<NurbsCurve, KernelRefusal> {
1790 project_piece_pcurve_within(piece, surface, start_is_crossing, end_is_crossing, guide, &[])
1791}
1792
1793pub(in crate::blend) fn project_piece_pcurve_within(
1798 piece: &NurbsCurve,
1799 surface: &NurbsSurface,
1800 start_is_crossing: bool,
1801 end_is_crossing: bool,
1802 guide: Option<&dyn Fn(f64) -> Option<[f64; 2]>>,
1803 refine_near: &[f64],
1804) -> Result<NurbsCurve, KernelRefusal> {
1805 let [u0, u1] = surface.domain_u().or_refuse(KernelStage::Refine, "domain_u")?;
1806 let [v0, v1] = surface.domain_v().or_refuse(KernelStage::Refine, "domain_v")?;
1807 let (_, closed_v) = surface.closed_directions().or_refuse(KernelStage::Refine, "closed_directions")?;
1808 let period = u1 - u0;
1809 let period_v = v1 - v0;
1810 let [d0, d1] = piece.domain().or_refuse(KernelStage::Refine, "domain")?;
1811 let dense = (8 * piece.control_points.len()).clamp(96, PIECE_TRACK_CEILING);
1819 crate::blend::record_count("count.track.piece_samples", dense as u64 + 1);
1820 let mut proj_u = Vec::with_capacity(dense + 1);
1821 let mut proj_v = Vec::with_capacity(dense + 1);
1822 let mut point3 = Vec::with_capacity(dense + 1);
1823 let mut params = Vec::with_capacity(dense + 1);
1824 let mut previous_u: Option<f64> = None;
1825 let mut previous_foot: Option<[f64; 2]> = None;
1830 let mut feet: Vec<[f64; 2]> = Vec::with_capacity(dense + 1);
1831 for section in 0..=dense {
1832 let t = d0 + (d1 - d0) * section as f64 / dense as f64;
1833 let point = piece.evaluate(t).or_refuse(KernelStage::Refine, "evaluate")?;
1834 let guide = guide.filter(|_| {
1835 true
1836 });
1837 let seeds: Vec<[f64; 2]> = guide.and_then(|guide| guide(section as f64 / dense as f64)).into_iter().chain(previous_foot).collect();
1842 let mut projection: Option<crate::projection::SurfaceProjection> = None;
1843 for seed in &seeds {
1844 let found = crate::projection::project_point_to_surface_from_seed(surface, point, *seed).or_refuse(KernelStage::Refine, "project_point_to_surface_from_seed")?;
1845 if projection.as_ref().map_or(true, |known| found.distance < known.distance) {
1846 projection = Some(found);
1847 }
1848 }
1849 let projection = match projection {
1850 Some(projection) => projection,
1851 None => crate::project_point_to_surface(surface, point).or_refuse(KernelStage::Refine, "project_point_to_surface")?,
1852 };
1853 previous_foot = Some([projection.u, projection.v]);
1854 feet.push([projection.u, projection.v]);
1855 let mut u = projection.u;
1856 if let Some(previous) = previous_u {
1857 while u - previous > period * 0.5 {
1858 u -= period;
1859 }
1860 while previous - u > period * 0.5 {
1861 u += period;
1862 }
1863 }
1864 previous_u = Some(u);
1865 proj_u.push(u);
1866 proj_v.push(projection.v);
1867 point3.push(point);
1868 params.push(section as f64 / dense as f64);
1869 }
1870 if closed_v {
1877 for index in 2..=dense {
1878 while proj_v[index] - proj_v[index - 1] > period_v * 0.5 {
1879 proj_v[index] -= period_v;
1880 }
1881 while proj_v[index - 1] - proj_v[index] > period_v * 0.5 {
1882 proj_v[index] += period_v;
1883 }
1884 }
1885 while proj_v[0] - proj_v[1] > period_v * 0.5 {
1886 proj_v[0] -= period_v;
1887 }
1888 while proj_v[1] - proj_v[0] > period_v * 0.5 {
1889 proj_v[0] += period_v;
1890 }
1891 }
1892 let mean_u: f64 = proj_u[1..dense].iter().sum::<f64>() / (dense - 1) as f64;
1895 let seam_u = if mean_u - u0 > u1 - mean_u { u1 } else { u0 };
1896 let pinned = |index: usize,
1905 neighbour: usize,
1906 proj_u: &[f64],
1907 proj_v: &[f64]|
1908 -> Result<(f64, f64), KernelRefusal> {
1909 let point = point3[index];
1910 let u_error = surface
1911 .evaluate(seam_u, proj_v[index]).or_refuse(KernelStage::Refine, "evaluate")?
1912 .sub(point)
1913 .length();
1914 if closed_v {
1915 let seam_v = nearest_seam_image(proj_v[neighbour], v0, v1);
1916 let v_error = surface
1917 .evaluate(proj_u[index], seam_v).or_refuse(KernelStage::Refine, "evaluate")?
1918 .sub(point)
1919 .length();
1920 if v_error < u_error {
1921 return Ok((proj_u[index], seam_v));
1922 }
1923 }
1924 Ok((seam_u, proj_v[index]))
1925 };
1926 if start_is_crossing {
1927 let (u, v) = pinned(0, 1, &proj_u, &proj_v)?;
1928 proj_u[0] = u;
1929 proj_v[0] = v;
1930 }
1931 if end_is_crossing {
1932 let (u, v) = pinned(dense, dense - 1, &proj_u, &proj_v)?;
1933 proj_u[dense] = u;
1934 proj_v[dense] = v;
1935 }
1936 let mut shift = 0.0;
1937 while mean_u + shift > u1 + 1e-9 {
1938 shift -= period;
1939 }
1940 while mean_u + shift < u0 - 1e-9 {
1941 shift += period;
1942 }
1943 for u in proj_u.iter_mut() {
1944 *u += shift;
1945 }
1946 if closed_v {
1947 let mean_v: f64 = proj_v[1..dense].iter().sum::<f64>() / (dense - 1) as f64;
1948 let mut shift_v = 0.0;
1949 while mean_v + shift_v > v1 + 1e-9 {
1950 shift_v -= period_v;
1951 }
1952 while mean_v + shift_v < v0 - 1e-9 {
1953 shift_v += period_v;
1954 }
1955 for v in proj_v.iter_mut() {
1956 *v += shift_v;
1957 }
1958 }
1959 let tolerance = crate::pcurve::PCURVE_REFINEMENT_TOLERANCE;
1974 let at = |fraction: f64| piece.evaluate(d0 + (d1 - d0) * fraction);
1981 let mut track = crate::blend::track_fit::Track {
1982 fractions: params,
1983 uv: proj_u.iter().zip(&proj_v).map(|(u, v)| [*u, *v]).collect(),
1984 feet,
1985 breaks: Vec::new(),
1986 };
1987 let breaks = crate::blend::track_fit::curve_breaks(piece, d0, d1, true);
1988 crate::blend::track_fit::polish_track(surface, &at, &mut track)?;
1989 crate::blend::track_fit::insert_knot_crossings(surface, &at, &mut track, &breaks)?;
1990 for &fraction in refine_near {
1991 for _ in 0..2 {
1992 let Some(index) = track.fractions.windows(2).position(|pair| pair[0] <= fraction && fraction <= pair[1]) else { break };
1993 if crate::blend::track_fit::refine_track_intervals(surface, &at, &mut track, &[index], PIECE_TRACK_CEILING)?.is_none() {
1994 break;
1995 }
1996 }
1997 }
1998 let (fit, inserted) = crate::blend::track_fit::fit_track_locally(
2005 surface,
2006 &mut track,
2007 &at,
2008 tolerance,
2009 REFINE_ROUNDS,
2010 PIECE_TRACK_CEILING,
2011 )?;
2012 if std::env::var("BREP_DEBUG_TRACK_FIT").is_ok() {
2013 eprintln!("TRACK_FIT closed-chain piece: {inserted} sample(s) inserted locally");
2014 eprintln!(
2015 "TRACK_FIT closed-chain piece: miss {:.3e} at {} samples of {} ({} breaks), on floor {}",
2016 fit.miss,
2017 fit.samples,
2018 track.fractions.len(),
2019 track.breaks.len(),
2020 fit.on_floor
2021 );
2022 if let Some(worst) = fit.worst {
2027 let parameter = d0 + (d1 - d0) * worst.fraction;
2028 let spans: Vec<[f64; 2]> = piece.knots.windows(2)
2029 .filter(|pair| pair[1] > pair[0] && pair[1] > d0 && pair[0] < d1)
2030 .map(|pair| [pair[0], pair[1]]).collect();
2031 let mean = (d1 - d0) / spans.len().max(1) as f64;
2032 let span = spans.iter().position(|pair| parameter >= pair[0] && parameter <= pair[1]);
2033 let width = span.map(|index| spans[index][1] - spans[index][0]);
2034 eprintln!(
2035 "TRACK_FIT closed-chain worst: fraction {:.9} parameter {:.9} (pinned start {start_is_crossing}, pinned end {end_is_crossing}) \
2036 knot span {:?} of {} width {:?} vs mean {:.3e}; dense bracket [{:.9}, {:.9}] (interval {})",
2037 worst.fraction, parameter, span, spans.len(), width, mean,
2038 worst.bracket[0], worst.bracket[1], worst.interval
2039 );
2040 }
2041 }
2042 if !fit.on_floor {
2049 return Err(KernelRefusal::non_convergence(KernelStage::Refine, "chain_pcurve_floor", format!(
2050 "{} a closed chain's support piece misses its pcurve by {:.3e} at {} samples, \
2051 against a floor of {tolerance:.1e}",
2052 crate::blend::PCURVE_OFF_FLOOR,
2053 fit.miss,
2054 fit.samples
2055 )));
2056 }
2057 Ok(fit.curve)
2058}