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