Skip to main content

brep_kernel/feature_pipeline/features/
common.rs

1//! Shared feature parameters, reference resolution, and solid operations.
2
3use rustc_hash::FxHashSet;
4
5use crate::feature_pipeline::{
6    AddedSolid, Axis, EdgeRef, FaceRef, FeatureContext, FeatureResult, Frame, SketchProfile,
7};
8use crate::{AffineTransform, BooleanOperation, BooleanOptions, BrepSolid, NurbsCurve, Vec3, transform_brep};
9
10/// Rotate a solid a half turn (180°) about the local X axis. This is a PROPER
11/// rotation (determinant +1), so `transform_brep` preserves face winding and every
12/// stamped face name. It realizes a NEGATIVE directional dimension: a primitive
13/// built along +Y with the value's MAGNITUDE is spun to occupy the -Y side, and a
14/// partial revolve/torus sweep is spun to the opposite side — exactly the geometry
15/// a signed value implies. `(x, y, z) -> (x, -y, -z)`.
16pub fn rotate_half_turn_about_x(solid: BrepSolid) -> Result<BrepSolid, String> {
17    let half_turn = AffineTransform::new([
18        1.0, 0.0, 0.0, 0.0,
19        0.0, -1.0, 0.0, 0.0,
20        0.0, 0.0, -1.0, 0.0,
21        0.0, 0.0, 0.0, 1.0,
22    ])?;
23    transform_brep(&solid, half_turn, false)
24}
25
26/// Collect `(face_id, name)` for every NAMED face, in shell/face order.
27pub fn collect_face_names(solid: &BrepSolid) -> Vec<(u64, String)> {
28    let mut names = Vec::new();
29    for shell in &solid.shells {
30        for face in &shell.faces {
31            if let Some(name) = &face.name {
32                names.push((face.id, name.clone()));
33            }
34        }
35    }
36    names
37}
38
39/// Collect `(edge_id, name)` for every NAMED edge.
40pub fn collect_edge_names(solid: &BrepSolid) -> Vec<(u64, String)> {
41    solid
42        .edges
43        .iter()
44        .filter_map(|edge| edge.name.as_ref().map(|name| (edge.id, name.clone())))
45        .collect()
46}
47
48/// Stamp one face's operation-role metadata (`faceRole` + `operationFaceType`,
49/// the established Sweep/Revolve convention the PMI dimension UI and tests read) into the
50/// kernel scene-metadata store, keyed by face NAME so it follows the face
51/// through booleans. Only the role keys are stamped — geometric metadata
52/// (`faceType`/`surfaceType`) stays inferred from the surface on the read side.
53pub fn stamp_face_role(face_name: &str, role: &str, op_type: &str) {
54    let mut record = serde_json::Map::new();
55    record.insert("faceRole".into(), serde_json::Value::String(role.into()));
56    record.insert(
57        "operationFaceType".into(),
58        serde_json::Value::String(op_type.into()),
59    );
60    crate::feature_pipeline::scene_metadata::merge_record(face_name, &record, true);
61}
62
63/// Stamp the whole sweep-family role convention on a BUILT solid's named faces:
64/// `start_name`/`end_name` → `start_cap`/`STARTCAP` + `end_cap`/`ENDCAP`, any
65/// other name ending in `wall_suffix` → `sidewall`/`SIDEWALL`. Walking the
66/// actual faces (not the intended name list) means an absent cap (full revolve)
67/// or a skipped axis wall never leaves a phantom record in the store.
68pub fn stamp_sweep_roles(solid: &BrepSolid, wall_suffix: &str, start_name: &str, end_name: &str) {
69    stamp_sweep_roles_multi(
70        solid,
71        wall_suffix,
72        std::slice::from_ref(&start_name.to_string()),
73        std::slice::from_ref(&end_name.to_string()),
74    );
75}
76
77/// [`stamp_sweep_roles`] for a profile with SEVERAL loops: each region names its
78/// own caps (`{cap_base}:L{loopId}_START`), so the role pass takes the whole
79/// list rather than one name per end.
80pub fn stamp_sweep_roles_multi(
81    solid: &BrepSolid,
82    wall_suffix: &str,
83    start_names: &[String],
84    end_names: &[String],
85) {
86    for face in solid.shells.iter().flat_map(|shell| shell.faces.iter()) {
87        let Some(name) = face.name.as_deref() else {
88            continue;
89        };
90        if start_names.iter().any(|start| start == name) {
91            stamp_face_role(name, "start_cap", "STARTCAP");
92        } else if end_names.iter().any(|end| end == name) {
93            stamp_face_role(name, "end_cap", "ENDCAP");
94        } else if name.ends_with(wall_suffix) {
95            stamp_face_role(name, "sidewall", "SIDEWALL");
96        }
97    }
98}
99
100/// The per-loop cap names of one profile-swept feature, plus the CONTAINER names
101/// they roll up into — the single place the per-loop cap convention is spelled,
102/// shared by extrude/sweep/revolve/path-sweep/loft so the five stay byte-identical.
103///
104/// `{cap_base}:{loop key}_START` / `_END` per region (see [`ProfileLoop::key`]),
105/// with `{cap_base}_START` / `_END` as the containers standing for all of them.
106/// A SINGLE-loop profile is the special case that matters most for compatibility:
107/// its one cap keys off its loop like any other, and its container has exactly one
108/// member, so every reference stored before per-loop naming resolves to exactly
109/// the face it always meant.
110pub struct CapNames {
111    /// Per region, in region order: `(start, end)`.
112    pub per_loop: Vec<(String, String)>,
113    pub start_container: String,
114    pub end_container: String,
115}
116
117impl CapNames {
118    /// Build the cap names for `regions` under `cap_base`.
119    ///
120    /// A region whose loop has no identity to key on (a FACE profile, a
121    /// hand-built profile) keeps the un-keyed `{cap_base}_START/_END` spelling it
122    /// has always had — such a profile is single-region, so there is nothing to
123    /// disambiguate and every saved reference to it stays exact.
124    pub fn new(cap_base: &str, regions: &[Vec<crate::feature_pipeline::ProfileLoop>]) -> Self {
125        let per_loop = regions
126            .iter()
127            .map(|region| {
128                match region.first().and_then(|outer| outer.key()) {
129                    Some(key) => (
130                        format!("{cap_base}:{key}_START"),
131                        format!("{cap_base}:{key}_END"),
132                    ),
133                    None => (format!("{cap_base}_START"), format!("{cap_base}_END")),
134                }
135            })
136            .collect();
137        Self {
138            per_loop,
139            start_container: format!("{cap_base}_START"),
140            end_container: format!("{cap_base}_END"),
141        }
142    }
143
144    /// This feature's `(container, members)` pairs for [`register_added_grouped`].
145    /// A container whose only member IS the container name (the un-keyed
146    /// single-region case) is dropped — the face is reachable exactly, so there is
147    /// no group to register.
148    pub fn containers(&self) -> Vec<(String, Vec<String>)> {
149        [
150            (self.start_container.clone(), self.starts()),
151            (self.end_container.clone(), self.ends()),
152        ]
153        .into_iter()
154        .filter(|(container, members)| members.as_slice() != [container.clone()])
155        .collect()
156    }
157
158    /// The INTERIOR cap names of a multi-segment sweep: one path SEGMENT's own
159    /// pair for `region_index`, spelled `{cap_base}:{loop key}:{segment}_START/_END`.
160    ///
161    /// A sweep along several path segments builds one portion per segment, and
162    /// every portion has two caps. The chain's own two ends keep the plain
163    /// per-loop spelling ([`Self::per_loop`]); every cap BETWEEN two portions is
164    /// a copy of the profile that the neighbouring portion's opposite cap cancels
165    /// in the union, so it normally does not reach the result at all. Naming it
166    /// after its segment anyway means that if a path ever leaves one standing
167    /// (a chain that doubles back), it arrives with a name tied to the segment
168    /// that built it instead of a positional `[n]` disambiguation.
169    pub fn interior(&self, region_index: usize, segment: &str) -> (String, String) {
170        let (start, end) = &self.per_loop[region_index];
171        let start_base = start.strip_suffix("_START").unwrap_or(start);
172        let end_base = end.strip_suffix("_END").unwrap_or(end);
173        (
174            format!("{start_base}:{segment}_START"),
175            format!("{end_base}:{segment}_END"),
176        )
177    }
178
179    /// All per-loop START names, for [`stamp_sweep_roles_multi`].
180    pub fn starts(&self) -> Vec<String> {
181        self.per_loop.iter().map(|(start, _)| start.clone()).collect()
182    }
183
184    /// All per-loop END names, for [`stamp_sweep_roles_multi`].
185    pub fn ends(&self) -> Vec<String> {
186        self.per_loop.iter().map(|(_, end)| end.clone()).collect()
187    }
188}
189
190pub(super) fn parse_boolean_operation(operation: &str) -> Result<BooleanOperation, String> {
191    match operation {
192        "UNION" => Ok(BooleanOperation::Union),
193        "SUBTRACT" => Ok(BooleanOperation::Subtract),
194        "INTERSECT" => Ok(BooleanOperation::Intersect),
195        other => Err(format!("unsupported boolean operation '{other}'")),
196    }
197}
198
199/// The optional `boolean` param, parsed from `inputParams.boolean`.
200struct BooleanParam {
201    operation: String,
202    targets: Vec<String>,
203    merge_coplanar_faces: bool,
204}
205
206fn read_boolean_param(ctx: &FeatureContext) -> BooleanParam {
207    let boolean = ctx.param("boolean");
208    let operation = boolean
209        .and_then(|value| value.get("operation"))
210        .and_then(|value| value.as_str())
211        .unwrap_or("NONE")
212        .to_uppercase();
213    let targets = boolean
214        .and_then(|value| value.get("targets"))
215        .and_then(|value| value.as_array())
216        .map(|array| {
217            array
218                .iter()
219                .filter_map(|entry| entry.as_str())
220                .map(|name| name.trim().to_string())
221                .filter(|name| !name.is_empty())
222                .collect()
223        })
224        .unwrap_or_default();
225    let merge_coplanar_faces = boolean
226        .and_then(|value| value.get("mergeCoplanarFaces"))
227        .and_then(|value| value.as_bool())
228        .unwrap_or(true);
229    BooleanParam {
230        operation,
231        targets,
232        merge_coplanar_faces,
233    }
234}
235
236/// Collect up to two distinct face names per edge, preserving first encounter order.
237fn collect_edge_face_names(
238    solid: &BrepSolid,
239) -> (std::collections::HashMap<u64, Vec<String>>, Vec<u64>) {
240    use std::collections::HashMap;
241    let mut edge_faces: HashMap<u64, Vec<String>> = HashMap::new();
242    let mut encounter_order: Vec<u64> = Vec::new();
243    for shell in &solid.shells {
244        for face in &shell.faces {
245            let face_name = face.name.clone().unwrap_or_default();
246            for loop_record in &face.loops {
247                for coedge in &loop_record.coedges {
248                    let entry = edge_faces.entry(coedge.edge_id).or_insert_with(|| {
249                        encounter_order.push(coedge.edge_id);
250                        Vec::new()
251                    });
252                    if entry.len() < 2 && !entry.contains(&face_name) {
253                        entry.push(face_name.clone());
254                    }
255                }
256            }
257        }
258    }
259    (edge_faces, encounter_order)
260}
261
262/// Name topology edges `{faceA}|{faceB}[n]`, sorting adjacent face names and
263/// numbering each pair in shell/face/loop encounter order. Existing names that
264/// contain `|` are regenerated; authored names are preserved.
265pub fn stamp_derived_edge_names(solid: &mut BrepSolid) {
266    use std::collections::HashMap;
267    let (edge_faces, encounter_order) = collect_edge_face_names(solid);
268    let solid_name_fallback = "Solid".to_string();
269    let mut base_counts: HashMap<String, usize> = HashMap::new();
270    for edge_id in encounter_order {
271        let Some(edge) = solid.edges.iter_mut().find(|edge| edge.id == edge_id) else {
272            continue;
273        };
274        if edge.degenerate {
275            continue;
276        }
277        let mut faces: Vec<String> = edge_faces
278            .get(&edge_id)
279            .map(|list| list.iter().filter(|n| !n.is_empty()).cloned().collect())
280            .unwrap_or_default();
281        faces.sort();
282        let base = if faces.len() >= 2 {
283            format!("{}|{}", faces[0], faces[1])
284        } else {
285            format!(
286                "{}|BOUNDARY",
287                faces.first().unwrap_or(&solid_name_fallback)
288            )
289        };
290        // Only topology edges advance the counter, keeping each pair's indices dense.
291        let is_topology_name = edge.name.as_deref().is_none_or(|n| n.contains('|'));
292        if is_topology_name {
293            let index = base_counts.entry(base.clone()).or_insert(0);
294            edge.name = Some(format!("{base}[{index}]"));
295            *index += 1;
296        }
297    }
298}
299
300/// Suffix copied face and authored-edge names with `::{suffix}`, then regenerate
301/// topology-edge names from the renamed faces. This keeps copies distinct from
302/// their sources in the scene's name lookup. Empty names are skipped.
303pub fn namespace_copy_names(solid: &mut BrepSolid, suffix: &str) {
304    for shell in &mut solid.shells {
305        for face in &mut shell.faces {
306            if let Some(name) = face.name.as_ref() {
307                let trimmed = name.trim();
308                if !trimmed.is_empty() {
309                    face.name = Some(format!("{trimmed}::{suffix}"));
310                }
311            }
312        }
313    }
314    for edge in &mut solid.edges {
315        if let Some(name) = edge.name.as_ref() {
316            let trimmed = name.trim();
317            // Topology edges (`|`) are re-derived below from the retagged faces;
318            // authored edges take the suffix directly.
319            if !trimmed.is_empty() && !trimmed.contains('|') {
320                edge.name = Some(format!("{trimmed}::{suffix}"));
321            }
322        }
323    }
324    stamp_derived_edge_names(solid);
325}
326
327/// Disambiguate duplicate face names with `[n]` in shell/face encounter order.
328/// Unique names stay unchanged. Run before [`stamp_derived_edge_names`] so edge
329/// names embed the final face names and scene lookups remain unambiguous.
330pub fn ensure_unique_face_names(solid: &mut BrepSolid) {
331    use std::collections::HashMap;
332    let mut counts: HashMap<String, usize> = HashMap::new();
333    for shell in &solid.shells {
334        for face in &shell.faces {
335            if let Some(name) = &face.name {
336                *counts.entry(name.clone()).or_insert(0) += 1;
337            }
338        }
339    }
340    let mut running: HashMap<String, usize> = HashMap::new();
341    for shell in &mut solid.shells {
342        for face in &mut shell.faces {
343            let Some(name) = face.name.clone() else { continue };
344            if counts.get(&name).copied().unwrap_or(0) > 1 {
345                let index = running.entry(name.clone()).or_insert(0);
346                face.name = Some(format!("{name}[{index}]"));
347                *index += 1;
348            }
349        }
350    }
351}
352
353/// Register a freshly built base solid as a single `AddedSolid` under `name`.
354/// Deduplicates FACE names, then stamps the derived `{faceA}|{faceB}[n]` names
355/// onto the edges (which embed the now-unique face names), so face AND edge
356/// reference_selections both resolve uniquely against the scene.
357pub fn register_added(base: BrepSolid, name: &str) -> AddedSolid {
358    register_added_grouped(base, name, &[])
359}
360
361/// [`register_added`] plus CONTAINER groups: `containers` is
362/// `(container_name, member_face_names)`, the un-keyed name a profile-swept
363/// feature publishes for all of its per-loop faces at once (`{cap_base}_START`
364/// standing for every `{cap_base}:L{id}_START`).
365///
366/// Members are resolved against the FINAL solid, so a face a boolean merged or
367/// consumed simply drops out of its group, and a container whose members all
368/// vanished registers nothing. Each container also gets the EDGE group implied by
369/// it — see [`collect_edge_group_aliases`].
370pub fn register_added_grouped(
371    mut base: BrepSolid,
372    name: &str,
373    containers: &[(String, Vec<String>)],
374) -> AddedSolid {
375    ensure_unique_face_names(&mut base);
376    stamp_derived_edge_names(&mut base);
377    let face_names = collect_face_names(&base);
378    let edge_names = collect_edge_names(&base);
379    let face_groups = collect_face_groups(&face_names, containers);
380    let mut edge_groups = collect_edge_group_aliases(&base, containers);
381    collect_derived_edge_bases(&edge_names, &mut edge_groups);
382    let handle = crate::register_solid_value(base);
383    AddedSolid {
384        handle,
385        name: name.to_string(),
386        face_names,
387        edge_names,
388        face_groups,
389        edge_groups,
390    }
391}
392
393/// Publish each derived edge name's BASE — `{faceA}|{faceB}` without the `[n]`
394/// — as a group standing for every edge that carries it.
395///
396/// [`stamp_derived_edge_names`] always appends the index, even where a face
397/// pair meets along a single edge, so the bare base is never an edge name and a
398/// reference stored as one resolves to nothing on its own. Bare bases are
399/// exactly what a model saved against an UNSTAMPED solid holds — the standalone
400/// Boolean feature published the imprint's raw `{faceA}|{faceB}` until it
401/// started stamping like every other feature — so they must keep naming the
402/// edges they always named.
403///
404/// The group carries every member, which is what [`SceneMap::resolve_edge`]
405/// (single) and [`SceneMap::resolve_edge_group`] (fan-out) already read
406/// correctly: a base one edge carries resolves everywhere, one several edges
407/// carry stays ambiguous for a single-edge consumer and fans out for a
408/// selection. A base an EXACT edge name already spells is left alone (both
409/// resolvers try the exact map first, so it could never be reached), and so is
410/// one a container alias already claims.
411fn collect_derived_edge_bases(
412    edge_names: &[(u64, String)],
413    groups: &mut Vec<(String, Vec<String>)>,
414) {
415    use std::collections::HashSet;
416    let taken: HashSet<&str> = groups.iter().map(|(name, _)| name.as_str()).collect();
417    let exact: HashSet<&str> = edge_names.iter().map(|(_, name)| name.as_str()).collect();
418    let mut bases: Vec<(String, Vec<String>)> = Vec::new();
419    for (_, name) in edge_names {
420        // `{base}[{index}]`: the index is the trailing bracketed run of digits.
421        let Some(base) = name.strip_suffix(']').and_then(|head| {
422            let at = head.rfind('[')?;
423            let (base, index) = (&head[..at], &head[at + 1..]);
424            (!index.is_empty() && index.bytes().all(|byte| byte.is_ascii_digit()))
425                .then_some(base)
426        }) else {
427            continue;
428        };
429        if base.is_empty() || !base.contains('|') {
430            continue;
431        }
432        if taken.contains(base) || exact.contains(base) {
433            continue;
434        }
435        match bases.iter_mut().find(|(existing, _)| existing == base) {
436            Some((_, members)) => members.push(name.clone()),
437            None => bases.push((base.to_string(), vec![name.clone()])),
438        }
439    }
440    groups.append(&mut bases);
441}
442
443/// Keep each container's member NAMES that actually survived onto the final
444/// solid. Containers with no surviving member are dropped.
445fn collect_face_groups(
446    face_names: &[(u64, String)],
447    containers: &[(String, Vec<String>)],
448) -> Vec<(String, Vec<String>)> {
449    let mut groups = Vec::new();
450    for (container, members) in containers {
451        let live: Vec<String> = members
452            .iter()
453            .filter(|member| face_names.iter().any(|(_, name)| name == *member))
454            .cloned()
455            .collect();
456        if !live.is_empty() {
457            groups.push((container.clone(), live));
458        }
459    }
460    groups
461}
462
463/// The CONTAINER-name spelling of each derived edge name.
464///
465/// Derived edge names embed face names (`{faceA}|{faceB}[n]`), so keying the caps
466/// renamed every cap-adjacent edge along with them — a saved fillet on the top
467/// edge of a box references a name no face pair spells any more. This recomputes
468/// each edge's derived name with every member face name replaced by its container
469/// name, and registers THAT as an alias for the edge.
470///
471/// It mirrors [`stamp_derived_edge_names`] step for step — same adjacency, same
472/// encounter order, same per-base counter, substitution applied BEFORE the pair is
473/// sorted (a substituted name can sort differently from the one it replaced). So
474/// when the mapping is 1:1 — every model with a single-loop profile, i.e. every
475/// model saved before per-loop naming — the alias is byte-identical to the name
476/// that solid's edges used to carry.
477fn collect_edge_group_aliases(
478    solid: &BrepSolid,
479    containers: &[(String, Vec<String>)],
480) -> Vec<(String, Vec<String>)> {
481    use std::collections::HashMap;
482    if containers.is_empty() {
483        return Vec::new();
484    }
485    // member face name -> its container name.
486    let mut container_of: HashMap<&str, &str> = HashMap::new();
487    for (container, members) in containers {
488        for member in members {
489            container_of.insert(member.as_str(), container.as_str());
490        }
491    }
492
493    let (edge_faces, encounter_order) = collect_edge_face_names(solid);
494
495    let solid_name_fallback = "Solid".to_string();
496    let mut base_counts: HashMap<String, usize> = HashMap::new();
497    let mut aliases: HashMap<String, Vec<String>> = HashMap::new();
498    let mut order: Vec<String> = Vec::new();
499    for edge_id in encounter_order {
500        let Some(edge) = solid.edges.iter().find(|edge| edge.id == edge_id) else {
501            continue;
502        };
503        if edge.degenerate {
504            continue;
505        }
506        // Only edges `stamp_derived_edge_names` actually named advance its
507        // counter, so only those advance this one.
508        if !edge.name.as_deref().is_none_or(|name| name.contains('|')) {
509            continue;
510        }
511        let mut faces: Vec<String> = edge_faces
512            .get(&edge_id)
513            .map(|list| list.iter().filter(|name| !name.is_empty()).cloned().collect())
514            .unwrap_or_default();
515        // Substitute BEFORE sorting — a container name need not sort where the
516        // member name it replaces did.
517        let substituted = faces.iter().any(|name| container_of.contains_key(name.as_str()));
518        for face in &mut faces {
519            if let Some(container) = container_of.get(face.as_str()) {
520                *face = (*container).to_string();
521            }
522        }
523        faces.sort();
524        let base = if faces.len() >= 2 {
525            format!("{}|{}", faces[0], faces[1])
526        } else {
527            format!("{}|BOUNDARY", faces.first().unwrap_or(&solid_name_fallback))
528        };
529        let index = base_counts.entry(base.clone()).or_insert(0);
530        let alias = format!("{base}[{index}]");
531        *index += 1;
532        // An edge touching no member face spells its own name — nothing to alias.
533        // An edge whose alias IS its own name needs none either.
534        let Some(live) = edge.name.clone() else { continue };
535        if !substituted || live == alias {
536            continue;
537        }
538        if aliases.entry(alias.clone()).or_default().is_empty() {
539            order.push(alias.clone());
540        }
541        aliases.get_mut(&alias).expect("just inserted").push(live);
542    }
543    order
544        .into_iter()
545        .map(|alias| {
546            let ids = aliases.remove(&alias).unwrap_or_default();
547            (alias, ids)
548        })
549        .filter(|(_, ids)| !ids.is_empty())
550        .collect()
551}
552
553/// Finalize several bodies using the optional boolean operation. Without an
554/// operation or resolved targets, register each body separately. Otherwise fold
555/// bodies into the targets in order and use the first target's name. Missing
556/// targets are reported in `unresolved` for the caller to repair.
557pub fn finalize_solids(ctx: &FeatureContext, bodies: Vec<(String, BrepSolid)>) -> FeatureResult {
558    let boolean = read_boolean_param(ctx);
559    let mut result = FeatureResult::empty(ctx.id.clone(), ctx.feature_type.clone());
560
561    let separate = |mut result: FeatureResult, bodies: Vec<(String, BrepSolid)>| {
562        for (name, solid) in bodies {
563            result.added.push(register_added(solid, &name));
564        }
565        result
566    };
567
568    if boolean.operation == "NONE" || boolean.targets.is_empty() {
569        return separate(result, bodies);
570    }
571    let operation = match parse_boolean_operation(&boolean.operation) {
572        Ok(operation) => operation,
573        Err(error) => return ctx.fail(error),
574    };
575    let resolved = resolve_solid_names(ctx.scene, &boolean.targets, &mut result.unresolved);
576    if resolved.is_empty() {
577        return separate(result, bodies);
578    }
579    let options = BooleanOptions {
580        merge_coplanar_faces: boolean.merge_coplanar_faces,
581        ..BooleanOptions::default()
582    };
583    let mut bodies = bodies.into_iter();
584    let Some((_, first)) = bodies.next() else {
585        return result; // no bodies at all (shouldn't happen; callers gate)
586    };
587    // Fold the first body through every target (mirrors `finalize_solid`), then
588    // fold each remaining body into the running result (targets already merged in).
589    let mut current = first;
590    for (_, target_handle) in &resolved {
591        let operand = crate::register_solid_value(current);
592        let folded = crate::with_two_registered_solids(*target_handle, operand, |target, op_solid| {
593            crate::boolean_operation(target, op_solid, operation, &options)
594        });
595        crate::free_registered_solid(operand);
596        match folded {
597            Ok(solid) => current = solid,
598            Err(error) => return ctx.fail(format!("boolean {} failed: {error}", boolean.operation)),
599        }
600    }
601    for (_, body) in bodies {
602        match crate::boolean_operation(&current, &body, operation, &options) {
603            Ok(solid) => current = solid,
604            Err(error) => return ctx.fail(format!("boolean {} failed: {error}", boolean.operation)),
605        }
606    }
607    result.added.push(register_added(current, &resolved[0].0));
608    result.removed = resolved.into_iter().map(|(name, _)| name).collect();
609    result
610}
611
612pub fn finalize_solid(ctx: &FeatureContext, base: BrepSolid, base_name: &str) -> FeatureResult {
613    finalize_solid_grouped(ctx, base, base_name, &[])
614}
615
616/// [`finalize_solid`] carrying CONTAINER groups (the profile-swept features'
617/// per-loop cap roll-ups) onto whichever solid ends up registered — the base
618/// itself, or the boolean's result when one is folded. Members that the boolean
619/// consumed drop out of their group on their own (`register_added_grouped`
620/// resolves members against the FINAL solid).
621pub fn finalize_solid_grouped(
622    ctx: &FeatureContext,
623    base: BrepSolid,
624    base_name: &str,
625    containers: &[(String, Vec<String>)],
626) -> FeatureResult {
627    let boolean = read_boolean_param(ctx);
628    let mut result = FeatureResult::empty(ctx.id.clone(), ctx.feature_type.clone());
629
630    if boolean.operation == "NONE" || boolean.targets.is_empty() {
631        result.added.push(register_added_grouped(base, base_name, containers));
632        return result;
633    }
634
635    let operation = match parse_boolean_operation(&boolean.operation) {
636        Ok(operation) => operation,
637        Err(error) => return ctx.fail(error),
638    };
639
640    let resolved = resolve_solid_names(ctx.scene, &boolean.targets, &mut result.unresolved);
641
642    // Nothing resolved: emit the base un-booleaned; `unresolved` signals the caller to
643    // repair + re-dispatch (NOT a hard error — Stage 5 gate).
644    if resolved.is_empty() {
645        result.added.push(register_added_grouped(base, base_name, containers));
646        return result;
647    }
648
649    let options = BooleanOptions {
650        merge_coplanar_faces: boolean.merge_coplanar_faces,
651        ..BooleanOptions::default()
652    };
653    // Fold, keeping the running result as a LOCAL owned BrepSolid: register only
654    // the operand needed for the two-solid borrow, fold, free that operand — no
655    // leaked intermediates. The base primitive is never itself scene-resident.
656    let mut current = base;
657    for (_, target_handle) in &resolved {
658        let operand_handle = crate::register_solid_value(current);
659        let folded = crate::with_two_registered_solids(*target_handle, operand_handle, |target, operand| {
660            crate::boolean_operation(target, operand, operation, &options)
661        });
662        crate::free_registered_solid(operand_handle);
663        match folded {
664            Ok(solid) => current = solid,
665            Err(error) => return ctx.fail(format!("boolean {} failed: {error}", boolean.operation)),
666        }
667    }
668
669    let result_name = resolved[0].0.clone();
670    result
671        .added
672        .push(register_added_grouped(current, &result_name, containers));
673    result.removed = resolved.into_iter().map(|(name, _)| name).collect();
674    result
675}
676
677// ===========================================================================
678// Dressup edge/face selection — shared by fillet.rs (F) and chamfer.rs (CH)
679// ===========================================================================
680//
681// Fillet and chamfer share selection resolution and direction validation.
682// Each feature owns its numeric parameters, kernel call, and abort policy.
683
684/// One solid and sampled edge points for a fillet or chamfer operation.
685pub struct BlendTarget {
686    pub handle: u32,
687    pub name: String,
688    pub edge_points: Vec<Vec3>,
689    /// Canonical names parallel to `edge_points`, used to name generated faces.
690    /// Unnamed edges fall back to `E{edge_id}`.
691    pub edge_names: Vec<String>,
692}
693
694/// Resolved blend selection; callers decide how to handle cross-solid input.
695pub struct BlendSelection {
696    /// Present when at least one reference resolves, all to the same solid.
697    pub target: Option<BlendTarget>,
698    pub multi_solid: bool,
699    /// Missing edge/face names for the caller to repair and redispatch.
700    pub unresolved: Vec<String>,
701}
702
703/// One resolved ref: which topology entity of the owning solid it names.
704enum ResolvedRef {
705    Edge(u64),
706    Face(u64),
707}
708
709/// A `reference_selection` entry -> its name: a plain string, or an object with a
710/// `name` field. No token-splitting / `[N]`-index /
711/// snapshot-scoring — exact match only (contract rule 1 forbids the heuristic).
712pub(crate) fn reference_name(value: &serde_json::Value) -> Option<String> {
713    let raw = match value {
714        serde_json::Value::String(text) => Some(text.as_str()),
715        serde_json::Value::Object(map) => map.get("name").and_then(|value| value.as_str()),
716        _ => None,
717    }?;
718    let trimmed = raw.trim();
719    (!trimmed.is_empty()).then(|| trimmed.to_string())
720}
721
722/// The canonical scene name of an edge (`{faceA}|{faceB}[n]`, stamped by
723/// `stamp_derived_edge_names`), used to name the blend face grown from it. An
724/// unnamed / empty edge (e.g. a hand-built test solid never run through the
725/// canonical pass) falls back to a deterministic `E{edge_id}` so parallel blend
726/// faces still get DISTINCT, stable names.
727fn edge_name_or_id(solid: &BrepSolid, edge_id: u64) -> String {
728    solid
729        .edges
730        .iter()
731        .find(|edge| edge.id == edge_id)
732        .and_then(|edge| edge.name.clone())
733        .filter(|name| !name.is_empty())
734        .unwrap_or_else(|| format!("E{edge_id}"))
735}
736
737/// Midpoint of an edge's curve (`evaluate((t0 + t1) / 2)`) — the sample the kernel
738/// decodes back to the edge.
739fn sample_edge_midpoint(solid: &BrepSolid, edge_id: u64) -> Result<Vec3, String> {
740    let edge = solid
741        .edges
742        .iter()
743        .find(|edge| edge.id == edge_id)
744        .ok_or_else(|| format!("dressup: edge {edge_id} not found on target solid"))?;
745    let mid = (edge.t0 + edge.t1) * 0.5;
746    edge.curve
747        .evaluate(mid)
748        .map_err(|error| format!("dressup: edge {edge_id} midpoint sample failed: {error}"))
749}
750
751/// Boundary edge ids of a face (its loops' coedges), deduped, skipping DEGENERATE
752/// (pole) edges — "fillet a face" means "fillet all its real shared edges".
753fn face_boundary_edges(solid: &BrepSolid, face_id: u64) -> Result<Vec<u64>, String> {
754    let face = solid
755        .shells
756        .iter()
757        .flat_map(|shell| &shell.faces)
758        .find(|face| face.id == face_id)
759        .ok_or_else(|| format!("dressup: face {face_id} not found on target solid"))?;
760    let mut ids = Vec::new();
761    let mut seen = FxHashSet::default();
762    for loop_record in &face.loops {
763        for coedge in &loop_record.coedges {
764            let degenerate = solid
765                .edges
766                .iter()
767                .find(|edge| edge.id == coedge.edge_id)
768                .map(|edge| edge.degenerate)
769                .unwrap_or(false);
770            if degenerate {
771                continue;
772            }
773            if seen.insert(coedge.edge_id) {
774                ids.push(coedge.edge_id);
775            }
776        }
777    }
778    Ok(ids)
779}
780
781/// Resolve the `edges` `reference_selection` (EDGE and/or FACE names) against the
782/// live scene-map and sample one 3D point per selected edge. Exact-match only;
783/// misses accumulate into `unresolved`. Errs only on a genuine geometry/lookup
784/// failure while sampling the resolved solid.
785pub fn resolve_blend_selection(ctx: &FeatureContext) -> Result<BlendSelection, String> {
786    let names = reference_names(ctx.param("edges"));
787
788    let mut unresolved = Vec::new();
789    let mut resolved: Vec<(u32, ResolvedRef)> = Vec::new();
790    for name in names {
791        // Exact edge, exact face, then the CONTAINER groups — a name a model
792        // stored before per-loop cap naming stands for every face (or edge) the
793        // feature built from that profile, so a fillet on "the end cap" of a
794        // 3-loop extrude blends all three, and one on a single-loop extrude
795        // blends the one face it always meant.
796        let edges = ctx.scene.resolve_edge_group(&name);
797        let faces = ctx.scene.resolve_face_group(&name);
798        if edges.is_empty() && faces.is_empty() {
799            unresolved.push(name);
800            continue;
801        }
802        for edge in edges {
803            resolved.push((edge.handle, ResolvedRef::Edge(edge.edge_id)));
804        }
805        for face in faces {
806            resolved.push((face.handle, ResolvedRef::Face(face.face_id)));
807        }
808    }
809
810    // Distinct owning handles among the resolved refs.
811    let mut handles: Vec<u32> = resolved.iter().map(|(handle, _)| *handle).collect();
812    handles.sort_unstable();
813    handles.dedup();
814    if handles.len() > 1 {
815        return Ok(BlendSelection {
816            target: None,
817            multi_solid: true,
818            unresolved,
819        });
820    }
821    let Some(&handle) = handles.first() else {
822        // Nothing resolved: `unresolved` carries the misses (rule 1); no target.
823        return Ok(BlendSelection {
824            target: None,
825            multi_solid: false,
826            unresolved,
827        });
828    };
829
830    // Reverse-lookup the target's scene name — the result reuses it (loop
831    // removes-then-adds, freeing the consumed handle), matching the established dressup naming
832    // (`new Solid(kernel, { name: targetSolid.name })`).
833    let name = ctx
834        .scene
835        .solids
836        .iter()
837        .find(|(_, &registered)| registered == handle)
838        .map(|(name, _)| name.clone())
839        .ok_or_else(|| format!("dressup: target handle {handle} has no scene name"))?;
840
841    // Sample one point per selected edge; dedup edge ids GLOBALLY across all refs
842    // (dedup spans the whole selection, not per-face) in a single short borrow.
843    // The originating edge NAME is captured PARALLEL to each point so the grown
844    // blend face can be named after the edge it came from.
845    let (edge_points, edge_names) = crate::with_registered_solid_str(handle, |solid| {
846        let mut seen = FxHashSet::default();
847        let mut points = Vec::new();
848        let mut names = Vec::new();
849        for (_, entity) in &resolved {
850            match entity {
851                ResolvedRef::Edge(edge_id) => {
852                    if seen.insert(*edge_id) {
853                        points.push(sample_edge_midpoint(solid, *edge_id)?);
854                        names.push(edge_name_or_id(solid, *edge_id));
855                    }
856                }
857                ResolvedRef::Face(face_id) => {
858                    for edge_id in face_boundary_edges(solid, *face_id)? {
859                        if seen.insert(edge_id) {
860                            points.push(sample_edge_midpoint(solid, edge_id)?);
861                            names.push(edge_name_or_id(solid, edge_id));
862                        }
863                    }
864                }
865            }
866        }
867        Ok((points, names))
868    })?;
869
870    Ok(BlendSelection {
871        target: Some(BlendTarget {
872            handle,
873            name,
874            edge_points,
875            edge_names,
876        }),
877        multi_solid: false,
878        unresolved,
879    })
880}
881
882/// Shared wall and corner prefix, `{featureID || 'F'}:BLEND`.
883pub fn blend_face_base(id: &str) -> String {
884    format!("{}:BLEND", if id.is_empty() { "F" } else { id })
885}
886
887/// Per-edge face name; distinct wall names keep derived blend-edge names stable.
888pub fn blend_face_name(id: &str, edge_name: &str) -> String {
889    format!("{}:{}", blend_face_base(id), edge_name)
890}
891
892/// Reject directions that depended on the removed mesh blend pipeline.
893pub fn require_blend_direction(ctx: &FeatureContext, operation: &str) -> Result<(), String> {
894    let direction = ctx
895        .param("direction")
896        .and_then(|value| value.as_str())
897        .map(|text| text.trim().to_uppercase())
898        .filter(|text| !text.is_empty())
899        .unwrap_or_else(|| "AUTO".to_string());
900    if direction != "AUTO" && direction != "INSET" {
901        return Err(format!(
902            "{operation} direction '{direction}' belonged to the removed legacy mesh pipeline (only AUTO/INSET exist)"
903        ));
904    }
905    Ok(())
906}
907
908/// Read a finite parameter value, falling back for missing/null entries or
909/// evaluation errors. Used by features whose optional fields are lenient.
910pub(super) fn number_or_default(ctx: &FeatureContext, key: &str, default: f64) -> f64 {
911    match ctx.param(key) {
912        None | Some(serde_json::Value::Null) => default,
913        Some(_) => match ctx.number(key) {
914            Ok(value) if value.is_finite() => value,
915            _ => default,
916        },
917    }
918}
919
920/// An OPTIONAL numeric param: `None` when absent, else evaluated via
921/// [`FeatureContext::number`] (a hard error on a broken expression, like the
922/// primitive features). Used for the dressup gate/shape params (`inflate`,
923/// `nudgeFaceDistance`, `radiusEnd`, `distance2`, `angle`).
924pub fn optional_number(ctx: &FeatureContext, key: &str) -> Result<Option<f64>, String> {
925    if ctx.param(key).is_some() {
926        ctx.number(key).map(Some)
927    } else {
928        Ok(None)
929    }
930}
931
932// ===========================================================================
933// The ONE feature-transform convention (XFORM, ACOMP, gizmo write-back)
934// ===========================================================================
935
936/// Compose the row-major TRS matrix `[ RS | translate + pivot − RS·pivot ]`
937/// with `R` the intrinsic `XYZ` Euler rotation (= `Rx·Ry·Rz`) and `S =
938/// diag(scale)` — the SINGLE feature-transform compose. XFORM, the ACOMP
939/// instance pose, and any solver/gizmo pose write-back must all speak this
940/// convention; forking it would make the same stored angles place geometry
941/// differently per consumer.
942pub fn compose_trs_matrix(
943    translate: [f64; 3],
944    rotate_rad: [f64; 3],
945    scale: [f64; 3],
946    pivot: [f64; 3],
947) -> [f64; 16] {
948    let (a, b) = (rotate_rad[0].cos(), rotate_rad[0].sin());
949    let (c, d) = (rotate_rad[1].cos(), rotate_rad[1].sin());
950    let (e, f) = (rotate_rad[2].cos(), rotate_rad[2].sin());
951    let (ae, af, be, bf) = (a * e, a * f, b * e, b * f);
952    // Intrinsic 'XYZ' Euler rotation (row-major) = Rx·Ry·Rz.
953    let r = [
954        [c * e, -c * f, d],
955        [af + be * d, ae - bf * d, -b * c],
956        [bf - ae * d, be + af * d, a * c],
957    ];
958    // RS = R·diag(scale): scale each column (matches the standard TRS compose).
959    let mut rs = [[0.0f64; 3]; 3];
960    for i in 0..3 {
961        for j in 0..3 {
962            rs[i][j] = r[i][j] * scale[j];
963        }
964    }
965    let rs_pivot = [
966        rs[0][0] * pivot[0] + rs[0][1] * pivot[1] + rs[0][2] * pivot[2],
967        rs[1][0] * pivot[0] + rs[1][1] * pivot[1] + rs[1][2] * pivot[2],
968        rs[2][0] * pivot[0] + rs[2][1] * pivot[1] + rs[2][2] * pivot[2],
969    ];
970    let tx = translate[0] + pivot[0] - rs_pivot[0];
971    let ty = translate[1] + pivot[1] - rs_pivot[1];
972    let tz = translate[2] + pivot[2] - rs_pivot[2];
973    [
974        rs[0][0], rs[0][1], rs[0][2], tx, //
975        rs[1][0], rs[1][1], rs[1][2], ty, //
976        rs[2][0], rs[2][1], rs[2][2], tz, //
977        0.0, 0.0, 0.0, 1.0,
978    ]
979}
980
981/// Read a vec3 VALUE (array `[x,y,z]` or object `{x,y,z}`); each component may
982/// be a JSON number, an expression string (evaluated against the shared env),
983/// or null/missing (→ default). `None`/`Null` as the whole value is the
984/// default. Anything else is a loud error naming `key`. The shared reader for
985/// TOP-LEVEL vec3 params (via [`FeatureContext::param`]) and NESTED ones (the
986/// ACOMP `transform.translate` / `transform.rotateEulerDeg`).
987pub fn vec3_from_value(
988    env: &crate::feature_pipeline::Env,
989    value: Option<&serde_json::Value>,
990    key: &str,
991    default: [f64; 3],
992) -> Result<[f64; 3], String> {
993    let Some(value) = value.filter(|value| !value.is_null()) else {
994        return Ok(default);
995    };
996    let component = |slot: Option<&serde_json::Value>, fallback: f64| -> Result<f64, String> {
997        match slot {
998            None | Some(serde_json::Value::Null) => Ok(fallback),
999            Some(serde_json::Value::Number(number)) => number
1000                .as_f64()
1001                .ok_or_else(|| format!("param `{key}` has a non-finite component")),
1002            Some(serde_json::Value::String(source)) => {
1003                let number = env
1004                    .eval(source)
1005                    .map_err(|error| format!("param `{key}`: {error}"))?;
1006                // An expression may evaluate to a NON-finite number (`1/0`) — that
1007                // must fail HERE, naming the slot, rather than travel on as a
1008                // point coordinate or reach `AffineTransform::new` as a nameless
1009                // "matrix must be finite".
1010                if !number.is_finite() {
1011                    return Err(format!(
1012                        "param `{key}`: `{source}` evaluated to {number}"
1013                    ));
1014                }
1015                Ok(number)
1016            }
1017            Some(other) => Err(format!(
1018                "param `{key}` component must be a number or expression, found {other}"
1019            )),
1020        }
1021    };
1022    if let Some(array) = value.as_array() {
1023        return Ok([
1024            component(array.first(), default[0])?,
1025            component(array.get(1), default[1])?,
1026            component(array.get(2), default[2])?,
1027        ]);
1028    }
1029    if value.is_object() {
1030        return Ok([
1031            component(value.get("x"), default[0])?,
1032            component(value.get("y"), default[1])?,
1033            component(value.get("z"), default[2])?,
1034        ]);
1035    }
1036    Err(format!("param `{key}` must be a vec3 array or object"))
1037}
1038
1039// ===========================================================================
1040// Reference-name + geometric-input resolution shared by profile-consumers
1041// ===========================================================================
1042
1043/// Resolve exact names in selection order, retaining duplicates and appending misses.
1044pub(super) fn resolve_solid_names(
1045    scene: &crate::feature_pipeline::SceneMap,
1046    names: &[String],
1047    unresolved: &mut Vec<String>,
1048) -> Vec<(String, u32)> {
1049    let mut resolved = Vec::new();
1050    for name in names {
1051        match scene.resolve_solid(name) {
1052            Some(handle) => resolved.push((name.clone(), handle)),
1053            None => unresolved.push(name.clone()),
1054        }
1055    }
1056    resolved
1057}
1058
1059/// Use an explicit sheet selection, or the sole sheet-metal body in the scene.
1060/// Missing or ambiguous implicit targets remain unselected.
1061pub(super) fn sheet_body_name(ctx: &FeatureContext) -> Option<String> {
1062    first_reference_name(ctx.param("sheet")).or_else(|| {
1063        let mut bodies = ctx.scene.solids.iter().filter_map(|(name, &handle)| {
1064            crate::feature_pipeline::sheet_metal::get_tree(handle).map(|_| name.clone())
1065        });
1066        match (bodies.next(), bodies.next()) {
1067            (Some(only), None) => Some(only),
1068            _ => None,
1069        }
1070    })
1071}
1072
1073/// Read a single selection without descending into nested arrays.
1074/// An empty first textual entry means no selection; later entries are ignored.
1075pub(super) fn single_reference_name(value: Option<&serde_json::Value>) -> Option<String> {
1076    let name = match value {
1077        Some(serde_json::Value::String(text)) => Some(text.clone()),
1078        Some(serde_json::Value::Array(array)) => array.iter().find_map(|entry| {
1079            entry
1080                .as_str()
1081                .or_else(|| entry.get("name").and_then(|name| name.as_str()))
1082                .map(str::to_string)
1083        }),
1084        Some(object @ serde_json::Value::Object(_)) => {
1085            object.get("name").and_then(|name| name.as_str()).map(str::to_string)
1086        }
1087        _ => None,
1088    }?;
1089    let trimmed = name.trim();
1090    (!trimmed.is_empty()).then(|| trimmed.to_string())
1091}
1092
1093/// The first reference name of a `reference_selection` param value (a plain
1094/// string, a `{name}` object, or an array of either — post-sanitization it is an
1095/// array). Exact match only; no `[N]` index / snapshot scoring.
1096pub fn first_reference_name(value: Option<&serde_json::Value>) -> Option<String> {
1097    fn one(value: &serde_json::Value) -> Option<String> {
1098        match value {
1099            serde_json::Value::Array(items) => items.iter().find_map(one),
1100            other => reference_name(other),
1101        }
1102    }
1103    value.and_then(one)
1104}
1105
1106/// Normalize a PROFILE reference name: a committed sketch is shown as a render-side
1107/// display SHEET whose planar face is PICKED as `{sketch}:FACE`, but the kernel run
1108/// never materializes that sheet — the pick actually names the sketch's PROFILE. So
1109/// strip a trailing `:FACE` to the sketch base, and every profile-consumer's resolve
1110/// + cap-naming + sketch-consume then uses the canonical id. Resident SOLID faces are
1111/// `{solid}|{face}[n]` and never end in `:FACE`, so real faces pass through untouched.
1112/// Apply ONLY to `profile` fields (never to `path`/`axis`).
1113pub fn normalize_profile_alias(name: String) -> String {
1114    match name.strip_suffix(":FACE") {
1115        Some(base) => base.to_string(),
1116        None => name,
1117    }
1118}
1119
1120/// Names from an array-valued reference selection, preserving order and duplicates.
1121/// Missing and non-array values are ignored; entries use [`reference_name`].
1122pub(crate) fn reference_name_array(value: Option<&serde_json::Value>) -> Vec<String> {
1123    value
1124        .and_then(serde_json::Value::as_array)
1125        .map(|items| items.iter().filter_map(reference_name).collect())
1126        .unwrap_or_default()
1127}
1128
1129/// ALL reference names of a `reference_selection` param, in order (a `multiple`
1130/// selection). Also accepts a single string or `{name}` object; empties are dropped.
1131pub fn reference_names(value: Option<&serde_json::Value>) -> Vec<String> {
1132    match value {
1133        Some(serde_json::Value::Array(items)) => items.iter().filter_map(reference_name).collect(),
1134        Some(other) => reference_name(other).into_iter().collect(),
1135        None => Vec::new(),
1136    }
1137}
1138
1139/// Reference names with duplicates removed, retaining first-occurrence order.
1140pub(super) fn unique_reference_names(value: Option<&serde_json::Value>) -> Vec<String> {
1141    let mut seen = std::collections::HashSet::new();
1142    reference_names(value)
1143        .into_iter()
1144        .filter(|name| seen.insert(name.clone()))
1145        .collect()
1146}
1147
1148/// `consumeProfileSketch` (default true) — the profile-consumers remove the sketch
1149/// after building, echoing its name into `removed` for the caller's display cleanup.
1150pub fn consume_profile_sketch(ctx: &FeatureContext) -> bool {
1151    !matches!(
1152        ctx.param("consumeProfileSketch"),
1153        Some(serde_json::Value::Bool(false))
1154    )
1155}
1156
1157/// Echo the consumed sketch's base name (`{ref}` with any `:PROFILE` stripped) into
1158/// `result.removed` when `consumeProfileSketch` is set. Sketches register no scene
1159/// solid, so this only signals caller-side display cleanup.
1160pub fn consume_sketch(ctx: &FeatureContext, reference_name: &str, result: &mut FeatureResult) {
1161    if !consume_profile_sketch(ctx) {
1162        return;
1163    }
1164    consume_sketch_always(reference_name, result);
1165}
1166
1167/// Sheet-metal contract: a sketch that fed a generated piece of geometry is
1168/// ALWAYS consumed (removed from the scene) — there is no keep-the-sketch
1169/// switch. Non-sheet-metal profile consumers keep the `consumeProfileSketch`
1170/// gate via `consume_sketch` above.
1171pub fn consume_sketch_always(reference_name: &str, result: &mut FeatureResult) {
1172    let base = reference_name
1173        .strip_suffix(":PROFILE")
1174        .unwrap_or(reference_name)
1175        .to_string();
1176    if !result.removed.contains(&base) {
1177        result.removed.push(base);
1178    }
1179}
1180
1181/// Map one profile loop's WORLD-space curves into the profile's own plane as
1182/// local `(u, v, 0)` curves: each control point `p` → `((p−origin)·x, (p−origin)·y, 0)`,
1183/// weights kept. A rigid in-plane change of frame, so rational curves (circles /
1184/// arcs) stay EXACT — the sheet-metal `Flat::holes` contract (hole loops in
1185/// flat-local coordinates at `z = 0`).
1186pub fn profile_loop_uv_curves(
1187    profile: &crate::feature_pipeline::SketchProfile,
1188    profile_loop: &crate::feature_pipeline::ProfileLoop,
1189) -> Result<Vec<NurbsCurve>, String> {
1190    let mut curves = Vec::with_capacity(profile_loop.curves.len());
1191    for curve in &profile_loop.curves {
1192        let mut control_points = Vec::with_capacity(curve.control_points.len());
1193        for cp in &curve.control_points {
1194            let delta = cp.point()?.sub(profile.origin);
1195            control_points.push(crate::Vec4::from_point(
1196                Vec3::new(delta.dot(profile.x_axis), delta.dot(profile.y_axis), 0.0),
1197                cp.w,
1198            ));
1199        }
1200        curves.push(NurbsCurve::new(
1201            curve.degree,
1202            curve.knots.clone(),
1203            control_points,
1204        )?);
1205    }
1206    Ok(curves)
1207}
1208
1209/// Resolve a sweep/rib PATH reference to its ordered world curve chain: a SKETCH
1210/// path (`scene.resolve_path`), a single resident solid EDGE (its curve TRIMMED
1211/// to the edge — [`edge_curve`]), or a sketch GEOMETRY name `{sketchId}:G{gid}`
1212/// → the owning sketch's published chain (the tube.rs convention —
1213/// per-geometry curves are not scene-indexed, and a chain holding more than the
1214/// named segment defers loudly downstream). A consumer wanting one path curve
1215/// uses the chain when it is length 1.
1216pub fn resolve_path(ctx: &FeatureContext, name: &str) -> Result<Vec<NurbsCurve>, String> {
1217    if let Some(chain) = ctx.scene.resolve_path(name) {
1218        return Ok(chain.clone());
1219    }
1220    if let Some(edge) = ctx.scene.resolve_edge(name) {
1221        return Ok(vec![edge_curve(edge)?]);
1222    }
1223    if let Some((owner, geometry)) = name.rsplit_once(':') {
1224        if geometry.len() > 1 && geometry.starts_with('G') {
1225            if let Some(chain) = ctx.scene.resolve_path(owner) {
1226                return Ok(chain.clone());
1227            }
1228        }
1229    }
1230    Err(format!(
1231        "path '{name}' not found (no sketch path or resident edge)"
1232    ))
1233}
1234
1235/// ONE segment of a resolved sweep path: the world curve, plus the SOURCE NAME
1236/// it came from (`{sketchId}:G{gid}` for a sketch geometry, the edge's own scene
1237/// name for a resident solid edge).
1238///
1239/// The name is the whole point: a feature that builds one PORTION per path
1240/// segment names that portion's faces after the segment, so adding, removing or
1241/// re-picking a path edge never renames a face built from a segment that did not
1242/// change. Naming by chain POSITION would renumber every downstream face the
1243/// moment a segment is inserted.
1244#[derive(Debug, Clone)]
1245pub struct PathSegment {
1246    pub name: String,
1247    pub curve: NurbsCurve,
1248}
1249
1250/// Resolve a `path` `reference_selection` — one name or MANY — to a single
1251/// ordered, head-to-tail connected chain of NAMED segments.
1252///
1253/// Each reference contributes its curves through [`resolve_path`] (a whole
1254/// SKETCH's published chain, a single `{sketchId}:G{gid}` sketch segment, or a
1255/// resident solid EDGE), and each curve carries a name: the publisher's
1256/// per-segment names when it published them
1257/// ([`SceneMap::resolve_path_segment_names`]), else the reference name itself
1258/// (a one-curve reference) or `{reference}[i]` (an unnamed multi-curve chain).
1259/// A curve already contributed under the same name is dropped, so selecting a
1260/// sketch AND one of its own segments is not a duplicate.
1261///
1262/// The segments are then CHAINED by endpoint coincidence: the first reference
1263/// seeds the chain in its natural orientation, the chain grows from its tail and
1264/// then from its head (mirroring the sketch chainer), and a segment that has to
1265/// run backwards to join is reversed. So the picking ORDER does not matter —
1266/// the same set of edges always yields the same chain. Any segment that reaches
1267/// neither end is a disconnected or branching selection, and is reported BY NAME
1268/// rather than silently dropped.
1269pub fn resolve_path_chain(
1270    ctx: &FeatureContext,
1271    names: &[String],
1272) -> Result<Vec<PathSegment>, String> {
1273    let mut segments: Vec<PathSegment> = Vec::new();
1274    let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
1275    for reference in names {
1276        let curves = resolve_path(ctx, reference)?;
1277        let published = ctx.scene.resolve_path_segment_names(reference);
1278        let single = curves.len() == 1;
1279        for (index, curve) in curves.into_iter().enumerate() {
1280            let name = published
1281                .and_then(|names| names.get(index).cloned().flatten())
1282                .filter(|name| !name.trim().is_empty())
1283                .unwrap_or_else(|| {
1284                    if single {
1285                        reference.clone()
1286                    } else {
1287                        format!("{reference}[{index}]")
1288                    }
1289                });
1290            if seen.insert(name.clone()) {
1291                segments.push(PathSegment { name, curve });
1292            }
1293        }
1294    }
1295    if segments.is_empty() {
1296        return Err("path selection resolved to no curves".into());
1297    }
1298    chain_path_segments(segments)
1299}
1300
1301/// A path curve's world endpoints (`(start, end)` at its domain ends).
1302fn path_endpoints(curve: &NurbsCurve) -> Result<(Vec3, Vec3), String> {
1303    let [t0, t1] = curve.domain()?;
1304    Ok((curve.evaluate(t0)?, curve.evaluate(t1)?))
1305}
1306
1307/// Order `segments` head-to-tail (see [`resolve_path_chain`]). Segments that join
1308/// nothing are reported by name.
1309fn chain_path_segments(segments: Vec<PathSegment>) -> Result<Vec<PathSegment>, String> {
1310    if segments.len() < 2 {
1311        return Ok(segments);
1312    }
1313    let ends: Vec<(Vec3, Vec3)> = segments
1314        .iter()
1315        .map(|segment| path_endpoints(&segment.curve))
1316        .collect::<Result<_, _>>()?;
1317    // Scale-relative join tolerance, on the same footing as the sketch chainer's
1318    // absolute 1e-5: individually picked solid edges meet only to within the
1319    // tolerance their own builders left behind.
1320    let scale = ends
1321        .iter()
1322        .flat_map(|(a, b)| [a, b])
1323        .map(|point| point.sub(ends[0].0).length())
1324        .fold(1.0_f64, f64::max);
1325    let tolerance = 1e-5 * scale;
1326    let joins = |a: Vec3, b: Vec3| a.sub(b).length() <= tolerance;
1327
1328    let mut used = vec![false; segments.len()];
1329    used[0] = true;
1330    // `(index, reversed)` in head-to-tail order, seeded on the FIRST picked
1331    // segment in its natural orientation.
1332    let mut order: Vec<(usize, bool)> = vec![(0, false)];
1333    let mut head = ends[0].0;
1334    let mut tail = ends[0].1;
1335    loop {
1336        // Closed chain: the tail returned to the head — stop before overshooting
1337        // into a segment attached at the seam (the sketch chainer's rule).
1338        if order.len() > 1 && joins(tail, head) {
1339            break;
1340        }
1341        if let Some((index, reversed, far)) = attach_path_segment(&ends, &used, tail, tolerance) {
1342            used[index] = true;
1343            order.push((index, reversed));
1344            tail = far;
1345            continue;
1346        }
1347        if let Some((index, reversed, far)) = attach_path_segment(&ends, &used, head, tolerance) {
1348            used[index] = true;
1349            // Walking head-ward: `attach_path_segment` orients tail-ward, so flip.
1350            order.insert(0, (index, !reversed));
1351            head = far;
1352            continue;
1353        }
1354        break;
1355    }
1356    let stranded: Vec<&str> = segments
1357        .iter()
1358        .zip(&used)
1359        .filter(|(_, used)| !**used)
1360        .map(|(segment, _)| segment.name.as_str())
1361        .collect();
1362    if !stranded.is_empty() {
1363        return Err(format!(
1364            "the selected path edges do not form ONE connected chain — {} joins neither \
1365             end of the chain the other selections form (a sweep path must be a single \
1366             head-to-tail run; select connected edges, or one branch at a time)",
1367            stranded.join(", ")
1368        ));
1369    }
1370    let mut chained = Vec::with_capacity(segments.len());
1371    let mut taken: Vec<Option<PathSegment>> = segments.into_iter().map(Some).collect();
1372    for (index, reversed) in order {
1373        let mut segment = taken[index].take().expect("each segment placed once");
1374        if reversed {
1375            segment.curve = segment.curve.reversed()?;
1376        }
1377        chained.push(segment);
1378    }
1379    Ok(chained)
1380}
1381
1382/// The first unused segment with an endpoint at `cursor`, oriented to walk AWAY
1383/// from it: `(index, reversed, far_end)`. Index-order scan, deterministic.
1384fn attach_path_segment(
1385    ends: &[(Vec3, Vec3)],
1386    used: &[bool],
1387    cursor: Vec3,
1388    tolerance: f64,
1389) -> Option<(usize, bool, Vec3)> {
1390    for (index, (start, end)) in ends.iter().enumerate() {
1391        if used[index] {
1392            continue;
1393        }
1394        if start.sub(cursor).length() <= tolerance {
1395            return Some((index, false, *end));
1396        }
1397        if end.sub(cursor).length() <= tolerance {
1398            return Some((index, true, *start));
1399        }
1400    }
1401    None
1402}
1403
1404/// Translate every curve of a profile loop by `offset` — the per-portion
1405/// placement a multi-segment sweep needs (each path segment sweeps a COPY of the
1406/// profile, moved to that segment's start).
1407pub fn translate_curves(curves: &[NurbsCurve], offset: Vec3) -> Result<Vec<NurbsCurve>, String> {
1408    curves
1409        .iter()
1410        .map(|curve| translate_curve(curve, offset))
1411        .collect()
1412}
1413
1414/// The SKETCH PLANE governing a path/profile reference, if it has one: the
1415/// reference name itself (a SKETCH publishes its resolved frame under its own id)
1416/// or the owner prefix of a sketch-geometry name (`{sketchId}:G{gid}`,
1417/// `{sketchId}:PROFILE`, `{sketchId}:FACE`). `None` for a non-sketch reference —
1418/// a resident solid EDGE publishes no frame.
1419///
1420/// This is the plane a sketch was AUTHORED on, and it is the answer to every
1421/// "which way is out of this chain?" question a consumer would otherwise re-derive
1422/// from the chain's own bends: the re-derivation is sign-ambiguous (it follows the
1423/// order the segments happen to be drawn in), and for a chain with no bend at all —
1424/// a single straight segment — it does not exist. Consumed by the sheet-metal
1425/// contour flange, and by the rib.
1426pub fn sketch_plane_frame(ctx: &FeatureContext, names: &[String]) -> Option<Frame> {
1427    for name in names {
1428        if let Some(frame) = ctx.scene.resolve_frame(name) {
1429            return Some(frame);
1430        }
1431        if let Some((owner, _)) = name.rsplit_once(':') {
1432            if let Some(frame) = ctx.scene.resolve_frame(owner) {
1433                return Some(frame);
1434            }
1435        }
1436    }
1437    None
1438}
1439
1440/// The base name a sketch-consuming feature should REMOVE for a reference: the
1441/// owning SKETCH for a sketch-geometry pick (`{sketchId}:G{gid}` whose owner
1442/// published a frame), else the raw reference name (`consume_sketch_always` strips
1443/// `:PROFILE` itself; non-sketch names are harmless display no-ops).
1444///
1445/// A viewport pick on a sketch's drawn SEGMENT stores `{sketchId}:G{gid}`, so
1446/// without this the consume would echo a name no display knows and the consumed
1447/// sketch would linger in the scene. Consumed by the sheet-metal contour flange,
1448/// and by the rib.
1449pub fn sketch_base_name(ctx: &FeatureContext, name: &str) -> String {
1450    if let Some((owner, tail)) = name.rsplit_once(':') {
1451        if tail.len() > 1 && tail.starts_with('G') && ctx.scene.resolve_frame(owner).is_some() {
1452            return owner.to_string();
1453        }
1454    }
1455    name.to_string()
1456}
1457
1458/// A curve trimmed to the parameter range `[t0, t1]` (the `coalesce.rs` pattern):
1459/// skip a split whose parameter sits within [`crate::NurbsCurve::split`]'s absolute
1460/// knot tolerance of a domain end, or the guard inside `split` rejects it. The
1461/// result keeps the original parameterization, so its domain IS `[t0, t1]`.
1462pub fn trimmed_curve(curve: &NurbsCurve, t0: f64, t1: f64) -> Result<NurbsCurve, String> {
1463    let [start, end] = curve.domain()?;
1464    let epsilon = (1e-9 * (end - start)).max(2e-9);
1465    let mut result = curve.clone();
1466    if t0 > start + epsilon && t0 < end - epsilon {
1467        result = result.split(t0)?.1;
1468    }
1469    let domain = result.domain()?;
1470    if t1 < domain[1] - epsilon && t1 > domain[0] + epsilon {
1471        result = result.split(t1)?.0;
1472    }
1473    Ok(result)
1474}
1475
1476/// The world curve of one resident solid EDGE, TRIMMED to that edge's own
1477/// `[t0, t1]`.
1478///
1479/// An `EdgeRecord` carries a curve plus the subrange of it the edge actually
1480/// spans, and the two disagree constantly: every boolean and every dressup that
1481/// shortens an edge rewrites `t0`/`t1` and leaves the whole underlying curve in
1482/// place (a box edge whose end is eaten by a fillet keeps its full 20mm line and
1483/// records `t=[0, 0.8]`). A consumer that clones `record.curve` and reads its
1484/// DOMAIN therefore builds along a curve that runs past the edge the user picked
1485/// — a tube or a sweep that overshoots into thin air. Everything that turns a
1486/// picked edge into a path goes through here so that cannot happen once per
1487/// feature.
1488pub fn edge_curve(edge: EdgeRef) -> Result<NurbsCurve, String> {
1489    crate::with_registered_solid_str(edge.handle, |solid| {
1490        let record = solid
1491            .edges
1492            .iter()
1493            .find(|candidate| candidate.id == edge.edge_id)
1494            .ok_or_else(|| format!("edge {} not found on solid", edge.edge_id))?;
1495        trimmed_curve(&record.curve, record.t0, record.t1)
1496    })
1497}
1498
1499/// Resolve a revolve/sweep axis from a resident solid EDGE: the axis passes through
1500/// the edge's start and runs along its chord (start → end). A straight edge is
1501/// exact; a curved edge yields its chord (best-effort, matching the established edge-axis use).
1502pub fn edge_axis(edge: EdgeRef) -> Result<Axis, String> {
1503    crate::with_registered_solid_str(edge.handle, |solid| {
1504        let record = solid
1505            .edges
1506            .iter()
1507            .find(|candidate| candidate.id == edge.edge_id)
1508            .ok_or_else(|| format!("edge {} not found on solid", edge.edge_id))?;
1509        let start = record.curve.evaluate(record.t0)?;
1510        let end = record.curve.evaluate(record.t1)?;
1511        let direction = end.sub(start).normalized()?;
1512        Ok(Axis {
1513            point: start,
1514            direction,
1515        })
1516    })
1517}
1518
1519// ===========================================================================
1520// Hole-loop subtraction (multi-loop regions) shared by the profile-consumers
1521// ===========================================================================
1522//
1523// A [`SketchProfile`] region carries `region[0]` = outer boundary,
1524// `region[1..]` = its containment-classified holes. Every profile-consumer
1525// (extrude, sweep, revolve, path sweep, loft) builds each region's OUTER solid
1526// with its own sweep, cuts the region's holes with the SAME sweep via
1527// [`subtract_region_holes`], then unions the region solids
1528// ([`union_region_solids`]). The nesting FOREST machinery below stays general
1529// (a hole group may carry children), though the sketch classifier promotes an
1530// island inside a hole to its own region, so sketch-produced regions are flat.
1531
1532/// Rigid-translate a curve by `offset` (homogeneous-safe: rational weights kept).
1533pub fn translate_curve(curve: &NurbsCurve, offset: Vec3) -> Result<NurbsCurve, String> {
1534    let mut control_points = Vec::with_capacity(curve.control_points.len());
1535    for cp in &curve.control_points {
1536        let cartesian = cp.point()?;
1537        control_points.push(crate::Vec4::from_point(cartesian.add(offset), cp.w));
1538    }
1539    NurbsCurve::new(curve.degree, curve.knots.clone(), control_points)
1540}
1541
1542/// One inner loop of a region with its DIRECTLY nested loops: `region[index]`
1543/// cuts material at even-odd `depth` 0; each child is one level deeper.
1544pub struct HoleGroup {
1545    /// Index into the region's loops (>= 1).
1546    pub index: usize,
1547    /// Nesting depth below the outer loop (0 = a direct hole).
1548    pub depth: usize,
1549    pub children: Vec<HoleGroup>,
1550}
1551
1552/// Classify `region[1..]` into a containment FOREST. Loops are sampled into 2D
1553/// polygons in the profile's own plane frame; loop `i` nests inside loop `j`
1554/// iff a representative point of `i` lies in `j`'s polygon (valid profiles
1555/// never intersect, so one point decides). Returns the depth-0 groups in loop
1556/// order.
1557pub fn hole_nesting(
1558    profile: &SketchProfile,
1559    region: &[crate::feature_pipeline::ProfileLoop],
1560) -> Result<Vec<HoleGroup>, String> {
1561    let count = region.len().saturating_sub(1);
1562    if count == 0 {
1563        return Ok(Vec::new());
1564    }
1565    // Sampled UV polygon per inner loop (8 samples per curve).
1566    let mut polygons: Vec<Vec<[f64; 2]>> = Vec::with_capacity(count);
1567    for hole in &region[1..] {
1568        let mut polygon = Vec::new();
1569        for curve in &hole.curves {
1570            let [t0, t1] = curve.domain()?;
1571            for step in 0..8 {
1572                let t = t0 + (t1 - t0) * (step as f64 / 8.0);
1573                let point = curve.evaluate(t)?;
1574                let delta = point.sub(profile.origin);
1575                polygon.push([delta.dot(profile.x_axis), delta.dot(profile.y_axis)]);
1576            }
1577        }
1578        polygons.push(polygon);
1579    }
1580    // Pairwise containment + per-loop depth (# of loops containing it).
1581    let mut contains = vec![vec![false; count]; count];
1582    for i in 0..count {
1583        let Some(representative) = polygons[i].first().copied() else {
1584            continue;
1585        };
1586        for j in 0..count {
1587            if i != j && point_in_polygon_uv(representative, &polygons[j]) {
1588                contains[i][j] = true;
1589            }
1590        }
1591    }
1592    let depths: Vec<usize> = (0..count)
1593        .map(|i| contains[i].iter().filter(|inside| **inside).count())
1594        .collect();
1595    Ok((0..count)
1596        .filter(|&i| depths[i] == 0)
1597        .map(|i| hole_group(i, &contains, &depths))
1598        .collect())
1599}
1600
1601/// Build the [`HoleGroup`] rooted at inner-loop `i`: its children are the loops
1602/// directly inside it (contained by it, exactly one level deeper).
1603fn hole_group(i: usize, contains: &[Vec<bool>], depths: &[usize]) -> HoleGroup {
1604    let children = (0..depths.len())
1605        .filter(|&k| contains[k][i] && depths[k] == depths[i] + 1)
1606        .map(|k| hole_group(k, contains, depths))
1607        .collect();
1608    HoleGroup {
1609        index: i + 1,
1610        depth: depths[i],
1611        children,
1612    }
1613}
1614
1615/// Standard even-odd ray-cast point-in-polygon in the profile's UV plane.
1616fn point_in_polygon_uv(point: [f64; 2], polygon: &[[f64; 2]]) -> bool {
1617    let count = polygon.len();
1618    if count < 3 {
1619        return false;
1620    }
1621    let mut inside = false;
1622    let mut j = count - 1;
1623    for i in 0..count {
1624        let pi = polygon[i];
1625        let pj = polygon[j];
1626        let intersects = (pi[1] > point[1]) != (pj[1] > point[1])
1627            && point[0] < (pj[0] - pi[0]) * (point[1] - pi[1]) / (pj[1] - pi[1]) + pi[0];
1628        if intersects {
1629            inside = !inside;
1630        }
1631        j = i;
1632    }
1633    inside
1634}
1635
1636/// Stamp `{id}:HOLE:{key}` on every still-unnamed face of a hole cutter — the
1637/// extrude hole-cutter convention every profile-consumer shares (the boolean
1638/// propagates these names onto the cut walls). `key` is the hole loop's STABLE
1639/// identity ([`ProfileLoop::key`]), not its position, so adding or removing one
1640/// hole never renames another's walls. `segment` keys the name further for a
1641/// feature that cuts the SAME hole once per path segment (see [`hole_face_name`]).
1642pub fn name_hole_cutter_faces(cutter: &mut BrepSolid, id: &str, key: &str, segment: Option<&str>) {
1643    let name = hole_face_name(id, key, segment);
1644    for face in cutter
1645        .shells
1646        .iter_mut()
1647        .flat_map(|shell| shell.faces.iter_mut())
1648    {
1649        if face.name.is_none() {
1650            face.name = Some(name.clone());
1651        }
1652    }
1653}
1654
1655/// A hole wall's face name: `{id}:HOLE:{key}`, and `{id}:HOLE:{key}:{segment}`
1656/// when the feature cuts the same hole once PER PATH SEGMENT (the multi-segment
1657/// sweep). The un-keyed spelling is then the CONTAINER standing for all of them,
1658/// exactly as it is for the per-loop caps.
1659pub fn hole_face_name(id: &str, key: &str, segment: Option<&str>) -> String {
1660    match segment {
1661        Some(segment) => format!("{id}:HOLE:{key}:{segment}"),
1662        None => format!("{id}:HOLE:{key}"),
1663    }
1664}
1665
1666/// Boolean-subtract `cutter` from `body` with `merge_coplanar_faces` — the
1667/// hole-cut boolean (register both, subtract, free both).
1668pub fn subtract_solid(body: BrepSolid, cutter: BrepSolid) -> Result<BrepSolid, String> {
1669    let options = BooleanOptions {
1670        merge_coplanar_faces: true,
1671        ..BooleanOptions::default()
1672    };
1673    let body_handle = crate::register_solid_value(body);
1674    let cutter_handle = crate::register_solid_value(cutter);
1675    let cut = crate::with_two_registered_solids(body_handle, cutter_handle, |body, tool| {
1676        crate::boolean_operation(body, tool, BooleanOperation::Subtract, &options)
1677    });
1678    crate::free_registered_solid(body_handle);
1679    crate::free_registered_solid(cutter_handle);
1680    // Lossy exit: the feature pipeline is still stringly (typed-refusal slice 3).
1681    cut.map_err(String::from)
1682}
1683
1684/// The straight-sweep hole cutter: the hole loop extruded into a prism that
1685/// clears BOTH caps (offset `margin` before the start plane, `2*margin`
1686/// over-long — the sheet-metal cutout pattern). `depth` scales the margin so a
1687/// nested island's prism strictly overhangs its parent hole's prism caps (no
1688/// coincident cutter-on-cutter cap faces); depth 0 is extrude's exact margin.
1689pub fn hole_prism(
1690    hole_curves: &[NurbsCurve],
1691    direction: Vec3,
1692    distance: f64,
1693    depth: usize,
1694) -> Result<BrepSolid, String> {
1695    let dir = direction.normalized()?;
1696    let span = distance.abs();
1697    let margin = span.max(1.0) * (depth as f64 + 1.0);
1698    let start_t = distance.min(0.0) - margin;
1699    let length = span + 2.0 * margin;
1700    let offset = dir.scale(start_t);
1701    let mut curves = Vec::with_capacity(hole_curves.len());
1702    for curve in hole_curves {
1703        curves.push(translate_curve(curve, offset)?);
1704    }
1705    crate::extrude_profile_brep(&curves, dir, length)
1706}
1707
1708/// Subtract one hole loop from `body` as a through prism — extrude's
1709/// `subtract_hole`, verbatim (build the over-long prism, stamp
1710/// `{id}:HOLE:{index}` on its faces, boolean-subtract with coplanar merge). A
1711/// degenerate (< 2 curve) hole loop is nothing to cut.
1712pub fn subtract_hole_prism(
1713    feature: &str,
1714    body: BrepSolid,
1715    hole_curves: &[NurbsCurve],
1716    direction: Vec3,
1717    distance: f64,
1718    id: &str,
1719    key: &str,
1720) -> Result<BrepSolid, String> {
1721    if hole_curves.len() < 2 {
1722        return Ok(body);
1723    }
1724    let mut cutter = hole_prism(hole_curves, direction, distance, 0)?;
1725    name_hole_cutter_faces(&mut cutter, id, key, None);
1726    subtract_solid(body, cutter)
1727        .map_err(|error| format!("{feature}: hole {key} cut failed: {error}"))
1728}
1729
1730/// Subtract every inner loop of `region` from `body`, nesting-aware: each
1731/// depth-0 hole becomes ONE cutter — its own swept solid minus its children's
1732/// sub-cutters (recursively). `build` sweeps `region[loop_index]` with the
1733/// FEATURE's own sweep (prism / revolve / path / loft); it receives the loop's
1734/// nesting depth for margin scaling. Cutter faces are stamped `{id}:HOLE:{key}`
1735/// with the hole loop's OWN stable identity ([`ProfileLoop::key`]), so the name
1736/// survives another hole being added or removed — the hole-wall sibling of the
1737/// per-loop cap naming (the old stamp counted holes positionally across regions,
1738/// so deleting one renumbered the rest). `segment`, when the feature cuts this
1739/// region once PER PATH SEGMENT (the multi-segment sweep), keys each cut's walls
1740/// by the segment that made them — otherwise adjacent portions' channel walls
1741/// would collide on one name and fall back to a positional `[n]`.
1742pub fn subtract_region_holes(
1743    mut body: BrepSolid,
1744    profile: &SketchProfile,
1745    region: &[crate::feature_pipeline::ProfileLoop],
1746    feature: &str,
1747    id: &str,
1748    segment: Option<&str>,
1749    build: &mut dyn FnMut(usize, usize) -> Result<BrepSolid, String>,
1750) -> Result<BrepSolid, String> {
1751    for group in hole_nesting(profile, region)? {
1752        let key = hole_key(&region[group.index], group.index);
1753        let Some(cutter) = hole_cutter(region, &group, id, segment, build)
1754            .map_err(|error| format!("{feature}: hole {key} cut failed: {error}"))?
1755        else {
1756            continue;
1757        };
1758        body = subtract_solid(body, cutter)
1759            .map_err(|error| format!("{feature}: hole {key} cut failed: {error}"))?;
1760    }
1761    Ok(body)
1762}
1763
1764/// A hole loop's naming key: its own stable loop identity, else its POSITION —
1765/// the pre-existing spelling, kept for a profile whose loops have no identity to
1766/// key on (a FACE profile, a hand-built profile), so their names never move.
1767pub fn hole_key(hole: &crate::feature_pipeline::ProfileLoop, index: usize) -> String {
1768    hole.key().unwrap_or_else(|| index.to_string())
1769}
1770
1771/// Build one hole group's CUTTER: the loop's swept solid minus each child's
1772/// cutter. `None` for a degenerate (< 2 curve) loop — nothing to cut.
1773fn hole_cutter(
1774    region: &[crate::feature_pipeline::ProfileLoop],
1775    group: &HoleGroup,
1776    id: &str,
1777    segment: Option<&str>,
1778    build: &mut dyn FnMut(usize, usize) -> Result<BrepSolid, String>,
1779) -> Result<Option<BrepSolid>, String> {
1780    if region[group.index].curves.len() < 2 {
1781        return Ok(None);
1782    }
1783    let mut cutter = build(group.index, group.depth)?;
1784    name_hole_cutter_faces(
1785        &mut cutter,
1786        id,
1787        &hole_key(&region[group.index], group.index),
1788        segment,
1789    );
1790    for child in &group.children {
1791        let Some(child_cutter) = hole_cutter(region, child, id, segment, build)? else {
1792            continue;
1793        };
1794        cutter = subtract_solid(cutter, child_cutter).map_err(|error| {
1795            format!("island {} carve from hole {} failed: {error}", child.index, group.index)
1796        })?;
1797    }
1798    Ok(Some(cutter))
1799}
1800
1801// ===========================================================================
1802// Face frame — a sketch/plane FRAME from a resident BREP face (planar-only)
1803// ===========================================================================
1804
1805/// A resolved "plane-like" reference — a solid FACE or a datum/construction PLANE
1806/// frame. THE shared resolution for a `["FACE","PLANE"]` reference: a datum plane
1807/// (from a `D`/`P` feature — both emit a scene [`Frame`]) and a planar face are
1808/// the same underlying object here, so every consumer (mirror, split, pattern,
1809/// plane) treats them identically instead of hand-rolling the two-table lookup.
1810/// That duplication was the source of the "picking a datum plane does nothing"
1811/// bug class — a new consumer just calls [`resolve_plane_reference`].
1812pub enum PlaneLikeRef {
1813    /// A solid face — its `(handle, face_id)`.
1814    Face(FaceRef),
1815    /// A datum / construction plane — its scene frame.
1816    Frame(Frame),
1817}
1818
1819impl PlaneLikeRef {
1820    /// The reference's plane as `(point, unit outward normal)`. A datum PLANE is
1821    /// its frame's `(origin, z-axis)`; a FACE is its midpoint tangent plane
1822    /// ([`face_point_normal`], valid for any face — a curved face yields the
1823    /// midpoint tangent, matching the pre-refactor mirror/split behaviour).
1824    pub fn point_normal(&self) -> Result<(Vec3, Vec3), String> {
1825        match self {
1826            PlaneLikeRef::Frame(frame) => Ok((frame.origin, frame.z_axis)),
1827            PlaneLikeRef::Face(face) => face_point_normal(*face),
1828        }
1829    }
1830
1831    /// The reference's full plane BASIS (origin + in-plane axes + normal). A datum
1832    /// PLANE is its frame directly; a FACE is [`face_frame`] (planar faces only).
1833    pub fn frame(&self) -> Result<Frame, String> {
1834        match self {
1835            PlaneLikeRef::Frame(frame) => Ok(*frame),
1836            PlaneLikeRef::Face(face) => face_frame(*face),
1837        }
1838    }
1839}
1840
1841/// Resolve a `["FACE","PLANE"]` reference name against the live scene-map: a solid
1842/// FACE first, else a datum / construction PLANE frame. The two name tables are
1843/// disjoint, so the order is irrelevant. `None` = unresolved (the caller records
1844/// it as an `unresolved` entry, contract rule 1 — never a no-op-with-no-signal).
1845pub fn resolve_plane_reference(ctx: &FeatureContext, name: &str) -> Option<PlaneLikeRef> {
1846    if let Some(face) = ctx.scene.resolve_face(name) {
1847        return Some(PlaneLikeRef::Face(face));
1848    }
1849    ctx.scene.resolve_frame(name).map(PlaneLikeRef::Frame)
1850}
1851
1852/// A face's plane as `(point on it, unit outward normal)`: the surface value +
1853/// normal at its parameter-domain midpoint, oriented by `same_sense`. Works on
1854/// ANY face (a curved face yields its midpoint tangent plane). The shared version
1855/// of the `plane_from_face` helper mirror/split/pattern each carried privately.
1856pub fn face_point_normal(face: FaceRef) -> Result<(Vec3, Vec3), String> {
1857    crate::with_registered_solid_str(face.handle, |solid| {
1858        for shell in &solid.shells {
1859            for record in &shell.faces {
1860                if record.id != face.face_id {
1861                    continue;
1862                }
1863                let [u0, u1] = record.surface.domain_u()?;
1864                let [v0, v1] = record.surface.domain_v()?;
1865                let (um, vm) = (0.5 * (u0 + u1), 0.5 * (v0 + v1));
1866                let point = record.surface.evaluate(um, vm)?;
1867                let mut normal = record.surface.normal(um, vm)?;
1868                if !record.same_sense {
1869                    normal = normal.scale(-1.0);
1870                }
1871                return Ok((point, normal));
1872            }
1873        }
1874        Err(format!("face {} not found on solid", face.face_id))
1875    })
1876}
1877
1878/// The world-space BOUNDARY SAMPLES of a face: five points along each
1879/// non-degenerate edge of each of its loops. This is the face EXTENT as this
1880/// kernel measures it — [`face_frame`]'s origin is the AABB centre of exactly
1881/// these points, and the assembly inference lane
1882/// ([`crate::feature_pipeline::assembly::infer`]) decides whether two faces
1883/// overlap by projecting them. Empty when every boundary edge is degenerate.
1884pub fn face_boundary_points(
1885    solid: &BrepSolid,
1886    record: &crate::FaceRecord,
1887) -> Result<Vec<Vec3>, String> {
1888    let mut points = Vec::new();
1889    for loop_record in &record.loops {
1890        for coedge in &loop_record.coedges {
1891            let Some(edge) = solid.edges.iter().find(|e| e.id == coedge.edge_id) else {
1892                continue;
1893            };
1894            if edge.degenerate {
1895                continue;
1896            }
1897            for step in 0..=4 {
1898                let t = edge.t0 + (edge.t1 - edge.t0) * (step as f64 / 4.0);
1899                points.push(edge.curve.evaluate(t)?);
1900            }
1901        }
1902    }
1903    Ok(points)
1904}
1905
1906/// The AABB of a point cloud (`None` when empty).
1907pub fn bounds_of(points: &[Vec3]) -> Option<(Vec3, Vec3)> {
1908    let mut iter = points.iter();
1909    let first = *iter.next()?;
1910    let (mut min, mut max) = (first, first);
1911    for point in iter {
1912        min = Vec3::new(min.x.min(point.x), min.y.min(point.y), min.z.min(point.z));
1913        max = Vec3::new(max.x.max(point.x), max.y.max(point.y), max.z.max(point.z));
1914    }
1915    Some((min, max))
1916}
1917
1918/// Compute a placement [`Frame`] from a resident face, for headless sketch/plane
1919/// resolution against a solid's face. Uses the face-basis convention:
1920/// the normal is the OUTWARD face normal (sense
1921/// respected); in-plane axes come from [`Frame::from_origin_normal`]; the origin is
1922/// the face boundary AABB center projected onto the plane. **Planar faces only** —
1923/// a curved face is not yet migrated (loud error, no-fallback).
1924pub fn face_frame(face: FaceRef) -> Result<Frame, String> {
1925    crate::with_registered_solid_str(face.handle, |solid| {
1926        let record = solid
1927            .shells
1928            .iter()
1929            .flat_map(|shell| &shell.faces)
1930            .find(|candidate| candidate.id == face.face_id)
1931            .ok_or_else(|| format!("face {} not found on solid", face.face_id))?;
1932
1933        let [u0, u1] = record.surface.domain_u()?;
1934        let [v0, v1] = record.surface.domain_v()?;
1935        let (um, vm) = ((u0 + u1) * 0.5, (v0 + v1) * 0.5);
1936
1937        // Planarity: the normal must be constant across the patch.
1938        let center_normal = record.surface.normal(um, vm)?;
1939        for (u, v) in [(u0, v0), (u1, v0), (u1, v1), (u0, v1)] {
1940            let normal = record.surface.normal(u, v)?;
1941            if normal.dot(center_normal).abs() < 1.0 - 1e-6 {
1942                return Err(
1943                    "sketch/plane on a non-planar face is not yet migrated to the Rust pipeline"
1944                        .into(),
1945                );
1946            }
1947        }
1948        // Outward face normal (respect the face sense, like `getAverageNormal`).
1949        let normal = if record.same_sense {
1950            center_normal
1951        } else {
1952            center_normal.scale(-1.0)
1953        };
1954
1955        // Boundary AABB center from the face loops' non-degenerate edges.
1956        let boundary = face_boundary_points(solid, record)?;
1957        let plane_point = record.surface.evaluate(um, vm)?;
1958        let center = match bounds_of(&boundary) {
1959            Some((min, max)) => min.add(max).scale(0.5),
1960            None => plane_point,
1961        };
1962        // Project the AABB center onto the plane so the origin lies exactly on it.
1963        let unit = normal.normalized()?;
1964        let signed = center.sub(plane_point).dot(unit);
1965        let origin = center.sub(unit.scale(signed));
1966        Frame::from_origin_normal(origin, normal)
1967    })
1968}
1969
1970// ===========================================================================
1971// Multi-region profiles — union the per-region solids into ONE result
1972// ===========================================================================
1973
1974/// UNION the per-region solids of a multi-region profile into ONE solid — the
1975/// established multi-region behavior (one solid per region, boolean-unioned). Folds with
1976/// `merge_coplanar_faces` (handle-registered operands, freed after each fold);
1977/// a single region passes through untouched, so single-region consumers are
1978/// byte-identical to the pre-region pipeline.
1979pub fn union_region_solids(solids: Vec<BrepSolid>) -> Result<BrepSolid, String> {
1980    union_solids_keeping(solids, &[])
1981}
1982
1983/// [`union_region_solids`] that PINS the named faces out of the coplanar merge:
1984/// a face whose name contains one of `keep_unmerged` is never coalesced with a
1985/// mergeable neighbour.
1986///
1987/// The multi-segment sweep needs it. Two portions built from CONSECUTIVE path
1988/// segments meet at a shared cap, and their sidewalls are frequently coplanar
1989/// (always so for two collinear segments, and for the walls parallel to the plane
1990/// a turn happens in). Merging those fuses two portions' walls into one face
1991/// carrying ONE of the two names — so which of the two source segments a
1992/// downstream fillet still resolves to would depend on the boolean's internal
1993/// face order, and would move whenever the path is edited. Pinning keeps one wall
1994/// face per (path segment × profile edge), each named after both — the same call
1995/// sheet metal makes to keep a flange attachable to a specific outline segment.
1996pub fn union_solids_keeping(
1997    solids: Vec<BrepSolid>,
1998    keep_unmerged: &[String],
1999) -> Result<BrepSolid, String> {
2000    let mut iter = solids.into_iter();
2001    let mut current = iter
2002        .next()
2003        .ok_or("profile produced no region solids to union")?;
2004    let options = BooleanOptions {
2005        merge_coplanar_faces: true,
2006        keep_unmerged_name_substrs: keep_unmerged.to_vec(),
2007        ..BooleanOptions::default()
2008    };
2009    for next in iter {
2010        let a = crate::register_solid_value(current);
2011        let b = crate::register_solid_value(next);
2012        let unioned = crate::with_two_registered_solids(a, b, |left, right| {
2013            crate::boolean_operation(left, right, BooleanOperation::Union, &options)
2014        });
2015        crate::free_registered_solid(a);
2016        crate::free_registered_solid(b);
2017        current = unioned.map_err(|error| format!("region union failed: {error}"))?;
2018    }
2019    Ok(current)
2020}
2021
2022// BREP private tests: 6df63fd1e9a86a54
2023
2024/// Transform controls shared by primitive solid schemas.
2025pub(super) fn primitive_transform_schema() -> serde_json::Value {
2026    serde_json::json!({
2027        "type": "transform",
2028        "default_value": {
2029            "position": [
2030                0,
2031                0,
2032                0
2033            ],
2034            "rotationEuler": [
2035                0,
2036                0,
2037                0
2038            ],
2039            "scale": [
2040                1,
2041                1,
2042                1
2043            ]
2044        },
2045        "referenceSelectionFilter": [
2046            "FACE",
2047            "EDGE",
2048            "VERTEX",
2049            "PLANE",
2050            "DATUM"
2051        ],
2052        "referenceLabel": "Start Reference",
2053        "referencePlaceholder": "Select point, edge, or face…",
2054        "hint": "Select a start reference, then position, rotate, and scale the solid relative to it."
2055    })
2056}
2057
2058/// Optional Boolean controls shared by solid-producing feature schemas.
2059pub(super) fn optional_boolean_schema() -> serde_json::Value {
2060    serde_json::json!({
2061        "type": "boolean_operation",
2062        "default_value": {
2063            "targets": [],
2064            "operation": "NONE",
2065            "mergeCoplanarFaces": true
2066        },
2067        "hint": "Optional boolean operation with selected solids"
2068    })
2069}
2070
2071
2072// BREP private tests: be6260a67d7d26af