Skip to main content

brep_kernel/brep/
transform_topology.rs

1use crate::topology::BrepSolid;
2use crate::{NurbsCurve, NurbsSurface, Vec3, Vec4};
3
4#[derive(Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
5pub struct AffineTransform {
6    pub elements: [f64; 16],
7}
8
9impl AffineTransform {
10    /// Whether this affine map is a finite, proper rigid placement.
11    pub fn is_rigid(&self, tolerance: f64) -> bool {
12        let m = &self.elements;
13        if !tolerance.is_finite() || tolerance < 0.0 || m.iter().any(|x| !x.is_finite()) {
14            return false;
15        }
16        if m[12].abs() > tolerance || m[13].abs() > tolerance || m[14].abs() > tolerance
17            || (m[15] - 1.0).abs() > tolerance {
18            return false;
19        }
20        let rows = [[m[0], m[1], m[2]], [m[4], m[5], m[6]], [m[8], m[9], m[10]]];
21        for i in 0..3 {
22            for j in i..3 {
23                let dot: f64 = (0..3).map(|k| rows[i][k] * rows[j][k]).sum();
24                let expected = if i == j { 1.0 } else { 0.0 };
25                if (dot - expected).abs() > tolerance { return false; }
26            }
27        }
28        (self.determinant3() - 1.0).abs() <= tolerance
29    }
30
31    /// Compose row-major transforms, applying `b` first.
32    pub fn compose(&self, b: &AffineTransform) -> Result<AffineTransform, String> {
33        // Iterator Sum starts at -0.0; the raw STEP loop starts at +0.0.
34        AffineTransform::new(multiply_elements_seeded(&self.elements, &b.elements, -0.0))
35    }
36
37    pub fn new(elements: [f64; 16]) -> Result<Self, String> {
38        if elements.iter().any(|value| !value.is_finite()) {
39            return Err("AffineTransform: matrix must be finite".into());
40        }
41        if elements[12].abs() > 1e-12
42            || elements[13].abs() > 1e-12
43            || elements[14].abs() > 1e-12
44            || (elements[15] - 1.0).abs() > 1e-12
45        {
46            return Err("AffineTransform: projective matrices are unsupported".into());
47        }
48        if (Self { elements }).determinant3().abs() <= 1e-14 {
49            return Err("AffineTransform: singular matrix".into());
50        }
51        Ok(Self { elements })
52    }
53
54    /// Invert a rigid map as `[Rᵀ | −Rᵀ·t]`. The caller must verify rigidity.
55    pub fn rigid_inverse(&self) -> Result<Self, String> {
56        let m = &self.elements;
57        let r = [[m[0], m[1], m[2]], [m[4], m[5], m[6]], [m[8], m[9], m[10]]];
58        let t = [m[3], m[7], m[11]];
59        let mut out = [0.0f64; 16];
60        for row in 0..3 {
61            for col in 0..3 {
62                out[row * 4 + col] = r[col][row]; // Rᵀ
63            }
64            out[row * 4 + 3] = -(0..3).map(|k| r[k][row] * t[k]).sum::<f64>();
65        }
66        out[15] = 1.0;
67        AffineTransform::new(out)
68    }
69
70    pub fn determinant3(self) -> f64 {
71        let m = self.elements;
72        m[0] * (m[5] * m[10] - m[6] * m[9]) - m[1] * (m[4] * m[10] - m[6] * m[8])
73            + m[2] * (m[4] * m[9] - m[5] * m[8])
74    }
75
76    pub fn point(self, point: Vec3) -> Vec3 {
77        let m = self.elements;
78        Vec3::new(
79            m[0] * point.x + m[1] * point.y + m[2] * point.z + m[3],
80            m[4] * point.x + m[5] * point.y + m[6] * point.z + m[7],
81            m[8] * point.x + m[9] * point.y + m[10] * point.z + m[11],
82        )
83    }
84
85    fn homogeneous(self, point: Vec4) -> Result<Vec4, String> {
86        Ok(Vec4::from_point(self.point(point.point()?), point.w))
87    }
88}
89
90pub(crate) fn transform_curve(
91    curve: &NurbsCurve,
92    transform: AffineTransform,
93) -> Result<NurbsCurve, String> {
94    NurbsCurve::new(
95        curve.degree,
96        curve.knots.clone(),
97        curve
98            .control_points
99            .iter()
100            .map(|point| transform.homogeneous(*point))
101            .collect::<Result<_, _>>()?,
102    )
103}
104
105pub(crate) fn transform_surface(
106    surface: &NurbsSurface,
107    transform: AffineTransform,
108) -> Result<NurbsSurface, String> {
109    NurbsSurface::new(
110        surface.degree_u,
111        surface.degree_v,
112        surface.knots_u.clone(),
113        surface.knots_v.clone(),
114        surface
115            .control_points
116            .iter()
117            .map(|row| {
118                row.iter()
119                    .map(|point| transform.homogeneous(*point))
120                    .collect::<Result<Vec<_>, _>>()
121            })
122            .collect::<Result<_, _>>()?,
123    )
124}
125
126/// Transform exact BREP geometry without changing entity IDs or parameter
127/// ranges. `reverse_orientation` is required for negative-determinant maps.
128pub fn transform_brep(
129    solid: &BrepSolid,
130    transform: AffineTransform,
131    reverse_orientation: bool,
132) -> Result<BrepSolid, String> {
133    let determinant = transform.determinant3();
134    if determinant < 0.0 && !reverse_orientation {
135        return Err("transformSolid: reflection requires orientation reversal".into());
136    }
137    if determinant > 0.0 && reverse_orientation {
138        return Err("transformSolid: orientation reversal requires a reflection".into());
139    }
140    let mut result = solid.clone();
141    for vertex in &mut result.vertices {
142        vertex.point = transform.point(vertex.point);
143    }
144    for edge in &mut result.edges {
145        edge.curve = transform_curve(&edge.curve, transform)?;
146    }
147    for shell in &mut result.shells {
148        for face in &mut shell.faces {
149            face.surface = transform_surface(&face.surface, transform)?;
150            if reverse_orientation {
151                face.same_sense = !face.same_sense;
152                for loop_record in &mut face.loops {
153                    loop_record.coedges.reverse();
154                    for coedge in &mut loop_record.coedges {
155                        coedge.forward = !coedge.forward;
156                        coedge.pcurve = coedge.pcurve.reversed()?;
157                    }
158                }
159            }
160        }
161    }
162    // Where the copy's coordinates are spaced finely, a placement moves the
163    // part faithfully. Farther out, rounding to the coordinates there can
164    // reshape or collapse it while every topological check still passes, so
165    // the move is measured against the part and the copy is validated itself.
166    let precise = arithmetic_spacing(solid, &result, transform) <= PRECISE_SPACING;
167    if !precise {
168        placement_resolves_the_part(solid, &result, transform)?;
169    }
170    let mode = carry_verdict_mode();
171    let carried = precise
172        && mode != crate::env_read::Mode::Off
173        && carries_clean_verdict(solid, transform, reverse_orientation);
174    if carried && mode == crate::env_read::Mode::On {
175        CARRIED_VERDICTS.with(|count| count.set(count.get() + 1));
176        if crate::profile::profile_enabled() {
177            profile_line!("transform.verdict carried=1");
178        }
179        return Ok(result);
180    }
181    let issues = result.validate();
182    if mode == crate::env_read::Mode::Check && crate::profile::profile_enabled() {
183        // What carrying would have answered, against the copy's own verdict.
184        profile_line!(
185            "transform.verdict check carried={} issues={} disagree={}",
186            u8::from(carried),
187            issues.len(),
188            u8::from(carried && !issues.is_empty())
189        );
190    }
191    if issues.is_empty() {
192        Ok(result)
193    } else {
194        Err(format!("transformed BREP is invalid: {issues:?}"))
195    }
196}
197
198/// Spacing of the coordinates a placement computes with, below which a moved
199/// copy is faithful to the model tolerance with room to spare (a tenth of
200/// it): within about 4.5e7 of the origin. Such copies keep the fast path
201/// unchanged.
202const PRECISE_SPACING: f64 = 0.1 * crate::tolerance::DEFAULT_MODEL;
203
204/// Every point a solid's geometry is stated by, in a fixed order: its
205/// vertices, then each edge curve's control points, then each face surface's.
206/// A source and its transformed copy list them in parallel. A pole that does
207/// not read as a point comes out non-finite.
208fn stated_points(solid: &BrepSolid) -> impl Iterator<Item = Vec3> + '_ {
209    let cartesian =
210        |point: &Vec4| point.point().unwrap_or(Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY));
211    solid
212        .vertices
213        .iter()
214        .map(|vertex| vertex.point)
215        .chain(solid.edges.iter().flat_map(move |edge| edge.curve.control_points.iter().map(cartesian)))
216        .chain(
217            solid
218                .shells
219                .iter()
220                .flat_map(|shell| &shell.faces)
221                .flat_map(move |face| face.surface.control_points.iter().flatten().map(cartesian)),
222        )
223}
224
225/// The farthest coordinate of `points` from the origin; infinite when one is
226/// not finite.
227fn reach(points: impl Iterator<Item = Vec3>) -> f64 {
228    points
229        .flat_map(|point| [point.x, point.y, point.z])
230        .fold(0.0f64, |reach, value| if value.is_finite() { reach.max(value.abs()) } else { f64::INFINITY })
231}
232
233/// The spacing of representable coordinates at the largest magnitude the
234/// placement computes with: the copy's points, the source's as the linear
235/// part scales them, and the translation. A far part brought back near the
236/// origin loses its precision on the way, so the copy alone cannot tell; a
237/// far pole loses it though every vertex is near.
238fn arithmetic_spacing(source: &BrepSolid, copy: &BrepSolid, transform: AffineTransform) -> f64 {
239    let m = transform.elements;
240    let gain = (0..3).map(|row| m[row * 4].abs() + m[row * 4 + 1].abs() + m[row * 4 + 2].abs()).fold(0.0f64, f64::max);
241    let translation = m[3].abs().max(m[7].abs()).max(m[11].abs());
242    reach(stated_points(copy)).max(gain * reach(stated_points(source))).max(translation) * f64::EPSILON
243}
244
245/// The sum of `terms`, exact until its final rounding: a Shewchuk expansion
246/// keeps every bit any partial sum would lose, however the terms cancel.
247fn exact_sum(terms: impl IntoIterator<Item = f64>) -> f64 {
248    let mut partials: Vec<f64> = Vec::new();
249    for mut term in terms {
250        let mut kept = 0;
251        for index in 0..partials.len() {
252            let mut other = partials[index];
253            if term.abs() < other.abs() {
254                std::mem::swap(&mut term, &mut other);
255            }
256            let high = term + other;
257            let low = other - (high - term);
258            if low != 0.0 {
259                partials[kept] = low;
260                kept += 1;
261            }
262            term = high;
263        }
264        partials.truncate(kept);
265        partials.push(term);
266    }
267    // Smallest first: the large partials do not overlap, so this rounds once
268    // to within an ulp of the result.
269    partials.iter().sum()
270}
271
272/// How far a computed coordinate lies from the exact `A p + t` for one row:
273/// the three products split exactly (fused multiply-add), the translation and
274/// the computed value summed exactly, so the rounding is measured to its own
275/// precision whatever the magnitudes.
276fn coordinate_rounding(row: [f64; 4], point: Vec3, computed: f64) -> f64 {
277    let mut terms = [0.0f64; 8];
278    for (slot, (factor, value)) in [(row[0], point.x), (row[1], point.y), (row[2], point.z)].into_iter().enumerate() {
279        let product = factor * value;
280        terms[2 * slot] = product;
281        terms[2 * slot + 1] = factor.mul_add(value, -product);
282    }
283    terms[6] = row[3];
284    terms[7] = -computed;
285    -exact_sum(terms)
286}
287
288/// Whether a measured rounding is fine enough for roundings to be compared
289/// against the model tolerance: its own ulp must sit well below it. One past
290/// that (tens of kilometres of rounding, from coordinates near 1e23) has lost
291/// the part in any case.
292fn measurable(rounding: f64) -> bool {
293    rounding.is_finite() && rounding.abs() * f64::EPSILON <= 0.01 * crate::tolerance::DEFAULT_MODEL
294}
295
296/// Refuse a copy the placement could not carry at the precision the kernel
297/// models to. Each stated point of the copy is set against its exact image
298/// under the placement: the difference is that coordinate's rounding. Points
299/// rounded alike have only moved together, which changes nothing; the spread
300/// of the roundings across the part is how far it was moved out of shape. A
301/// spread past the model tolerance, the band vertex identity is judged in,
302/// has reshaped the part (a thin side or wall lost, a corner merged, a cavity
303/// shifted into its solid), however small that is next to the part, and
304/// validation cannot see it. No reference point is subtracted, so nothing the
305/// placement rounds away can be rounded away from the measure too.
306fn placement_resolves_the_part(
307    source: &BrepSolid,
308    copy: &BrepSolid,
309    transform: AffineTransform,
310) -> Result<(), String> {
311    let m = transform.elements;
312    let rows = [[m[0], m[1], m[2], m[3]], [m[4], m[5], m[6], m[7]], [m[8], m[9], m[10], m[11]]];
313    let mut low = [f64::INFINITY; 3];
314    let mut high = [f64::NEG_INFINITY; 3];
315    let mut lost = false;
316    for (from, to) in stated_points(source).zip(stated_points(copy)) {
317        for (axis, value) in [to.x, to.y, to.z].into_iter().enumerate() {
318            let rounding = coordinate_rounding(rows[axis], from, value);
319            if !measurable(rounding) {
320                lost = true;
321                continue;
322            }
323            low[axis] = low[axis].min(rounding);
324            high[axis] = high[axis].max(rounding);
325        }
326    }
327    let spread = (0..3).map(|axis| (high[axis] - low[axis]).max(0.0).powi(2)).sum::<f64>().sqrt();
328    let worst = if lost { f64::INFINITY } else { spread };
329    if worst > crate::tolerance::DEFAULT_MODEL {
330        return Err(format!(
331            "transformSolid: the placement computes with coordinates spaced {:.1e}, too coarse to hold the part: it moves its points against one another by up to {worst:.1e}, past the {:.0e} modelling tolerance",
332            arithmetic_spacing(source, copy, transform),
333            crate::tolerance::DEFAULT_MODEL
334        ));
335    }
336    Ok(())
337}
338
339/// Whether a rigid placement may keep its source's clean validation verdict
340/// instead of validating the moved copy. A proper rigid map (the shared
341/// `RIGID_TOL` band components are placed under) changes no distance, angle,
342/// parameter or topology. It does change one input of `validate`: the
343/// identity and pcurve bands are sized from the AXIS-ALIGNED bounding box of
344/// the vertices, whose diagonal moves under a rotation, so a copy read with
345/// its own (narrower) bands could report an issue its source does not. The
346/// carried verdict is the source's, read in the source's frame. The source's
347/// verdict comes from the content-keyed validate memo: the first placement of
348/// a part validates the part once, each further placement of the same
349/// content reads the memo. A source with issues is never carried; its copy is
350/// validated as before. `BREP_TRANSFORM_CARRY_VERDICT`: on by default (`0`
351/// validates every copy, as before), `check` validates every copy anyway and
352/// prints (`BREP_PROFILE`) whether carrying would have disagreed.
353fn carries_clean_verdict(
354    solid: &BrepSolid,
355    transform: AffineTransform,
356    reverse_orientation: bool,
357) -> bool {
358    !reverse_orientation
359        && transform.is_rigid(crate::RIGID_TOL)
360        && solid.validate_memoised().is_empty()
361}
362
363thread_local! {
364    /// Placements on this thread that kept their source's verdict.
365    static CARRIED_VERDICTS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
366}
367
368
369fn carry_verdict_mode() -> crate::env_read::Mode {
370    crate::mode_switch!("BREP_TRANSFORM_CARRY_VERDICT", true)
371}
372
373/// Reflect an exact BREP across the plane through `plane_point` with unit
374/// normal `n = plane_normal.normalized()`. The reflection is the affine map
375/// `p' = R p + t` with linear part `R = I - 2 n nᵀ` and translation
376/// `t = 2 (plane_point·n) n`, so points on the plane map to themselves. A
377/// reflection has negative determinant (it flips handedness), so faces are
378/// re-oriented via the existing transform with `reverse_orientation = true`,
379/// keeping outward normals.
380pub fn mirror_brep(
381    solid: &BrepSolid,
382    plane_point: Vec3,
383    plane_normal: Vec3,
384) -> Result<BrepSolid, String> {
385    let n = plane_normal.normalized()?;
386    let (nx, ny, nz) = (n.x, n.y, n.z);
387    let d = plane_point.dot(n);
388    let (tx, ty, tz) = (2.0 * d * nx, 2.0 * d * ny, 2.0 * d * nz);
389    let matrix = [
390        1.0 - 2.0 * nx * nx,
391        -2.0 * nx * ny,
392        -2.0 * nx * nz,
393        tx,
394        -2.0 * ny * nx,
395        1.0 - 2.0 * ny * ny,
396        -2.0 * ny * nz,
397        ty,
398        -2.0 * nz * nx,
399        -2.0 * nz * ny,
400        1.0 - 2.0 * nz * nz,
401        tz,
402        0.0,
403        0.0,
404        0.0,
405        1.0,
406    ];
407    let transform = AffineTransform::new(matrix)?;
408    transform_brep(solid, transform, true)
409}
410
411
412pub(crate) fn multiply_elements(a: &[f64; 16], b: &[f64; 16]) -> [f64; 16] {
413    multiply_elements_seeded(a, b, 0.0)
414}
415
416fn multiply_elements_seeded(a: &[f64; 16], b: &[f64; 16], seed: f64) -> [f64; 16] {
417    let mut out = [0.0f64; 16];
418    for row in 0..4 {
419        for col in 0..4 {
420            let mut sum = seed;
421            for k in 0..4 {
422                sum += a[row * 4 + k] * b[k * 4 + col];
423            }
424            out[row * 4 + col] = sum;
425        }
426    }
427    out
428}
429