1use super::*;
2
3#[derive(Clone)]
4struct SectionFrame {
5 normal: Vec3,
6 centroid: Vec3,
7 samples: Vec<Vec3>,
8 planar: bool,
9}
10
11pub(super) fn closed_points(
12 curves: &[NurbsCurve],
13 tolerance: f64,
14) -> Result<Vec<Vec3>, KernelRefusal> {
15 if curves.len() < 2 {
16 return Err(KernelRefusal::input(
17 KernelStage::Collect,
18 "section_curve_count",
19 "loftSolid: a section needs at least 2 curves",
20 ));
21 }
22 let mut points = Vec::with_capacity(curves.len());
23 for (index, curve) in curves.iter().enumerate() {
24 let [start, end] = curve.domain().or_refuse(KernelStage::Collect, "domain")?;
25 let next = &curves[(index + 1) % curves.len()];
26 let next_start = next.domain().or_refuse(KernelStage::Collect, "domain")?[0];
27 if curve
28 .evaluate(end)
29 .or_refuse(KernelStage::Collect, "evaluate")?
30 .sub(
31 next.evaluate(next_start)
32 .or_refuse(KernelStage::Collect, "evaluate")?,
33 )
34 .length()
35 > tolerance
36 {
37 return Err(KernelRefusal::input(
38 KernelStage::Collect,
39 "open_section",
40 format!("loftSolid: section is open at curve {index}"),
41 ));
42 }
43 points.push(
44 curve
45 .evaluate(start)
46 .or_refuse(KernelStage::Collect, "evaluate")?,
47 );
48 }
49 Ok(points)
50}
51
52fn section_frame(curves: &[NurbsCurve], tolerance: f64) -> Result<SectionFrame, KernelRefusal> {
53 let mut samples = Vec::new();
54 for curve in curves {
55 let [start, end] = curve.domain().or_refuse(KernelStage::Classify, "domain")?;
56 for index in 0..16 {
57 samples.push(
58 curve
59 .evaluate(start + (end - start) * index as f64 / 16.0)
60 .or_refuse(KernelStage::Classify, "evaluate")?,
61 );
62 }
63 }
64 let mut normal = crate::polygon::newell_normal(&samples);
65 let mut centroid = samples.iter().fold(Vec3::default(), |sum, &point| sum.add(point));
66 normal = normal
69 .normalized()
70 .or_input(KernelStage::Classify, "section_normal")?;
71 centroid = centroid.scale(1.0 / samples.len() as f64);
72 let planar = samples
73 .iter()
74 .all(|point| point.sub(samples[0]).dot(normal).abs() <= tolerance * 100.0);
75 Ok(SectionFrame {
76 normal,
77 centroid,
78 samples,
79 planar,
80 })
81}
82
83const CAP_ADVANCE_MIN: f64 = 0.1;
88
89fn advance_from(
95 sections: &[Vec<NurbsCurve>],
96 anchor: Vec3,
97 normal: Vec3,
98 order: impl Iterator<Item = usize>,
99 tolerance: f64,
100) -> Result<Option<Vec3>, KernelRefusal> {
101 for index in order {
102 let step = section_frame(§ions[index], tolerance)?
103 .centroid
104 .sub(anchor);
105 let length = step.length();
106 if length > tolerance && (step.dot(normal) / length).abs() >= CAP_ADVANCE_MIN {
107 return Ok(Some(step.scale(1.0 / length)));
108 }
109 }
110 Ok(None)
111}
112
113fn reverse_section(curves: &[NurbsCurve]) -> Result<Vec<NurbsCurve>, KernelRefusal> {
114 curves
115 .iter()
116 .rev()
117 .map(NurbsCurve::reversed)
118 .collect::<Result<Vec<_>, String>>()
119 .or_refuse(KernelStage::Classify, "reverse_section")
120}
121
122fn cap_face(
127 curves: &[NurbsCurve],
128 edge_ids: &[u64],
129 frame: &SectionFrame,
130 advance: Vec3,
131 outward: bool,
132 next_id: &mut u64,
133) -> Result<FaceRecord, KernelRefusal> {
134 let normal = if frame.normal.dot(advance) >= 0.0 {
135 frame.normal
136 } else {
137 frame.normal.scale(-1.0)
138 };
139 let x_axis = normal
140 .perpendicular()
141 .or_refuse(KernelStage::Fragment, "cap_frame")?;
142 let y_axis = normal
143 .cross(x_axis)
144 .normalized()
145 .or_refuse(KernelStage::Fragment, "cap_frame")?;
146 let (mut min_x, mut min_y) = (f64::INFINITY, f64::INFINITY);
147 let (mut max_x, mut max_y) = (f64::NEG_INFINITY, f64::NEG_INFINITY);
148 for point in &frame.samples {
149 let delta = point.sub(frame.centroid);
150 min_x = min_x.min(delta.dot(x_axis));
151 max_x = max_x.max(delta.dot(x_axis));
152 min_y = min_y.min(delta.dot(y_axis));
153 max_y = max_y.max(delta.dot(y_axis));
154 }
155 let padding = (max_x - min_x).max(max_y - min_y) * 0.05 + 1e-6;
156 let origin = frame
157 .centroid
158 .add(x_axis.scale(min_x - padding))
159 .add(y_axis.scale(min_y - padding));
160 let surface = make_plane(
161 origin,
162 x_axis,
163 y_axis,
164 max_x - min_x + 2.0 * padding,
165 max_y - min_y + 2.0 * padding,
166 )
167 .or_refuse(KernelStage::Fragment, "cap_plane")?;
168 let mut coedges = Vec::with_capacity(curves.len());
169 if outward {
170 for (index, curve) in curves.iter().enumerate() {
171 coedges.push(CoedgeRecord {
172 id: *next_id,
173 edge_id: edge_ids[index],
174 forward: true,
175 pcurve: curve_to_plane_parameters(curve, origin, x_axis, y_axis)
176 .or_refuse(KernelStage::Fragment, "cap_pcurve")?,
177 });
178 *next_id += 1;
179 }
180 } else {
181 for index in (0..curves.len()).rev() {
182 coedges.push(CoedgeRecord {
183 id: *next_id,
184 edge_id: edge_ids[index],
185 forward: false,
186 pcurve: curve_to_plane_parameters(&curves[index], origin, x_axis, y_axis)
187 .or_refuse(KernelStage::Fragment, "cap_pcurve")?
188 .reversed()
189 .or_refuse(KernelStage::Fragment, "cap_pcurve")?,
190 });
191 *next_id += 1;
192 }
193 }
194 let loop_id = *next_id;
195 *next_id += 1;
196 let face_id = *next_id;
197 *next_id += 1;
198 Ok(FaceRecord {
199 id: face_id,
200 surface,
201 same_sense: outward,
202 loops: vec![LoopRecord {
203 id: loop_id,
204 coedges,
205 }],
206 name: None,
207 })
208}
209
210pub fn loft_profile_brep(input_sections: &[Vec<NurbsCurve>]) -> Result<BrepSolid, KernelRefusal> {
215 loft_profile_brep_core(input_sections, None, &[])
216}
217
218pub fn loft_profile_brep_broken(
224 input_sections: &[Vec<NurbsCurve>],
225 breaks: &[usize],
226) -> Result<BrepSolid, KernelRefusal> {
227 loft_profile_brep_core(input_sections, None, breaks)
228}
229
230pub fn loft_profile_brep_tangent(
237 input_sections: &[Vec<NurbsCurve>],
238 start_direction: Vec3,
239 end_direction: Vec3,
240) -> Result<BrepSolid, KernelRefusal> {
241 let start = start_direction.normalized().map_err(|_| {
242 KernelRefusal::input(
243 KernelStage::Collect,
244 "start_tangent",
245 "loftSolid: start tangent must be a nonzero direction",
246 )
247 })?;
248 let end = end_direction.normalized().map_err(|_| {
249 KernelRefusal::input(
250 KernelStage::Collect,
251 "end_tangent",
252 "loftSolid: end tangent must be a nonzero direction",
253 )
254 })?;
255 loft_profile_brep_core(input_sections, Some((start, end)), &[])
256}
257
258fn loft_profile_brep_core(
259 input_sections: &[Vec<NurbsCurve>],
260 end_tangents: Option<(Vec3, Vec3)>,
261 breaks: &[usize],
262) -> Result<BrepSolid, KernelRefusal> {
263 let mut profile = super::ConstructionProfile::new("loft");
264 let tolerance = 1e-6;
265 let section_count = input_sections.len();
266 if section_count < 2 {
267 return Err(KernelRefusal::input(
268 KernelStage::Collect,
269 "section_count",
270 "loftSolid: need at least 2 sections",
271 ));
272 }
273 let mut sections = input_sections.to_vec();
274 let ruled = section_count == 2 && end_tangents.is_none();
277 if !breaks.is_empty() && (end_tangents.is_some() || breaks.iter().any(|&b| b == 0 || b >= section_count - 1)) {
278 return Err(KernelRefusal::internal(
279 KernelStage::Collect,
280 "loft_breaks",
281 format!("loftSolid: column breaks {breaks:?} must be interior to {section_count} sections and need no end tangents"),
282 ));
283 }
284 let curve_count = if ruled {
285 super::validation::validate_section_loops(§ions, tolerance, "loftSolid")?
286 } else {
287 validate_sections(§ions, tolerance, "loftSolid", true)?
288 };
289
290 let first_frame = section_frame(§ions[0], tolerance)?;
291 let last_frame = section_frame(§ions[section_count - 1], tolerance)?;
292 if !first_frame.planar || !last_frame.planar {
293 return Err(KernelRefusal::unsupported(
294 KernelStage::Classify,
295 "planar_end_sections",
296 "loftSolid: end sections must be planar",
297 ));
298 }
299 last_frame
302 .centroid
303 .sub(first_frame.centroid)
304 .normalized()
305 .map_err(|_| {
306 KernelRefusal::input(
307 KernelStage::Classify,
308 "coincident_ends",
309 "loftSolid: end sections coincide",
310 )
311 })?;
312 let start_advance = advance_from(
315 §ions,
316 first_frame.centroid,
317 first_frame.normal,
318 1..section_count,
319 tolerance,
320 )?
321 .ok_or_else(|| {
322 KernelRefusal::input(
323 KernelStage::Classify,
324 "start_in_plane",
325 "loftSolid: the loft runs inside its START section's plane — every later section \
326 lies in it, so the start cap would be a sliver rather than a face",
327 )
328 })?;
329 let finish_advance = advance_from(
332 §ions,
333 last_frame.centroid,
334 last_frame.normal,
335 (0..section_count - 1).rev(),
336 tolerance,
337 )?
338 .map(|step| step.scale(-1.0))
339 .ok_or_else(|| {
340 KernelRefusal::input(
341 KernelStage::Classify,
342 "end_in_plane",
343 "loftSolid: the loft runs inside its END section's plane — every earlier section \
344 lies in it, so the end cap would be a sliver rather than a face",
345 )
346 })?;
347 let first_normal = if first_frame.normal.dot(start_advance) >= 0.0 {
348 first_frame.normal
349 } else {
350 first_frame.normal.scale(-1.0)
351 };
352 let x_axis = first_normal
353 .perpendicular()
354 .or_refuse(KernelStage::Classify, "section_frame")?;
355 let y_axis = first_normal
356 .cross(x_axis)
357 .normalized()
358 .or_refuse(KernelStage::Classify, "section_frame")?;
359 let mut section_reversed = Vec::with_capacity(section_count);
395 section_reversed.push(
396 profile_area(§ions[0], first_frame.centroid, x_axis, y_axis)
397 .or_refuse(KernelStage::Classify, "profile_area")?
398 < 0.0,
399 );
400 let mut previous_normal = if section_reversed[0] {
401 first_frame.normal.scale(-1.0)
402 } else {
403 first_frame.normal
404 };
405 for section in sections.iter().skip(1) {
406 let normal = section_frame(section, tolerance)?.normal;
407 let flip = normal.dot(previous_normal) < 0.0;
408 section_reversed.push(flip);
409 previous_normal = if flip { normal.scale(-1.0) } else { normal };
410 }
411 let reversed_winding = section_reversed[0];
414 for (index, flip) in section_reversed.into_iter().enumerate() {
415 if flip {
416 sections[index] = reverse_section(§ions[index])?;
417 }
418 }
419
420 if ruled {
421 for curve_index in 0..curve_count {
425 let family = [
426 sections[0][curve_index].clone(),
427 sections[1][curve_index].clone(),
428 ];
429 if family[0].degree == family[1].degree
431 && family[0].knots == family[1].knots
432 && family[0].control_points.len() == family[1].control_points.len()
433 {
434 continue;
435 }
436 let (compatible, _) = crate::coons::compat::make_family_compatible(&family, 1)
437 .or_refuse(KernelStage::Refine, "section_compatibility")?;
438 for (section, curve) in sections.iter_mut().zip(compatible) {
439 section[curve_index] = curve;
440 }
441 }
442 }
443
444 profile.lap("profile");
445 let mut parameters = vec![0.0; section_count];
446 let mut accumulated = vec![0.0; section_count];
447 let mut columns = 0usize;
448 for curve_index in 0..curve_count {
449 for control_index in 0..sections[0][curve_index].control_points.len() {
450 let mut total = 0.0;
451 let mut chords = vec![0.0; section_count];
452 for section_index in 1..section_count {
453 let previous = sections[section_index - 1][curve_index].control_points
454 [control_index]
455 .point()
456 .or_refuse(KernelStage::Refine, "control_point")?;
457 let current = sections[section_index][curve_index].control_points[control_index]
458 .point()
459 .or_refuse(KernelStage::Refine, "control_point")?;
460 total += current.sub(previous).length();
461 chords[section_index] = total;
462 }
463 if total <= tolerance {
464 continue;
465 }
466 for section_index in 0..section_count {
467 accumulated[section_index] += chords[section_index] / total;
468 }
469 columns += 1;
470 }
471 }
472 if columns == 0 {
473 return Err(KernelRefusal::input(
474 KernelStage::Classify,
475 "coincident_sections",
476 "loftSolid: sections coincide",
477 ));
478 }
479 for index in 0..section_count {
480 parameters[index] = accumulated[index] / columns as f64;
481 }
482 parameters[0] = 0.0;
483 parameters[section_count - 1] = 1.0;
484 if parameters.windows(2).any(|pair| pair[1] <= pair[0] + 1e-9) {
485 return Err(KernelRefusal::input(
486 KernelStage::Classify,
487 "section_order",
488 "loftSolid: sections are not strictly ordered",
489 ));
490 }
491 let degree_v = if end_tangents.is_some() || !breaks.is_empty() {
494 3
495 } else {
496 3usize.min(section_count - 1)
497 };
498 let mut skins = Vec::with_capacity(curve_count);
499 for curve_index in 0..curve_count {
500 let reference = §ions[0][curve_index];
501 if ruled {
502 let grid = reference
506 .control_points
507 .iter()
508 .zip(§ions[1][curve_index].control_points)
509 .map(|(&start, &end)| vec![start, end])
510 .collect();
511 skins.push(
512 NurbsSurface::new(
513 reference.degree,
514 1,
515 reference.knots.clone(),
516 vec![0.0, 0.0, 1.0, 1.0],
517 grid,
518 )
519 .or_refuse(KernelStage::Fragment, "skin")?,
520 );
521 continue;
522 }
523 let mut grid = Vec::with_capacity(reference.control_points.len());
524 let mut knots_v = Vec::new();
525 for control_index in 0..reference.control_points.len() {
526 let points = sections
527 .iter()
528 .map(|section| section[curve_index].control_points[control_index].point())
529 .collect::<Result<Vec<_>, String>>()
530 .or_refuse(KernelStage::Refine, "control_point")?;
531 let interpolated = match end_tangents {
532 None if !breaks.is_empty() => super::broken::interpolate_column_broken(&points, ¶meters, breaks)
533 .or_refuse(KernelStage::Refine, "interpolate_broken")?,
534 None => interpolate_curve(&points, degree_v, ¶meters)
535 .or_refuse(KernelStage::Refine, "interpolate")?,
536 Some((start_direction, end_direction)) => {
537 let chord: f64 = points
538 .windows(2)
539 .map(|pair| pair[1].sub(pair[0]).length())
540 .sum();
541 let magnitude = if chord > tolerance { chord } else { 1.0 };
544 crate::interpolate_curve_with_end_tangents(
545 &points,
546 ¶meters,
547 start_direction.scale(magnitude),
548 end_direction.scale(magnitude),
549 )
550 .or_refuse(KernelStage::Refine, "interpolate_tangent")?
551 }
552 };
553 knots_v = interpolated.knots.clone();
554 let weight = reference.control_points[control_index].w;
555 grid.push(
556 interpolated
557 .control_points
558 .iter()
559 .map(|point| Vec4::from_point(point.point().unwrap(), weight))
560 .collect(),
561 );
562 }
563 skins.push(NurbsSurface::new(
564 reference.degree,
565 degree_v,
566 reference.knots.clone(),
567 knots_v,
568 grid,
569 )
570 .or_refuse(KernelStage::Fragment, "skin")?);
571 }
572
573 profile.lap("surface");
574 let bottom = §ions[0];
575 let top = §ions[section_count - 1];
576 let bottom_points = closed_points(bottom, tolerance)?;
577 let top_points = closed_points(top, tolerance)?;
578 let mut vertices = Vec::with_capacity(2 * curve_count);
579 for (index, point) in bottom_points.iter().chain(&top_points).enumerate() {
580 vertices.push(VertexRecord {
581 id: index as u64 + 1,
582 point: *point,
583 });
584 }
585 let mut edges = Vec::with_capacity(3 * curve_count);
586 let mut bottom_edge_ids = Vec::new();
587 let mut top_edge_ids = Vec::new();
588 let mut vertical_edge_ids = Vec::new();
589 for index in 0..curve_count {
590 let [start, end] = bottom[index]
591 .domain()
592 .or_refuse(KernelStage::Fragment, "domain")?;
593 let [top_start, top_end] = top[index]
602 .domain()
603 .or_refuse(KernelStage::Fragment, "domain")?;
604 let bottom_id = 10 + index as u64;
605 let top_id = 10 + curve_count as u64 + index as u64;
606 let vertical_id = 10 + 2 * curve_count as u64 + index as u64;
607 bottom_edge_ids.push(bottom_id);
608 top_edge_ids.push(top_id);
609 vertical_edge_ids.push(vertical_id);
610 edges.push(EdgeRecord {
611 id: bottom_id,
612 curve: bottom[index].clone(),
613 t0: start,
614 t1: end,
615 start_vertex_id: index as u64 + 1,
616 end_vertex_id: ((index + 1) % curve_count) as u64 + 1,
617 degenerate: false,
618 name: None,
619 });
620 edges.push(EdgeRecord {
621 id: top_id,
622 curve: top[index].clone(),
623 t0: top_start,
624 t1: top_end,
625 start_vertex_id: (curve_count + index) as u64 + 1,
626 end_vertex_id: (curve_count + (index + 1) % curve_count) as u64 + 1,
627 degenerate: false,
628 name: None,
629 });
630 let vertical = skins[index]
631 .iso_curve_u(start)
632 .or_refuse(KernelStage::Fragment, "iso_curve")?;
633 let [v_start, v_end] = vertical
634 .domain()
635 .or_refuse(KernelStage::Fragment, "domain")?;
636 edges.push(EdgeRecord {
637 id: vertical_id,
638 curve: vertical,
639 t0: v_start,
640 t1: v_end,
641 start_vertex_id: index as u64 + 1,
642 end_vertex_id: (curve_count + index) as u64 + 1,
643 degenerate: false,
644 name: None,
645 });
646 }
647
648 profile.lap("edges");
649 let mut next_id = 1000u64;
650 let mut faces = Vec::with_capacity(curve_count + 2);
651 for index in 0..curve_count {
652 let [start, end] = bottom[index]
653 .domain()
654 .or_refuse(KernelStage::Fragment, "domain")?;
655 let coedges = vec![
656 CoedgeRecord {
657 id: next_id,
658 edge_id: bottom_edge_ids[index],
659 forward: true,
660 pcurve: parameter_line(start, 0.0, end, 0.0)
661 .or_refuse(KernelStage::Fragment, "pcurve")?,
662 },
663 CoedgeRecord {
664 id: next_id + 1,
665 edge_id: vertical_edge_ids[(index + 1) % curve_count],
666 forward: true,
667 pcurve: parameter_line(end, 0.0, end, 1.0)
668 .or_refuse(KernelStage::Fragment, "pcurve")?,
669 },
670 CoedgeRecord {
671 id: next_id + 2,
672 edge_id: top_edge_ids[index],
673 forward: false,
674 pcurve: parameter_line(end, 1.0, start, 1.0)
675 .or_refuse(KernelStage::Fragment, "pcurve")?,
676 },
677 CoedgeRecord {
678 id: next_id + 3,
679 edge_id: vertical_edge_ids[index],
680 forward: false,
681 pcurve: parameter_line(start, 1.0, start, 0.0)
682 .or_refuse(KernelStage::Fragment, "pcurve")?,
683 },
684 ];
685 next_id += 4;
686 let loop_id = next_id;
687 next_id += 1;
688 let face_id = next_id;
689 next_id += 1;
690 faces.push(FaceRecord {
691 id: face_id,
692 surface: skins[index].clone(),
693 same_sense: true,
694 loops: vec![LoopRecord {
695 id: loop_id,
696 coedges,
697 }],
698 name: None,
699 });
700 }
701 if reversed_winding {
702 faces.reverse();
707 }
708 faces.push(cap_face(
709 bottom,
710 &bottom_edge_ids,
711 &first_frame,
712 start_advance,
713 false,
714 &mut next_id,
715 )?);
716 faces.push(cap_face(
717 top,
718 &top_edge_ids,
719 &last_frame,
720 finish_advance,
721 true,
722 &mut next_id,
723 )?);
724 let solid = BrepSolid {
725 mass_properties_cache: Default::default(),
726 cells: Default::default(),
727 id: next_id + 1,
728 vertices,
729 edges,
730 shells: vec![ShellRecord { id: next_id, faces }],
731 genus: 0,
732 kind: crate::BodyKind::Solid,
733 };
734 profile.lap("topology_pcurves");
735 let issues = solid.validate();
736 profile.lap("validation");
737 if !issues.is_empty() {
738 return Err(KernelRefusal::internal(
739 KernelStage::Validate,
740 "validate",
741 format!(
742 "Rust loft builder produced invalid topology: {issues:?}"
743 ),
744 ));
745 }
746 let accepted = crate::accept_sound(solid, "loftSolid");
752 profile.lap("acceptance");
753 accepted
754}