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(
91 solid: &BrepSolid,
92 segments: &[ChainSegment<'_>],
93 radius: f64,
94 chamfer: bool,
95 name: Option<&str>,
96) -> Result<BrepSolid, KernelRefusal> {
97 let mode = std::env::var("BREP_CHAIN_LADDER_MEMO");
98 let (memo_on, verify) = match mode.as_deref() {
99 Ok("0") => (false, false),
100 Ok("verify") => (true, true),
101 _ => (true, false),
102 };
103 if !memo_on {
104 return blend_closed_smooth_chain_unmemoized(solid, segments, radius, chamfer, name);
105 }
106 let bar = crate::KernelTolerances::for_solid(solid, 1e-7).intersection_fit;
107 let signed = if chain_ladder_signed_key_on() {
116 let mut signs = Vec::with_capacity(segments.len());
117 for segment in segments {
118 match crate::blend::stations::signed_radii(
119 segment.edge,
120 segment.first.face,
121 segment.first.coedge,
122 segment.second.face,
123 segment.second.coedge,
124 radius,
125 ) {
126 Ok(pair) => signs.push(pair),
127 Err(_) => return blend_closed_smooth_chain_unmemoized(solid, segments, radius, chamfer, name),
129 }
130 }
131 Some(signs)
132 } else {
133 None
134 };
135 let key = ladder_memo_key(segments, radius, chamfer, bar, signed.as_deref());
136 let cached = LADDER_MEMO.with(|memo| memo.borrow().iter().find(|(stored, _)| *stored == key).map(|(_, refusal)| refusal.clone()));
137 crate::blend::carve::carve_trace(format_args!(
138 "blend chain ladder memo: {} for segments {:?}",
139 if cached.is_some() { "hit" } else { "miss" },
140 segments
141 .iter()
142 .map(|segment| (segment.edge.id, segment.forward, segment.first.face.id, segment.second.face.id))
143 .collect::<Vec<_>>()
144 ));
145 if let (Some(refusal), false) = (&cached, verify) {
146 crate::blend::record_count("count.chain_ladder_memo.hit", 1);
147 return Err(refusal.clone());
148 }
149 let result = blend_closed_smooth_chain_unmemoized(solid, segments, radius, chamfer, name);
150 if let Some(refusal) = cached {
151 let same = matches!(&result, Err(again) if *again == refusal && format!("{again:?}") == format!("{refusal:?}"));
152 assert!(same, "chain ladder memo mismatch: cached {refusal:?}, recomputed {:?}", result.as_ref().err());
153 crate::blend::record_count("count.chain_ladder_memo.verified", 1);
154 return result;
155 }
156 if let Err(refusal) = &result {
157 if matches!(&refusal.class, crate::RefusalClass::NonConvergence { what } if what == "chain_ladder_top") {
158 LADDER_MEMO.with(|memo| {
159 let mut memo = memo.borrow_mut();
160 if memo.len() >= LADDER_MEMO_CAPACITY {
161 memo.remove(0);
162 }
163 memo.push((key, refusal.clone()));
164 });
165 }
166 }
167 result
168}
169
170fn chain_ladder_signed_key_on() -> bool {
174 switch!("BREP_CHAIN_LADDER_SIGNED_KEY", true)
175}
176
177fn chain_ladder_rotation_key_on() -> bool {
181 switch!("BREP_CHAIN_LADDER_ROTATION_KEY", true)
182}
183
184const LADDER_MEMO_CAPACITY: usize = 32;
186
187thread_local! {
188 static LADDER_MEMO: std::cell::RefCell<Vec<(Vec<u64>, KernelRefusal)>> = const { std::cell::RefCell::new(Vec::new()) };
190}
191
192fn ladder_memo_key(segments: &[ChainSegment<'_>], radius: f64, chamfer: bool, bar: f64, signed: Option<&[(f64, f64)]>) -> Vec<u64> {
194 fn curve(key: &mut Vec<u64>, curve: &NurbsCurve) {
195 key.extend([curve.degree as u64, curve.knots.len() as u64, curve.control_points.len() as u64]);
196 key.extend(curve.knots.iter().map(|knot| knot.to_bits()));
197 for point in &curve.control_points {
198 key.extend([point.x.to_bits(), point.y.to_bits(), point.z.to_bits(), point.w.to_bits()]);
199 }
200 }
201 fn face(key: &mut Vec<u64>, face: &FaceRecord, loops: bool) {
202 let surface = &face.surface;
203 key.extend([face.id, face.same_sense as u64, surface.degree_u as u64, surface.degree_v as u64]);
204 key.extend([surface.knots_u.len() as u64, surface.knots_v.len() as u64, surface.control_points.len() as u64]);
205 key.extend(surface.knots_u.iter().chain(&surface.knots_v).map(|knot| knot.to_bits()));
206 for row in &surface.control_points {
207 key.push(row.len() as u64);
208 for point in row {
209 key.extend([point.x.to_bits(), point.y.to_bits(), point.z.to_bits(), point.w.to_bits()]);
210 }
211 }
212 if !loops {
213 return;
214 }
215 key.push(face.loops.len() as u64);
216 for loop_record in &face.loops {
217 key.extend([loop_record.id, loop_record.coedges.len() as u64]);
218 for coedge in &loop_record.coedges {
219 key.extend([coedge.id, coedge.edge_id, coedge.forward as u64]);
220 curve(key, &coedge.pcurve);
221 }
222 }
223 }
224 let mut key = vec![
225 radius.to_bits(),
226 chamfer as u64,
227 bar.to_bits(),
228 crate::blend::station_refinement_on() as u64,
229 crate::blend::chain_arc_stations_on() as u64,
230 wall_verdict_on() as u64,
231 local_continue_on() as u64,
232 segments.len() as u64,
233 signed.is_some() as u64,
234 ];
235 let start = if chain_ladder_rotation_key_on() {
240 key.push(1);
241 segments.iter().enumerate().min_by_key(|(_, segment)| segment.edge.id).map_or(0, |(index, _)| index)
242 } else {
243 0
244 };
245 for index in (0..segments.len()).map(|offset| (start + offset) % segments.len()) {
246 let segment = &segments[index];
247 if let Some((rho1, rho2)) = signed.and_then(|signs| signs.get(index)) {
248 key.extend([rho1.to_bits(), rho2.to_bits()]);
249 }
250 let edge = segment.edge;
251 key.extend([edge.id, edge.start_vertex_id, edge.end_vertex_id, edge.t0.to_bits(), edge.t1.to_bits(), segment.forward as u64]);
252 curve(&mut key, &edge.curve);
253 for mate in [&segment.first, &segment.second] {
254 key.extend([mate.coedge.id, mate.coedge.edge_id, mate.coedge.forward as u64, mate.loop_index as u64, mate.rho.to_bits()]);
255 curve(&mut key, &mate.coedge.pcurve);
256 face(&mut key, mate.face, signed.is_none());
257 }
258 }
259 key
260}
261fn blend_closed_smooth_chain_unmemoized(
274 solid: &BrepSolid,
275 segments: &[ChainSegment<'_>],
276 radius: f64,
277 chamfer: bool,
278 name: Option<&str>,
279) -> Result<BrepSolid, KernelRefusal> {
280 let bar = crate::KernelTolerances::for_solid(solid, 1e-7).intersection_fit;
281 let mut budget = ChainBudget::for_chain(segments, CHAIN_PER_SEGMENT)?;
284 let mut trend: Vec<(usize, f64)> = Vec::new();
286 let first = loop {
287 let per_segment = budget.rung;
288 let rung = build_closed_smooth_chain(
289 solid,
290 segments,
291 radius,
292 chamfer,
293 name,
294 &budget,
295 FoldPolicy::Refuse,
296 bar,
297 );
298 match rung {
299 Ok(Rung::TooCoarse { deviation }) => {
300 crate::blend::carve::carve_trace(format_args!(
301 "blend chain: {} leaves the rails \
302 {deviation:.6e} from the rolling ball, against {bar:.3e}",
303 budget.describe()
304 ));
305 trend.push((per_segment, deviation));
306 if budget.largest() * 2 > CHAIN_CARVE_MAX_PER_SEGMENT {
307 let (best_rung, best, listing) = ladder_trend(&trend);
308 return Err(KernelRefusal::non_convergence(KernelStage::Refine, "chain_ladder_top", format!(
309 "blend: the chain's ladder reached its top, {per_segment} stations per segment, \
310 and no rung passed — its best, {best_rung} stations per segment, left this \
311 collar's fitted rails {best:.6e} from the rolling ball's own contacts against \
312 a bar of {bar:.3e} (rung by rung: {listing}), so there is no wall accurate \
313 enough to build"
314 )));
315 }
316 budget = budget.doubled();
317 }
318 Ok(Rung::StationFailed(failure)) => {
323 crate::blend::carve::carve_trace(format_args!(
324 "blend chain: {per_segment} stations per segment: segment {} position {} \
325 (t {:.9}) continued from position {} (t {:.9}, seed {:?}) did not converge: {}",
326 failure.segment, failure.position, failure.t, failure.from_position,
327 failure.from_t, failure.seed_uv, failure.error
328 ));
329 if budget.largest() * 2 > CHAIN_CARVE_MAX_PER_SEGMENT {
330 break Err(failure.error);
331 }
332 budget = budget.doubled();
333 }
334 other => break other,
335 }
336 };
337 if let Err(error) = &first {
338 crate::blend::carve::carve_trace(format_args!(
339 "blend chain: the march at {} refused: {error}", budget.describe()
340 ));
341 }
342 match first {
343 Ok(Rung::Built(built)) => Ok(built),
344 Ok(Rung::TooCoarse { .. }) | Ok(Rung::StationFailed(_)) => {
345 Err(KernelRefusal::internal(KernelStage::Refine, "chain_ladder_rung", "blend: the chain ladder left an accuracy rung unhandled"))
346 }
347 Err(error) if crate::blend::fold::is_rail_fold(&error) => Err(error),
353 Err(error) if crate::blend::is_wall_fold(&error) && !chamfer => {
356 carve_ladder(solid, segments, radius, name, bar)
357 .map_err(|carve_error| {
365 if crate::blend::is_wall_fold(&carve_error) {
366 carve_error
367 } else {
368 crate::blend::fold::wall_fold_refusal(
369 Vec::new(),
370 format!(
371 "{} {} fits this edge: the wall folds, and the fold band could not \
372 be carved — {carve_error}",
373 crate::blend::WALL_FOLDS,
374 radius.abs()
375 ),
376 )
377 }
378 })
379 }
380 Err(error) => Err(error),
381 }
382}
383
384fn carve_ladder(
394 solid: &BrepSolid,
395 segments: &[ChainSegment<'_>],
396 radius: f64,
397 name: Option<&str>,
398 bar: f64,
399) -> Result<BrepSolid, KernelRefusal> {
400 let mut budget = ChainBudget::for_chain(segments, CHAIN_PER_SEGMENT)?;
401 loop {
402 let per_segment = budget.rung;
403 match build_closed_smooth_chain(
404 solid,
405 segments,
406 radius,
407 false,
408 name,
409 &budget,
410 FoldPolicy::Carve,
411 bar,
412 )? {
413 Rung::Built(built) => {
414 crate::blend::carve::carve_trace(format_args!(
415 "blend carve: {} is the first rung inside \
416 {bar:.3e}",
417 budget.describe()
418 ));
419 return Ok(built);
420 }
421 Rung::StationFailed(failure) => return Err(failure.error),
424 Rung::TooCoarse { deviation } => {
425 crate::blend::carve::carve_trace(format_args!(
426 "blend carve: {} leaves the rails \
427 {deviation:.6e} from the rolling ball, against {bar:.3e}",
428 budget.describe()
429 ));
430 if budget.largest() * 2 > CHAIN_CARVE_MAX_PER_SEGMENT {
431 return Err(crate::blend::fold::wall_fold_refusal(
432 Vec::new(),
433 format!(
434 "{} {} fits this edge: the wall folds, and at {per_segment} stations \
435 per segment — the top of the carve's ladder — its fitted rails are \
436 still {deviation:.6e} from the rolling ball's own contacts against a \
437 bar of {bar:.3e}, so there is no wall accurate enough to carve",
438 crate::blend::WALL_FOLDS,
439 radius.abs()
440 ),
441 ));
442 }
443 budget = budget.doubled();
444 }
445 }
446 }
447}
448
449enum Rung {
452 Built(BrepSolid),
453 TooCoarse { deviation: f64 },
454 StationFailed(ChainStationFailure),
457}
458
459fn rail_deviation(
483 samples: &[ChainSample],
484 cr: &NurbsCurve,
485 cs: &NurbsCurve,
486 fit_low: f64,
487 fit_range: f64,
488 budget: &ChainBudget,
489 bar: f64,
490) -> Result<(f64, Vec<usize>), KernelRefusal> {
491 let mut order: Vec<usize> = (0..samples.len())
495 .filter(|&index| (0..=budget.count(samples[index].segment) as isize).contains(&samples[index].position))
496 .collect();
497 order.sort_by(|&a, &b| {
498 let (a, b) = (&samples[a], &samples[b]);
499 a.segment.cmp(&b.segment).then(a.position.cmp(&b.position)).then(a.offset.total_cmp(&b.offset))
500 });
501 let next_of: std::collections::HashMap<usize, f64> = order
502 .windows(2)
503 .filter(|pair| samples[pair[0]].segment == samples[pair[1]].segment)
504 .map(|pair| (pair[0], samples[pair[1]].parameter))
505 .collect();
506 let mut failing = Vec::new();
507 let closest = closest_on_rail;
508 let mut worst: f64 = 0.0;
509 let mut per_segment_worst: Vec<(f64, isize, f64, f64, Vec3, Vec3)> = Vec::new();
512 for &index in &order {
513 let sample = &samples[index];
514 let Some([p1, p2]) = sample.midpoint else {
515 continue;
516 };
517 let Some(&next) = next_of.get(&index) else {
518 continue;
519 };
520 let global = (0.5 * (sample.parameter + next)).rem_euclid(1.0);
521 let seed = (global - fit_low) / fit_range;
522 let reach = (next - sample.parameter).abs() / fit_range;
523 let (miss1, miss2) = (closest(cr, p1, seed, reach)?, closest(cs, p2, seed, reach)?);
524 worst = worst.max(miss1).max(miss2);
525 if miss1.max(miss2) > bar {
526 failing.push(index);
527 }
528 if per_segment_worst.len() <= sample.segment {
529 per_segment_worst.resize(
530 sample.segment + 1,
531 (0.0, 0, 0.0, 0.0, Vec3::default(), Vec3::default()),
532 );
533 }
534 if miss1.max(miss2) >= per_segment_worst[sample.segment].0 {
535 per_segment_worst[sample.segment] = (miss1.max(miss2), sample.position, miss1, miss2, p1, p2);
536 }
537 }
538 for (segment, (miss, position, miss1, miss2, p1, p2)) in per_segment_worst.iter().enumerate() {
539 crate::blend::carve::carve_trace(format_args!(
540 " rail miss segment {segment}: worst {miss:.6e} after station {position} \
541 (cr {miss1:.6e} at ({:.6}, {:.6}, {:.6}), cs {miss2:.6e} at ({:.6}, {:.6}, {:.6}))",
542 p1.x, p1.y, p1.z, p2.x, p2.y, p2.z
543 ));
544 }
545 Ok((worst, failing))
546}
547
548const PIECE_TRACK_CEILING: usize = 4096;
552
553fn closest_on_rail(curve: &NurbsCurve, target: Vec3, seed: f64, reach: f64) -> Result<f64, KernelRefusal> {
556 let [low, high] = curve.domain().or_refuse(KernelStage::Refine, "domain")?;
557 let (u, _) = crate::projection::curve_foot_newton(curve, target, seed, [low, high],
558 crate::projection::CurveFootPolicy {
559 domain: crate::projection::FootDomain::Clamp,
560 iterations: 40,
561 slope_guard: -1.0, step_limit: reach,
563 parameter_tolerance: 1e-15,
564 mode: crate::projection::FootMode::Backtracked,
565 }).or_refuse(KernelStage::Refine, "curve_foot_newton")?;
566 Ok(curve.derivatives_extended(u, 0).or_refuse(KernelStage::Refine, "derivatives_extended")?[0].sub(target).length())
567}
568
569pub(super) const LOCAL_RAIL_STENCIL: usize = 16;
572
573fn rail_pair_miss(cr_miss: f64, cs_miss: f64) -> Option<f64> {
577 (cr_miss.is_finite() && cs_miss.is_finite()).then(|| cr_miss.max(cs_miss))
578}
579
580#[allow(clippy::too_many_arguments)]
586pub(super) fn dense_rail_misses(
587 contacts: &crate::blend::chain::DenseContacts,
588 samples: &[ChainSample],
589 cr: &NurbsCurve,
590 cs: &NurbsCurve,
591 low: f64,
592 range: f64,
593 wrap: bool,
594) -> Result<(Vec<(usize, f64)>, Vec<usize>), KernelRefusal> {
595 let mut readable = Vec::with_capacity(contacts.solved.len());
596 let mut unreadable = Vec::new();
597 for (left, next, fraction, p1, p2) in &contacts.solved {
598 let (from, to) = (samples[*left].parameter, samples[*next].parameter);
599 let global = from + fraction * (to - from);
603 let global = if wrap { global.rem_euclid(1.0) } else { global };
604 let seed = (global - low) / range;
605 let reach = (to - from).abs() / range;
606 let cr_miss = closest_on_rail(cr, *p1, seed, reach).unwrap_or(f64::NAN);
609 let cs_miss = closest_on_rail(cs, *p2, seed, reach).unwrap_or(f64::NAN);
610 match rail_pair_miss(cr_miss, cs_miss) {
611 Some(miss) => readable.push((*left, miss)),
612 None => unreadable.push(*left),
613 }
614 }
615 Ok((readable, unreadable))
616}
617
618pub(super) fn combine_rail_verdict(
624 halfway: (f64, Vec<usize>),
625 dense: &[(usize, f64)],
626 unsolved: &[usize],
627 bar: f64,
628) -> (f64, Vec<usize>) {
629 let (mut worst, mut failing) = halfway;
630 for &(left, miss) in dense {
631 if !miss.is_finite() {
632 failing.push(left);
633 continue;
634 }
635 if miss > bar {
636 failing.push(left);
637 }
638 worst = worst.max(miss);
639 }
640 failing.extend_from_slice(unsolved);
641 failing.sort_unstable();
642 failing.dedup();
643 (worst, failing)
644}
645
646pub(super) fn model_rounds_limit() -> usize {
653 REFINE_ROUNDS
654}
655
656pub(super) fn model_request_on() -> bool {
657 wall_verdict_on()
658}
659
660
661pub(super) fn wall_verdict_on() -> bool {
664 true
665}
666
667
668
669
670
671pub(super) const WALL_SECTION_PROBES: usize = 8;
674
675pub(in crate::blend) fn sweep_residual(p: Vec3, nodes: &[Vec3], j: usize, radius: f64) -> Option<f64> {
696 let j = locate_foot(p, nodes, j, radius)?;
697 sweep_residual_on(p, nodes, (j - 1).min(nodes.len() - 4), j, radius)
698}
699
700const FOOT_TRAVEL: usize = 4;
703
704fn locate_foot(p: Vec3, nodes: &[Vec3], j: usize, radius: f64) -> Option<usize> {
714 locate_foot_read(p, nodes, j, radius).map(|(node, _)| node)
715}
716
717fn locate_foot_read(p: Vec3, nodes: &[Vec3], j: usize, radius: f64) -> Option<(usize, f64)> {
720 locate_foot_read_prepared(p, nodes, j, radius, None)
721}
722
723fn locate_foot_read_prepared(p: Vec3, nodes: &[Vec3], j: usize, radius: f64, prepared: Option<&StencilPreparation>) -> Option<(usize, f64)> {
724 let n = nodes.len();
725 if n < 4 || j == 0 || j + 1 >= n {
726 return None;
727 }
728 let mut tried: Vec<usize> = Vec::new();
729 let mut at = j;
730 loop {
731 let base = (at - 1).min(n - 4);
732 match stencil_solve_prepared(p, nodes, base, at, radius, prepared) {
733 Solve::Read(distance) => return Some((at, distance)),
734 Solve::Unread => return None,
735 Solve::Window(s) => {
736 tried.push(at);
737 let next = (base as f64 + s).round();
738 let next = if next.is_finite() { next.clamp(1.0, (n - 2) as f64) as usize } else { at };
739 if tried.contains(&next) || next.abs_diff(j) > FOOT_TRAVEL {
740 wall_decline(|| format!(
741 "foot search from node {j} of {n}: tried {tried:?}, next {next} ({})",
742 if tried.contains(&next) { "already tried" } else { "beyond FOOT_TRAVEL" }
743 ));
744 return None;
745 }
746 at = next;
747 }
748 }
749 }
750}
751
752fn sweep_residual_on(p: Vec3, nodes: &[Vec3], base: usize, j: usize, radius: f64) -> Option<f64> {
755 match stencil_solve(p, nodes, base, j, radius) {
756 Solve::Read(distance) => Some(distance),
757 Solve::Window(_) | Solve::Unread => None,
758 }
759}
760
761enum Solve {
764 Read(f64),
765 Window(f64),
766 Unread,
767}
768
769thread_local! {
770 static WALL_DECLINES: std::cell::RefCell<Option<Vec<String>>> = const { std::cell::RefCell::new(None) };
775}
776
777fn wall_decline(reason: impl FnOnce() -> String) {
778 WALL_DECLINES.with(|log| {
779 if let Some(lines) = log.borrow_mut().as_mut() {
780 lines.push(reason());
781 }
782 });
783}
784
785pub(in crate::blend) fn declared_wall_probe_why(p: Vec3, fine: &[Vec3], jf: usize, radius: f64) -> Result<(f64, f64), String> {
793 let previous = WALL_DECLINES.with(|log| log.replace(Some(Vec::new())));
794 let read = declared_wall_probe(p, fine, jf, radius);
795 let lines = WALL_DECLINES.with(|log| log.replace(previous)).unwrap_or_default();
796 read.ok_or_else(|| if lines.is_empty() { "declined (no inner cause recorded)".to_string() } else { lines.join(" <- ") })
797}
798
799fn stencil_solve(p: Vec3, nodes: &[Vec3], base: usize, j: usize, radius: f64) -> Solve {
800 stencil_solve_prepared(p, nodes, base, j, radius, None)
801}
802
803fn stencil_solve_prepared(p: Vec3, nodes: &[Vec3], base: usize, j: usize, radius: f64, prepared: Option<&StencilPreparation>) -> Solve {
804 let finite = |v: Vec3| v.x.is_finite() && v.y.is_finite() && v.z.is_finite();
805 let n = nodes.len();
806 if n < 4 || j == 0 || j + 1 >= n || base + 4 > n || !radius.is_finite() || !finite(p) || !prepared.map_or_else(|| wall_nodes_finite(nodes), |cache| cache.finite) {
807 wall_decline(|| format!("stencil {n} nodes base {base} j {j}: unreadable input"));
808 return Solve::Unread;
809 }
810 let [p0, d1, d2, d3] = prepared.map_or_else(|| wall_coefficients(nodes, base), |cache| cache.coefficients(nodes, base));
811 let curve = |s: f64| -> (Vec3, Vec3, Vec3) {
812 let c = p0.add(d1.scale(s)).add(d2.scale(s * (s - 1.0))).add(d3.scale(s * (s - 1.0) * (s - 2.0)));
813 let c1 = d1.add(d2.scale(2.0 * s - 1.0)).add(d3.scale(3.0 * s * s - 6.0 * s + 2.0));
814 let c2 = d2.scale(2.0).add(d3.scale(6.0 * s - 6.0));
815 (c, c1, c2)
816 };
817 let start = j as f64 - base as f64;
818 let initial = prepared.and_then(|cache| cache.start(base, j, &curve));
819 let point_length = p.length();
820 let mut s = start;
821 let mut converged = false;
822 let mut converged_point = None;
823 for iteration in 0..50 {
824 let state = if iteration == 0 { initial.unwrap_or_else(|| WallStart::new(curve(s))) }
825 else { WallStart::new(curve(s)) };
826 let (c, c1, c2) = state.curve;
827 let w = c.sub(p);
828 let (g, slope) = (w.dot(c1), state.tangent_squared + w.dot(c2));
829 if !(g.is_finite() && slope.is_finite()) || slope == 0.0 {
830 wall_decline(|| format!("stencil {n} nodes base {base} j {j}: slope {slope:e} g {g:e} at s {s}"));
831 return Solve::Unread;
832 }
833 let stationary = g.abs() <= 16.0 * f64::EPSILON * (point_length + state.point_length) * state.tangent_length;
846 if stationary {
847 converged = true;
848 converged_point = Some(c);
849 break;
850 }
851 let step = g / slope;
852 let before = s;
853 s -= step;
854 if !((s - start).abs() <= 1.0) {
855 wall_decline(|| {
856 let (c, c1, _) = curve(s);
859 let g_after = c.sub(p).dot(c1);
860 let stationary_after = g_after.abs() <= 16.0 * f64::EPSILON * (p.length() + c.length()) * c1.length();
861 format!(
862 "stencil {n} nodes base {base} j {j}: window exit s {before} -> {s} (start {start}, |s - start| - 1 = {:e}), \
863 g {g:e} -> {g_after:e}, stationary at the overshot s: {stationary_after}",
864 (s - start).abs() - 1.0
865 )
866 });
867 return if s.is_finite() { Solve::Window(s) } else { Solve::Unread };
868 }
869 if step.abs() <= 1e-14 * (1.0 + s.abs()) {
870 converged = true;
871 break;
872 }
873 }
874 if !converged {
875 wall_decline(|| format!("stencil {n} nodes base {base} j {j}: no convergence in 50 steps, s {s}"));
876 return Solve::Unread;
877 }
878 let distance = converged_point.unwrap_or_else(|| curve(s).0).sub(p).length() - radius;
879 if distance.is_finite() {
880 Solve::Read(distance)
881 } else {
882 wall_decline(|| format!("stencil {n} nodes base {base} j {j}: non-finite distance at s {s}"));
883 Solve::Unread
884 }
885}
886
887pub(in crate::blend) fn wall_probe_reading(p: Vec3, nodes: &[Vec3], j: usize, radius: f64) -> Option<(f64, f64)> {
896 let n = nodes.len();
897 if n < 5 || j == 0 || j + 1 >= n {
898 return None;
899 }
900 let j = locate_foot(p, nodes, j, radius)?;
901 let first = (j - 1).min(n - 4);
902 let second = if j >= 2 { (j - 2).min(n - 4) } else { j.min(n - 4) };
903 let second = if second == first { if first >= 1 { first - 1 } else { first + 1 } } else { second };
904 let a = sweep_residual_on(p, nodes, first, j, radius)?;
905 let b = sweep_residual_on(p, nodes, second, j, radius)?;
906 Some((a.abs().max(b.abs()), (a - b).abs()))
907}
908
909fn wall_solve_reuse_on() -> bool {
922 switch!(live "BREP_WALL_SOLVE_REUSE", true)
923}
924
925pub(in crate::blend) fn declared_wall_probe(p: Vec3, fine: &[Vec3], jf: usize, radius: f64) -> Option<(f64, f64)> {
926 declared_wall_probe_with(p, fine, jf, radius, wall_solve_reuse_on())
927}
928
929fn declared_wall_probe_with(p: Vec3, fine: &[Vec3], jf: usize, radius: f64, reuse: bool) -> Option<(f64, f64)> {
930 declared_wall_probe_prepared(p, fine, jf, radius, reuse, None)
931}
932
933fn declared_wall_probe_prepared(p: Vec3, fine: &[Vec3], jf: usize, radius: f64, reuse: bool, prepared: Option<&PreparedWall<'_>>) -> Option<(f64, f64)> {
934 if jf % 2 != 0 || fine.len() < 9 || fine.len() % 2 == 0 {
935 wall_decline(|| format!("declared reader: node {jf} of {} not an even node of an odd fine set", fine.len()));
936 return None;
937 }
938 let (reading, spread, at_fine) = if reuse {
939 let read = (|| {
940 let n = fine.len();
941 let (j, a) = locate_foot_read_prepared(p, fine, jf, radius, prepared.map(|c| &c.fine_stencils))?;
942 let first = (j - 1).min(n - 4);
943 let second = if j >= 2 { (j - 2).min(n - 4) } else { j.min(n - 4) };
944 let second = if second == first { if first >= 1 { first - 1 } else { first + 1 } } else { second };
945 let b = match stencil_solve_prepared(p, fine, second, j, radius, prepared.map(|c| &c.fine_stencils)) {
946 Solve::Read(distance) => distance,
947 _ => return None,
948 };
949 Some((a.abs().max(b.abs()), (a - b).abs(), a))
950 })();
951 let Some(read) = read else {
952 wall_decline(|| format!("FINE two-stencil reading at node {jf} of {}", fine.len()));
953 return None;
954 };
955 read
956 } else {
957 let Some((reading, spread)) = wall_probe_reading(p, fine, jf, radius) else {
958 wall_decline(|| format!("FINE two-stencil reading at node {jf} of {}", fine.len()));
959 return None;
960 };
961 let Some(at_fine) = sweep_residual(p, fine, jf, radius) else {
962 wall_decline(|| format!("FINE sweep at node {jf} of {}", fine.len()));
963 return None;
964 };
965 (reading, spread, at_fine)
966 };
967 let coarse_owned;
968 let coarse = match prepared {
969 Some(cache) => cache.coarse.as_slice(),
970 None => { coarse_owned = wall_coarse(fine); &coarse_owned }
971 };
972 let at_coarse = if reuse {
973 locate_foot_read_prepared(p, coarse, jf / 2, radius, prepared.map(|c| &c.coarse_stencils)).map(|(_, distance)| distance)
974 } else {
975 sweep_residual(p, coarse, jf / 2, radius)
976 };
977 let Some(at_coarse) = at_coarse else {
978 wall_decline(|| format!("COARSE sweep at node {} of {}", jf / 2, coarse.len()));
979 return None;
980 };
981 let uncertainty = spread.max((at_fine - at_coarse).abs());
982 uncertainty.is_finite().then_some((reading, uncertainty))
983}
984
985pub(in crate::blend) fn centre_path_node(fine: &[Vec3], fraction: f64) -> Option<usize> {
1001 let n = fine.len();
1002 if n < 7 || !(fraction.is_finite()) {
1003 return None;
1004 }
1005 let mut cumulative = Vec::with_capacity(n);
1006 cumulative.push(0.0_f64);
1007 for pair in fine.windows(2) {
1008 let step = pair[1].sub(pair[0]).length();
1009 cumulative.push(cumulative.last().copied().unwrap_or(0.0) + step);
1010 }
1011 let total = *cumulative.last()?;
1012 if !(total.is_finite() && total > 0.0) {
1013 return None;
1014 }
1015 let target = fraction.clamp(0.0, 1.0) * total;
1016 let nearest = (0..n).min_by(|&a, &b| (cumulative[a] - target).abs().total_cmp(&(cumulative[b] - target).abs()))?;
1017 let even = 2 * ((nearest as f64 / 2.0).round() as usize);
1018 Some(even.clamp(2, (n - 3) & !1))
1019}
1020
1021pub(in crate::blend) fn declared_wall_probe_located_why(p: Vec3, fine: &[Vec3], jf: usize, fraction: f64, radius: f64) -> Result<(f64, f64), String> {
1028 let first = match declared_wall_probe_why(p, fine, jf, radius) {
1029 Ok(read) => return Ok(read),
1030 Err(why) => why,
1031 };
1032 match centre_path_node(fine, fraction) {
1033 Some(located) if located != jf => declared_wall_probe_why(p, fine, located, radius)
1034 .map_err(|again| format!("{first} -- and from centre-path node {located}: {again}")),
1035 _ => Err(first),
1036 }
1037}
1038
1039pub(in crate::blend) fn declared_wall_probe_located(p: Vec3, fine: &[Vec3], jf: usize, fraction: f64, radius: f64) -> Option<(f64, f64)> {
1041 match declared_wall_probe(p, fine, jf, radius) {
1042 Some(read) => Some(read),
1043 None => match centre_path_node(fine, fraction) {
1044 Some(located) if located != jf => declared_wall_probe(p, fine, located, radius),
1045 _ => None,
1046 },
1047 }
1048}
1049
1050pub(in crate::blend) fn declared_wall_probe_at_why(p: Vec3, fine: &[Vec3], ts: &[f64], jf: usize, radius: f64) -> Result<(f64, f64), String> {
1062 if jf % 2 != 0
1063 || fine.len() < 9
1064 || fine.len() % 2 == 0
1065 || ts.len() != fine.len()
1066 || !ts.iter().all(|t| t.is_finite())
1067 || !ts.windows(2).all(|pair| pair[1] > pair[0])
1068 {
1069 return Err(format!("native-abscissa reader: node {jf} of {} with {} finite, strictly increasing abscissae required", fine.len(), ts.len()));
1070 }
1071 let previous = WALL_DECLINES.with(|log| log.replace(Some(Vec::new())));
1072 let read = (|| -> Option<(f64, f64)> {
1073 let (reading, spread) = wall_probe_reading_at(p, fine, ts, jf, radius).or_else(|| {
1074 wall_decline(|| format!("FINE two-stencil reading (native abscissae) at node {jf} of {}", fine.len()));
1075 None
1076 })?;
1077 let at_fine = sweep_residual_at(p, fine, ts, jf, radius).or_else(|| {
1078 wall_decline(|| format!("FINE sweep (native abscissae) at node {jf} of {}", fine.len()));
1079 None
1080 })?;
1081 let coarse: Vec<Vec3> = fine.iter().step_by(2).copied().collect();
1082 let coarse_ts: Vec<f64> = ts.iter().step_by(2).copied().collect();
1083 let at_coarse = sweep_residual_at(p, &coarse, &coarse_ts, jf / 2, radius).or_else(|| {
1084 wall_decline(|| format!("COARSE sweep (native abscissae) at node {} of {}", jf / 2, coarse.len()));
1085 None
1086 })?;
1087 let uncertainty = spread.max((at_fine - at_coarse).abs());
1088 uncertainty.is_finite().then_some((reading, uncertainty))
1089 })();
1090 let lines = WALL_DECLINES.with(|log| log.replace(previous)).unwrap_or_default();
1091 read.ok_or_else(|| if lines.is_empty() { "declined (no inner cause recorded)".to_string() } else { lines.join(" <- ") })
1092}
1093
1094fn wall_probe_reading_at(p: Vec3, nodes: &[Vec3], ts: &[f64], j: usize, radius: f64) -> Option<(f64, f64)> {
1095 let n = nodes.len();
1096 if n < 5 || j == 0 || j + 1 >= n {
1097 return None;
1098 }
1099 let j = locate_foot_at(p, nodes, ts, j, radius)?;
1100 let first = (j - 1).min(n - 4);
1101 let second = if j >= 2 { (j - 2).min(n - 4) } else { j.min(n - 4) };
1102 let second = if second == first { if first >= 1 { first - 1 } else { first + 1 } } else { second };
1103 let a = match stencil_solve_at(p, nodes, ts, first, j, radius) { Solve::Read(distance) => distance, _ => return None };
1104 let b = match stencil_solve_at(p, nodes, ts, second, j, radius) { Solve::Read(distance) => distance, _ => return None };
1105 Some((a.abs().max(b.abs()), (a - b).abs()))
1106}
1107
1108fn sweep_residual_at(p: Vec3, nodes: &[Vec3], ts: &[f64], j: usize, radius: f64) -> Option<f64> {
1109 let j = locate_foot_at(p, nodes, ts, j, radius)?;
1110 match stencil_solve_at(p, nodes, ts, (j - 1).min(nodes.len() - 4), j, radius) {
1111 Solve::Read(distance) => Some(distance),
1112 Solve::Window(_) | Solve::Unread => None,
1113 }
1114}
1115
1116fn locate_foot_at(p: Vec3, nodes: &[Vec3], ts: &[f64], j: usize, radius: f64) -> Option<usize> {
1120 let n = nodes.len();
1121 if n < 4 || j == 0 || j + 1 >= n {
1122 return None;
1123 }
1124 let mut tried: Vec<usize> = Vec::new();
1125 let mut at = j;
1126 loop {
1127 let base = (at - 1).min(n - 4);
1128 match stencil_solve_at(p, nodes, ts, base, at, radius) {
1129 Solve::Read(_) => return Some(at),
1130 Solve::Unread => return None,
1131 Solve::Window(t) => {
1132 tried.push(at);
1133 let nearest = (0..n).min_by(|&a, &b| (ts[a] - t).abs().total_cmp(&(ts[b] - t).abs())).unwrap_or(at);
1134 let next = if t.is_finite() { nearest.clamp(1, n - 2) } else { at };
1135 if tried.contains(&next) || next.abs_diff(j) > FOOT_TRAVEL {
1136 wall_decline(|| format!(
1137 "foot search (native abscissae) from node {j} of {n}: tried {tried:?}, next {next} ({})",
1138 if tried.contains(&next) { "already tried" } else { "beyond FOOT_TRAVEL" }
1139 ));
1140 return None;
1141 }
1142 at = next;
1143 }
1144 }
1145 }
1146}
1147
1148fn stencil_solve_at(p: Vec3, nodes: &[Vec3], ts: &[f64], base: usize, j: usize, radius: f64) -> Solve {
1153 let finite = |v: Vec3| v.x.is_finite() && v.y.is_finite() && v.z.is_finite();
1154 let n = nodes.len();
1155 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)) {
1156 wall_decline(|| format!("native stencil {n} nodes base {base} j {j}: unreadable input"));
1157 return Solve::Unread;
1158 }
1159 let [p0, p1, p2, p3] = [nodes[base], nodes[base + 1], nodes[base + 2], nodes[base + 3]];
1160 let [t0, t1, t2, t3] = [ts[base], ts[base + 1], ts[base + 2], ts[base + 3]];
1161 let d1 = p1.sub(p0).scale(1.0 / (t1 - t0));
1162 let d12 = p2.sub(p1).scale(1.0 / (t2 - t1));
1163 let d23 = p3.sub(p2).scale(1.0 / (t3 - t2));
1164 let d2 = d12.sub(d1).scale(1.0 / (t2 - t0));
1165 let d123 = d23.sub(d12).scale(1.0 / (t3 - t1));
1166 let d3 = d123.sub(d2).scale(1.0 / (t3 - t0));
1167 let curve = |t: f64| -> (Vec3, Vec3, Vec3) {
1168 let (a, b, c) = (t - t0, t - t1, t - t2);
1169 let point = p0.add(d1.scale(a)).add(d2.scale(a * b)).add(d3.scale(a * b * c));
1170 let first = d1.add(d2.scale(a + b)).add(d3.scale(b * c + a * c + a * b));
1171 let second = d2.scale(2.0).add(d3.scale(2.0 * (a + b + c)));
1172 (point, first, second)
1173 };
1174 let (low, high) = (ts[j - 1], ts[j + 1]);
1175 let start = ts[j];
1176 let mut t = start;
1177 let mut converged = false;
1178 for _ in 0..50 {
1179 let (c, c1, c2) = curve(t);
1180 let w = c.sub(p);
1181 let (g, slope) = (w.dot(c1), c1.dot(c1) + w.dot(c2));
1182 if !(g.is_finite() && slope.is_finite()) || slope == 0.0 {
1183 wall_decline(|| format!("native stencil {n} nodes base {base} j {j}: slope {slope:e} g {g:e} at t {t}"));
1184 return Solve::Unread;
1185 }
1186 if g.abs() <= 16.0 * f64::EPSILON * (p.length() + c.length()) * c1.length() {
1187 converged = true;
1188 break;
1189 }
1190 let step = g / slope;
1191 let before = t;
1192 t -= step;
1193 if !(t >= low && t <= high) {
1194 wall_decline(|| format!("native stencil {n} nodes base {base} j {j}: window exit t {before} -> {t} (window [{low}, {high}])"));
1195 return if t.is_finite() { Solve::Window(t) } else { Solve::Unread };
1196 }
1197 let node = 0.5 * (high - low);
1202 if (step / node).abs() <= 1e-14 * (1.0 + ((t - t0) / node).abs()) {
1203 converged = true;
1204 break;
1205 }
1206 }
1207 if !converged {
1208 wall_decline(|| format!("native stencil {n} nodes base {base} j {j}: no convergence in 50 steps, t {t}"));
1209 return Solve::Unread;
1210 }
1211 let distance = curve(t).0.sub(p).length() - radius;
1212 if distance.is_finite() {
1213 Solve::Read(distance)
1214 } else {
1215 wall_decline(|| format!("native stencil {n} nodes base {base} j {j}: non-finite distance at t {t}"));
1216 Solve::Unread
1217 }
1218}
1219
1220pub(in crate::blend) fn wall_model_missing(readings: &[(usize, f64, f64, f64)], model: f64) -> Vec<usize> {
1225 readings.iter().filter(|&&(_, declared, _, _)| !(declared <= model)).map(|&(left, _, _, _)| left).collect()
1226}
1227
1228#[allow(clippy::too_many_arguments)]
1238pub(super) fn wall_interior_misses(
1239 contacts: &crate::blend::chain::DenseContacts,
1240 samples: &[ChainSample],
1241 surface: &crate::NurbsSurface,
1242 low: f64,
1243 range: f64,
1244 radius: f64,
1245 subdivisions: usize,
1246 probes: usize,
1247 wrap: bool,
1248) -> (Vec<(usize, f64, f64, f64)>, Vec<usize>) {
1249 use std::collections::BTreeMap;
1250 let mut nodes: BTreeMap<usize, (usize, Vec<Option<Vec3>>)> = BTreeMap::new();
1253 for (index, (left, next, fraction, _, _)) in contacts.solved.iter().enumerate() {
1254 let entry = nodes.entry(*left).or_insert_with(|| {
1255 let mut row = vec![None; subdivisions + 1];
1256 row[0] = Some(samples[*left].station.center);
1257 row[subdivisions] = Some(samples[*next].station.center);
1258 (*next, row)
1259 });
1260 let step = (fraction * subdivisions as f64).round() as usize;
1261 if (1..subdivisions).contains(&step) {
1262 entry.1[step] = contacts.centers.get(index).copied().flatten();
1263 }
1264 }
1265 let mut readable = Vec::new();
1266 let mut unreadable: Vec<usize> = contacts.unsolved_at.clone();
1267 for (&left, (next, row)) in &nodes {
1268 let Some(centres) = row.iter().copied().collect::<Option<Vec<Vec3>>>() else {
1269 unreadable.push(left);
1270 continue;
1271 };
1272 let (from, to) = (samples[left].parameter, samples[*next].parameter);
1273 let (mut declared, mut worst, mut spread) = (0.0_f64, 0.0_f64, 0.0_f64);
1274 let mut read = true;
1275 let prepared = PreparedWall::for_interval(¢res);
1276 'probes: for step in (2..subdivisions).step_by(2) {
1277 let global = from + (step as f64 / subdivisions as f64) * (to - from);
1278 let global = if wrap { global.rem_euclid(1.0) } else { global };
1279 let u = (global - low) / range;
1280 for k in 1..probes {
1281 let v = k as f64 / probes as f64;
1282 let reading = surface.evaluate(u, v).ok().and_then(|p| {
1283 match &prepared {
1284 Some(cache) => cache.read(p, step, step as f64 / subdivisions as f64, radius),
1285 None => declared_wall_probe_located(p, ¢res, step, step as f64 / subdivisions as f64, radius),
1286 }
1287 });
1288 match reading {
1289 Some((distance, gap)) => {
1290 declared = declared.max(distance + gap);
1291 worst = worst.max(distance);
1292 spread = spread.max(gap);
1293 }
1294 None => {
1295 read = false;
1296 break 'probes;
1297 }
1298 }
1299 }
1300 }
1301 if read {
1302 readable.push((left, declared, worst, spread));
1303 } else {
1304 unreadable.push(left);
1305 }
1306 }
1307 unreadable.sort_unstable();
1308 unreadable.dedup();
1309 (readable, unreadable)
1310}
1311
1312
1313fn build_closed_smooth_chain(
1314 solid: &BrepSolid,
1315 segments: &[ChainSegment<'_>],
1316 radius: f64,
1317 chamfer: bool,
1318 name: Option<&str>,
1319 budget: &ChainBudget,
1320 fold: FoldPolicy,
1321 bar: f64,
1322) -> Result<Rung, KernelRefusal> {
1323 let samples = match march_chain_typed(segments, radius, false, budget, fold) {
1324 Ok(samples) => samples,
1325 Err(ChainMarchError::Station(failure)) => return Ok(Rung::StationFailed(failure)),
1326 Err(ChainMarchError::Incoherent(failure)) => return Err(failure.error),
1329 Err(ChainMarchError::Other(error)) => return Err(error),
1330 };
1331 CHAIN_DEEPEST_ROUND.with(|deepest| deepest.set(0));
1332 build_closed_chain_from_samples(solid, segments, radius, chamfer, name, budget, fold, bar, samples, 0)
1333}
1334
1335
1336thread_local! {
1337 static CHAIN_DEEPEST_ROUND: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1341}
1342
1343fn local_continue_on() -> bool {
1349 switch!(live "BREP_CHAIN_LOCAL_CONTINUE", false)
1350}
1351
1352const LOCAL_CONTINUE_MAX_ROUNDS: usize = 4 * REFINE_ROUNDS;
1354
1355const LOCAL_CONTINUE_STALL_ROUNDS: usize = 3;
1357
1358thread_local! {
1359 static CHAIN_LOCAL_BEST: std::cell::Cell<(f64, usize)> = const { std::cell::Cell::new((f64::INFINITY, 0)) };
1361}
1362
1363fn local_rounds_spent(round: usize, deviation: f64) -> bool {
1369 if round == 0 {
1370 CHAIN_LOCAL_BEST.with(|best| best.set((f64::INFINITY, 0)));
1371 return false;
1372 }
1373 let (_, best_round) = CHAIN_LOCAL_BEST.with(|best| {
1374 let (reading, at) = best.get();
1375 if deviation < reading {
1376 best.set((deviation, round));
1377 (deviation, round)
1378 } else {
1379 (reading, at)
1380 }
1381 });
1382 round >= LOCAL_CONTINUE_MAX_ROUNDS || round - best_round >= LOCAL_CONTINUE_STALL_ROUNDS
1383}
1384#[allow(clippy::too_many_arguments)]
1395fn build_closed_chain_from_samples(
1396 solid: &BrepSolid,
1397 segments: &[ChainSegment<'_>],
1398 radius: f64,
1399 chamfer: bool,
1400 name: Option<&str>,
1401 budget: &ChainBudget,
1402 fold: FoldPolicy,
1403 bar: f64,
1404 mut samples: Vec<ChainSample>,
1405 round: usize,
1406) -> Result<Rung, KernelRefusal> {
1407 let per_segment = budget.rung;
1410 CHAIN_DEEPEST_ROUND.with(|deepest| deepest.set(deepest.get().max(round)));
1411
1412 let mut global: Vec<(f64, &ChainSample)> = samples
1414 .iter()
1415 .filter(|sample| (0..budget.count(sample.segment) as isize).contains(&sample.position))
1416 .map(|sample| (sample.parameter.rem_euclid(1.0), sample))
1417 .collect();
1418 global.sort_by(|a, b| a.0.total_cmp(&b.0));
1419 let count = global.len();
1420 let degree = FIT_DEGREE;
1421 let mut extended_params = Vec::new();
1422 let mut samples_cr = Vec::new();
1423 let mut samples_mid = Vec::new();
1424 let mut samples_cs = Vec::new();
1425 let mut push = |station: &Station, parameter: f64| {
1426 extended_params.push(parameter);
1427 samples_cr.push(Vec4::from_point(station.p1, 1.0));
1428 samples_cs.push(Vec4::from_point(station.p2, 1.0));
1429 samples_mid.push(Vec4 {
1430 x: station.apex.x * station.weight,
1431 y: station.apex.y * station.weight,
1432 z: station.apex.z * station.weight,
1433 w: station.weight,
1434 });
1435 };
1436 for offset in (1..=degree).rev() {
1437 let (parameter, sample) = &global[count - offset];
1438 push(&sample.station, parameter - 1.0);
1439 }
1440 for (parameter, sample) in &global {
1441 push(&sample.station, *parameter);
1442 }
1443 push(&global[0].1.station, global[0].0 + 1.0);
1446 for offset in 1..=degree {
1447 let (parameter, sample) = &global[offset];
1448 push(&sample.station, parameter + 1.0);
1449 }
1450 let low = extended_params[0];
1451 let high = *extended_params.last().unwrap();
1452 let range = high - low;
1453 let normalized: Vec<f64> = extended_params
1454 .iter()
1455 .map(|parameter| (parameter - low) / range)
1456 .collect();
1457 let seam_low = (0.0 - low) / range;
1458 let seam_high = (1.0 - low) / range;
1459 let fit_row = |row: &[Vec4]| -> Result<NurbsCurve, KernelRefusal> {
1460 let curve = fit::interpolate_homogeneous(row, degree, &normalized).or_refuse(KernelStage::Refine, "interpolate_homogeneous")?;
1461 let (_, tail) = curve.split(seam_low).or_refuse(KernelStage::Refine, "split")?;
1462 let (middle, _) = tail.split(seam_high).or_refuse(KernelStage::Refine, "split")?;
1463 Ok(middle)
1464 };
1465 let cr = fit_row(&samples_cr)?;
1466 let cs = fit_row(&samples_cs)?;
1467 let mid = if chamfer {
1468 None
1469 } else {
1470 Some(fit_row(&samples_mid)?)
1471 };
1472 let u_domain = cr.domain().or_refuse(KernelStage::Refine, "domain")?;
1473 let surface = crate::blend::rows::surface_from_rows(degree, &cr, &cs, mid.as_ref(), true)?;
1474
1475 let (halfway, halfway_failing) = rail_deviation(&samples, &cr, &cs, low, range, budget, bar)?;
1488 let stencil = if round > 0 {
1500 Some(crate::blend::chain::chain_dense_contacts(segments, radius, budget, &samples, LOCAL_RAIL_STENCIL)?)
1501 } else {
1502 None
1503 };
1504 let wall_stencil = if !chamfer && wall_verdict_on() {
1509 Some(crate::blend::chain::chain_dense_contacts(segments, radius, budget, &samples, 2 * LOCAL_RAIL_STENCIL)?)
1510 } else {
1511 None
1512 };
1513 let (mut deviation, mut failing, _stencil_reads) = if round > 0 {
1514 let contacts = stencil.as_ref().expect("the local path solves the stencil");
1515 let (dense, unreadable) = dense_rail_misses(contacts, &samples, &cr, &cs, low, range, true)?;
1516 let reads = dense.len() + unreadable.len() + contacts.unsolved;
1517 let failed_to_read: Vec<usize> = contacts.unsolved_at.iter().chain(&unreadable).copied().collect();
1518 let verdict = combine_rail_verdict((halfway, halfway_failing), &dense, &failed_to_read, bar);
1519 crate::blend::carve::carve_trace(format_args!(
1520 "blend chain local rails: rung {per_segment} round {round}: stencil verdict {:.9e} (halfway {halfway:.9e}), \
1521 {} failing interval(s), {} unsolved contact(s)",
1522 verdict.0, verdict.1.len(), contacts.unsolved
1523 ));
1524 (verdict.0, verdict.1, reads)
1525 } else {
1526 (halfway, halfway_failing, 0)
1527 };
1528 let mut _wall_worst = 0.0_f64;
1534 let mut _wall_spread = 0.0_f64;
1535 let mut wall_readings: Vec<(usize, f64, f64, f64)> = Vec::new();
1536 if let Some(contacts) = wall_stencil.as_ref() {
1537 let (wall, unreadable) =
1538 wall_interior_misses(contacts, &samples, &surface, low, range, radius, 2 * LOCAL_RAIL_STENCIL, WALL_SECTION_PROBES, true);
1539 wall_readings = wall.clone();
1540 for &(left, declared, _, uncertainty) in &wall {
1542 if declared > bar {
1543 failing.push(left);
1544 }
1545 _wall_worst = _wall_worst.max(declared);
1546 _wall_spread = _wall_spread.max(uncertainty);
1547 }
1548 failing.extend_from_slice(&unreadable);
1549 failing.sort_unstable();
1550 failing.dedup();
1551 deviation = deviation.max(_wall_worst);
1552 crate::blend::carve::carve_trace(format_args!(
1553 "blend chain wall: rung {per_segment} round {round}: wall interior worst {_wall_worst:.9e} over {} \
1554 interval(s), {} unreadable, bar {bar:.3e}",
1555 wall.len(),
1556 unreadable.len()
1557 ));
1558 }
1559 if deviation > bar || !failing.is_empty() {
1560 let in_segment = |segment: usize| {
1561 samples
1562 .iter()
1563 .filter(|sample| sample.segment == segment && (0..budget.count(segment) as isize).contains(&sample.position))
1564 .count()
1565 };
1566 let within_ceiling = (0..segments.len()).all(|segment| {
1567 in_segment(segment) + failing.iter().filter(|&&index| samples[index].segment == segment).count()
1568 <= CHAIN_CARVE_MAX_PER_SEGMENT
1569 });
1570 crate::blend::carve::carve_trace(format_args!(
1571 "blend chain local rails: rung {per_segment} round {round} stations {} failing {} \
1572 worst {deviation:.9e} bar {bar:.9e} ceiling {}",
1573 samples.len(),
1574 failing.len(),
1575 if within_ceiling { "ok" } else { "reached" }
1576 ));
1577 let rounds_spent = if local_continue_on() {
1579 local_rounds_spent(round, deviation)
1580 } else {
1581 round >= REFINE_ROUNDS
1582 };
1583 if fold != FoldPolicy::Refuse || rounds_spent || !within_ceiling {
1585 return Ok(Rung::TooCoarse { deviation });
1586 }
1587 CHAIN_DEEPEST_ROUND.with(|deepest| deepest.set(deepest.get().max(round + 1)));
1589 match insert_chain_stations(segments, radius, budget, &mut samples, &failing) {
1590 Ok(()) => {}
1591 Err(ChainMarchError::Station(failure)) => return Ok(Rung::StationFailed(failure)),
1592 Err(ChainMarchError::Incoherent(failure)) => {
1596 crate::blend::carve::carve_trace(format_args!(
1597 "blend chain local rails: rung {per_segment} round {round}: segment {} station \
1598 at t {:.9} does not reach its retained right neighbour: {}",
1599 failure.segment, failure.t, failure.error
1600 ));
1601 return Ok(Rung::TooCoarse { deviation });
1602 }
1603 Err(ChainMarchError::Other(error)) => return Err(error),
1604 }
1605 assign_chain_parameters(&mut samples, segments.len(), budget, false);
1606 return build_closed_chain_from_samples(
1607 solid, segments, radius, chamfer, name, budget, fold, bar, samples, round + 1,
1608 );
1609 }
1610 crate::blend::carve::carve_trace(format_args!(
1611 "blend chain: {per_segment} stations per segment leaves the rails {deviation:.6e} \
1612 from the rolling ball, inside {bar:.3e}"
1613 ));
1614 let model = crate::KernelTolerances::for_solid(solid, 1e-7).model;
1628 let stations_now = (0..segments.len())
1629 .map(|segment| {
1630 samples
1631 .iter()
1632 .filter(|sample| sample.segment == segment && (0..budget.count(segment) as isize).contains(&sample.position))
1633 .count()
1634 })
1635 .max()
1636 .unwrap_or(0);
1637 let mut unmet: Option<(f64, crate::BudgetReason)> = None;
1638 let mut request_detail: Option<String> = None;
1642 let mut request_component = crate::MeasuredComponent::Wall;
1643 let mut request_unread = 0usize;
1644 if !chamfer && fold == FoldPolicy::Refuse && model_request_on() {
1645 let wall_missing = wall_model_missing(&wall_readings, model);
1646 let (rail_dense, rail_unread) = match wall_stencil.as_ref() {
1654 Some(contacts) => dense_rail_misses(contacts, &samples, &cr, &cs, low, range, true)?,
1655 None => (Vec::new(), Vec::new()),
1656 };
1657 let rail_over: std::collections::BTreeSet<usize> =
1659 rail_dense.iter().filter(|&&(_, miss)| !(miss <= model)).map(|&(left, _)| left).collect();
1660 let rail_unread_intervals: std::collections::BTreeSet<usize> = rail_unread.iter().copied().collect();
1661 let rail_missing: Vec<usize> = rail_over.union(&rail_unread_intervals).copied().collect();
1662 let mut missing: Vec<usize> = wall_missing.iter().chain(&rail_missing).copied().collect();
1663 missing.sort_unstable();
1664 missing.dedup();
1665 if !missing.is_empty() {
1666 let wall_short = wall_readings
1668 .iter()
1669 .filter(|reading| wall_missing.contains(&reading.0))
1670 .map(|&(_, declared, _, _)| declared)
1671 .fold(0.0_f64, f64::max);
1672 let rail_short = rail_dense.iter().filter(|&&(_, miss)| !(miss <= model)).map(|&(_, miss)| miss).fold(0.0_f64, f64::max);
1673 let short = wall_short.max(rail_short);
1674 request_component = if rail_short > wall_short { crate::MeasuredComponent::Rails } else { crate::MeasuredComponent::Wall };
1675 request_unread = rail_unread_intervals.len();
1676 request_detail = Some(format!(
1677 "short of {model:.3e}: rails {rail_short:.3e} off the exact contacts over {} interval(s) ({} unread), \
1678 wall {wall_short:.3e} over {} interval(s)",
1679 rail_over.len(),
1680 rail_unread_intervals.len(),
1681 wall_missing.len()
1682 ));
1683 let within_ceiling = (0..segments.len()).all(|segment| {
1684 let present = samples
1685 .iter()
1686 .filter(|sample| sample.segment == segment && (0..budget.count(segment) as isize).contains(&sample.position))
1687 .count();
1688 present + missing.iter().filter(|&&index| samples[index].segment == segment).count()
1689 <= CHAIN_CARVE_MAX_PER_SEGMENT
1690 });
1691 crate::blend::carve::carve_trace(format_args!(
1692 "blend chain wall model: rung {per_segment} round {round}: {} interval(s) short of {model:.3e} \
1693 (worst reading + spread {short:.3e}), ceiling {}",
1694 missing.len(),
1695 if within_ceiling { "ok" } else { "reached" }
1696 ));
1697 unmet = if round >= model_rounds_limit() {
1698 Some((short, crate::BudgetReason::RoundsSpent))
1699 } else if !within_ceiling {
1700 Some((short, crate::BudgetReason::StationCeiling))
1701 } else {
1702 let mut refined = samples.clone();
1703 CHAIN_DEEPEST_ROUND.with(|deepest| deepest.set(deepest.get().max(round + 1)));
1705 match insert_chain_stations(segments, radius, budget, &mut refined, &missing) {
1706 Ok(()) => {
1707 assign_chain_parameters(&mut refined, segments.len(), budget, false);
1708 match build_closed_chain_from_samples(
1709 solid, segments, radius, chamfer, name, budget, fold, bar, refined, round + 1,
1710 ) {
1711 Ok(Rung::Built(built)) => return Ok(Rung::Built(built)),
1712 _ => Some((short, crate::BudgetReason::Rejected)),
1713 }
1714 }
1715 Err(_) => {
1716 CHAIN_DEEPEST_ROUND.with(|deepest| deepest.set(deepest.get().max(round + 1)));
1718 Some((short, crate::BudgetReason::Incoherent))
1719 }
1720 }
1721 };
1722 }
1723 }
1724 if let Some(subdivisions) = std::env::var("BREP_DEBUG_CHAIN_DENSE_RAILS").ok().and_then(|value| value.parse::<usize>().ok()) {
1729 let contacts = crate::blend::chain::chain_dense_contacts(segments, radius, budget, &samples, subdivisions.max(2))?;
1730 let mut worst = (0.0_f64, 0usize, 0isize, 0.0_f64);
1731 let mut unreadable = 0usize;
1732 for (left, next, fraction, p1, p2) in &contacts.solved {
1733 let (from, to) = (samples[*left].parameter, samples[*next].parameter);
1734 let global = (from + fraction * (to - from)).rem_euclid(1.0);
1735 let seed = (global - low) / range;
1736 let reach = (to - from).abs() / range;
1737 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)) {
1738 Some(miss) if miss > worst.0 => worst = (miss, samples[*left].segment, samples[*left].position, *fraction),
1739 Some(_) => {}
1740 None => unreadable += 1,
1741 }
1742 }
1743 eprintln!(
1744 "blend chain dense rails: rung {per_segment} round {round}: {} contacts at {subdivisions} per interval, \
1745 worst {:.9e} (halfway reading {halfway:.9e}, bar {bar:.3e}) at segment {} position {} fraction {:.4}; {} unsolved, {unreadable} unreadable",
1746 contacts.solved.len(), worst.0, worst.1, worst.2, worst.3, contacts.unsolved
1747 );
1748 }
1749 let crease = if fold == FoldPolicy::Carve {
1750 let bar = crate::KernelTolerances::for_solid(solid, 1e-7).pcurve_consistency;
1760 let Some(carved) = crate::blend::carve::trace_wall_crease(&surface, radius.abs())? else {
1761 return Err(KernelRefusal::internal(KernelStage::Refine, "carve_no_fold", format!(
1762 "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"
1763 )));
1764 };
1765 Some(crate::blend::carve::fit_crease(&surface, &carved, bar)?)
1766 } else {
1767 None
1768 };
1769
1770 let single_face = |side: usize| -> bool {
1774 let first_id = segments[0].mate(side).face.id;
1775 segments
1776 .iter()
1777 .all(|segment| segment.mate(side).face.id == first_id)
1778 };
1779 let mut whole_pcurves: [Option<NurbsCurve>; 2] = [None, None];
1780 for side in 0..2 {
1781 if !single_face(side) {
1782 continue;
1783 }
1784 let mut row = Vec::new();
1785 let select = |station: &Station| -> [f64; 2] {
1786 if side == 0 {
1787 station.uv1
1788 } else {
1789 station.uv2
1790 }
1791 };
1792 let mut push_uv = |station: &Station| {
1793 let uv = select(station);
1794 row.push(Vec4::from_point(Vec3::new(uv[0], uv[1], 0.0), 1.0));
1795 };
1796 for offset in (1..=degree).rev() {
1797 push_uv(&global[count - offset].1.station);
1798 }
1799 for (_, sample) in &global {
1800 push_uv(&sample.station);
1801 }
1802 push_uv(&global[0].1.station);
1803 for offset in 1..=degree {
1804 push_uv(&global[offset].1.station);
1805 }
1806 whole_pcurves[side] = Some(fit_row(&row)?);
1807 }
1808
1809 let mut pcurves1 = Vec::with_capacity(segments.len());
1812 let mut pcurves2 = Vec::with_capacity(segments.len());
1813 for segment in 0..segments.len() {
1814 let mut window: Vec<&ChainSample> = samples
1815 .iter()
1816 .filter(|sample| sample.segment == segment)
1817 .collect();
1818 window.sort_by(|a, b| a.parameter.total_cmp(&b.parameter));
1819 let params: Vec<f64> = window.iter().map(|sample| sample.parameter).collect();
1820 let low = params[0];
1821 let high = *params.last().unwrap();
1822 let normalized: Vec<f64> = params
1823 .iter()
1824 .map(|parameter| (parameter - low) / (high - low))
1825 .collect();
1826 let fit_uv = |select: &dyn Fn(&Station) -> [f64; 2]| -> Result<NurbsCurve, KernelRefusal> {
1827 let points: Vec<Vec4> = window
1828 .iter()
1829 .map(|sample| {
1830 let uv = select(&sample.station);
1831 Vec4::from_point(Vec3::new(uv[0], uv[1], 0.0), 1.0)
1832 })
1833 .collect();
1834 let curve = fit::interpolate_homogeneous(&points, degree, &normalized).or_refuse(KernelStage::Refine, "interpolate_homogeneous")?;
1835 Ok(curve)
1839 };
1840 pcurves1.push((low, high, fit_uv(&|station| station.uv1)?));
1841 pcurves2.push((low, high, fit_uv(&|station| station.uv2)?));
1842 }
1843
1844 let wall_surface = unmet.as_ref().map(|_| surface.clone());
1845 let built = chain_surgery(
1846 solid,
1847 segments,
1848 ChainRows {
1849 surface,
1850 cr,
1851 cs,
1852 u_domain,
1853 fit_low: low,
1854 fit_range: range,
1855 pcurves1,
1856 pcurves2,
1857 whole_pcurves,
1858 crease,
1859 },
1860 name,
1861 )?;
1862 if let (Some((residual, reason)), Some(surface)) = (unmet, wall_surface) {
1863 crate::blend::record_wall_model_report(crate::blend::WallModelReport {
1864 name: name.map(str::to_string),
1865 surface,
1866 request: model,
1867 residual,
1868 detail: request_detail,
1869 budget: crate::ApproximationBudget {
1870 reason,
1871 rounds_used: CHAIN_DEEPEST_ROUND.with(|deepest| deepest.get()).max(round),
1874 rounds_limit: model_rounds_limit(),
1875 stations: stations_now,
1876 station_limit: CHAIN_CARVE_MAX_PER_SEGMENT,
1877 mechanism: crate::BudgetMechanism::LocalRounds,
1878 measured_component: request_component,
1879 unread: request_unread,
1880 },
1881 });
1882 }
1883 Ok(Rung::Built(built))
1884}
1885
1886pub(super) struct ChainRows {
1887 pub(super) surface: NurbsSurface,
1888 pub(super) cr: NurbsCurve,
1889 pub(super) cs: NurbsCurve,
1890 pub(super) u_domain: [f64; 2],
1891 pub(super) fit_low: f64,
1895 pub(super) fit_range: f64,
1896 pub(super) pcurves1: Vec<(f64, f64, NurbsCurve)>,
1899 pub(super) pcurves2: Vec<(f64, f64, NurbsCurve)>,
1900 pub(super) whole_pcurves: [Option<NurbsCurve>; 2],
1902 pub(super) crease: Option<crate::blend::carve::CarvedCrease>,
1905}
1906
1907impl ChainRows {
1908 pub(super) fn to_global(&self, fit_parameter: f64) -> f64 {
1909 self.fit_low + fit_parameter * self.fit_range
1910 }
1911}
1912
1913pub(super) fn pcurve_portion(fitted: &(f64, f64, NurbsCurve), a: f64, b: f64) -> Result<NurbsCurve, KernelRefusal> {
1917 let (low, high, curve) = fitted;
1918 let to_local = |value: f64| {
1921 let mut best = value;
1922 for candidate in [value, value + 1.0, value - 1.0] {
1923 if candidate >= low - 1e-9 && candidate <= high + 1e-9 {
1924 best = candidate;
1925 break;
1926 }
1927 }
1928 ((best - low) / (high - low)).clamp(0.0, 1.0)
1929 };
1930 let mut local_a = to_local(a);
1931 let mut local_b = to_local(b);
1932 if local_a > local_b {
1933 std::mem::swap(&mut local_a, &mut local_b);
1934 }
1935 let epsilon = 1e-9;
1936 let (_, tail) = if local_a > epsilon {
1937 curve.split(local_a).or_refuse(KernelStage::Refine, "split")?
1938 } else {
1939 (curve.clone(), curve.clone())
1940 };
1941 let tail = if local_a > epsilon {
1942 tail
1943 } else {
1944 curve.clone()
1945 };
1946 let portion = if local_b < 1.0 - epsilon {
1947 tail.split(local_b).or_refuse(KernelStage::Refine, "split")?.0
1948 } else {
1949 tail
1950 };
1951 Ok(portion)
1952}
1953
1954pub(super) fn cross_edge_at(
1960 solid: &BrepSolid,
1961 face_before: &FaceRecord,
1962 loop_before: usize,
1963 face_after: &FaceRecord,
1964 loop_after: usize,
1965 vertex: u64,
1966 before_edge: u64,
1967 after_edge: u64,
1968) -> Result<Option<u64>, KernelRefusal> {
1969 let mut found: Option<u64> = None;
1970 let mut consider = |face: &FaceRecord, loop_index: usize| -> Result<(), KernelRefusal> {
1971 for coedge in &face.loops[loop_index].coedges {
1972 if coedge.edge_id == before_edge || coedge.edge_id == after_edge {
1973 continue;
1974 }
1975 let edge = solid
1976 .edges
1977 .iter()
1978 .find(|edge| edge.id == coedge.edge_id)
1979 .ok_or(KernelRefusal::internal(KernelStage::Refine, "missing_edge", "blend: loop references missing edge"))?;
1980 if edge.start_vertex_id == vertex || edge.end_vertex_id == vertex {
1981 if found.is_some() && found != Some(edge.id) {
1982 return Err(KernelRefusal::unsupported(KernelStage::Classify, "chain_cross_edges", "blend: multiple cross edges at a chain vertex"));
1983 }
1984 found = Some(edge.id);
1985 }
1986 }
1987 Ok(())
1988 };
1989 consider(face_before, loop_before)?;
1990 if !(face_after.id == face_before.id && loop_after == loop_before) {
1991 consider(face_after, loop_after)?;
1992 }
1993 Ok(found)
1994}
1995
1996fn nearest_seam_image(value: f64, low: f64, high: f64) -> f64 {
1999 let period = high - low;
2000 low + ((value - low) / period).round() * period
2001}
2002
2003pub(in crate::blend) fn project_piece_pcurve(
2021 piece: &NurbsCurve,
2022 surface: &NurbsSurface,
2023 start_is_crossing: bool,
2024 end_is_crossing: bool,
2025) -> Result<NurbsCurve, KernelRefusal> {
2026 project_piece_pcurve_from(piece, surface, start_is_crossing, end_is_crossing, None)
2027}
2028
2029
2030pub(in crate::blend) fn pcurve_guide<'a>(old: &'a NurbsCurve, surface: &NurbsSurface) -> Result<impl Fn(f64) -> Option<[f64; 2]> + 'a, KernelRefusal> {
2035 let [o0, o1] = old.domain().or_refuse(KernelStage::Refine, "domain")?;
2036 let (closed_u, closed_v) = surface.closed_directions().or_refuse(KernelStage::Refine, "closed_directions")?;
2037 let [u0, u1] = surface.domain_u().or_refuse(KernelStage::Refine, "domain_u")?;
2038 let [v0, v1] = surface.domain_v().or_refuse(KernelStage::Refine, "domain_v")?;
2039 let into = move |value: f64, closed: bool, low: f64, high: f64| {
2040 if closed && high > low {
2041 low + (value - low).rem_euclid(high - low)
2042 } else {
2043 value.clamp(low, high)
2044 }
2045 };
2046 Ok(move |fraction: f64| {
2047 let uv = old.evaluate(o0 + (o1 - o0) * fraction).ok()?;
2048 let seed = [into(uv.x, closed_u, u0, u1), into(uv.y, closed_v, v0, v1)];
2049 seed.iter().all(|value| value.is_finite()).then_some(seed)
2050 })
2051}
2052
2053pub(in crate::blend) fn project_piece_pcurve_from(
2063 piece: &NurbsCurve,
2064 surface: &NurbsSurface,
2065 start_is_crossing: bool,
2066 end_is_crossing: bool,
2067 guide: Option<&dyn Fn(f64) -> Option<[f64; 2]>>,
2068) -> Result<NurbsCurve, KernelRefusal> {
2069 project_piece_pcurve_within(piece, surface, start_is_crossing, end_is_crossing, guide, &[])
2070}
2071
2072pub(crate) const CHAIN_PCURVE_FLOOR_WHAT: &str = "chain_pcurve_floor";
2078
2079pub(in crate::blend) fn project_piece_pcurve_within(
2080 piece: &NurbsCurve,
2081 surface: &NurbsSurface,
2082 start_is_crossing: bool,
2083 end_is_crossing: bool,
2084 guide: Option<&dyn Fn(f64) -> Option<[f64; 2]>>,
2085 refine_near: &[f64],
2086) -> Result<NurbsCurve, KernelRefusal> {
2087 project_piece_pcurve_track(piece, surface, start_is_crossing, end_is_crossing, guide, refine_near, false)
2088}
2089
2090pub(in crate::blend) fn project_piece_pcurve_within_knot_retry(
2101 piece: &NurbsCurve,
2102 surface: &NurbsSurface,
2103 start_is_crossing: bool,
2104 end_is_crossing: bool,
2105 guide: Option<&dyn Fn(f64) -> Option<[f64; 2]>>,
2106 refine_near: &[f64],
2107) -> Result<NurbsCurve, KernelRefusal> {
2108 match project_piece_pcurve_track(piece, surface, start_is_crossing, end_is_crossing, guide, refine_near, false) {
2109 Err(uniform) if matches!(&uniform.class, crate::RefusalClass::NonConvergence { what } if what == CHAIN_PCURVE_FLOOR_WHAT) => {
2110 project_piece_pcurve_track(piece, surface, start_is_crossing, end_is_crossing, guide, refine_near, true).map_err(|_| uniform)
2111 }
2112 other => other,
2113 }
2114}
2115
2116#[allow(clippy::too_many_arguments)]
2120fn project_piece_pcurve_track(
2121 piece: &NurbsCurve,
2122 surface: &NurbsSurface,
2123 start_is_crossing: bool,
2124 end_is_crossing: bool,
2125 guide: Option<&dyn Fn(f64) -> Option<[f64; 2]>>,
2126 refine_near: &[f64],
2127 knot_aware: bool,
2128) -> Result<NurbsCurve, KernelRefusal> {
2129 let [u0, u1] = surface.domain_u().or_refuse(KernelStage::Refine, "domain_u")?;
2130 let [v0, v1] = surface.domain_v().or_refuse(KernelStage::Refine, "domain_v")?;
2131 let (_, closed_v) = surface.closed_directions().or_refuse(KernelStage::Refine, "closed_directions")?;
2132 let period = u1 - u0;
2133 let period_v = v1 - v0;
2134 let [d0, d1] = piece.domain().or_refuse(KernelStage::Refine, "domain")?;
2135 let ceiling = if knot_aware { 2 * PIECE_TRACK_CEILING } else { PIECE_TRACK_CEILING };
2145 let uniform = (8 * piece.control_points.len()).clamp(96, PIECE_TRACK_CEILING);
2146 let mut fractions: Vec<f64> = (0..=uniform).map(|section| section as f64 / uniform as f64).collect();
2147 if knot_aware {
2148 let span = d1 - d0;
2151 let mut knots: Vec<f64> = piece.knots.iter().copied().filter(|knot| *knot > d0 && *knot < d1).map(|knot| (knot - d0) / span).collect();
2152 knots.dedup();
2153 fractions.extend(knots);
2154 fractions.sort_by(|a, b| a.total_cmp(b));
2155 fractions.dedup_by(|b, a| (*b - *a).abs() <= 1e-6 / uniform as f64);
2156 }
2157 let dense = fractions.len() - 1;
2158 crate::blend::record_count("count.track.piece_samples", dense as u64 + 1);
2159 let mut proj_u = Vec::with_capacity(dense + 1);
2160 let mut proj_v = Vec::with_capacity(dense + 1);
2161 let mut point3 = Vec::with_capacity(dense + 1);
2162 let mut params = Vec::with_capacity(dense + 1);
2163 let mut previous_u: Option<f64> = None;
2164 let mut previous_foot: Option<[f64; 2]> = None;
2169 let mut feet: Vec<[f64; 2]> = Vec::with_capacity(dense + 1);
2170 let project_timer = crate::blend::BlendTimer::start("timing.track.project_ms");
2171 for section in 0..=dense {
2172 let fraction = fractions[section];
2173 let t = if knot_aware { d0 + (d1 - d0) * fraction } else { d0 + (d1 - d0) * section as f64 / dense as f64 };
2177 let point = piece.evaluate(t).or_refuse(KernelStage::Refine, "evaluate")?;
2178 let guide = guide.filter(|_| {
2179 true
2180 });
2181 let seeds: Vec<[f64; 2]> = guide.and_then(|guide| guide(fraction)).into_iter().chain(previous_foot).collect();
2186 let mut projection: Option<crate::projection::SurfaceProjection> = None;
2187 for seed in &seeds {
2188 let found = crate::projection::project_point_to_surface_from_seed(surface, point, *seed).or_refuse(KernelStage::Refine, "project_point_to_surface_from_seed")?;
2189 if projection.as_ref().map_or(true, |known| found.distance < known.distance) {
2190 projection = Some(found);
2191 }
2192 }
2193 let projection = match projection {
2194 Some(projection) => projection,
2195 None => crate::project_point_to_surface(surface, point).or_refuse(KernelStage::Refine, "project_point_to_surface")?,
2196 };
2197 previous_foot = Some([projection.u, projection.v]);
2198 feet.push([projection.u, projection.v]);
2199 let mut u = projection.u;
2200 if let Some(previous) = previous_u {
2201 while u - previous > period * 0.5 {
2202 u -= period;
2203 }
2204 while previous - u > period * 0.5 {
2205 u += period;
2206 }
2207 }
2208 previous_u = Some(u);
2209 proj_u.push(u);
2210 proj_v.push(projection.v);
2211 point3.push(point);
2212 params.push(fraction);
2213 }
2214 project_timer.stop();
2215 if closed_v {
2222 for index in 2..=dense {
2223 while proj_v[index] - proj_v[index - 1] > period_v * 0.5 {
2224 proj_v[index] -= period_v;
2225 }
2226 while proj_v[index - 1] - proj_v[index] > period_v * 0.5 {
2227 proj_v[index] += period_v;
2228 }
2229 }
2230 while proj_v[0] - proj_v[1] > period_v * 0.5 {
2231 proj_v[0] -= period_v;
2232 }
2233 while proj_v[1] - proj_v[0] > period_v * 0.5 {
2234 proj_v[0] += period_v;
2235 }
2236 }
2237 let mean_u: f64 = proj_u[1..dense].iter().sum::<f64>() / (dense - 1) as f64;
2240 let seam_u = if mean_u - u0 > u1 - mean_u { u1 } else { u0 };
2241 let pinned = |index: usize,
2250 neighbour: usize,
2251 proj_u: &[f64],
2252 proj_v: &[f64]|
2253 -> Result<(f64, f64), KernelRefusal> {
2254 let point = point3[index];
2255 let u_error = surface
2256 .evaluate(seam_u, proj_v[index]).or_refuse(KernelStage::Refine, "evaluate")?
2257 .sub(point)
2258 .length();
2259 if closed_v {
2260 let seam_v = nearest_seam_image(proj_v[neighbour], v0, v1);
2261 let v_error = surface
2262 .evaluate(proj_u[index], seam_v).or_refuse(KernelStage::Refine, "evaluate")?
2263 .sub(point)
2264 .length();
2265 if v_error < u_error {
2266 return Ok((proj_u[index], seam_v));
2267 }
2268 }
2269 Ok((seam_u, proj_v[index]))
2270 };
2271 if start_is_crossing {
2272 let (u, v) = pinned(0, 1, &proj_u, &proj_v)?;
2273 proj_u[0] = u;
2274 proj_v[0] = v;
2275 }
2276 if end_is_crossing {
2277 let (u, v) = pinned(dense, dense - 1, &proj_u, &proj_v)?;
2278 proj_u[dense] = u;
2279 proj_v[dense] = v;
2280 }
2281 let mut shift = 0.0;
2282 while mean_u + shift > u1 + 1e-9 {
2283 shift -= period;
2284 }
2285 while mean_u + shift < u0 - 1e-9 {
2286 shift += period;
2287 }
2288 for u in proj_u.iter_mut() {
2289 *u += shift;
2290 }
2291 if closed_v {
2292 let mean_v: f64 = proj_v[1..dense].iter().sum::<f64>() / (dense - 1) as f64;
2293 let mut shift_v = 0.0;
2294 while mean_v + shift_v > v1 + 1e-9 {
2295 shift_v -= period_v;
2296 }
2297 while mean_v + shift_v < v0 - 1e-9 {
2298 shift_v += period_v;
2299 }
2300 for v in proj_v.iter_mut() {
2301 *v += shift_v;
2302 }
2303 }
2304 let tolerance = crate::pcurve::PCURVE_REFINEMENT_TOLERANCE;
2319 let at = |fraction: f64| piece.evaluate(d0 + (d1 - d0) * fraction);
2326 let mut track = crate::blend::track_fit::Track {
2327 fractions: params,
2328 uv: proj_u.iter().zip(&proj_v).map(|(u, v)| [*u, *v]).collect(),
2329 feet,
2330 breaks: Vec::new(),
2331 };
2332 let breaks = crate::blend::track_fit::curve_breaks(piece, d0, d1, true);
2333 let polish_timer = crate::blend::BlendTimer::start("timing.track.polish_ms");
2334 crate::blend::track_fit::polish_track(surface, &at, &mut track)?;
2335 polish_timer.stop();
2336 let crossings_timer = crate::blend::BlendTimer::start("timing.track.crossings_ms");
2337 crate::blend::track_fit::insert_knot_crossings(surface, &at, &mut track, &breaks)?;
2338 crossings_timer.stop();
2339 crate::blend::record_count("count.track.breaks", track.breaks.len() as u64);
2340 for &fraction in refine_near {
2341 for _ in 0..2 {
2342 let Some(index) = track.fractions.windows(2).position(|pair| pair[0] <= fraction && fraction <= pair[1]) else { break };
2343 if crate::blend::track_fit::refine_track_intervals(surface, &at, &mut track, &[index], ceiling)?.is_none() {
2344 break;
2345 }
2346 }
2347 }
2348 let fit_timer = crate::blend::BlendTimer::start("timing.track.fit_local_ms");
2355 let (fit, inserted) = crate::blend::track_fit::fit_track_locally(
2356 surface,
2357 &mut track,
2358 &at,
2359 tolerance,
2360 REFINE_ROUNDS,
2361 ceiling,
2362 )?;
2363 fit_timer.stop();
2364 crate::blend::record_count("count.track.fit_sections", fit.sections as u64);
2365 crate::blend::record_count("count.track.local_inserted", inserted as u64);
2366 if std::env::var("BREP_DEBUG_TRACK_FIT").is_ok() {
2367 eprintln!("TRACK_FIT closed-chain piece: {inserted} sample(s) inserted locally");
2368 eprintln!(
2369 "TRACK_FIT closed-chain piece: miss {:.3e} at {} samples of {} ({} breaks), on floor {}",
2370 fit.miss,
2371 fit.samples,
2372 track.fractions.len(),
2373 track.breaks.len(),
2374 fit.on_floor
2375 );
2376 if let Some(worst) = fit.worst {
2381 let parameter = d0 + (d1 - d0) * worst.fraction;
2382 let spans: Vec<[f64; 2]> = piece.knots.windows(2)
2383 .filter(|pair| pair[1] > pair[0] && pair[1] > d0 && pair[0] < d1)
2384 .map(|pair| [pair[0], pair[1]]).collect();
2385 let mean = (d1 - d0) / spans.len().max(1) as f64;
2386 let span = spans.iter().position(|pair| parameter >= pair[0] && parameter <= pair[1]);
2387 let width = span.map(|index| spans[index][1] - spans[index][0]);
2388 eprintln!(
2389 "TRACK_FIT closed-chain worst: fraction {:.9} parameter {:.9} (pinned start {start_is_crossing}, pinned end {end_is_crossing}) \
2390 knot span {:?} of {} width {:?} vs mean {:.3e}; dense bracket [{:.9}, {:.9}] (interval {})",
2391 worst.fraction, parameter, span, spans.len(), width, mean,
2392 worst.bracket[0], worst.bracket[1], worst.interval
2393 );
2394 }
2395 }
2396 if !fit.on_floor {
2403 if std::env::var("BREP_DEBUG_TRACK_FIT").is_ok() {
2404 for (label, t) in [("start", d0), ("end", d1)] {
2407 if let Ok(point) = piece.evaluate(t) {
2408 let standoff = crate::project_point_to_surface(surface, point).map(|p| p.distance).unwrap_or(f64::NAN);
2409 eprintln!(
2410 "TRACK_FIT closed-chain piece {label} ({:.9}, {:.9}, {:.9}) stands {standoff:.3e} off the carrier",
2411 point.x, point.y, point.z
2412 );
2413 }
2414 }
2415 }
2416 return Err(KernelRefusal::non_convergence(KernelStage::Refine, CHAIN_PCURVE_FLOOR_WHAT, format!(
2417 "{} a closed chain's support piece misses its pcurve by {:.3e} at {} samples, \
2418 against a floor of {tolerance:.1e}",
2419 crate::blend::PCURVE_OFF_FLOOR,
2420 fit.miss,
2421 fit.samples
2422 )));
2423 }
2424 Ok(fit.curve)
2425}
2426
2427
2428
2429pub(in crate::blend) struct PreparedWall<'a> {
2432 fine: &'a [Vec3],
2433 coarse: Vec<Vec3>,
2434 fine_stencils: StencilPreparation,
2435 coarse_stencils: StencilPreparation,
2436}
2437
2438#[derive(Clone, Copy)]
2439struct WallStart {
2440 curve: (Vec3, Vec3, Vec3),
2441 point_length: f64,
2442 tangent_length: f64,
2443 tangent_squared: f64,
2444}
2445impl WallStart {
2446 fn new(curve: (Vec3, Vec3, Vec3)) -> Self {
2447 Self { point_length: curve.0.length(), tangent_length: curve.1.length(),
2448 tangent_squared: curve.1.dot(curve.1), curve }
2449 }
2450}
2451
2452struct StencilPreparation {
2453 finite: bool,
2454 coefficients: std::cell::RefCell<Vec<Option<[Vec3; 4]>>>,
2455 starts: std::cell::RefCell<Vec<[Option<WallStart>; 2]>>,
2458}
2459impl StencilPreparation {
2460 fn new(nodes: &[Vec3]) -> Self {
2461 Self { finite: wall_nodes_finite(nodes), coefficients: std::cell::RefCell::new(vec![None; nodes.len().saturating_sub(3)]),
2462 starts: std::cell::RefCell::new(vec![[None; 2]; nodes.len().saturating_sub(3)]) }
2463 }
2464 fn start(&self, base: usize, j: usize, curve: &impl Fn(f64) -> (Vec3, Vec3, Vec3)) -> Option<WallStart> {
2465 let offset = j.checked_sub(base)?;
2466 if !(1..=2).contains(&offset) { return None; }
2467 let mut entries = self.starts.borrow_mut();
2468 Some(*entries.get_mut(base)?[offset-1].get_or_insert_with(|| WallStart::new(curve(offset as f64))))
2469 }
2470 fn coefficients(&self, nodes: &[Vec3], base: usize) -> [Vec3; 4] {
2471 let mut entries = self.coefficients.borrow_mut();
2472 *entries[base].get_or_insert_with(|| wall_coefficients(nodes, base))
2473 }
2474}
2475
2476fn wall_nodes_finite(nodes: &[Vec3]) -> bool {
2477 nodes.iter().all(|c| c.x.is_finite() && c.y.is_finite() && c.z.is_finite())
2478}
2479
2480fn wall_coefficients(nodes: &[Vec3], base: usize) -> [Vec3; 4] {
2481 let [p0, p1, p2, p3] = [nodes[base], nodes[base + 1], nodes[base + 2], nodes[base + 3]];
2483 let d1 = p1.sub(p0);
2484 let d2 = p2.sub(p1.scale(2.0)).add(p0).scale(0.5);
2485 let d3 = p3.sub(p2.scale(3.0)).add(p1.scale(3.0)).sub(p0).scale(1.0 / 6.0);
2486 [p0, d1, d2, d3]
2487}
2488
2489fn wall_coarse(fine: &[Vec3]) -> Vec<Vec3> {
2490 fine.iter().step_by(2).copied().collect()
2491}
2492
2493fn wall_preparation_on() -> bool {
2494 switch!(live "BREP_WALL_PREPARE", true)
2495}
2496
2497impl<'a> PreparedWall<'a> {
2498 pub(in crate::blend) fn for_interval(fine: &'a [Vec3]) -> Option<Self> {
2499 (wall_preparation_on() && wall_solve_reuse_on()).then(|| Self::new(fine))
2500 }
2501 fn new(fine: &'a [Vec3]) -> Self {
2502 let coarse = wall_coarse(fine);
2503 let fine_stencils = StencilPreparation::new(fine);
2504 let coarse_stencils = StencilPreparation::new(&coarse);
2505 Self { fine, coarse, fine_stencils, coarse_stencils }
2506 }
2507 pub(in crate::blend) fn read(&self, p: Vec3, j: usize, fraction: f64, radius: f64) -> Option<(f64, f64)> {
2508 let read = |at| declared_wall_probe_prepared(p, self.fine, at, radius, true, Some(self));
2509 match read(j) {
2510 Some(read) => Some(read),
2511 None => match centre_path_node(self.fine, fraction) {
2512 Some(located) if located != j => read(located),
2513 _ => None,
2514 },
2515 }
2516 }
2517}