1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
//! 3D transform matrix computations for CSS transforms.
//!
//! This module implements 4x4 transformation matrices for CSS `transform` properties,
//! including translation, rotation, scaling, skewing, and perspective. It handles conversion
//! from CSS transform functions to hardware-accelerated matrices for WebRender.
//!
//! On x86_64 platforms, the module automatically detects and uses SSE/AVX instructions
//! for optimized matrix multiplication and inversion.
//!
//! **NOTE**: Matrices are stored in **row-major** format (unlike some graphics APIs that
//! use column-major). The module handles coordinate system differences between WebRender
//! and hit-testing via the `RotationMode` enum.
use core::sync::atomic::{AtomicBool, Ordering as AtomicOrdering};
use azul_css::props::style::{StyleTransform, StyleTransformOrigin};
use crate::geom::LogicalPosition;
/// CPU feature detection: true if initialization has been performed
pub static INITIALIZED: AtomicBool = AtomicBool::new(false);
/// CPU feature detection: true if AVX instructions are available
pub static USE_AVX: AtomicBool = AtomicBool::new(false);
/// CPU feature detection: true if SSE instructions are available
pub static USE_SSE: AtomicBool = AtomicBool::new(false);
/// Specifies the coordinate system convention for rotations.
///
/// `WebRender` uses a different rotation direction than hit-testing, so transforms
/// must be adjusted based on their use case. This enum controls whether the
/// rotation matrix is inverted to match the expected behavior.
#[derive(Debug, Copy, Clone)]
pub enum RotationMode {
/// Use rotation convention for `WebRender` (counter-clockwise, requires inversion)
ForWebRender,
/// Use rotation convention for hit-testing (clockwise, no inversion)
ForHitTesting,
}
/// A computed 4x4 transformation matrix in pixel space.
///
/// Represents the final transformation matrix for a DOM element after applying
/// all CSS transform functions (translate, rotate, scale, etc.) and accounting
/// for transform-origin.
///
/// # Memory Layout
///
/// Matrix is stored in **row-major** format:
/// ```text
/// m[0] = [m11, m12, m13, m14]
/// m[1] = [m21, m22, m23, m24]
/// m[2] = [m31, m32, m33, m34]
/// m[3] = [m41, m42, m43, m44]
/// ```
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd)]
#[repr(C)]
pub struct ComputedTransform3D {
/// The 4x4 matrix in row-major format
pub m: [[f32; 4]; 4],
}
impl ComputedTransform3D {
/// The identity matrix (no transformation).
pub const IDENTITY: Self = Self {
m: [
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
],
};
/// Creates a new 4x4 transformation matrix with the given elements.
///
/// Elements are specified in row-major order (m11, m12, ..., m44).
#[must_use]
pub const fn new(
m11: f32,
m12: f32,
m13: f32,
m14: f32,
m21: f32,
m22: f32,
m23: f32,
m24: f32,
m31: f32,
m32: f32,
m33: f32,
m34: f32,
m41: f32,
m42: f32,
m43: f32,
m44: f32,
) -> Self {
Self {
m: [
[m11, m12, m13, m14],
[m21, m22, m23, m24],
[m31, m32, m33, m34],
[m41, m42, m43, m44],
],
}
}
/// Creates a 2D transformation matrix (3D matrix with Z = 0).
///
/// This is equivalent to the CSS `matrix()` function. The transformation
/// only affects the X and Y axes.
///
/// Corresponds to `matrix(m11, m12, m21, m22, m41, m42)` in CSS.
const fn new_2d(m11: f32, m12: f32, m21: f32, m22: f32, m41: f32, m42: f32) -> Self {
Self::new(
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,
)
}
/// Computes the inverse of this transformation matrix.
///
/// This function uses a standard matrix inversion algorithm. Returns the
/// identity matrix if the determinant is zero (singular matrix).
///
/// NOTE: This is a relatively expensive operation.
#[must_use]
#[allow(clippy::suboptimal_flops)] // mul_add not guaranteed faster/available without target +fma; keep explicit a*b+c
pub fn inverse(&self) -> Self {
let det = self.determinant();
if det.abs() < f32::EPSILON {
return Self::IDENTITY;
}
let m = Self::new(
self.m[1][2] * self.m[2][3] * self.m[3][1] - self.m[1][3] * self.m[2][2] * self.m[3][1]
+ self.m[1][3] * self.m[2][1] * self.m[3][2]
- self.m[1][1] * self.m[2][3] * self.m[3][2]
- self.m[1][2] * self.m[2][1] * self.m[3][3]
+ self.m[1][1] * self.m[2][2] * self.m[3][3],
self.m[0][3] * self.m[2][2] * self.m[3][1]
- self.m[0][2] * self.m[2][3] * self.m[3][1]
- self.m[0][3] * self.m[2][1] * self.m[3][2]
+ self.m[0][1] * self.m[2][3] * self.m[3][2]
+ self.m[0][2] * self.m[2][1] * self.m[3][3]
- self.m[0][1] * self.m[2][2] * self.m[3][3],
self.m[0][2] * self.m[1][3] * self.m[3][1] - self.m[0][3] * self.m[1][2] * self.m[3][1]
+ self.m[0][3] * self.m[1][1] * self.m[3][2]
- self.m[0][1] * self.m[1][3] * self.m[3][2]
- self.m[0][2] * self.m[1][1] * self.m[3][3]
+ self.m[0][1] * self.m[1][2] * self.m[3][3],
self.m[0][3] * self.m[1][2] * self.m[2][1]
- self.m[0][2] * self.m[1][3] * self.m[2][1]
- self.m[0][3] * self.m[1][1] * self.m[2][2]
+ self.m[0][1] * self.m[1][3] * self.m[2][2]
+ self.m[0][2] * self.m[1][1] * self.m[2][3]
- self.m[0][1] * self.m[1][2] * self.m[2][3],
self.m[1][3] * self.m[2][2] * self.m[3][0]
- self.m[1][2] * self.m[2][3] * self.m[3][0]
- self.m[1][3] * self.m[2][0] * self.m[3][2]
+ self.m[1][0] * self.m[2][3] * self.m[3][2]
+ self.m[1][2] * self.m[2][0] * self.m[3][3]
- self.m[1][0] * self.m[2][2] * self.m[3][3],
self.m[0][2] * self.m[2][3] * self.m[3][0] - self.m[0][3] * self.m[2][2] * self.m[3][0]
+ self.m[0][3] * self.m[2][0] * self.m[3][2]
- self.m[0][0] * self.m[2][3] * self.m[3][2]
- self.m[0][2] * self.m[2][0] * self.m[3][3]
+ self.m[0][0] * self.m[2][2] * self.m[3][3],
self.m[0][3] * self.m[1][2] * self.m[3][0]
- self.m[0][2] * self.m[1][3] * self.m[3][0]
- self.m[0][3] * self.m[1][0] * self.m[3][2]
+ self.m[0][0] * self.m[1][3] * self.m[3][2]
+ self.m[0][2] * self.m[1][0] * self.m[3][3]
- self.m[0][0] * self.m[1][2] * self.m[3][3],
self.m[0][2] * self.m[1][3] * self.m[2][0] - self.m[0][3] * self.m[1][2] * self.m[2][0]
+ self.m[0][3] * self.m[1][0] * self.m[2][2]
- self.m[0][0] * self.m[1][3] * self.m[2][2]
- self.m[0][2] * self.m[1][0] * self.m[2][3]
+ self.m[0][0] * self.m[1][2] * self.m[2][3],
self.m[1][1] * self.m[2][3] * self.m[3][0] - self.m[1][3] * self.m[2][1] * self.m[3][0]
+ self.m[1][3] * self.m[2][0] * self.m[3][1]
- self.m[1][0] * self.m[2][3] * self.m[3][1]
- self.m[1][1] * self.m[2][0] * self.m[3][3]
+ self.m[1][0] * self.m[2][1] * self.m[3][3],
self.m[0][3] * self.m[2][1] * self.m[3][0]
- self.m[0][1] * self.m[2][3] * self.m[3][0]
- self.m[0][3] * self.m[2][0] * self.m[3][1]
+ self.m[0][0] * self.m[2][3] * self.m[3][1]
+ self.m[0][1] * self.m[2][0] * self.m[3][3]
- self.m[0][0] * self.m[2][1] * self.m[3][3],
self.m[0][1] * self.m[1][3] * self.m[3][0] - self.m[0][3] * self.m[1][1] * self.m[3][0]
+ self.m[0][3] * self.m[1][0] * self.m[3][1]
- self.m[0][0] * self.m[1][3] * self.m[3][1]
- self.m[0][1] * self.m[1][0] * self.m[3][3]
+ self.m[0][0] * self.m[1][1] * self.m[3][3],
self.m[0][3] * self.m[1][1] * self.m[2][0]
- self.m[0][1] * self.m[1][3] * self.m[2][0]
- self.m[0][3] * self.m[1][0] * self.m[2][1]
+ self.m[0][0] * self.m[1][3] * self.m[2][1]
+ self.m[0][1] * self.m[1][0] * self.m[2][3]
- self.m[0][0] * self.m[1][1] * self.m[2][3],
self.m[1][2] * self.m[2][1] * self.m[3][0]
- self.m[1][1] * self.m[2][2] * self.m[3][0]
- self.m[1][2] * self.m[2][0] * self.m[3][1]
+ self.m[1][0] * self.m[2][2] * self.m[3][1]
+ self.m[1][1] * self.m[2][0] * self.m[3][2]
- self.m[1][0] * self.m[2][1] * self.m[3][2],
self.m[0][1] * self.m[2][2] * self.m[3][0] - self.m[0][2] * self.m[2][1] * self.m[3][0]
+ self.m[0][2] * self.m[2][0] * self.m[3][1]
- self.m[0][0] * self.m[2][2] * self.m[3][1]
- self.m[0][1] * self.m[2][0] * self.m[3][2]
+ self.m[0][0] * self.m[2][1] * self.m[3][2],
self.m[0][2] * self.m[1][1] * self.m[3][0]
- self.m[0][1] * self.m[1][2] * self.m[3][0]
- self.m[0][2] * self.m[1][0] * self.m[3][1]
+ self.m[0][0] * self.m[1][2] * self.m[3][1]
+ self.m[0][1] * self.m[1][0] * self.m[3][2]
- self.m[0][0] * self.m[1][1] * self.m[3][2],
self.m[0][1] * self.m[1][2] * self.m[2][0] - self.m[0][2] * self.m[1][1] * self.m[2][0]
+ self.m[0][2] * self.m[1][0] * self.m[2][1]
- self.m[0][0] * self.m[1][2] * self.m[2][1]
- self.m[0][1] * self.m[1][0] * self.m[2][2]
+ self.m[0][0] * self.m[1][1] * self.m[2][2],
);
m.multiply_scalar(1.0 / det)
}
#[allow(clippy::suboptimal_flops)] // mul_add not guaranteed faster/available without target +fma; keep explicit a*b+c
fn determinant(&self) -> f32 {
// Accumulate in f64. Individual f32 products (e.g. m[0][0]*m[1][1] on a
// diag(1e20) matrix = 1e40) overflow to ±inf BEFORE the legitimately-zero
// off-diagonal factors multiply in, and inf * 0 = NaN, poisoning the whole sum.
// f64 has the range to hold the products; the final cast saturates a real
// overflow to ±inf and propagates a NaN input as NaN.
let m = |i: usize, j: usize| f64::from(self.m[i][j]);
let det = m(0, 3) * m(1, 2) * m(2, 1) * m(3, 0)
- m(0, 2) * m(1, 3) * m(2, 1) * m(3, 0)
- m(0, 3) * m(1, 1) * m(2, 2) * m(3, 0)
+ m(0, 1) * m(1, 3) * m(2, 2) * m(3, 0)
+ m(0, 2) * m(1, 1) * m(2, 3) * m(3, 0)
- m(0, 1) * m(1, 2) * m(2, 3) * m(3, 0)
- m(0, 3) * m(1, 2) * m(2, 0) * m(3, 1)
+ m(0, 2) * m(1, 3) * m(2, 0) * m(3, 1)
+ m(0, 3) * m(1, 0) * m(2, 2) * m(3, 1)
- m(0, 0) * m(1, 3) * m(2, 2) * m(3, 1)
- m(0, 2) * m(1, 0) * m(2, 3) * m(3, 1)
+ m(0, 0) * m(1, 2) * m(2, 3) * m(3, 1)
+ m(0, 3) * m(1, 1) * m(2, 0) * m(3, 2)
- m(0, 1) * m(1, 3) * m(2, 0) * m(3, 2)
- m(0, 3) * m(1, 0) * m(2, 1) * m(3, 2)
+ m(0, 0) * m(1, 3) * m(2, 1) * m(3, 2)
+ m(0, 1) * m(1, 0) * m(2, 3) * m(3, 2)
- m(0, 0) * m(1, 1) * m(2, 3) * m(3, 2)
- m(0, 2) * m(1, 1) * m(2, 0) * m(3, 3)
+ m(0, 1) * m(1, 2) * m(2, 0) * m(3, 3)
+ m(0, 2) * m(1, 0) * m(2, 1) * m(3, 3)
- m(0, 0) * m(1, 2) * m(2, 1) * m(3, 3)
- m(0, 1) * m(1, 0) * m(2, 2) * m(3, 3)
+ m(0, 0) * m(1, 1) * m(2, 2) * m(3, 3);
#[allow(clippy::cast_possible_truncation)]
// determinant computed in f64, narrowed to the f32 public type
let det = det as f32;
det
}
fn multiply_scalar(&self, x: f32) -> Self {
Self::new(
self.m[0][0] * x,
self.m[0][1] * x,
self.m[0][2] * x,
self.m[0][3] * x,
self.m[1][0] * x,
self.m[1][1] * x,
self.m[1][2] * x,
self.m[1][3] * x,
self.m[2][0] * x,
self.m[2][1] * x,
self.m[2][2] * x,
self.m[2][3] * x,
self.m[3][0] * x,
self.m[3][1] * x,
self.m[3][2] * x,
self.m[3][3] * x,
)
}
/// Computes the matrix of a rect from a `&[StyleTransform]`.
pub fn from_style_transform_vec(
t_vec: &[StyleTransform],
transform_origin: &StyleTransformOrigin,
percent_resolve_x: f32,
percent_resolve_y: f32,
rotation_mode: RotationMode,
) -> Self {
// Uses AVX or SSE SIMD when available on x86_64
//
// AUDIT-TODO: `USE_AVX`/`USE_SSE` are populated in `gpu.rs` from a raw
// CPUID leaf-1 feature bit (ECX[28] for AVX), which reports only that
// the CPU *implements* AVX — NOT that the OS has enabled the YMM state
// via XCR0 (XGETBV). On a kernel that didn't `XSETBV`-enable AVX, using
// these intrinsics faults with SIGILL. The robust gate is
// `is_x86_feature_detected!("avx")` / `("sse")`, which also checks the
// OS-enabled bit. That detection lives in `gpu.rs` (out of scope for
// this edit); consumers here rely on it having gated the flags. Prefer
// migrating the `gpu.rs` probe to `is_x86_feature_detected!`.
// CSS Transforms Level 1 §9 ("The Transform Rendering Model"):
//
// 1. The functions are MULTIPLIED left to right, so the LAST listed
// function is the first one applied to a point: `translate(100px)
// scale(2)` scales first, then translates - a point at (1, 0)
// lands at (102, 0), not (202, 0). `a.then(b)` applies `a` first,
// so each function is composed BEFORE the accumulated rest.
// (This used to fold left to right - the reverse - so every
// multi-function transform rendered differently than in a
// browser, and `perspective() rotateX()` projected the
// un-rotated plane, i.e. did nothing.)
// 2. The WHOLE product is applied about `transform-origin`:
// `translate(origin) * M * translate(-origin)`. Wrapping happens
// ONCE, here - not per component - so `scale()` and `skew()`
// pivot at the origin exactly like `rotate()` does.
use azul_css::props::basic::pixel::DEFAULT_FONT_SIZE;
use azul_css::props::basic::PixelValue;
let no_origin = StyleTransformOrigin {
x: PixelValue::const_px(0),
y: PixelValue::const_px(0),
};
let mut matrix = Self::IDENTITY;
let use_avx =
INITIALIZED.load(AtomicOrdering::Relaxed) && USE_AVX.load(AtomicOrdering::Relaxed);
let use_sse = !use_avx
&& INITIALIZED.load(AtomicOrdering::Relaxed)
&& USE_SSE.load(AtomicOrdering::Relaxed);
if use_avx {
for t in t_vec {
let component = Self::from_style_transform(
t,
&no_origin,
percent_resolve_x,
percent_resolve_y,
rotation_mode,
);
// SAFETY: `use_avx` is only set when the AVX feature flag was
// detected (see AUDIT-TODO above), so calling the AVX intrinsics
// in `then_avx8` is legal on this CPU.
#[cfg(target_arch = "x86_64")]
unsafe {
matrix = component.then_avx8(&matrix);
}
}
} else if use_sse {
for t in t_vec {
let component = Self::from_style_transform(
t,
&no_origin,
percent_resolve_x,
percent_resolve_y,
rotation_mode,
);
// SAFETY: `use_sse` is only set when the SSE feature flag was
// detected (see AUDIT-TODO above), so calling the SSE intrinsics
// in `then_sse` is legal on this CPU.
#[cfg(target_arch = "x86_64")]
unsafe {
matrix = component.then_sse(&matrix);
}
}
} else {
// fallback for everything else
for t in t_vec {
let component = Self::from_style_transform(
t,
&no_origin,
percent_resolve_x,
percent_resolve_y,
rotation_mode,
);
matrix = component.then(&matrix);
}
}
// Percentages in `transform-origin` resolve against the element's
// own border box (the caller passes its size as the percent basis).
let origin_x = transform_origin.x.to_pixels_internal(
percent_resolve_x,
DEFAULT_FONT_SIZE,
DEFAULT_FONT_SIZE,
);
let origin_y = transform_origin.y.to_pixels_internal(
percent_resolve_y,
DEFAULT_FONT_SIZE,
DEFAULT_FONT_SIZE,
);
if origin_x == 0.0 && origin_y == 0.0 {
return matrix;
}
Self::new_translation(-origin_x, -origin_y, 0.0)
.then(&matrix)
.then(&Self::new_translation(origin_x, origin_y, 0.0))
}
/// Creates a new transform from a style transform using the
/// parent width as a way to resolve for percentages
#[allow(clippy::many_single_char_names)] // domain-standard colour/coordinate component names
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose parser/builder/dispatch (one branch per input variant)
fn from_style_transform(
t: &StyleTransform,
transform_origin: &StyleTransformOrigin,
percent_resolve_x: f32,
percent_resolve_y: f32,
rotation_mode: RotationMode,
) -> Self {
use azul_css::props::basic::pixel::DEFAULT_FONT_SIZE;
use azul_css::props::style::StyleTransform::{
Matrix, Matrix3D, Perspective, Rotate, Rotate3D, RotateX, RotateY, RotateZ, Scale,
Scale3D, ScaleX, ScaleY, ScaleZ, Skew, SkewX, SkewY, Translate, Translate3D,
TranslateX, TranslateY, TranslateZ,
};
match t {
Matrix(mat2d) => {
let a = mat2d.a.get();
let b = mat2d.b.get();
let c = mat2d.c.get();
let d = mat2d.d.get();
let tx = mat2d.tx.get();
let ty = mat2d.ty.get();
Self::new_2d(a, b, c, d, tx, ty)
}
Matrix3D(mat3d) => {
let m11 = mat3d.m11.get();
let m12 = mat3d.m12.get();
let m13 = mat3d.m13.get();
let m14 = mat3d.m14.get();
let m21 = mat3d.m21.get();
let m22 = mat3d.m22.get();
let m23 = mat3d.m23.get();
let m24 = mat3d.m24.get();
let m31 = mat3d.m31.get();
let m32 = mat3d.m32.get();
let m33 = mat3d.m33.get();
let m34 = mat3d.m34.get();
let m41 = mat3d.m41.get();
let m42 = mat3d.m42.get();
let m43 = mat3d.m43.get();
let m44 = mat3d.m44.get();
Self::new(
m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44,
)
}
Translate(trans2d) => Self::new_translation(
trans2d.x.to_pixels_internal(
percent_resolve_x,
DEFAULT_FONT_SIZE,
DEFAULT_FONT_SIZE,
),
trans2d.y.to_pixels_internal(
percent_resolve_y,
DEFAULT_FONT_SIZE,
DEFAULT_FONT_SIZE,
),
0.0,
),
Translate3D(trans3d) => {
Self::new_translation(
trans3d.x.to_pixels_internal(
percent_resolve_x,
DEFAULT_FONT_SIZE,
DEFAULT_FONT_SIZE,
),
trans3d.y.to_pixels_internal(
percent_resolve_y,
DEFAULT_FONT_SIZE,
DEFAULT_FONT_SIZE,
),
trans3d
.z
// CSS has no containing block for Z-axis percentages; use X as fallback
.to_pixels_internal(percent_resolve_x, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE),
)
}
TranslateX(trans_x) => Self::new_translation(
trans_x.to_pixels_internal(percent_resolve_x, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE),
0.0,
0.0,
),
TranslateY(trans_y) => Self::new_translation(
0.0,
trans_y.to_pixels_internal(percent_resolve_y, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE),
0.0,
),
TranslateZ(trans_z) => Self::new_translation(
0.0,
0.0,
trans_z.to_pixels_internal(percent_resolve_x, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE),
), // CSS has no containing block for Z-axis percentages; use X as fallback
Rotate3D(rot3d) => {
let rotation_origin = (
transform_origin.x.to_pixels_internal(
percent_resolve_x,
DEFAULT_FONT_SIZE,
DEFAULT_FONT_SIZE,
),
transform_origin.y.to_pixels_internal(
percent_resolve_y,
DEFAULT_FONT_SIZE,
DEFAULT_FONT_SIZE,
),
);
Self::make_rotation(
rotation_origin,
rot3d.angle.to_degrees(),
rot3d.x.get(),
rot3d.y.get(),
rot3d.z.get(),
rotation_mode,
)
}
RotateX(angle_x) => {
let rotation_origin = (
transform_origin.x.to_pixels_internal(
percent_resolve_x,
DEFAULT_FONT_SIZE,
DEFAULT_FONT_SIZE,
),
transform_origin.y.to_pixels_internal(
percent_resolve_y,
DEFAULT_FONT_SIZE,
DEFAULT_FONT_SIZE,
),
);
Self::make_rotation(
rotation_origin,
angle_x.to_degrees(),
1.0,
0.0,
0.0,
rotation_mode,
)
}
RotateY(angle_y) => {
let rotation_origin = (
transform_origin.x.to_pixels_internal(
percent_resolve_x,
DEFAULT_FONT_SIZE,
DEFAULT_FONT_SIZE,
),
transform_origin.y.to_pixels_internal(
percent_resolve_y,
DEFAULT_FONT_SIZE,
DEFAULT_FONT_SIZE,
),
);
Self::make_rotation(
rotation_origin,
angle_y.to_degrees(),
0.0,
1.0,
0.0,
rotation_mode,
)
}
Rotate(angle_z) | RotateZ(angle_z) => {
let rotation_origin = (
transform_origin.x.to_pixels_internal(
percent_resolve_x,
DEFAULT_FONT_SIZE,
DEFAULT_FONT_SIZE,
),
transform_origin.y.to_pixels_internal(
percent_resolve_y,
DEFAULT_FONT_SIZE,
DEFAULT_FONT_SIZE,
),
);
Self::make_rotation(
rotation_origin,
angle_z.to_degrees(),
0.0,
0.0,
1.0,
rotation_mode,
)
}
Scale(scale2d) => Self::new_scale(scale2d.x.get(), scale2d.y.get(), 1.0),
Scale3D(scale3d) => Self::new_scale(scale3d.x.get(), scale3d.y.get(), scale3d.z.get()),
ScaleX(scale_x) => Self::new_scale(scale_x.normalized(), 1.0, 1.0),
ScaleY(scale_y) => Self::new_scale(1.0, scale_y.normalized(), 1.0),
ScaleZ(scale_z) => Self::new_scale(1.0, 1.0, scale_z.normalized()),
Skew(skew2d) => Self::new_skew(skew2d.x.to_degrees(), skew2d.y.to_degrees()),
SkewX(skew_x) => Self::new_skew(skew_x.to_degrees(), 0.0),
SkewY(skew_y) => Self::new_skew(0.0, skew_y.to_degrees()),
Perspective(px) => {
// CSS applies the WHOLE transform list about the
// transform-origin, `perspective()` included: the vanishing
// point sits at the origin. Building it about (0, 0) skewed a
// `perspective() rotateX()` tilt towards the element's
// top-left corner instead of keeping the centre line
// vertical (the map's 3D tilt leaned sideways).
let origin_x = transform_origin.x.to_pixels_internal(
percent_resolve_x,
DEFAULT_FONT_SIZE,
DEFAULT_FONT_SIZE,
);
let origin_y = transform_origin.y.to_pixels_internal(
percent_resolve_y,
DEFAULT_FONT_SIZE,
DEFAULT_FONT_SIZE,
);
let d =
px.to_pixels_internal(percent_resolve_x, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);
Self::new_translation(-origin_x, -origin_y, 0.0)
.then(&Self::new_perspective(d))
.then(&Self::new_translation(origin_x, origin_y, 0.0))
}
}
}
/// The plane z = 0 of this transform as a 3x3 homography.
///
/// Over `(x, y, 1)` row vectors — `[x' y' w'] = [x y 1] * H`, row-major
/// `[m00 m01 m03; m10 m11 m13; m30 m31 m33]` — i.e. exactly what a 2D
/// compositor needs to place a flat layer: the affine part plus the
/// perspective row. [`Self::is_plane_affine`] tells whether the
/// perspective row is the trivial `[0 0 1]`.
#[must_use]
pub const fn plane_homography(&self) -> [f32; 9] {
[
self.m[0][0],
self.m[0][1],
self.m[0][3],
self.m[1][0],
self.m[1][1],
self.m[1][3],
self.m[3][0],
self.m[3][1],
self.m[3][3],
]
}
/// Does the z = 0 plane map affinely (no perspective foreshortening)?
#[must_use]
pub const fn is_plane_affine(&self) -> bool {
let (a, b, w) = (self.m[0][3], self.m[1][3], self.m[3][3]);
a > -1e-7 && a < 1e-7 && b > -1e-7 && b < 1e-7 && w > 1.0 - 1e-6 && w < 1.0 + 1e-6
}
/// Creates a scaling matrix with independent scale factors per axis.
#[must_use]
#[inline]
pub const fn new_scale(x: f32, y: f32, z: f32) -> Self {
Self::new(
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,
)
}
/// Creates a translation matrix that moves by `(x, y, z)`.
#[must_use]
#[inline]
pub const fn new_translation(x: f32, y: f32, z: f32) -> Self {
Self::new(
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,
)
}
/// Creates a perspective projection matrix with distance `d`.
#[must_use]
#[inline]
fn new_perspective(d: f32) -> Self {
Self::new(
1.0,
0.0,
0.0,
0.0,
0.0,
1.0,
0.0,
0.0,
0.0,
0.0,
1.0,
-1.0 / d,
0.0,
0.0,
0.0,
1.0,
)
}
/// Create a 3d rotation transform from an angle / axis.
/// The supplied axis must be normalized.
#[must_use]
#[inline]
#[allow(clippy::suboptimal_flops)] // mul_add not guaranteed faster/available without target +fma; keep explicit a*b+c
fn new_rotation(x: f32, y: f32, z: f32, theta_radians: f32) -> Self {
let xx = x * x;
let yy = y * y;
let zz = z * z;
let half_theta = theta_radians / 2.0;
let sc = half_theta.sin() * half_theta.cos();
let sq = half_theta.sin() * half_theta.sin();
Self::new(
1.0 - 2.0 * (yy + zz) * sq,
2.0 * (x * y * sq + z * sc),
2.0 * (x * z * sq - y * sc),
0.0,
2.0 * (x * y * sq - z * sc),
1.0 - 2.0 * (xx + zz) * sq,
2.0 * (y * z * sq + x * sc),
0.0,
2.0 * (x * z * sq + y * sc),
2.0 * (y * z * sq - x * sc),
1.0 - 2.0 * (xx + yy) * sq,
0.0,
0.0,
0.0,
0.0,
1.0,
)
}
/// Creates a 2D skew matrix from angles in degrees.
#[must_use]
#[inline]
fn new_skew(alpha: f32, beta: f32) -> Self {
let (sx, sy) = (beta.to_radians().tan(), alpha.to_radians().tan());
Self::new(
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,
)
}
/// Returns this matrix transposed to column-major layout.
#[must_use]
pub(crate) const fn get_column_major(&self) -> Self {
Self::new(
self.m[0][0],
self.m[1][0],
self.m[2][0],
self.m[3][0],
self.m[0][1],
self.m[1][1],
self.m[2][1],
self.m[3][1],
self.m[0][2],
self.m[1][2],
self.m[2][2],
self.m[3][2],
self.m[0][3],
self.m[1][3],
self.m[2][3],
self.m[3][3],
)
}
/// Transforms a 2D point into the target coordinate space.
#[must_use]
pub fn transform_point2d(&self, p: LogicalPosition) -> Option<LogicalPosition> {
let w =
p.x.mul_add(self.m[0][3], p.y.mul_add(self.m[1][3], self.m[3][3]));
if !w.is_sign_positive() {
return None;
}
let x =
p.x.mul_add(self.m[0][0], p.y.mul_add(self.m[1][0], self.m[3][0]));
let y =
p.x.mul_add(self.m[0][1], p.y.mul_add(self.m[1][1], self.m[3][1]));
Some(LogicalPosition { x: x / w, y: y / w })
}
/// Scales the translation components of this matrix by `scale_factor` for DPI adjustment.
pub fn scale_for_dpi(&mut self, scale_factor: f32) {
// only scale the translation, don't scale anything else
self.m[3][0] *= scale_factor;
self.m[3][1] *= scale_factor;
self.m[3][2] *= scale_factor;
}
/// Multiplies this matrix by `other`, applying `other` AFTER the current matrix.
#[must_use]
#[inline]
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose parser/builder/dispatch (one branch per input variant)
pub fn then(&self, other: &Self) -> Self {
Self::new(
self.m[0][0].mul_add(
other.m[0][0],
self.m[0][1].mul_add(
other.m[1][0],
self.m[0][2].mul_add(other.m[2][0], self.m[0][3] * other.m[3][0]),
),
),
self.m[0][0].mul_add(
other.m[0][1],
self.m[0][1].mul_add(
other.m[1][1],
self.m[0][2].mul_add(other.m[2][1], self.m[0][3] * other.m[3][1]),
),
),
self.m[0][0].mul_add(
other.m[0][2],
self.m[0][1].mul_add(
other.m[1][2],
self.m[0][2].mul_add(other.m[2][2], self.m[0][3] * other.m[3][2]),
),
),
self.m[0][0].mul_add(
other.m[0][3],
self.m[0][1].mul_add(
other.m[1][3],
self.m[0][2].mul_add(other.m[2][3], self.m[0][3] * other.m[3][3]),
),
),
self.m[1][0].mul_add(
other.m[0][0],
self.m[1][1].mul_add(
other.m[1][0],
self.m[1][2].mul_add(other.m[2][0], self.m[1][3] * other.m[3][0]),
),
),
self.m[1][0].mul_add(
other.m[0][1],
self.m[1][1].mul_add(
other.m[1][1],
self.m[1][2].mul_add(other.m[2][1], self.m[1][3] * other.m[3][1]),
),
),
self.m[1][0].mul_add(
other.m[0][2],
self.m[1][1].mul_add(
other.m[1][2],
self.m[1][2].mul_add(other.m[2][2], self.m[1][3] * other.m[3][2]),
),
),
self.m[1][0].mul_add(
other.m[0][3],
self.m[1][1].mul_add(
other.m[1][3],
self.m[1][2].mul_add(other.m[2][3], self.m[1][3] * other.m[3][3]),
),
),
self.m[2][0].mul_add(
other.m[0][0],
self.m[2][1].mul_add(
other.m[1][0],
self.m[2][2].mul_add(other.m[2][0], self.m[2][3] * other.m[3][0]),
),
),
self.m[2][0].mul_add(
other.m[0][1],
self.m[2][1].mul_add(
other.m[1][1],
self.m[2][2].mul_add(other.m[2][1], self.m[2][3] * other.m[3][1]),
),
),
self.m[2][0].mul_add(
other.m[0][2],
self.m[2][1].mul_add(
other.m[1][2],
self.m[2][2].mul_add(other.m[2][2], self.m[2][3] * other.m[3][2]),
),
),
self.m[2][0].mul_add(
other.m[0][3],
self.m[2][1].mul_add(
other.m[1][3],
self.m[2][2].mul_add(other.m[2][3], self.m[2][3] * other.m[3][3]),
),
),
self.m[3][0].mul_add(
other.m[0][0],
self.m[3][1].mul_add(
other.m[1][0],
self.m[3][2].mul_add(other.m[2][0], self.m[3][3] * other.m[3][0]),
),
),
self.m[3][0].mul_add(
other.m[0][1],
self.m[3][1].mul_add(
other.m[1][1],
self.m[3][2].mul_add(other.m[2][1], self.m[3][3] * other.m[3][1]),
),
),
self.m[3][0].mul_add(
other.m[0][2],
self.m[3][1].mul_add(
other.m[1][2],
self.m[3][2].mul_add(other.m[2][2], self.m[3][3] * other.m[3][2]),
),
),
self.m[3][0].mul_add(
other.m[0][3],
self.m[3][1].mul_add(
other.m[1][3],
self.m[3][2].mul_add(other.m[2][3], self.m[3][3] * other.m[3][3]),
),
),
)
}
// credit: https://gist.github.com/rygorous/4172889
// linear combination:
// a[0] * B.row[0] + a[1] * B.row[1] + a[2] * B.row[2] + a[3] * B.row[3]
//
// SAFETY: the caller must guarantee SSE is available on this CPU (see the
// `use_sse` gate in `from_style_transform_vec`). Every `mem::transmute` here
// is a BY-VALUE `[f32; 4]` -> `__m128` conversion: both types are 16 bytes
// and the value is moved through a register, so no *reference* to under-
// aligned storage is ever formed and there is no alignment invariant to
// violate (unlike the AVX broadcast, which must use an unaligned load).
#[cfg(target_arch = "x86_64")]
#[inline]
unsafe fn linear_combine_sse(a: [f32; 4], b: &Self) -> [f32; 4] {
unsafe {
use core::{
arch::x86_64::{__m128, _mm_add_ps, _mm_mul_ps, _mm_shuffle_ps},
mem,
};
let a: __m128 = mem::transmute(a);
let mut result = _mm_mul_ps(
_mm_shuffle_ps(a, a, 0x00),
mem::transmute::<[f32; 4], __m128>(b.m[0]),
);
result = _mm_add_ps(
result,
_mm_mul_ps(
_mm_shuffle_ps(a, a, 0x55),
mem::transmute::<[f32; 4], __m128>(b.m[1]),
),
);
result = _mm_add_ps(
result,
_mm_mul_ps(
_mm_shuffle_ps(a, a, 0xaa),
mem::transmute::<[f32; 4], __m128>(b.m[2]),
),
);
result = _mm_add_ps(
result,
_mm_mul_ps(
_mm_shuffle_ps(a, a, 0xff),
mem::transmute::<[f32; 4], __m128>(b.m[3]),
),
);
mem::transmute(result)
}
}
/// Multiplies this matrix by `other` using SSE instructions.
///
/// SAFETY: caller must guarantee SSE is available; only forwards to
/// `linear_combine_sse`, whose safety contract is identical.
#[cfg(target_arch = "x86_64")]
#[inline]
unsafe fn then_sse(&self, other: &Self) -> Self {
unsafe {
Self {
m: [
Self::linear_combine_sse(self.m[0], other),
Self::linear_combine_sse(self.m[1], other),
Self::linear_combine_sse(self.m[2], other),
Self::linear_combine_sse(self.m[3], other),
],
}
}
}
/// Dual linear combination using AVX instructions on YMM registers.
///
/// AUDIT: the rows `b.m[i]` are `[f32; 4]` fields with alignment 4, but
/// `_mm256_broadcast_ps` takes a `&__m128` (alignment 16). Forming that
/// reference — `&*(ptr as *const __m128)` — from an align-4 field is
/// misaligned-reference UB even though the underlying `vbroadcastf128`
/// tolerates it. Use `_mm256_loadu2_m128`, which does an *unaligned*
/// 128-bit load from a raw `*const f32` and never forms a `&__m128`;
/// passing the same row pointer for both lanes reproduces the broadcast
/// (`result[127:0] = result[255:128] = row`).
///
/// SAFETY: caller must guarantee AVX is available. Each `broadcast_row`
/// reads exactly 4 f32 (16 bytes) through `_mm256_loadu2_m128`, an
/// *unaligned* load, so the align-4 `[f32; 4]` rows are read in-bounds and
/// no `&__m128` (align 16) is ever formed from them.
#[cfg(target_arch = "x86_64")]
unsafe fn linear_combine_avx8(
a01: core::arch::x86_64::__m256,
b: &Self,
) -> core::arch::x86_64::__m256 {
unsafe {
use core::arch::x86_64::{
_mm256_add_ps, _mm256_loadu2_m128, _mm256_mul_ps, _mm256_shuffle_ps,
};
// Unaligned broadcast of a row into both 128-bit lanes. Runs inside the
// enclosing `unsafe` block, so the intrinsic call needs no inner `unsafe`.
let broadcast_row = |row: &[f32; 4]| {
let p = row.as_ptr();
_mm256_loadu2_m128(p, p)
};
let mut result =
_mm256_mul_ps(_mm256_shuffle_ps(a01, a01, 0x00), broadcast_row(&b.m[0]));
result = _mm256_add_ps(
result,
_mm256_mul_ps(_mm256_shuffle_ps(a01, a01, 0x55), broadcast_row(&b.m[1])),
);
result = _mm256_add_ps(
result,
_mm256_mul_ps(_mm256_shuffle_ps(a01, a01, 0xaa), broadcast_row(&b.m[2])),
);
result = _mm256_add_ps(
result,
_mm256_mul_ps(_mm256_shuffle_ps(a01, a01, 0xff), broadcast_row(&b.m[3])),
);
result
}
}
/// 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]
unsafe fn then_avx8(&self, other: &Self) -> Self {
unsafe {
use core::{
arch::x86_64::{__m256, _mm256_loadu_ps, _mm256_storeu_ps, _mm256_zeroupper},
mem,
};
_mm256_zeroupper();
let a01: __m256 = _mm256_loadu_ps(&raw const self.m[0][0]);
let a23: __m256 = _mm256_loadu_ps(&raw const self.m[2][0]);
let out01x = Self::linear_combine_avx8(a01, other);
let out23x = Self::linear_combine_avx8(a23, other);
let mut out = Self {
m: [self.m[0], self.m[1], self.m[2], self.m[3]],
};
_mm256_storeu_ps(&raw mut out.m[0][0], out01x);
_mm256_storeu_ps(&raw mut out.m[2][0], out23x);
out
}
}
/// 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
fn make_rotation(
rotation_origin: (f32, f32),
mut degrees: f32,
axis_x: f32,
axis_y: f32,
axis_z: f32,
// see documentation for RotationMode
rotation_mode: RotationMode,
) -> Self {
degrees = match rotation_mode {
// CSS rotations are clockwise
RotationMode::ForWebRender => -degrees,
// hit-testing turns counter-clockwise
RotationMode::ForHitTesting => degrees,
};
let (origin_x, origin_y) = rotation_origin;
let pre_transform = Self::new_translation(-origin_x, -origin_y, 0.0);
let post_transform = Self::new_translation(origin_x, origin_y, 0.0);
let theta = 2.0_f32 * core::f32::consts::PI - degrees.to_radians();
let rotate_transform = Self::new_rotation(axis_x, axis_y, axis_z, theta);
pre_transform.then(&rotate_transform).then(&post_transform)
}
}
#[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::*;
fn sample_a() -> ComputedTransform3D {
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,
)
}
fn sample_b() -> ComputedTransform3D {
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,
)
}
fn approx_eq(a: &ComputedTransform3D, b: &ComputedTransform3D) {
for r in 0..4 {
for c in 0..4 {
assert!(
(a.m[r][c] - b.m[r][c]).abs() < 1e-3,
"mismatch at [{r}][{c}]: {} vs {}",
a.m[r][c],
b.m[r][c]
);
}
}
}
/// 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.
fn naive_then(a: &ComputedTransform3D, b: &ComputedTransform3D) -> ComputedTransform3D {
let mut out = ComputedTransform3D::IDENTITY;
for r in 0..4 {
for c in 0..4 {
let mut acc = 0.0f32;
for k in 0..4 {
acc += a.m[r][k] * b.m[k][c];
}
out.m[r][c] = acc;
}
}
out
}
// 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]
fn scalar_matmul_matches_reference() {
let a = sample_a();
let b = sample_b();
approx_eq(&a.then(&b), &naive_then(&a, &b));
// Identity is a left/right unit.
approx_eq(&ComputedTransform3D::IDENTITY.then(&b), &b);
approx_eq(&a.then(&ComputedTransform3D::IDENTITY), &a);
}
// 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]
fn simd_matmul_matches_scalar() {
let a = sample_a();
let b = sample_b();
let scalar = a.then(&b);
#[cfg(target_arch = "x86_64")]
{
if std::is_x86_feature_detected!("sse") {
let sse = unsafe { a.then_sse(&b) };
approx_eq(&scalar, &sse);
}
if std::is_x86_feature_detected!("avx") {
let avx = unsafe { a.then_avx8(&b) };
approx_eq(&scalar, &avx);
}
}
// Always assert the scalar path is self-consistent (identity * b == b).
approx_eq(&ComputedTransform3D::IDENTITY.then(&b), &b);
}
// 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]
fn avx_result_independent_of_row_alignment() {
if !std::is_x86_feature_detected!("avx") {
return;
}
let a = sample_a();
let b = sample_b();
let expected = unsafe { a.then_avx8(&b) };
const N: usize = core::mem::size_of::<ComputedTransform3D>(); // 64, no padding
let mut buf = vec![0u8; N * 2 + 16];
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 {
let aligned = base.add(base.align_offset(16));
let misaligned = aligned.add(4); // 4 mod 16: not 16-aligned
for off_ptr in [aligned, misaligned] {
core::ptr::copy_nonoverlapping((&raw const a).cast::<u8>(), off_ptr, N);
let a_ref = &*off_ptr.cast::<ComputedTransform3D>();
let got = a_ref.then_avx8(&b);
approx_eq(&expected, &got);
}
}
}
}
#[cfg(test)]
#[path = "transform_test.rs"]
mod transform_test;