1use super::*;
2
3pub fn loft_profile_brep_closed(
12 input_sections: &[Vec<NurbsCurve>],
13) -> Result<BrepSolid, KernelRefusal> {
14 loft_profile_brep_closed_shifted(input_sections, 0)
15}
16
17const MAX_SHIFTED_COLUMN_STATIONS: usize = 1024;
21
22pub fn loft_profile_brep_closed_shifted(
47 input_sections: &[Vec<NurbsCurve>],
48 shift: usize,
49) -> Result<BrepSolid, KernelRefusal> {
50 loft_profile_brep_closed_core(input_sections, shift, None)
51}
52
53pub fn loft_profile_brep_closed_broken(
60 input_sections: &[Vec<NurbsCurve>],
61 breaks: &[usize],
62) -> Result<BrepSolid, KernelRefusal> {
63 loft_profile_brep_closed_core(input_sections, 0, Some(breaks))
64}
65
66fn loft_profile_brep_closed_core(
67 input_sections: &[Vec<NurbsCurve>],
68 shift: usize,
69 breaks: Option<&[usize]>,
70) -> Result<BrepSolid, KernelRefusal> {
71 let tolerance = 1e-6;
72 let section_count = input_sections.len();
73 if section_count < 4 {
74 return Err(KernelRefusal::input(
75 KernelStage::Collect,
76 "section_count",
77 "loftSolid: a closed loft needs at least 4 sections",
78 ));
79 }
80 let sections = input_sections.to_vec();
81 let curve_count = validate_sections(§ions, tolerance, "loftSolid", false)?;
82 if shift >= curve_count {
83 return Err(KernelRefusal::input(
84 KernelStage::Collect,
85 "seam_shift",
86 format!(
87 "loftSolid: a closed loft's seam shift {shift} must be below its {curve_count} curves"
88 ),
89 ));
90 }
91 let landing = |curve_index: usize| (curve_index + shift) % curve_count;
93 for curve_index in 0..curve_count {
94 let (from, to) = (§ions[0][curve_index], §ions[0][landing(curve_index)]);
95 if from.degree != to.degree
96 || from.control_points.len() != to.control_points.len()
97 || from.knots.len() != to.knots.len()
98 || from.knots.iter().zip(&to.knots).any(|(a, b)| (a - b).abs() > 1e-9)
99 || from
100 .control_points
101 .iter()
102 .zip(&to.control_points)
103 .any(|(a, b)| (a.w - b.w).abs() > 1e-12 * a.w.abs().max(1.0))
104 {
105 return Err(KernelRefusal::input(
106 KernelStage::Collect,
107 "seam_compatibility",
108 format!(
109 "loftSolid: curve {curve_index} flows across the seam into curve {}, and the two \
110 are not representation-compatible",
111 landing(curve_index)
112 ),
113 ));
114 }
115 }
116
117 let mut accumulated = vec![0.0; section_count + 1];
120 let mut columns = 0usize;
121 for curve_index in 0..curve_count {
122 for control_index in 0..sections[0][curve_index].control_points.len() {
123 let mut chords = vec![0.0; section_count + 1];
124 let mut total = 0.0;
125 for station in 1..=section_count {
126 let previous = sections[station - 1][curve_index].control_points[control_index]
127 .point()
128 .or_refuse(KernelStage::Refine, "control_point")?;
129 let across = if station == section_count {
130 landing(curve_index)
131 } else {
132 curve_index
133 };
134 let current = sections[station % section_count][across].control_points
135 [control_index]
136 .point()
137 .or_refuse(KernelStage::Refine, "control_point")?;
138 total += current.sub(previous).length();
139 chords[station] = total;
140 }
141 if total <= tolerance {
142 continue;
143 }
144 for station in 0..=section_count {
145 accumulated[station] += chords[station] / total;
146 }
147 columns += 1;
148 }
149 }
150 if columns == 0 {
151 return Err(KernelRefusal::input(
152 KernelStage::Classify,
153 "coincident_sections",
154 "loftSolid: sections coincide",
155 ));
156 }
157 let mut parameters = vec![0.0; section_count + 1];
158 for station in 0..=section_count {
159 parameters[station] = accumulated[station] / columns as f64;
160 }
161 parameters[0] = 0.0;
162 parameters[section_count] = 1.0;
163 if parameters.windows(2).any(|pair| pair[1] <= pair[0] + 1e-9) {
164 return Err(KernelRefusal::input(
165 KernelStage::Classify,
166 "section_order",
167 "loftSolid: closed sections are not strictly ordered",
168 ));
169 }
170
171 if let Some(breaks) = breaks.filter(|breaks| shift != 0 || breaks.iter().any(|&b| b == 0 || b >= section_count)) {
172 return Err(KernelRefusal::internal(
173 KernelStage::Collect,
174 "loft_breaks",
175 format!("loftSolid: closed column breaks {breaks:?} must be interior to {section_count} sections on an unshifted ring"),
176 ));
177 }
178 let mut skins = Vec::with_capacity(curve_count);
179 if shift == 0 {
180 for curve_index in 0..curve_count {
181 let reference = §ions[0][curve_index];
182 let mut grid = Vec::with_capacity(reference.control_points.len());
183 let mut knots_v = Vec::new();
184 for control_index in 0..reference.control_points.len() {
185 let points = sections
186 .iter()
187 .map(|section| section[curve_index].control_points[control_index].point())
188 .collect::<Result<Vec<_>, String>>()
189 .or_refuse(KernelStage::Refine, "control_point")?;
190 let interpolated = if let Some(breaks) = breaks {
191 let mut unrolled = points.clone();
193 unrolled.push(points[0]);
194 super::broken::interpolate_column_broken(&unrolled, ¶meters, breaks)
195 .or_refuse(KernelStage::Refine, "interpolate_broken")?
196 } else {
197 crate::interpolate_curve_closed(&points, ¶meters)
198 .or_refuse(KernelStage::Refine, "interpolate_closed")?
199 };
200 knots_v = interpolated.knots.clone();
201 let weight = reference.control_points[control_index].w;
202 grid.push(
203 interpolated
204 .control_points
205 .iter()
206 .map(|point| Vec4::from_point(point.point().unwrap(), weight))
207 .collect(),
208 );
209 }
210 skins.push(NurbsSurface::new(
211 reference.degree,
212 3,
213 reference.knots.clone(),
214 knots_v,
215 grid,
216 )
217 .or_refuse(KernelStage::Fragment, "skin")?);
218 }
219 } else {
220 skins = shifted_skins(§ions, ¶meters, curve_count, shift)?;
221 }
222
223 let base_points = closed_points(§ions[0], tolerance)?;
227 let mut vertices = Vec::with_capacity(curve_count);
228 for (index, point) in base_points.iter().enumerate() {
229 vertices.push(VertexRecord {
230 id: index as u64 + 1,
231 point: *point,
232 });
233 }
234 let mut edges = Vec::with_capacity(2 * curve_count);
235 let mut ring_edge_ids = Vec::with_capacity(curve_count);
236 let mut seam_edge_ids = Vec::with_capacity(curve_count);
237 for index in 0..curve_count {
238 let [u_start, u_end] = sections[0][index]
239 .domain()
240 .or_refuse(KernelStage::Fragment, "domain")?;
241 let _ = u_end;
242 let ring = skins[index]
243 .iso_curve_u(u_start)
244 .or_refuse(KernelStage::Fragment, "iso_curve")?;
245 let [ring_start, ring_end] = ring
246 .domain()
247 .or_refuse(KernelStage::Fragment, "domain")?;
248 let ring_id = 100 + index as u64;
249 ring_edge_ids.push(ring_id);
250 edges.push(EdgeRecord {
251 id: ring_id,
252 curve: ring,
253 t0: ring_start,
254 t1: ring_end,
255 start_vertex_id: index as u64 + 1,
256 end_vertex_id: landing(index) as u64 + 1,
257 degenerate: false,
258 name: None,
259 });
260 let seam = sections[0][index].clone();
261 let [seam_start, seam_end] = seam
262 .domain()
263 .or_refuse(KernelStage::Fragment, "domain")?;
264 let seam_id = 100 + curve_count as u64 + index as u64;
265 seam_edge_ids.push(seam_id);
266 edges.push(EdgeRecord {
267 id: seam_id,
268 curve: seam,
269 t0: seam_start,
270 t1: seam_end,
271 start_vertex_id: index as u64 + 1,
272 end_vertex_id: ((index + 1) % curve_count) as u64 + 1,
273 degenerate: false,
274 name: None,
275 });
276 }
277
278 let mut next_id = 1000u64;
279 let mut faces = Vec::with_capacity(curve_count);
280 for index in 0..curve_count {
281 let [u_start, u_end] = sections[0][index]
282 .domain()
283 .or_refuse(KernelStage::Fragment, "domain")?;
284 let coedges = vec![
288 CoedgeRecord {
289 id: next_id,
290 edge_id: seam_edge_ids[index],
291 forward: true,
292 pcurve: parameter_line(u_start, 0.0, u_end, 0.0)
293 .or_refuse(KernelStage::Fragment, "pcurve")?,
294 },
295 CoedgeRecord {
296 id: next_id + 1,
297 edge_id: ring_edge_ids[(index + 1) % curve_count],
298 forward: true,
299 pcurve: parameter_line(u_end, 0.0, u_end, 1.0)
300 .or_refuse(KernelStage::Fragment, "pcurve")?,
301 },
302 CoedgeRecord {
303 id: next_id + 2,
304 edge_id: seam_edge_ids[landing(index)],
305 forward: false,
306 pcurve: parameter_line(u_end, 1.0, u_start, 1.0)
307 .or_refuse(KernelStage::Fragment, "pcurve")?,
308 },
309 CoedgeRecord {
310 id: next_id + 3,
311 edge_id: ring_edge_ids[index],
312 forward: false,
313 pcurve: parameter_line(u_start, 1.0, u_start, 0.0)
314 .or_refuse(KernelStage::Fragment, "pcurve")?,
315 },
316 ];
317 next_id += 4;
318 let loop_id = next_id;
319 next_id += 1;
320 let face_id = next_id;
321 next_id += 1;
322 faces.push(FaceRecord {
323 id: face_id,
324 surface: skins[index].clone(),
325 same_sense: true,
326 loops: vec![LoopRecord {
327 id: loop_id,
328 coedges,
329 }],
330 name: None,
331 });
332 }
333
334 let mut solid = BrepSolid {
335 mass_properties_cache: Default::default(),
336 cells: Default::default(),
337 id: next_id,
338 vertices,
339 edges,
340 shells: vec![ShellRecord {
341 id: next_id + 1,
342 faces,
343 }],
344 genus: 1,
345 kind: crate::BodyKind::Solid,
346 };
347 let issues = solid.validate();
348 if !issues.is_empty() {
349 return Err(KernelRefusal::internal(
350 KernelStage::Validate,
351 "validate",
352 format!(
353 "loftSolid: closed loft failed validation: {issues:?}"
354 ),
355 ));
356 }
357 if crate::solid_signed_volume(&solid).or_refuse(KernelStage::Validate, "signed_volume")? < 0.0
360 {
361 crate::orientation::flip_all_faces(&mut solid)
362 ?;
363 }
364 crate::accept_sound(solid, "loftSolid")
368}
369
370fn shifted_skins(
374 sections: &[Vec<NurbsCurve>],
375 parameters: &[f64],
376 curve_count: usize,
377 shift: usize,
378) -> Result<Vec<NurbsSurface>, KernelRefusal> {
379 let section_count = sections.len();
380 let gcd = |mut a: usize, mut b: usize| {
381 while b != 0 {
382 (a, b) = (b, a % b);
383 }
384 a
385 };
386 let laps = curve_count / gcd(curve_count, shift);
387 if laps * section_count > MAX_SHIFTED_COLUMN_STATIONS {
388 return Err(KernelRefusal::unsupported(
391 KernelStage::Collect,
392 "station_cap",
393 format!(
394 "loftSolid: a ring whose curves land {shift} along after one lap runs each skin \
395 through {laps} laps of {section_count} stations, {} in all, past the \
396 {MAX_SHIFTED_COLUMN_STATIONS}-station cap the loft's dense column solve can carry",
397 laps * section_count
398 ),
399 ));
400 }
401 let mut lap_knots = vec![parameters[0]; 4];
403 lap_knots.extend_from_slice(¶meters[1..section_count]);
404 lap_knots.extend(std::iter::repeat_n(parameters[section_count], 4));
405 let mut lap_parameters = Vec::with_capacity(laps * section_count + 1);
406 for lap in 0..laps {
407 for station in 0..section_count {
408 lap_parameters.push(lap as f64 + parameters[station]);
409 }
410 }
411 lap_parameters.push(laps as f64);
412
413 let mut grids: Vec<Vec<Vec<Vec4>>> = sections[0]
414 .iter()
415 .map(|curve| vec![Vec::new(); curve.control_points.len()])
416 .collect();
417 let mut visited = vec![false; curve_count];
418 for start in 0..curve_count {
419 if visited[start] {
420 continue;
421 }
422 let cycle: Vec<usize> = (0..laps).map(|lap| (start + lap * shift) % curve_count).collect();
423 for &curve_index in &cycle {
424 visited[curve_index] = true;
425 }
426 for control_index in 0..sections[0][start].control_points.len() {
427 let mut points = Vec::with_capacity(laps * section_count);
428 for &curve_index in &cycle {
429 for section in sections {
430 points.push(
431 section[curve_index].control_points[control_index]
432 .point()
433 .or_refuse(KernelStage::Refine, "control_point")?,
434 );
435 }
436 }
437 let mut rest = crate::interpolate_curve_closed(&points, &lap_parameters)
438 .or_refuse(KernelStage::Refine, "interpolate_closed")?;
439 for (lap, &curve_index) in cycle.iter().enumerate() {
440 let piece = if lap + 1 < laps {
441 let (piece, remainder) = rest
442 .split((lap + 1) as f64)
443 .or_refuse(KernelStage::Refine, "split")?;
444 rest = remainder;
445 piece
446 } else {
447 rest.clone()
448 };
449 if piece.knots.len() != lap_knots.len()
450 || piece
451 .knots
452 .iter()
453 .zip(&lap_knots)
454 .any(|(knot, own)| (knot - lap as f64 - own).abs() > 1e-9)
455 {
456 return Err(KernelRefusal::internal(
457 KernelStage::Refine,
458 "lap_split",
459 format!(
460 "loftSolid: lap {lap} of a shifted ring's column did not split onto the \
461 lap's own knots"
462 ),
463 ));
464 }
465 let weight = sections[0][curve_index].control_points[control_index].w;
466 grids[curve_index][control_index] = piece
467 .control_points
468 .iter()
469 .map(|point| Ok(Vec4::from_point(point.point()?, weight)))
470 .collect::<Result<Vec<_>, String>>()
471 .or_refuse(KernelStage::Refine, "control_point")?;
472 }
473 }
474 }
475 sections[0]
476 .iter()
477 .zip(grids)
478 .map(|(reference, grid)| {
479 NurbsSurface::new(reference.degree, 3, reference.knots.clone(), lap_knots.clone(), grid)
480 })
481 .collect::<Result<Vec<_>, String>>()
482 .or_refuse(KernelStage::Fragment, "skin")
483}