ifc_lite_geometry/placement/
heading.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! The heading of a resolved placement about the world vertical.
6
7/// The building/site rotation about the world vertical (Z) axis, derived from a
8/// resolved **column-major** 4×4 placement matrix (as returned by
9/// [`crate::GeometryRouter::resolve_scaled_placement`]). The local X-axis (the
10/// placement's RefDirection, composed through the full parent chain and
11/// normalized) is column 0 — elements `[0]`, `[1]`, `[2]` — so its angle in the
12/// world XY plane is `atan2(m[1], m[0])`.
13///
14/// This is the single source of truth for site rotation: the processor consumes
15/// the full matrix (baking the inverse rotation into vertices for the
16/// `site_local` frame) while the viewer takes this angle for its render-frame
17/// rotation — both off the *same* resolved matrix, so they cannot drift on
18/// nested, scaled, or tilted-axis placements (where `atan2` of the raw
19/// top-level RefDirection is incomplete). Returns `None` for a degenerate
20/// (zero-length) projected X-axis.
21pub fn rotation_angle_about_z(matrix: &[f64; 16]) -> Option<f64> {
22    let x = matrix[0];
23    let y = matrix[1];
24    if x * x + y * y < 1e-10 {
25        return None;
26    }
27    Some(y.atan2(x))
28}
29
30#[cfg(test)]
31mod tests {
32    use super::*;
33
34    #[test]
35    fn rotation_angle_about_z_handles_identity_rotation_and_scale() {
36        // Identity → 0 rad.
37        let mut m = [0.0f64; 16];
38        m[0] = 1.0;
39        m[5] = 1.0;
40        m[10] = 1.0;
41        m[15] = 1.0;
42        assert!(rotation_angle_about_z(&m).unwrap().abs() < 1e-12);
43
44        // 45° about Z: column-0 X-axis = (cos45, sin45, 0). Matches the legacy
45        // atan2(RefDirection.y, RefDirection.x) for an axis-aligned placement.
46        let a = std::f64::consts::FRAC_PI_4;
47        let mut r = [0.0f64; 16];
48        r[0] = a.cos();
49        r[1] = a.sin();
50        r[4] = -a.sin();
51        r[5] = a.cos();
52        r[10] = 1.0;
53        r[15] = 1.0;
54        assert!((rotation_angle_about_z(&r).unwrap() - a).abs() < 1e-12);
55
56        // Uniform scale is angle-invariant (resolve_scaled_placement may carry scale).
57        let mut s = r;
58        for v in s.iter_mut().take(3) {
59            *v *= 3.0;
60        }
61        assert!((rotation_angle_about_z(&s).unwrap() - a).abs() < 1e-9);
62
63        // Degenerate (zero-length) projected X-axis → None.
64        assert!(rotation_angle_about_z(&[0.0f64; 16]).is_none());
65    }
66}