1
//! 3D transform matrix computations for CSS transforms.
2
//!
3
//! This module implements 4x4 transformation matrices for CSS `transform` properties,
4
//! including translation, rotation, scaling, skewing, and perspective. It handles conversion
5
//! from CSS transform functions to hardware-accelerated matrices for WebRender.
6
//!
7
//! On x86_64 platforms, the module automatically detects and uses SSE/AVX instructions
8
//! for optimized matrix multiplication and inversion.
9
//!
10
//! **NOTE**: Matrices are stored in **row-major** format (unlike some graphics APIs that
11
//! use column-major). The module handles coordinate system differences between WebRender
12
//! and hit-testing via the `RotationMode` enum.
13

            
14
use core::sync::atomic::{AtomicBool, Ordering as AtomicOrdering};
15

            
16
use azul_css::props::style::{StyleTransform, StyleTransformOrigin};
17

            
18
use crate::geom::LogicalPosition;
19

            
20
/// CPU feature detection: true if initialization has been performed
21
pub static INITIALIZED: AtomicBool = AtomicBool::new(false);
22
/// CPU feature detection: true if AVX instructions are available
23
pub static USE_AVX: AtomicBool = AtomicBool::new(false);
24
/// CPU feature detection: true if SSE instructions are available
25
pub static USE_SSE: AtomicBool = AtomicBool::new(false);
26

            
27
/// Specifies the coordinate system convention for rotations.
28
///
29
/// `WebRender` uses a different rotation direction than hit-testing, so transforms
30
/// must be adjusted based on their use case. This enum controls whether the
31
/// rotation matrix is inverted to match the expected behavior.
32
#[derive(Debug, Copy, Clone)]
33
pub enum RotationMode {
34
    /// Use rotation convention for `WebRender` (counter-clockwise, requires inversion)
35
    ForWebRender,
36
    /// Use rotation convention for hit-testing (clockwise, no inversion)
37
    ForHitTesting,
38
}
39

            
40
/// A computed 4x4 transformation matrix in pixel space.
41
///
42
/// Represents the final transformation matrix for a DOM element after applying
43
/// all CSS transform functions (translate, rotate, scale, etc.) and accounting
44
/// for transform-origin.
45
///
46
/// # Memory Layout
47
///
48
/// Matrix is stored in **row-major** format:
49
/// ```text
50
/// m[0] = [m11, m12, m13, m14]
51
/// m[1] = [m21, m22, m23, m24]
52
/// m[2] = [m31, m32, m33, m34]
53
/// m[3] = [m41, m42, m43, m44]
54
/// ```
55
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd)]
56
#[repr(C)]
57
pub struct ComputedTransform3D {
58
    /// The 4x4 matrix in row-major format
59
    pub m: [[f32; 4]; 4],
60
}
61

            
62
impl ComputedTransform3D {
63
    /// The identity matrix (no transformation).
64
    pub const IDENTITY: Self = Self {
65
        m: [
66
            [1.0, 0.0, 0.0, 0.0],
67
            [0.0, 1.0, 0.0, 0.0],
68
            [0.0, 0.0, 1.0, 0.0],
69
            [0.0, 0.0, 0.0, 1.0],
70
        ],
71
    };
72

            
73
    /// Creates a new 4x4 transformation matrix with the given elements.
74
    ///
75
    /// Elements are specified in row-major order (m11, m12, ..., m44).
76
    #[must_use]
77
38318
    pub const fn new(
78
38318
        m11: f32,
79
38318
        m12: f32,
80
38318
        m13: f32,
81
38318
        m14: f32,
82
38318
        m21: f32,
83
38318
        m22: f32,
84
38318
        m23: f32,
85
38318
        m24: f32,
86
38318
        m31: f32,
87
38318
        m32: f32,
88
38318
        m33: f32,
89
38318
        m34: f32,
90
38318
        m41: f32,
91
38318
        m42: f32,
92
38318
        m43: f32,
93
38318
        m44: f32,
94
38318
    ) -> Self {
95
38318
        Self {
96
38318
            m: [
97
38318
                [m11, m12, m13, m14],
98
38318
                [m21, m22, m23, m24],
99
38318
                [m31, m32, m33, m34],
100
38318
                [m41, m42, m43, m44],
101
38318
            ],
102
38318
        }
103
38318
    }
104

            
105
    /// Creates a 2D transformation matrix (3D matrix with Z = 0).
106
    ///
107
    /// This is equivalent to the CSS `matrix()` function. The transformation
108
    /// only affects the X and Y axes.
109
    ///
110
    /// Corresponds to `matrix(m11, m12, m21, m22, m41, m42)` in CSS.
111
3
    const fn new_2d(m11: f32, m12: f32, m21: f32, m22: f32, m41: f32, m42: f32) -> Self {
112
3
        Self::new(
113
3
            m11, m12, 0.0, 0.0, m21, m22, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, m41, m42, 0.0, 1.0,
114
        )
115
3
    }
116

            
117
    /// Computes the inverse of this transformation matrix.
118
    ///
119
    /// This function uses a standard matrix inversion algorithm. Returns the
120
    /// identity matrix if the determinant is zero (singular matrix).
121
    ///
122
    /// NOTE: This is a relatively expensive operation.
123
    #[must_use]
124
    #[allow(clippy::suboptimal_flops)] // mul_add not guaranteed faster/available without target
125
                                       // +fma; keep explicit a*b+c
126
24
    pub fn inverse(&self) -> Self {
127
24
        let det = self.determinant();
128

            
129
24
        if det.abs() < f32::EPSILON {
130
5
            return Self::IDENTITY;
131
19
        }
132

            
133
19
        let m = Self::new(
134
19
            self.m[1][2] * self.m[2][3] * self.m[3][1] - self.m[1][3] * self.m[2][2] * self.m[3][1]
135
19
                + self.m[1][3] * self.m[2][1] * self.m[3][2]
136
19
                - self.m[1][1] * self.m[2][3] * self.m[3][2]
137
19
                - self.m[1][2] * self.m[2][1] * self.m[3][3]
138
19
                + self.m[1][1] * self.m[2][2] * self.m[3][3],
139
19
            self.m[0][3] * self.m[2][2] * self.m[3][1]
140
19
                - self.m[0][2] * self.m[2][3] * self.m[3][1]
141
19
                - self.m[0][3] * self.m[2][1] * self.m[3][2]
142
19
                + self.m[0][1] * self.m[2][3] * self.m[3][2]
143
19
                + self.m[0][2] * self.m[2][1] * self.m[3][3]
144
19
                - self.m[0][1] * self.m[2][2] * self.m[3][3],
145
19
            self.m[0][2] * self.m[1][3] * self.m[3][1] - self.m[0][3] * self.m[1][2] * self.m[3][1]
146
19
                + self.m[0][3] * self.m[1][1] * self.m[3][2]
147
19
                - self.m[0][1] * self.m[1][3] * self.m[3][2]
148
19
                - self.m[0][2] * self.m[1][1] * self.m[3][3]
149
19
                + self.m[0][1] * self.m[1][2] * self.m[3][3],
150
19
            self.m[0][3] * self.m[1][2] * self.m[2][1]
151
19
                - self.m[0][2] * self.m[1][3] * self.m[2][1]
152
19
                - self.m[0][3] * self.m[1][1] * self.m[2][2]
153
19
                + self.m[0][1] * self.m[1][3] * self.m[2][2]
154
19
                + self.m[0][2] * self.m[1][1] * self.m[2][3]
155
19
                - self.m[0][1] * self.m[1][2] * self.m[2][3],
156
19
            self.m[1][3] * self.m[2][2] * self.m[3][0]
157
19
                - self.m[1][2] * self.m[2][3] * self.m[3][0]
158
19
                - self.m[1][3] * self.m[2][0] * self.m[3][2]
159
19
                + self.m[1][0] * self.m[2][3] * self.m[3][2]
160
19
                + self.m[1][2] * self.m[2][0] * self.m[3][3]
161
19
                - self.m[1][0] * self.m[2][2] * self.m[3][3],
162
19
            self.m[0][2] * self.m[2][3] * self.m[3][0] - self.m[0][3] * self.m[2][2] * self.m[3][0]
163
19
                + self.m[0][3] * self.m[2][0] * self.m[3][2]
164
19
                - self.m[0][0] * self.m[2][3] * self.m[3][2]
165
19
                - self.m[0][2] * self.m[2][0] * self.m[3][3]
166
19
                + self.m[0][0] * self.m[2][2] * self.m[3][3],
167
19
            self.m[0][3] * self.m[1][2] * self.m[3][0]
168
19
                - self.m[0][2] * self.m[1][3] * self.m[3][0]
169
19
                - self.m[0][3] * self.m[1][0] * self.m[3][2]
170
19
                + self.m[0][0] * self.m[1][3] * self.m[3][2]
171
19
                + self.m[0][2] * self.m[1][0] * self.m[3][3]
172
19
                - self.m[0][0] * self.m[1][2] * self.m[3][3],
173
19
            self.m[0][2] * self.m[1][3] * self.m[2][0] - self.m[0][3] * self.m[1][2] * self.m[2][0]
174
19
                + self.m[0][3] * self.m[1][0] * self.m[2][2]
175
19
                - self.m[0][0] * self.m[1][3] * self.m[2][2]
176
19
                - self.m[0][2] * self.m[1][0] * self.m[2][3]
177
19
                + self.m[0][0] * self.m[1][2] * self.m[2][3],
178
19
            self.m[1][1] * self.m[2][3] * self.m[3][0] - self.m[1][3] * self.m[2][1] * self.m[3][0]
179
19
                + self.m[1][3] * self.m[2][0] * self.m[3][1]
180
19
                - self.m[1][0] * self.m[2][3] * self.m[3][1]
181
19
                - self.m[1][1] * self.m[2][0] * self.m[3][3]
182
19
                + self.m[1][0] * self.m[2][1] * self.m[3][3],
183
19
            self.m[0][3] * self.m[2][1] * self.m[3][0]
184
19
                - self.m[0][1] * self.m[2][3] * self.m[3][0]
185
19
                - self.m[0][3] * self.m[2][0] * self.m[3][1]
186
19
                + self.m[0][0] * self.m[2][3] * self.m[3][1]
187
19
                + self.m[0][1] * self.m[2][0] * self.m[3][3]
188
19
                - self.m[0][0] * self.m[2][1] * self.m[3][3],
189
19
            self.m[0][1] * self.m[1][3] * self.m[3][0] - self.m[0][3] * self.m[1][1] * self.m[3][0]
190
19
                + self.m[0][3] * self.m[1][0] * self.m[3][1]
191
19
                - self.m[0][0] * self.m[1][3] * self.m[3][1]
192
19
                - self.m[0][1] * self.m[1][0] * self.m[3][3]
193
19
                + self.m[0][0] * self.m[1][1] * self.m[3][3],
194
19
            self.m[0][3] * self.m[1][1] * self.m[2][0]
195
19
                - self.m[0][1] * self.m[1][3] * self.m[2][0]
196
19
                - self.m[0][3] * self.m[1][0] * self.m[2][1]
197
19
                + self.m[0][0] * self.m[1][3] * self.m[2][1]
198
19
                + self.m[0][1] * self.m[1][0] * self.m[2][3]
199
19
                - self.m[0][0] * self.m[1][1] * self.m[2][3],
200
19
            self.m[1][2] * self.m[2][1] * self.m[3][0]
201
19
                - self.m[1][1] * self.m[2][2] * self.m[3][0]
202
19
                - self.m[1][2] * self.m[2][0] * self.m[3][1]
203
19
                + self.m[1][0] * self.m[2][2] * self.m[3][1]
204
19
                + self.m[1][1] * self.m[2][0] * self.m[3][2]
205
19
                - self.m[1][0] * self.m[2][1] * self.m[3][2],
206
19
            self.m[0][1] * self.m[2][2] * self.m[3][0] - self.m[0][2] * self.m[2][1] * self.m[3][0]
207
19
                + self.m[0][2] * self.m[2][0] * self.m[3][1]
208
19
                - self.m[0][0] * self.m[2][2] * self.m[3][1]
209
19
                - self.m[0][1] * self.m[2][0] * self.m[3][2]
210
19
                + self.m[0][0] * self.m[2][1] * self.m[3][2],
211
19
            self.m[0][2] * self.m[1][1] * self.m[3][0]
212
19
                - self.m[0][1] * self.m[1][2] * self.m[3][0]
213
19
                - self.m[0][2] * self.m[1][0] * self.m[3][1]
214
19
                + self.m[0][0] * self.m[1][2] * self.m[3][1]
215
19
                + self.m[0][1] * self.m[1][0] * self.m[3][2]
216
19
                - self.m[0][0] * self.m[1][1] * self.m[3][2],
217
19
            self.m[0][1] * self.m[1][2] * self.m[2][0] - self.m[0][2] * self.m[1][1] * self.m[2][0]
218
19
                + self.m[0][2] * self.m[1][0] * self.m[2][1]
219
19
                - self.m[0][0] * self.m[1][2] * self.m[2][1]
220
19
                - self.m[0][1] * self.m[1][0] * self.m[2][2]
221
19
                + self.m[0][0] * self.m[1][1] * self.m[2][2],
222
        );
223

            
224
19
        m.multiply_scalar(1.0 / det)
225
24
    }
226

            
227
    #[allow(clippy::suboptimal_flops)] // mul_add not guaranteed faster/available without target
228
                                       // +fma; keep explicit a*b+c
229
44
    fn determinant(&self) -> f32 {
230
        // Accumulate in f64. Individual f32 products (e.g. m[0][0]*m[1][1] on a
231
        // diag(1e20) matrix = 1e40) overflow to ±inf BEFORE the legitimately-zero
232
        // off-diagonal factors multiply in, and inf * 0 = NaN, poisoning the whole sum.
233
        // f64 has the range to hold the products; the final cast saturates a real
234
        // overflow to ±inf and propagates a NaN input as NaN.
235
4224
        let m = |i: usize, j: usize| f64::from(self.m[i][j]);
236
44
        let det = m(0, 3) * m(1, 2) * m(2, 1) * m(3, 0)
237
44
            - m(0, 2) * m(1, 3) * m(2, 1) * m(3, 0)
238
44
            - m(0, 3) * m(1, 1) * m(2, 2) * m(3, 0)
239
44
            + m(0, 1) * m(1, 3) * m(2, 2) * m(3, 0)
240
44
            + m(0, 2) * m(1, 1) * m(2, 3) * m(3, 0)
241
44
            - m(0, 1) * m(1, 2) * m(2, 3) * m(3, 0)
242
44
            - m(0, 3) * m(1, 2) * m(2, 0) * m(3, 1)
243
44
            + m(0, 2) * m(1, 3) * m(2, 0) * m(3, 1)
244
44
            + m(0, 3) * m(1, 0) * m(2, 2) * m(3, 1)
245
44
            - m(0, 0) * m(1, 3) * m(2, 2) * m(3, 1)
246
44
            - m(0, 2) * m(1, 0) * m(2, 3) * m(3, 1)
247
44
            + m(0, 0) * m(1, 2) * m(2, 3) * m(3, 1)
248
44
            + m(0, 3) * m(1, 1) * m(2, 0) * m(3, 2)
249
44
            - m(0, 1) * m(1, 3) * m(2, 0) * m(3, 2)
250
44
            - m(0, 3) * m(1, 0) * m(2, 1) * m(3, 2)
251
44
            + m(0, 0) * m(1, 3) * m(2, 1) * m(3, 2)
252
44
            + m(0, 1) * m(1, 0) * m(2, 3) * m(3, 2)
253
44
            - m(0, 0) * m(1, 1) * m(2, 3) * m(3, 2)
254
44
            - m(0, 2) * m(1, 1) * m(2, 0) * m(3, 3)
255
44
            + m(0, 1) * m(1, 2) * m(2, 0) * m(3, 3)
256
44
            + m(0, 2) * m(1, 0) * m(2, 1) * m(3, 3)
257
44
            - m(0, 0) * m(1, 2) * m(2, 1) * m(3, 3)
258
44
            - m(0, 1) * m(1, 0) * m(2, 2) * m(3, 3)
259
44
            + m(0, 0) * m(1, 1) * m(2, 2) * m(3, 3);
260
        #[allow(clippy::cast_possible_truncation)]
261
        // determinant computed in f64, narrowed to the f32 public type
262
44
        let det = det as f32;
263
44
        det
264
44
    }
265

            
266
25
    fn multiply_scalar(&self, x: f32) -> Self {
267
25
        Self::new(
268
25
            self.m[0][0] * x,
269
25
            self.m[0][1] * x,
270
25
            self.m[0][2] * x,
271
25
            self.m[0][3] * x,
272
25
            self.m[1][0] * x,
273
25
            self.m[1][1] * x,
274
25
            self.m[1][2] * x,
275
25
            self.m[1][3] * x,
276
25
            self.m[2][0] * x,
277
25
            self.m[2][1] * x,
278
25
            self.m[2][2] * x,
279
25
            self.m[2][3] * x,
280
25
            self.m[3][0] * x,
281
25
            self.m[3][1] * x,
282
25
            self.m[3][2] * x,
283
25
            self.m[3][3] * x,
284
        )
285
25
    }
286

            
287
    /// Computes the matrix of a rect from a `&[StyleTransform]`.
288
345
    pub fn from_style_transform_vec(
289
345
        t_vec: &[StyleTransform],
290
345
        transform_origin: &StyleTransformOrigin,
291
345
        percent_resolve_x: f32,
292
345
        percent_resolve_y: f32,
293
345
        rotation_mode: RotationMode,
294
345
    ) -> Self {
295
        // Uses AVX or SSE SIMD when available on x86_64
296
        //
297
        // AUDIT-TODO: `USE_AVX`/`USE_SSE` are populated in `gpu.rs` from a raw
298
        // CPUID leaf-1 feature bit (ECX[28] for AVX), which reports only that
299
        // the CPU *implements* AVX — NOT that the OS has enabled the YMM state
300
        // via XCR0 (XGETBV). On a kernel that didn't `XSETBV`-enable AVX, using
301
        // these intrinsics faults with SIGILL. The robust gate is
302
        // `is_x86_feature_detected!("avx")` / `("sse")`, which also checks the
303
        // OS-enabled bit. That detection lives in `gpu.rs` (out of scope for
304
        // this edit); consumers here rely on it having gated the flags. Prefer
305
        // migrating the `gpu.rs` probe to `is_x86_feature_detected!`.
306
        // CSS Transforms Level 1 §9 ("The Transform Rendering Model"):
307
        //
308
        //   1. The functions are MULTIPLIED left to right, so the LAST listed function is the first
309
        //      one applied to a point: `translate(100px) scale(2)` scales first, then translates -
310
        //      a point at (1, 0) lands at (102, 0), not (202, 0). `a.then(b)` applies `a` first, so
311
        //      each function is composed BEFORE the accumulated rest. (This used to fold left to
312
        //      right - the reverse - so every multi-function transform rendered differently than in
313
        //      a browser, and `perspective() rotateX()` projected the un-rotated plane, i.e. did
314
        //      nothing.)
315
        //   2. The WHOLE product is applied about `transform-origin`: `translate(origin) * M *
316
        //      translate(-origin)`. Wrapping happens ONCE, here - not per component - so `scale()`
317
        //      and `skew()` pivot at the origin exactly like `rotate()` does.
318
        use azul_css::props::basic::{pixel::DEFAULT_FONT_SIZE, PixelValue};
319
345
        let no_origin = StyleTransformOrigin {
320
345
            x: PixelValue::const_px(0),
321
345
            y: PixelValue::const_px(0),
322
345
        };
323
345
        let mut matrix = Self::IDENTITY;
324
345
        let use_avx =
325
345
            INITIALIZED.load(AtomicOrdering::Relaxed) && USE_AVX.load(AtomicOrdering::Relaxed);
326
345
        let use_sse = !use_avx
327
            && INITIALIZED.load(AtomicOrdering::Relaxed)
328
            && USE_SSE.load(AtomicOrdering::Relaxed);
329

            
330
345
        if use_avx {
331
2201
            for t in t_vec {
332
1856
                let component = Self::from_style_transform(
333
1856
                    t,
334
1856
                    &no_origin,
335
1856
                    percent_resolve_x,
336
1856
                    percent_resolve_y,
337
1856
                    rotation_mode,
338
                );
339
                // SAFETY: `use_avx` is only set when the AVX feature flag was
340
                // detected (see AUDIT-TODO above), so calling the AVX intrinsics
341
                // in `then_avx8` is legal on this CPU.
342
                #[cfg(target_arch = "x86_64")]
343
1856
                unsafe {
344
1856
                    matrix = component.then_avx8(&matrix);
345
1856
                }
346
            }
347
        } else if use_sse {
348
            for t in t_vec {
349
                let component = Self::from_style_transform(
350
                    t,
351
                    &no_origin,
352
                    percent_resolve_x,
353
                    percent_resolve_y,
354
                    rotation_mode,
355
                );
356
                // SAFETY: `use_sse` is only set when the SSE feature flag was
357
                // detected (see AUDIT-TODO above), so calling the SSE intrinsics
358
                // in `then_sse` is legal on this CPU.
359
                #[cfg(target_arch = "x86_64")]
360
                unsafe {
361
                    matrix = component.then_sse(&matrix);
362
                }
363
            }
364
        } else {
365
            // fallback for everything else
366
            for t in t_vec {
367
                let component = Self::from_style_transform(
368
                    t,
369
                    &no_origin,
370
                    percent_resolve_x,
371
                    percent_resolve_y,
372
                    rotation_mode,
373
                );
374
                matrix = component.then(&matrix);
375
            }
376
        }
377

            
378
        // Percentages in `transform-origin` resolve against the element's
379
        // own border box (the caller passes its size as the percent basis).
380
345
        let origin_x = transform_origin.x.to_pixels_internal(
381
345
            percent_resolve_x,
382
            DEFAULT_FONT_SIZE,
383
            DEFAULT_FONT_SIZE,
384
        );
385
345
        let origin_y = transform_origin.y.to_pixels_internal(
386
345
            percent_resolve_y,
387
            DEFAULT_FONT_SIZE,
388
            DEFAULT_FONT_SIZE,
389
        );
390
345
        if origin_x == 0.0 && origin_y == 0.0 {
391
294
            return matrix;
392
51
        }
393
51
        Self::new_translation(-origin_x, -origin_y, 0.0)
394
51
            .then(&matrix)
395
51
            .then(&Self::new_translation(origin_x, origin_y, 0.0))
396
345
    }
397

            
398
    /// Creates a new transform from a style transform using the
399
    /// parent width as a way to resolve for percentages
400
    #[allow(clippy::many_single_char_names)] // domain-standard colour/coordinate component names
401
    #[allow(clippy::too_many_lines)] // large but cohesive: single-purpose parser/builder/dispatch
402
                                     // (one branch per input variant)
403
1890
    fn from_style_transform(
404
1890
        t: &StyleTransform,
405
1890
        transform_origin: &StyleTransformOrigin,
406
1890
        percent_resolve_x: f32,
407
1890
        percent_resolve_y: f32,
408
1890
        rotation_mode: RotationMode,
409
1890
    ) -> Self {
410
        use azul_css::props::{
411
            basic::pixel::DEFAULT_FONT_SIZE,
412
            style::StyleTransform::{
413
                Matrix, Matrix3D, Perspective, Rotate, Rotate3D, RotateX, RotateY, RotateZ, Scale,
414
                Scale3D, ScaleX, ScaleY, ScaleZ, Skew, SkewX, SkewY, Translate, Translate3D,
415
                TranslateX, TranslateY, TranslateZ,
416
            },
417
        };
418
1890
        match t {
419
1
            Matrix(mat2d) => {
420
1
                let a = mat2d.a.get();
421
1
                let b = mat2d.b.get();
422
1
                let c = mat2d.c.get();
423
1
                let d = mat2d.d.get();
424
1
                let tx = mat2d.tx.get();
425
1
                let ty = mat2d.ty.get();
426

            
427
1
                Self::new_2d(a, b, c, d, tx, ty)
428
            }
429
1
            Matrix3D(mat3d) => {
430
1
                let m11 = mat3d.m11.get();
431
1
                let m12 = mat3d.m12.get();
432
1
                let m13 = mat3d.m13.get();
433
1
                let m14 = mat3d.m14.get();
434
1
                let m21 = mat3d.m21.get();
435
1
                let m22 = mat3d.m22.get();
436
1
                let m23 = mat3d.m23.get();
437
1
                let m24 = mat3d.m24.get();
438
1
                let m31 = mat3d.m31.get();
439
1
                let m32 = mat3d.m32.get();
440
1
                let m33 = mat3d.m33.get();
441
1
                let m34 = mat3d.m34.get();
442
1
                let m41 = mat3d.m41.get();
443
1
                let m42 = mat3d.m42.get();
444
1
                let m43 = mat3d.m43.get();
445
1
                let m44 = mat3d.m44.get();
446

            
447
1
                Self::new(
448
1
                    m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44,
449
                )
450
            }
451
4
            Translate(trans2d) => Self::new_translation(
452
4
                trans2d.x.to_pixels_internal(
453
4
                    percent_resolve_x,
454
                    DEFAULT_FONT_SIZE,
455
                    DEFAULT_FONT_SIZE,
456
                ),
457
4
                trans2d.y.to_pixels_internal(
458
4
                    percent_resolve_y,
459
                    DEFAULT_FONT_SIZE,
460
                    DEFAULT_FONT_SIZE,
461
                ),
462
                0.0,
463
            ),
464
1
            Translate3D(trans3d) => {
465
1
                Self::new_translation(
466
1
                    trans3d.x.to_pixels_internal(
467
1
                        percent_resolve_x,
468
                        DEFAULT_FONT_SIZE,
469
                        DEFAULT_FONT_SIZE,
470
                    ),
471
1
                    trans3d.y.to_pixels_internal(
472
1
                        percent_resolve_y,
473
                        DEFAULT_FONT_SIZE,
474
                        DEFAULT_FONT_SIZE,
475
                    ),
476
1
                    trans3d
477
1
                        .z
478
                        // CSS has no containing block for Z-axis percentages; use X as fallback
479
1
                        .to_pixels_internal(percent_resolve_x, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE),
480
                )
481
            }
482
1086
            TranslateX(trans_x) => Self::new_translation(
483
1086
                trans_x.to_pixels_internal(percent_resolve_x, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE),
484
                0.0,
485
                0.0,
486
            ),
487
132
            TranslateY(trans_y) => Self::new_translation(
488
                0.0,
489
132
                trans_y.to_pixels_internal(percent_resolve_y, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE),
490
                0.0,
491
            ),
492
1
            TranslateZ(trans_z) => Self::new_translation(
493
                0.0,
494
                0.0,
495
1
                trans_z.to_pixels_internal(percent_resolve_x, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE),
496
            ), // CSS has no containing block for Z-axis percentages; use X as fallback
497
1
            Rotate3D(rot3d) => {
498
1
                let rotation_origin = (
499
1
                    transform_origin.x.to_pixels_internal(
500
1
                        percent_resolve_x,
501
1
                        DEFAULT_FONT_SIZE,
502
1
                        DEFAULT_FONT_SIZE,
503
1
                    ),
504
1
                    transform_origin.y.to_pixels_internal(
505
1
                        percent_resolve_y,
506
1
                        DEFAULT_FONT_SIZE,
507
1
                        DEFAULT_FONT_SIZE,
508
1
                    ),
509
1
                );
510
1
                Self::make_rotation(
511
1
                    rotation_origin,
512
1
                    rot3d.angle.to_degrees(),
513
1
                    rot3d.x.get(),
514
1
                    rot3d.y.get(),
515
1
                    rot3d.z.get(),
516
1
                    rotation_mode,
517
                )
518
            }
519
2
            RotateX(angle_x) => {
520
2
                let rotation_origin = (
521
2
                    transform_origin.x.to_pixels_internal(
522
2
                        percent_resolve_x,
523
2
                        DEFAULT_FONT_SIZE,
524
2
                        DEFAULT_FONT_SIZE,
525
2
                    ),
526
2
                    transform_origin.y.to_pixels_internal(
527
2
                        percent_resolve_y,
528
2
                        DEFAULT_FONT_SIZE,
529
2
                        DEFAULT_FONT_SIZE,
530
2
                    ),
531
2
                );
532
2
                Self::make_rotation(
533
2
                    rotation_origin,
534
2
                    angle_x.to_degrees(),
535
                    1.0,
536
                    0.0,
537
                    0.0,
538
2
                    rotation_mode,
539
                )
540
            }
541
1
            RotateY(angle_y) => {
542
1
                let rotation_origin = (
543
1
                    transform_origin.x.to_pixels_internal(
544
1
                        percent_resolve_x,
545
1
                        DEFAULT_FONT_SIZE,
546
1
                        DEFAULT_FONT_SIZE,
547
1
                    ),
548
1
                    transform_origin.y.to_pixels_internal(
549
1
                        percent_resolve_y,
550
1
                        DEFAULT_FONT_SIZE,
551
1
                        DEFAULT_FONT_SIZE,
552
1
                    ),
553
1
                );
554
1
                Self::make_rotation(
555
1
                    rotation_origin,
556
1
                    angle_y.to_degrees(),
557
                    0.0,
558
                    1.0,
559
                    0.0,
560
1
                    rotation_mode,
561
                )
562
            }
563
387
            Rotate(angle_z) | RotateZ(angle_z) => {
564
389
                let rotation_origin = (
565
389
                    transform_origin.x.to_pixels_internal(
566
389
                        percent_resolve_x,
567
389
                        DEFAULT_FONT_SIZE,
568
389
                        DEFAULT_FONT_SIZE,
569
389
                    ),
570
389
                    transform_origin.y.to_pixels_internal(
571
389
                        percent_resolve_y,
572
389
                        DEFAULT_FONT_SIZE,
573
389
                        DEFAULT_FONT_SIZE,
574
389
                    ),
575
389
                );
576
389
                Self::make_rotation(
577
389
                    rotation_origin,
578
389
                    angle_z.to_degrees(),
579
                    0.0,
580
                    0.0,
581
                    1.0,
582
389
                    rotation_mode,
583
                )
584
            }
585
131
            Scale(scale2d) => Self::new_scale(scale2d.x.get(), scale2d.y.get(), 1.0),
586
2
            Scale3D(scale3d) => Self::new_scale(scale3d.x.get(), scale3d.y.get(), scale3d.z.get()),
587
1
            ScaleX(scale_x) => Self::new_scale(scale_x.normalized(), 1.0, 1.0),
588
1
            ScaleY(scale_y) => Self::new_scale(1.0, scale_y.normalized(), 1.0),
589
1
            ScaleZ(scale_z) => Self::new_scale(1.0, 1.0, scale_z.normalized()),
590
1
            Skew(skew2d) => Self::new_skew(skew2d.x.to_degrees(), skew2d.y.to_degrees()),
591
130
            SkewX(skew_x) => Self::new_skew(skew_x.to_degrees(), 0.0),
592
1
            SkewY(skew_y) => Self::new_skew(0.0, skew_y.to_degrees()),
593
3
            Perspective(px) => {
594
                // CSS applies the WHOLE transform list about the
595
                // transform-origin, `perspective()` included: the vanishing
596
                // point sits at the origin. Building it about (0, 0) skewed a
597
                // `perspective() rotateX()` tilt towards the element's
598
                // top-left corner instead of keeping the centre line
599
                // vertical (the map's 3D tilt leaned sideways).
600
3
                let origin_x = transform_origin.x.to_pixels_internal(
601
3
                    percent_resolve_x,
602
                    DEFAULT_FONT_SIZE,
603
                    DEFAULT_FONT_SIZE,
604
                );
605
3
                let origin_y = transform_origin.y.to_pixels_internal(
606
3
                    percent_resolve_y,
607
                    DEFAULT_FONT_SIZE,
608
                    DEFAULT_FONT_SIZE,
609
                );
610
3
                let d =
611
3
                    px.to_pixels_internal(percent_resolve_x, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);
612
3
                Self::new_translation(-origin_x, -origin_y, 0.0)
613
3
                    .then(&Self::new_perspective(d))
614
3
                    .then(&Self::new_translation(origin_x, origin_y, 0.0))
615
            }
616
        }
617
1890
    }
618

            
619
    /// The plane z = 0 of this transform as a 3x3 homography.
620
    ///
621
    /// Over `(x, y, 1)` row vectors — `[x' y' w'] = [x y 1] * H`, row-major
622
    /// `[m00 m01 m03; m10 m11 m13; m30 m31 m33]` — i.e. exactly what a 2D
623
    /// compositor needs to place a flat layer: the affine part plus the
624
    /// perspective row. [`Self::is_plane_affine`] tells whether the
625
    /// perspective row is the trivial `[0 0 1]`.
626
    #[must_use]
627
1
    pub const fn plane_homography(&self) -> [f32; 9] {
628
1
        [
629
1
            self.m[0][0],
630
1
            self.m[0][1],
631
1
            self.m[0][3],
632
1
            self.m[1][0],
633
1
            self.m[1][1],
634
1
            self.m[1][3],
635
1
            self.m[3][0],
636
1
            self.m[3][1],
637
1
            self.m[3][3],
638
1
        ]
639
1
    }
640

            
641
    /// Does the z = 0 plane map affinely (no perspective foreshortening)?
642
    #[must_use]
643
1
    pub const fn is_plane_affine(&self) -> bool {
644
1
        let (a, b, w) = (self.m[0][3], self.m[1][3], self.m[3][3]);
645
1
        a > -1e-7 && a < 1e-7 && b > -1e-7 && b < 1e-7 && w > 1.0 - 1e-6 && w < 1.0 + 1e-6
646
1
    }
647

            
648
    /// Creates a scaling matrix with independent scale factors per axis.
649
    #[must_use]
650
    #[inline]
651
408
    pub const fn new_scale(x: f32, y: f32, z: f32) -> Self {
652
408
        Self::new(
653
408
            x, 0.0, 0.0, 0.0, 0.0, y, 0.0, 0.0, 0.0, 0.0, z, 0.0, 0.0, 0.0, 0.0, 1.0,
654
        )
655
408
    }
656

            
657
    /// Creates a translation matrix that moves by `(x, y, z)`.
658
    #[must_use]
659
    #[inline]
660
34548
    pub const fn new_translation(x: f32, y: f32, z: f32) -> Self {
661
34548
        Self::new(
662
34548
            1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0,
663
        )
664
34548
    }
665

            
666
    /// Creates a perspective projection matrix with distance `d`.
667
    #[must_use]
668
    #[inline]
669
8
    fn new_perspective(d: f32) -> Self {
670
8
        Self::new(
671
            1.0,
672
            0.0,
673
            0.0,
674
            0.0,
675
            0.0,
676
            1.0,
677
            0.0,
678
            0.0,
679
            0.0,
680
            0.0,
681
            1.0,
682
8
            -1.0 / d,
683
            0.0,
684
            0.0,
685
            0.0,
686
            1.0,
687
        )
688
8
    }
689

            
690
    /// Create a 3d rotation transform from an angle / axis.
691
    /// The supplied axis must be normalized.
692
    #[must_use]
693
    #[inline]
694
    #[allow(clippy::suboptimal_flops)] // mul_add not guaranteed faster/available without target
695
                                       // +fma; keep explicit a*b+c
696
920
    fn new_rotation(x: f32, y: f32, z: f32, theta_radians: f32) -> Self {
697
920
        let xx = x * x;
698
920
        let yy = y * y;
699
920
        let zz = z * z;
700

            
701
920
        let half_theta = theta_radians / 2.0;
702
920
        let sc = half_theta.sin() * half_theta.cos();
703
920
        let sq = half_theta.sin() * half_theta.sin();
704

            
705
920
        Self::new(
706
920
            1.0 - 2.0 * (yy + zz) * sq,
707
920
            2.0 * (x * y * sq + z * sc),
708
920
            2.0 * (x * z * sq - y * sc),
709
            0.0,
710
920
            2.0 * (x * y * sq - z * sc),
711
920
            1.0 - 2.0 * (xx + zz) * sq,
712
920
            2.0 * (y * z * sq + x * sc),
713
            0.0,
714
920
            2.0 * (x * z * sq + y * sc),
715
920
            2.0 * (y * z * sq - x * sc),
716
920
            1.0 - 2.0 * (xx + yy) * sq,
717
            0.0,
718
            0.0,
719
            0.0,
720
            0.0,
721
            1.0,
722
        )
723
920
    }
724

            
725
    /// Creates a 2D skew matrix from angles in degrees.
726
    #[must_use]
727
    #[inline]
728
136
    fn new_skew(alpha: f32, beta: f32) -> Self {
729
136
        let (sx, sy) = (beta.to_radians().tan(), alpha.to_radians().tan());
730
136
        Self::new(
731
136
            1.0, sx, 0.0, 0.0, sy, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0,
732
        )
733
136
    }
734

            
735
    /// Returns this matrix transposed to column-major layout.
736
    #[must_use]
737
12
    pub(crate) const fn get_column_major(&self) -> Self {
738
12
        Self::new(
739
12
            self.m[0][0],
740
12
            self.m[1][0],
741
12
            self.m[2][0],
742
12
            self.m[3][0],
743
12
            self.m[0][1],
744
12
            self.m[1][1],
745
12
            self.m[2][1],
746
12
            self.m[3][1],
747
12
            self.m[0][2],
748
12
            self.m[1][2],
749
12
            self.m[2][2],
750
12
            self.m[3][2],
751
12
            self.m[0][3],
752
12
            self.m[1][3],
753
12
            self.m[2][3],
754
12
            self.m[3][3],
755
        )
756
12
    }
757

            
758
    /// Transforms a 2D point into the target coordinate space.
759
    #[must_use]
760
31
    pub fn transform_point2d(&self, p: LogicalPosition) -> Option<LogicalPosition> {
761
31
        let w =
762
31
            p.x.mul_add(self.m[0][3], p.y.mul_add(self.m[1][3], self.m[3][3]));
763

            
764
31
        if !w.is_sign_positive() {
765
3
            return None;
766
28
        }
767

            
768
28
        let x =
769
28
            p.x.mul_add(self.m[0][0], p.y.mul_add(self.m[1][0], self.m[3][0]));
770
28
        let y =
771
28
            p.x.mul_add(self.m[0][1], p.y.mul_add(self.m[1][1], self.m[3][1]));
772

            
773
28
        Some(LogicalPosition { x: x / w, y: y / w })
774
31
    }
775

            
776
    /// Scales the translation components of this matrix by `scale_factor` for DPI adjustment.
777
9
    pub fn scale_for_dpi(&mut self, scale_factor: f32) {
778
        // only scale the translation, don't scale anything else
779
9
        self.m[3][0] *= scale_factor;
780
9
        self.m[3][1] *= scale_factor;
781
9
        self.m[3][2] *= scale_factor;
782
9
    }
783

            
784
    /// Multiplies this matrix by `other`, applying `other` AFTER the current matrix.
785
    #[must_use]
786
    #[inline]
787
    #[allow(clippy::too_many_lines)] // large but cohesive: single-purpose parser/builder/dispatch
788
                                     // (one branch per input variant)
789
1956
    pub fn then(&self, other: &Self) -> Self {
790
1956
        Self::new(
791
1956
            self.m[0][0].mul_add(
792
1956
                other.m[0][0],
793
1956
                self.m[0][1].mul_add(
794
1956
                    other.m[1][0],
795
1956
                    self.m[0][2].mul_add(other.m[2][0], self.m[0][3] * other.m[3][0]),
796
                ),
797
            ),
798
1956
            self.m[0][0].mul_add(
799
1956
                other.m[0][1],
800
1956
                self.m[0][1].mul_add(
801
1956
                    other.m[1][1],
802
1956
                    self.m[0][2].mul_add(other.m[2][1], self.m[0][3] * other.m[3][1]),
803
                ),
804
            ),
805
1956
            self.m[0][0].mul_add(
806
1956
                other.m[0][2],
807
1956
                self.m[0][1].mul_add(
808
1956
                    other.m[1][2],
809
1956
                    self.m[0][2].mul_add(other.m[2][2], self.m[0][3] * other.m[3][2]),
810
                ),
811
            ),
812
1956
            self.m[0][0].mul_add(
813
1956
                other.m[0][3],
814
1956
                self.m[0][1].mul_add(
815
1956
                    other.m[1][3],
816
1956
                    self.m[0][2].mul_add(other.m[2][3], self.m[0][3] * other.m[3][3]),
817
                ),
818
            ),
819
1956
            self.m[1][0].mul_add(
820
1956
                other.m[0][0],
821
1956
                self.m[1][1].mul_add(
822
1956
                    other.m[1][0],
823
1956
                    self.m[1][2].mul_add(other.m[2][0], self.m[1][3] * other.m[3][0]),
824
                ),
825
            ),
826
1956
            self.m[1][0].mul_add(
827
1956
                other.m[0][1],
828
1956
                self.m[1][1].mul_add(
829
1956
                    other.m[1][1],
830
1956
                    self.m[1][2].mul_add(other.m[2][1], self.m[1][3] * other.m[3][1]),
831
                ),
832
            ),
833
1956
            self.m[1][0].mul_add(
834
1956
                other.m[0][2],
835
1956
                self.m[1][1].mul_add(
836
1956
                    other.m[1][2],
837
1956
                    self.m[1][2].mul_add(other.m[2][2], self.m[1][3] * other.m[3][2]),
838
                ),
839
            ),
840
1956
            self.m[1][0].mul_add(
841
1956
                other.m[0][3],
842
1956
                self.m[1][1].mul_add(
843
1956
                    other.m[1][3],
844
1956
                    self.m[1][2].mul_add(other.m[2][3], self.m[1][3] * other.m[3][3]),
845
                ),
846
            ),
847
1956
            self.m[2][0].mul_add(
848
1956
                other.m[0][0],
849
1956
                self.m[2][1].mul_add(
850
1956
                    other.m[1][0],
851
1956
                    self.m[2][2].mul_add(other.m[2][0], self.m[2][3] * other.m[3][0]),
852
                ),
853
            ),
854
1956
            self.m[2][0].mul_add(
855
1956
                other.m[0][1],
856
1956
                self.m[2][1].mul_add(
857
1956
                    other.m[1][1],
858
1956
                    self.m[2][2].mul_add(other.m[2][1], self.m[2][3] * other.m[3][1]),
859
                ),
860
            ),
861
1956
            self.m[2][0].mul_add(
862
1956
                other.m[0][2],
863
1956
                self.m[2][1].mul_add(
864
1956
                    other.m[1][2],
865
1956
                    self.m[2][2].mul_add(other.m[2][2], self.m[2][3] * other.m[3][2]),
866
                ),
867
            ),
868
1956
            self.m[2][0].mul_add(
869
1956
                other.m[0][3],
870
1956
                self.m[2][1].mul_add(
871
1956
                    other.m[1][3],
872
1956
                    self.m[2][2].mul_add(other.m[2][3], self.m[2][3] * other.m[3][3]),
873
                ),
874
            ),
875
1956
            self.m[3][0].mul_add(
876
1956
                other.m[0][0],
877
1956
                self.m[3][1].mul_add(
878
1956
                    other.m[1][0],
879
1956
                    self.m[3][2].mul_add(other.m[2][0], self.m[3][3] * other.m[3][0]),
880
                ),
881
            ),
882
1956
            self.m[3][0].mul_add(
883
1956
                other.m[0][1],
884
1956
                self.m[3][1].mul_add(
885
1956
                    other.m[1][1],
886
1956
                    self.m[3][2].mul_add(other.m[2][1], self.m[3][3] * other.m[3][1]),
887
                ),
888
            ),
889
1956
            self.m[3][0].mul_add(
890
1956
                other.m[0][2],
891
1956
                self.m[3][1].mul_add(
892
1956
                    other.m[1][2],
893
1956
                    self.m[3][2].mul_add(other.m[2][2], self.m[3][3] * other.m[3][2]),
894
                ),
895
            ),
896
1956
            self.m[3][0].mul_add(
897
1956
                other.m[0][3],
898
1956
                self.m[3][1].mul_add(
899
1956
                    other.m[1][3],
900
1956
                    self.m[3][2].mul_add(other.m[2][3], self.m[3][3] * other.m[3][3]),
901
                ),
902
            ),
903
        )
904
1956
    }
905

            
906
    // credit: https://gist.github.com/rygorous/4172889
907

            
908
    // linear combination:
909
    // a[0] * B.row[0] + a[1] * B.row[1] + a[2] * B.row[2] + a[3] * B.row[3]
910
    //
911
    // SAFETY: the caller must guarantee SSE is available on this CPU (see the
912
    // `use_sse` gate in `from_style_transform_vec`). Every `mem::transmute` here
913
    // is a BY-VALUE `[f32; 4]` -> `__m128` conversion: both types are 16 bytes
914
    // and the value is moved through a register, so no *reference* to under-
915
    // aligned storage is ever formed and there is no alignment invariant to
916
    // violate (unlike the AVX broadcast, which must use an unaligned load).
917
    #[cfg(target_arch = "x86_64")]
918
    #[inline]
919
333
    unsafe fn linear_combine_sse(a: [f32; 4], b: &Self) -> [f32; 4] {
920
        unsafe {
921
            use core::{
922
                arch::x86_64::{__m128, _mm_add_ps, _mm_mul_ps, _mm_shuffle_ps},
923
                mem,
924
            };
925

            
926
333
            let a: __m128 = mem::transmute(a);
927
333
            let mut result = _mm_mul_ps(
928
333
                _mm_shuffle_ps(a, a, 0x00),
929
333
                mem::transmute::<[f32; 4], __m128>(b.m[0]),
930
            );
931
333
            result = _mm_add_ps(
932
333
                result,
933
333
                _mm_mul_ps(
934
333
                    _mm_shuffle_ps(a, a, 0x55),
935
333
                    mem::transmute::<[f32; 4], __m128>(b.m[1]),
936
333
                ),
937
333
            );
938
333
            result = _mm_add_ps(
939
333
                result,
940
333
                _mm_mul_ps(
941
333
                    _mm_shuffle_ps(a, a, 0xaa),
942
333
                    mem::transmute::<[f32; 4], __m128>(b.m[2]),
943
333
                ),
944
333
            );
945
333
            result = _mm_add_ps(
946
333
                result,
947
333
                _mm_mul_ps(
948
333
                    _mm_shuffle_ps(a, a, 0xff),
949
333
                    mem::transmute::<[f32; 4], __m128>(b.m[3]),
950
333
                ),
951
333
            );
952

            
953
333
            mem::transmute(result)
954
        }
955
333
    }
956

            
957
    /// Multiplies this matrix by `other` using SSE instructions.
958
    ///
959
    /// SAFETY: caller must guarantee SSE is available; only forwards to
960
    /// `linear_combine_sse`, whose safety contract is identical.
961
    #[cfg(target_arch = "x86_64")]
962
    #[inline]
963
19
    unsafe fn then_sse(&self, other: &Self) -> Self {
964
        unsafe {
965
19
            Self {
966
19
                m: [
967
19
                    Self::linear_combine_sse(self.m[0], other),
968
19
                    Self::linear_combine_sse(self.m[1], other),
969
19
                    Self::linear_combine_sse(self.m[2], other),
970
19
                    Self::linear_combine_sse(self.m[3], other),
971
19
                ],
972
19
            }
973
        }
974
19
    }
975

            
976
    /// Dual linear combination using AVX instructions on YMM registers.
977
    ///
978
    /// AUDIT: the rows `b.m[i]` are `[f32; 4]` fields with alignment 4, but
979
    /// `_mm256_broadcast_ps` takes a `&__m128` (alignment 16). Forming that
980
    /// reference — `&*(ptr as *const __m128)` — from an align-4 field is
981
    /// misaligned-reference UB even though the underlying `vbroadcastf128`
982
    /// tolerates it. Use `_mm256_loadu2_m128`, which does an *unaligned*
983
    /// 128-bit load from a raw `*const f32` and never forms a `&__m128`;
984
    /// passing the same row pointer for both lanes reproduces the broadcast
985
    /// (`result[127:0] = result[255:128] = row`).
986
    ///
987
    /// SAFETY: caller must guarantee AVX is available. Each `broadcast_row`
988
    /// reads exactly 4 f32 (16 bytes) through `_mm256_loadu2_m128`, an
989
    /// *unaligned* load, so the align-4 `[f32; 4]` rows are read in-bounds and
990
    /// no `&__m128` (align 16) is ever formed from them.
991
    #[cfg(target_arch = "x86_64")]
992
3757
    unsafe fn linear_combine_avx8(
993
3757
        a01: core::arch::x86_64::__m256,
994
3757
        b: &Self,
995
3757
    ) -> core::arch::x86_64::__m256 {
996
        unsafe {
997
            use core::arch::x86_64::{
998
                _mm256_add_ps, _mm256_loadu2_m128, _mm256_mul_ps, _mm256_shuffle_ps,
999
            };
            // Unaligned broadcast of a row into both 128-bit lanes. Runs inside the
            // enclosing `unsafe` block, so the intrinsic call needs no inner `unsafe`.
15028
            let broadcast_row = |row: &[f32; 4]| {
15028
                let p = row.as_ptr();
15028
                _mm256_loadu2_m128(p, p)
15028
            };
3757
            let mut result =
3757
                _mm256_mul_ps(_mm256_shuffle_ps(a01, a01, 0x00), broadcast_row(&b.m[0]));
3757
            result = _mm256_add_ps(
3757
                result,
3757
                _mm256_mul_ps(_mm256_shuffle_ps(a01, a01, 0x55), broadcast_row(&b.m[1])),
3757
            );
3757
            result = _mm256_add_ps(
3757
                result,
3757
                _mm256_mul_ps(_mm256_shuffle_ps(a01, a01, 0xaa), broadcast_row(&b.m[2])),
3757
            );
3757
            result = _mm256_add_ps(
3757
                result,
3757
                _mm256_mul_ps(_mm256_shuffle_ps(a01, a01, 0xff), broadcast_row(&b.m[3])),
3757
            );
3757
            result
        }
3757
    }
    /// Multiplies this matrix by `other` using AVX instructions.
    ///
    /// SAFETY: caller must guarantee AVX is available. Both `_mm256_loadu_ps`
    /// reads and `_mm256_storeu_ps` writes are *unaligned* 8-f32 (32-byte)
    /// accesses. `m` is `[[f32; 4]; 4]`, i.e. 16 contiguous f32 with no padding,
    /// so `&m[0][0]..` and `&m[2][0]..` each span two full rows in-bounds; the
    /// raw pointers come from live `self`/`out` locals, so lifetimes are valid.
    #[cfg(target_arch = "x86_64")]
    #[inline]
1878
    unsafe fn then_avx8(&self, other: &Self) -> Self {
        unsafe {
            use core::{
                arch::x86_64::{__m256, _mm256_loadu_ps, _mm256_storeu_ps, _mm256_zeroupper},
                mem,
            };
1878
            _mm256_zeroupper();
1878
            let a01: __m256 = _mm256_loadu_ps(&raw const self.m[0][0]);
1878
            let a23: __m256 = _mm256_loadu_ps(&raw const self.m[2][0]);
1878
            let out01x = Self::linear_combine_avx8(a01, other);
1878
            let out23x = Self::linear_combine_avx8(a23, other);
1878
            let mut out = Self {
1878
                m: [self.m[0], self.m[1], self.m[2], self.m[3]],
1878
            };
1878
            _mm256_storeu_ps(&raw mut out.m[0][0], out01x);
1878
            _mm256_storeu_ps(&raw mut out.m[2][0], out23x);
1878
            out
        }
1878
    }
    /// Creates a rotation matrix around the given axis, adjusted for the coordinate system.
    #[must_use]
    #[inline]
    #[allow(clippy::suboptimal_flops)] // mul_add not guaranteed faster/available without target
                                       // +fma; keep explicit a*b+c
913
    fn make_rotation(
913
        rotation_origin: (f32, f32),
913
        mut degrees: f32,
913
        axis_x: f32,
913
        axis_y: f32,
913
        axis_z: f32,
913
        // see documentation for RotationMode
913
        rotation_mode: RotationMode,
913
    ) -> Self {
913
        degrees = match rotation_mode {
            // CSS rotations are clockwise
641
            RotationMode::ForWebRender => -degrees,
            // hit-testing turns counter-clockwise
272
            RotationMode::ForHitTesting => degrees,
        };
913
        let (origin_x, origin_y) = rotation_origin;
913
        let pre_transform = Self::new_translation(-origin_x, -origin_y, 0.0);
913
        let post_transform = Self::new_translation(origin_x, origin_y, 0.0);
913
        let theta = 2.0_f32 * core::f32::consts::PI - degrees.to_radians();
913
        let rotate_transform = Self::new_rotation(axis_x, axis_y, axis_z, theta);
913
        pre_transform.then(&rotate_transform).then(&post_transform)
913
    }
}
#[cfg(test)]
#[allow(
    clippy::items_after_statements,
    clippy::redundant_clone,
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    trivial_casts,
    clippy::borrow_as_ptr,
    clippy::cast_ptr_alignment,
    clippy::unused_self,
    unused_qualifications,
    unreachable_pub,
    private_interfaces
)] // pedantic lints are noise in unsafe-exercising test code
mod audit_tests {
    use super::*;
3
    fn sample_a() -> ComputedTransform3D {
3
        ComputedTransform3D::new(
            1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0,
        )
3
    }
3
    fn sample_b() -> ComputedTransform3D {
3
        ComputedTransform3D::new(
            16.0, 15.0, 14.0, 13.0, 12.0, 11.0, 10.0, 9.0, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0,
        )
3
    }
8
    fn approx_eq(a: &ComputedTransform3D, b: &ComputedTransform3D) {
40
        for r in 0..4 {
160
            for c in 0..4 {
128
                assert!(
128
                    (a.m[r][c] - b.m[r][c]).abs() < 1e-3,
                    "mismatch at [{r}][{c}]: {} vs {}",
                    a.m[r][c],
                    b.m[r][c]
                );
            }
        }
8
    }
    /// Naive row-major 4x4 multiply used as an independent reference for the
    /// `then` (and hence SIMD) paths. Deliberately avoids `mul_add` so it is a
    /// separate implementation from the code under test.
1
    fn naive_then(a: &ComputedTransform3D, b: &ComputedTransform3D) -> ComputedTransform3D {
1
        let mut out = ComputedTransform3D::IDENTITY;
5
        for r in 0..4 {
20
            for c in 0..4 {
16
                let mut acc = 0.0f32;
80
                for k in 0..4 {
64
                    acc += a.m[r][k] * b.m[k][c];
64
                }
16
                out.m[r][c] = acc;
            }
        }
1
        out
1
    }
    // Miri-compatible: exercises only the safe scalar `then` against an
    // independent naive reference. Runs everywhere, including under Miri, so the
    // scalar anchor that the SIMD paths are compared against is itself checked.
    #[test]
1
    fn scalar_matmul_matches_reference() {
1
        let a = sample_a();
1
        let b = sample_b();
1
        approx_eq(&a.then(&b), &naive_then(&a, &b));
        // Identity is a left/right unit.
1
        approx_eq(&ComputedTransform3D::IDENTITY.then(&b), &b);
1
        approx_eq(&a.then(&ComputedTransform3D::IDENTITY), &a);
1
    }
    // AUDIT: the SSE/AVX matrix-multiply paths must agree with the scalar
    // reference. In particular this exercises `linear_combine_avx8`, whose
    // unaligned-load fix (`_mm256_loadu2_m128` instead of forming a misaligned
    // `&__m128`) must produce identical results. Only runs the SIMD paths when
    // the CPU (and OS) actually support the feature.
    //
    // `#[cfg(not(miri))]`: the AVX/SSE intrinsics cannot execute under Miri, so
    // this test is skipped there; a native run covers it.
    #[cfg(not(miri))]
    #[test]
1
    fn simd_matmul_matches_scalar() {
1
        let a = sample_a();
1
        let b = sample_b();
1
        let scalar = a.then(&b);
        #[cfg(target_arch = "x86_64")]
        {
1
            if std::is_x86_feature_detected!("sse") {
1
                let sse = unsafe { a.then_sse(&b) };
1
                approx_eq(&scalar, &sse);
1
            }
1
            if std::is_x86_feature_detected!("avx") {
1
                let avx = unsafe { a.then_avx8(&b) };
1
                approx_eq(&scalar, &avx);
1
            }
        }
        // Always assert the scalar path is self-consistent (identity * b == b).
1
        approx_eq(&ComputedTransform3D::IDENTITY.then(&b), &b);
1
    }
    // AUDIT regression test for the misaligned-`&__m128` bug: the AVX path reads
    // matrix rows (`[f32; 4]`, alignment 4) that are NOT guaranteed to sit on a
    // 16-byte boundary. The earlier code formed a `&__m128` from such a row,
    // which is misaligned-reference UB; the current code uses unaligned loads.
    // This runs `then_avx8` on the same logical matrix placed at a 16-byte
    // aligned address AND at that address + 4 (i.e. 4-mod-16, deliberately not
    // 16-aligned) and asserts identical results. A sanitizer/Valgrind run over
    // this test would fault on the pre-fix misaligned access.
    //
    // `#[cfg(not(miri))]`: invokes AVX intrinsics, which Miri cannot execute.
    #[cfg(all(target_arch = "x86_64", not(miri)))]
    #[test]
1
    fn avx_result_independent_of_row_alignment() {
1
        if !std::is_x86_feature_detected!("avx") {
            return;
1
        }
1
        let a = sample_a();
1
        let b = sample_b();
1
        let expected = unsafe { a.then_avx8(&b) };
        const N: usize = core::mem::size_of::<ComputedTransform3D>(); // 64, no padding
1
        let mut buf = vec![0u8; N * 2 + 16];
1
        let base = buf.as_mut_ptr();
        // SAFETY: `aligned` lands within `buf` (align_offset < 16, then +N),
        // `misaligned` = aligned + 4 stays in-bounds (buf has N*2+16 bytes).
        // Both are >= 4-byte aligned (base is heap-aligned; +4 preserves that),
        // so forming `&ComputedTransform3D` (alignment 4) from them is valid.
        unsafe {
1
            let aligned = base.add(base.align_offset(16));
1
            let misaligned = aligned.add(4); // 4 mod 16: not 16-aligned
2
            for off_ptr in [aligned, misaligned] {
2
                core::ptr::copy_nonoverlapping((&raw const a).cast::<u8>(), off_ptr, N);
2
                let a_ref = &*off_ptr.cast::<ComputedTransform3D>();
2
                let got = a_ref.then_avx8(&b);
2
                approx_eq(&expected, &got);
2
            }
        }
1
    }
}
#[cfg(test)]
#[path = "transform_test.rs"]
mod transform_test;