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