Skip to main content

brep_ransac/
design_intent.rs

1//! Safe translation of neighboring analytic geometry into constrained hints.
2//!
3//! These helpers deliberately produce ordinary [`SurfaceHint::Constrained`]
4//! values. They do not add a hidden coupled solver or claim relations that the
5//! current parameter-group constraints cannot preserve.
6
7use crate::{
8    AnalyticSurface, ConstraintMask, CylinderSurface, MetadataTrust, PlaneSurface, SphereSurface,
9    SurfaceConstraints, SurfaceHint, SurfaceType, Vec3,
10};
11use std::fmt::{Display, Formatter};
12
13/// Failure to express a requested design-intent relation with the current
14/// parameter-group constraint model.
15#[derive(Clone, Debug, PartialEq, Eq)]
16pub enum DesignIntentError {
17    /// The target or reference carrier contains invalid parameters.
18    InvalidSurface {
19        /// Whether the invalid carrier was the `target` or `reference`.
20        role: &'static str,
21    },
22    /// The supplied geometry does not determine a unique requested relation.
23    DegenerateRelation {
24        /// Human-readable name of the degenerate relation.
25        relation: &'static str,
26    },
27    /// The relation cannot be represented by the current parameter groups.
28    UnsupportedRelation {
29        /// Human-readable name of the unsupported relation.
30        relation: &'static str,
31        /// Primitive type that would be constrained.
32        target: SurfaceType,
33        /// Primitive type used as design-intent evidence.
34        reference: SurfaceType,
35    },
36}
37
38impl Display for DesignIntentError {
39    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
40        match self {
41            Self::InvalidSurface { role } => write!(formatter, "invalid {role} analytic surface"),
42            Self::DegenerateRelation { relation } => {
43                write!(formatter, "cannot derive a unique {relation} relation")
44            }
45            Self::UnsupportedRelation {
46                relation,
47                target,
48                reference,
49            } => write!(
50                formatter,
51                "{relation} is not representable for {target:?} from {reference:?} with current parameter groups"
52            ),
53        }
54    }
55}
56
57impl std::error::Error for DesignIntentError {}
58
59fn validate(target: AnalyticSurface, reference: AnalyticSurface) -> Result<(), DesignIntentError> {
60    if !target.is_valid() {
61        return Err(DesignIntentError::InvalidSurface { role: "target" });
62    }
63    if !reference.is_valid() {
64        return Err(DesignIntentError::InvalidSurface { role: "reference" });
65    }
66    Ok(())
67}
68
69fn hint(surface: AnalyticSurface, fixed: ConstraintMask) -> SurfaceHint {
70    SurfaceHint::Constrained {
71        surface_type: surface.surface_type(),
72        constraints: SurfaceConstraints {
73            initial: Some(surface),
74            fixed,
75        },
76        trust: MetadataTrust::StrongHint,
77    }
78}
79
80fn axial_line(surface: AnalyticSurface) -> Option<(Vec3, Vec3)> {
81    match surface {
82        AnalyticSurface::Cylinder(value) => Some((value.axis_origin, value.axis)),
83        AnalyticSurface::Cone(value) => Some((value.apex, value.axis)),
84        AnalyticSurface::Torus(value) => Some((value.center, value.axis)),
85        _ => None,
86    }
87}
88
89fn aligned(reference: Vec3, preferred: Vec3) -> Vec3 {
90    if reference.dot(preferred) < 0.0 {
91        -reference
92    } else {
93        reference
94    }
95}
96
97/// Fix a target cylinder, cone, or torus axis direction to an existing axial
98/// carrier. Cone-to-nondirected-carrier transfer is rejected because a cone's
99/// nappe direction is not sign-equivalent.
100pub fn constrain_shared_axis(
101    target: AnalyticSurface,
102    reference: AnalyticSurface,
103) -> Result<SurfaceHint, DesignIntentError> {
104    validate(target, reference)?;
105    let (_, reference_axis) =
106        axial_line(reference).ok_or_else(|| unsupported("shared axis", target, reference))?;
107    let constrained = match target {
108        AnalyticSurface::Cylinder(mut value) => {
109            value.axis = aligned(reference_axis, value.axis);
110            AnalyticSurface::Cylinder(value)
111        }
112        AnalyticSurface::Torus(mut value) => {
113            value.axis = aligned(reference_axis, value.axis);
114            AnalyticSurface::Torus(value)
115        }
116        AnalyticSurface::Cone(mut value) if matches!(reference, AnalyticSurface::Cone(_)) => {
117            value.axis = reference_axis;
118            AnalyticSurface::Cone(value)
119        }
120        _ => return Err(unsupported("shared axis", target, reference)),
121    };
122    Ok(hint(
123        constrained,
124        ConstraintMask {
125            axis_or_normal: true,
126            ..Default::default()
127        },
128    ))
129}
130
131/// Constrain a cylinder to the complete axis line of another axial carrier.
132/// This is safe because a cylinder's axis origin has gauge freedom along the
133/// line; cone apex and torus center locations do not, so those target types are
134/// intentionally unsupported here.
135pub fn constrain_cylinder_coaxial(
136    target: CylinderSurface,
137    reference: AnalyticSurface,
138) -> Result<SurfaceHint, DesignIntentError> {
139    let target_surface = AnalyticSurface::Cylinder(target);
140    validate(target_surface, reference)?;
141    let (reference_origin, reference_axis) = axial_line(reference)
142        .ok_or_else(|| unsupported("coaxial axes", target_surface, reference))?;
143    let constrained = AnalyticSurface::Cylinder(CylinderSurface {
144        axis_origin: reference_origin,
145        axis: aligned(reference_axis, target.axis),
146        radius: target.radius,
147    });
148    Ok(hint(
149        constrained,
150        ConstraintMask {
151            origin_or_center: true,
152            axis_or_normal: true,
153            ..Default::default()
154        },
155    ))
156}
157
158/// Constrain a plane to be perpendicular to a known axis. The plane normal is
159/// the axis direction; its offset remains free.
160pub fn constrain_plane_perpendicular_to_axis(
161    target: PlaneSurface,
162    axis: Vec3,
163) -> Result<SurfaceHint, DesignIntentError> {
164    let axis = axis.normalized().filter(|axis| axis.is_finite()).ok_or(
165        DesignIntentError::DegenerateRelation {
166            relation: "plane perpendicular to axis",
167        },
168    )?;
169    let target_surface = AnalyticSurface::Plane(target);
170    if !target_surface.is_valid() {
171        return Err(DesignIntentError::InvalidSurface { role: "target" });
172    }
173    Ok(hint(
174        AnalyticSurface::Plane(PlaneSurface {
175            normal: aligned(axis, target.normal),
176            ..target
177        }),
178        ConstraintMask {
179            axis_or_normal: true,
180            ..Default::default()
181        },
182    ))
183}
184
185/// Preserve parallelism to a reference plane while leaving plane offset free.
186pub fn constrain_planes_parallel(
187    target: PlaneSurface,
188    reference: PlaneSurface,
189) -> Result<SurfaceHint, DesignIntentError> {
190    let target_surface = AnalyticSurface::Plane(target);
191    let reference_surface = AnalyticSurface::Plane(reference);
192    validate(target_surface, reference_surface)?;
193    Ok(hint(
194        AnalyticSurface::Plane(PlaneSurface {
195            normal: aligned(reference.normal, target.normal),
196            ..target
197        }),
198        ConstraintMask {
199            axis_or_normal: true,
200            ..Default::default()
201        },
202    ))
203}
204
205/// Preserve perpendicularity to a reference plane using the target's current
206/// normal to select the otherwise non-unique perpendicular direction.
207pub fn constrain_planes_perpendicular(
208    target: PlaneSurface,
209    reference: PlaneSurface,
210) -> Result<SurfaceHint, DesignIntentError> {
211    let target_surface = AnalyticSurface::Plane(target);
212    let reference_surface = AnalyticSurface::Plane(reference);
213    validate(target_surface, reference_surface)?;
214    let projected = target.normal - reference.normal * target.normal.dot(reference.normal);
215    let normal = projected
216        .normalized()
217        .ok_or(DesignIntentError::DegenerateRelation {
218            relation: "perpendicular planes",
219        })?;
220    Ok(hint(
221        AnalyticSurface::Plane(PlaneSurface { normal, ..target }),
222        ConstraintMask {
223            axis_or_normal: true,
224            ..Default::default()
225        },
226    ))
227}
228
229/// Fix a plane to the same infinite carrier as a reference plane. Tangential
230/// origin coordinates are a gauge and are preserved from the target.
231pub fn constrain_planes_coplanar(
232    target: PlaneSurface,
233    reference: PlaneSurface,
234) -> Result<SurfaceHint, DesignIntentError> {
235    let target_surface = AnalyticSurface::Plane(target);
236    let reference_surface = AnalyticSurface::Plane(reference);
237    validate(target_surface, reference_surface)?;
238    let normal = aligned(reference.normal, target.normal);
239    let origin = target.origin + normal * (reference.origin - target.origin).dot(normal);
240    Ok(hint(
241        AnalyticSurface::Plane(PlaneSurface { origin, normal }),
242        ConstraintMask {
243            origin_or_center: true,
244            axis_or_normal: true,
245            ..Default::default()
246        },
247    ))
248}
249
250/// Fix sphere or torus centers to an existing sphere/torus center.
251pub fn constrain_concentric_centers(
252    target: AnalyticSurface,
253    reference: AnalyticSurface,
254) -> Result<SurfaceHint, DesignIntentError> {
255    validate(target, reference)?;
256    let reference_center = match reference {
257        AnalyticSurface::Sphere(value) => value.center,
258        AnalyticSurface::Torus(value) => value.center,
259        _ => return Err(unsupported("concentric centers", target, reference)),
260    };
261    let constrained = match target {
262        AnalyticSurface::Sphere(mut value) => {
263            value.center = reference_center;
264            AnalyticSurface::Sphere(value)
265        }
266        AnalyticSurface::Torus(mut value) => {
267            value.center = reference_center;
268            AnalyticSurface::Torus(value)
269        }
270        _ => return Err(unsupported("concentric centers", target, reference)),
271    };
272    Ok(hint(
273        constrained,
274        ConstraintMask {
275            origin_or_center: true,
276            ..Default::default()
277        },
278    ))
279}
280
281/// Fix equal radius groups for two carriers of the same type. For tori this
282/// copies and fixes both major and minor radii; mixed-type radius semantics are
283/// deliberately rejected.
284pub fn constrain_equal_radii(
285    target: AnalyticSurface,
286    reference: AnalyticSurface,
287) -> Result<SurfaceHint, DesignIntentError> {
288    validate(target, reference)?;
289    let (constrained, fixed) = match (target, reference) {
290        (AnalyticSurface::Sphere(mut target), AnalyticSurface::Sphere(reference)) => {
291            target.radius = reference.radius;
292            (
293                AnalyticSurface::Sphere(target),
294                ConstraintMask {
295                    radius: true,
296                    ..Default::default()
297                },
298            )
299        }
300        (AnalyticSurface::Cylinder(mut target), AnalyticSurface::Cylinder(reference)) => {
301            target.radius = reference.radius;
302            (
303                AnalyticSurface::Cylinder(target),
304                ConstraintMask {
305                    radius: true,
306                    ..Default::default()
307                },
308            )
309        }
310        (AnalyticSurface::Torus(mut target), AnalyticSurface::Torus(reference)) => {
311            target.major_radius = reference.major_radius;
312            target.minor_radius = reference.minor_radius;
313            (
314                AnalyticSurface::Torus(target),
315                ConstraintMask {
316                    radius: true,
317                    major_radius: true,
318                    ..Default::default()
319                },
320            )
321        }
322        _ => return Err(unsupported("equal radii", target, reference)),
323    };
324    Ok(hint(constrained, fixed))
325}
326
327/// Derive exact sphere/plane tangency from the target's current side and
328/// orientation. Other tangency pairs require coupled parameters and are
329/// rejected explicitly.
330pub fn constrain_tangent(
331    target: AnalyticSurface,
332    reference: AnalyticSurface,
333) -> Result<SurfaceHint, DesignIntentError> {
334    validate(target, reference)?;
335    match (target, reference) {
336        (AnalyticSurface::Plane(target), AnalyticSurface::Sphere(reference)) => {
337            let signed = (target.origin - reference.center).dot(target.normal);
338            let side = if signed < 0.0 { -1.0 } else { 1.0 };
339            let origin = reference.center + target.normal * (side * reference.radius);
340            Ok(hint(
341                AnalyticSurface::Plane(PlaneSurface { origin, ..target }),
342                ConstraintMask {
343                    origin_or_center: true,
344                    axis_or_normal: true,
345                    ..Default::default()
346                },
347            ))
348        }
349        (AnalyticSurface::Sphere(target), AnalyticSurface::Plane(reference)) => {
350            let signed = (target.center - reference.origin).dot(reference.normal);
351            let side = if signed < 0.0 { -1.0 } else { 1.0 };
352            let tangent_component = target.center - reference.normal * signed;
353            let center = tangent_component + reference.normal * (side * target.radius);
354            Ok(hint(
355                AnalyticSurface::Sphere(SphereSurface { center, ..target }),
356                ConstraintMask {
357                    origin_or_center: true,
358                    radius: true,
359                    ..Default::default()
360                },
361            ))
362        }
363        _ => Err(unsupported("tangency", target, reference)),
364    }
365}
366
367fn unsupported(
368    relation: &'static str,
369    target: AnalyticSurface,
370    reference: AnalyticSurface,
371) -> DesignIntentError {
372    DesignIntentError::UnsupportedRelation {
373        relation,
374        target: target.surface_type(),
375        reference: reference.surface_type(),
376    }
377}
378