Skip to main content
← PSoXide SDK guides and examples · SDK 80d1c329e977 · All Cargo features enabled; check feature gates before use.

psx_gte/
scene.rs

1//! Scene / camera / projection helpers.
2//!
3//! The register macros in [`regs`][crate::regs] are the only thing
4//! that actually touches the GTE; everything here is a convenience
5//! layer that bundles the ~8 writes a typical 3D frame needs into
6//! named functions. All functions are safe -- the macros they wrap
7//! already contain the `unsafe { asm! }` internally, and there's
8//! nothing we can do with a bad matrix value that would be undefined
9//! behaviour (worst case: the projected vertex is garbage).
10//!
11//! Typical frame:
12//!
13//! ```ignore
14//! scene::set_screen_offset(160 << 16, 120 << 16);
15//! scene::set_projection_plane(200);
16//! let rot = Mat3I16::rotate_y(angle);
17//! scene::load_rotation(&rot);
18//! scene::load_translation(Vec3I32::new(0, 0, 0x4000));
19//! for v in vertices {
20//!     let p = scene::project_vertex(v);
21//!     draw_point(p.sx, p.sy);
22//! }
23//! ```
24
25use crate::math::{Mat3I16, Vec3I16, Vec3I32};
26use crate::regs::pack_xy;
27use crate::{ops, read_control, read_data, write_control, write_data};
28#[cfg(target_arch = "mips")]
29use core::arch::asm;
30
31/// Result of a single perspective-projected vertex -- screen-space
32/// (x, y) in pixels plus the MAC3 depth used for ordering-table
33/// inserts. `Projected` is `Copy` + trivially packed so the caller
34/// can collect per-vertex results into an array and rasterise later.
35#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
36#[repr(C)]
37pub struct Projected {
38    /// Screen-space X, clamped to GTE's ±0x400 range.
39    pub sx: i16,
40    /// Screen-space Y.
41    pub sy: i16,
42    /// Depth post-divide, 0..0xFFFF after saturation.
43    pub sz: u16,
44}
45
46/// A direction scaled to Q12 unit length by
47/// [`normalize_classic_q12_scheduled`], with the squared lengths it came
48/// from.
49#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
50#[repr(C)]
51pub struct ClassicNormalizedVector {
52    /// The input direction at length 4096 (Q12 1.0); zero when the
53    /// squared length is zero or wrapped negative.
54    pub vector: Vec3I16,
55    /// `x * x + y * y` of the whole-unit components, wrapping.
56    pub xy_squared: i32,
57    /// `x * x + y * y + z * z` of the whole-unit components, wrapping.
58    pub squared: i32,
59}
60
61/// floor(sqrt(n)) by bisection, for building tables at compile time.
62const fn isqrt_u32(n: u32) -> u32 {
63    let (mut lo, mut hi) = (0u32, 1u32 << 16);
64    while hi - lo > 1 {
65        let mid = (lo + hi) / 2;
66        if mid * mid <= n {
67            lo = mid;
68        } else {
69            hi = mid;
70        }
71    }
72    lo
73}
74
75/// Q12 reciprocal square roots of the sums 64..=255, scaled so the sum 64
76/// maps to 1.0: entry `m - 64` is floor(4096 * sqrt(64 / m)). That equals
77/// floor(32768 / sqrt(m)) = floor(sqrt(2^30 / m)), and since flooring the
78/// argument first doesn't change an integer square root's floor, it is
79/// computed exactly in integers.
80const RSQRT_Q12_FROM_64: [i16; 192] = {
81    let mut table = [0i16; 192];
82    let mut i = 0;
83    while i < 192 {
84        table[i] = isqrt_u32((1u32 << 30) / (64 + i as u32)) as i16;
85        i += 1;
86    }
87    table
88};
89
90/// Scale a Q12 direction to length 4096 with a 192-entry reciprocal square
91/// root table, the classic fixed-point way.
92///
93/// Each component is floored to whole units (`>> 12`) and kept as 16 bits.
94/// With `s` the sum of their squares (wrapping `i32`):
95///
96/// 1. `L` = leading zero bits of `s`, rounded down to even.
97/// 2. `s` shifted by `L - 24` lands in 64..=255; the table gives
98///    `r` = floor(4096 * sqrt(64 / that)).
99/// 3. Each component becomes `(c * r) >> ((31 - L) / 2)`.
100///
101/// Because `L` is even, the table entry equals 4096 * 2^(15 - L/2) / sqrt(s),
102/// and the shift in step 3 removes that power of two exactly, leaving
103/// 4096 * c / sqrt(s) up to the table's truncation. A zero or wrapped (negative)
104/// `s` gives a zero vector. Pure integer work: no GTE state is used.
105pub fn normalize_classic_q12_scheduled(input: Vec3I32) -> ClassicNormalizedVector {
106    let c = [
107        (input.x >> 12) as i16,
108        (input.y >> 12) as i16,
109        (input.z >> 12) as i16,
110    ];
111    let square = |v: i16| i32::from(v) * i32::from(v);
112    let xy_squared = square(c[0]).wrapping_add(square(c[1]));
113    let squared = xy_squared.wrapping_add(square(c[2]));
114    if squared <= 0 {
115        return ClassicNormalizedVector {
116            vector: Vec3I16::new(0, 0, 0),
117            xy_squared,
118            squared,
119        };
120    }
121    let even_zeros = (squared as u32).leading_zeros() & !1;
122    let in_range = if even_zeros >= 24 {
123        squared << (even_zeros - 24)
124    } else {
125        squared >> (24 - even_zeros)
126    };
127    let r = i32::from(RSQRT_Q12_FROM_64[(in_range - 64) as usize]);
128    let shift = (31 - even_zeros) / 2;
129    let scale = |v: i16| ((i32::from(v) * r) >> shift) as i16;
130    ClassicNormalizedVector {
131        vector: Vec3I16::new(scale(c[0]), scale(c[1]), scale(c[2])),
132        xy_squared,
133        squared,
134    }
135}
136
137/// Four-byte-aligned plane record used by the GTE AABB clip batch.
138///
139/// This layout deliberately matches retained engines that store
140/// `(normal, kind, signbits, distance)`. `kind` remains caller-owned, while
141/// `signbits` caches the negative-normal mask (`x | y << 1 | z << 2`) used to
142/// select AABB support points without rereading the normal components.
143#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
144#[repr(C)]
145pub struct AabbClipPlane {
146    /// Signed Q12 plane normal.
147    pub normal: [i16; 3],
148    /// Caller-owned plane kind or axial classification.
149    pub kind: u8,
150    /// Negative-normal mask (`x | y << 1 | z << 2`).
151    pub signbits: u8,
152    /// Q12 plane distance.
153    pub distance: i32,
154}
155
156/// Load the rotation matrix into the GTE's RT control registers (0..=4).
157#[doc(alias = "SetRotMatrix")]
158pub fn load_rotation(m: &Mat3I16) {
159    write_control!(0, pack_xy(m.m[0][0], m.m[0][1]));
160    write_control!(1, pack_xy(m.m[0][2], m.m[1][0]));
161    write_control!(2, pack_xy(m.m[1][1], m.m[1][2]));
162    write_control!(3, pack_xy(m.m[2][0], m.m[2][1]));
163    write_control!(4, m.m[2][2] as i32 as u32);
164}
165
166/// Load the light-direction matrix (LLM, control 8..=12).
167#[doc(alias = "SetLightMatrix")]
168pub fn load_light_matrix(m: &Mat3I16) {
169    write_control!(8, pack_xy(m.m[0][0], m.m[0][1]));
170    write_control!(9, pack_xy(m.m[0][2], m.m[1][0]));
171    write_control!(10, pack_xy(m.m[1][1], m.m[1][2]));
172    write_control!(11, pack_xy(m.m[2][0], m.m[2][1]));
173    write_control!(12, m.m[2][2] as i32 as u32);
174}
175
176/// Load four clip-plane normals for [`classify_aabb_clip4`] and
177/// [`is_aabb_outside_clip4`].
178///
179/// Planes zero through two occupy the rotation-matrix rows. Plane three uses
180/// the first light-matrix row. This intentionally replaces both matrices;
181/// callers must restore their camera and lighting state before projection or
182/// lit geometry submission.
183pub fn load_aabb_clip4(planes: &[AabbClipPlane; 4]) {
184    load_rotation(&Mat3I16 {
185        m: [planes[0].normal, planes[1].normal, planes[2].normal],
186    });
187    load_light_matrix(&Mat3I16 {
188        m: [planes[3].normal, [0; 3], [0; 3]],
189    });
190}
191
192/// Load the light-color matrix (LCM, control 16..=20).
193#[doc(alias = "SetColorMatrix")]
194pub fn load_light_color_matrix(m: &Mat3I16) {
195    write_control!(16, pack_xy(m.m[0][0], m.m[0][1]));
196    write_control!(17, pack_xy(m.m[0][2], m.m[1][0]));
197    write_control!(18, pack_xy(m.m[1][1], m.m[1][2]));
198    write_control!(19, pack_xy(m.m[2][0], m.m[2][1]));
199    write_control!(20, m.m[2][2] as i32 as u32);
200}
201
202/// Load the translation vector (TR, control 5..=7).
203#[doc(alias = "SetTransMatrix")]
204pub fn load_translation(t: Vec3I32) {
205    write_control!(5, t.x as u32);
206    write_control!(6, t.y as u32);
207    write_control!(7, t.z as u32);
208}
209
210/// Load the background-color bias (BK, control 13..=15).
211#[doc(alias = "SetBackColor")]
212pub fn load_background_color(c: Vec3I32) {
213    write_control!(13, c.x as u32);
214    write_control!(14, c.y as u32);
215    write_control!(15, c.z as u32);
216}
217
218/// Load the far-color bias (FC, control 21..=23) used by depth-cue
219/// interpolation.
220#[doc(alias = "SetFarColor")]
221pub fn load_far_color(c: Vec3I32) {
222    write_control!(21, c.x as u32);
223    write_control!(22, c.y as u32);
224    write_control!(23, c.z as u32);
225}
226
227/// Set OFX and OFY (control 24, 25) -- the screen-space offsets applied
228/// post-divide. Values are 15.16 fixed point; `160 << 16` = 160.0 px.
229#[doc(alias = "SetGeomOffset")]
230pub fn set_screen_offset(ofx_15_16: i32, ofy_15_16: i32) {
231    write_control!(24, ofx_15_16 as u32);
232    write_control!(25, ofy_15_16 as u32);
233}
234
235/// Set the projection-plane distance H (control 26). Larger H = longer
236/// focal length = narrower FOV.
237#[doc(alias = "SetGeomScreen")]
238pub fn set_projection_plane(h: u16) {
239    write_control!(26, h as i32 as u32);
240}
241
242/// Set the depth-cue coefficients DQA / DQB (control 27, 28).
243/// Depth-cue outputs IR0 = DQA/H + DQB, scaled to 0..0x1000.
244pub fn set_depth_cue(dqa: i16, dqb: i32) {
245    write_control!(27, dqa as i32 as u32);
246    write_control!(28, dqb as u32);
247}
248
249/// Set the AVSZ3/AVSZ4 averaging weights (control 29, 30). Typical
250/// values: `ZSF3 = 0x555` (= 1/3 in 0.12), `ZSF4 = 0x400` (= 1/4).
251#[doc(alias = "AVSZ")]
252#[doc(alias = "ZSF3")]
253#[doc(alias = "ZSF4")]
254pub fn set_average_z_weights(zsf3: i16, zsf4: i16) {
255    write_control!(29, zsf3 as i32 as u32);
256    write_control!(30, zsf4 as i32 as u32);
257}
258
259/// Load `v` into the V0 input slot (data registers 0 and 1) and run
260/// RTPS to project it. Returns the screen-space pair + depth so the
261/// caller can immediately use the result.
262///
263/// Assumes the rotation matrix, translation, screen offset, and
264/// projection plane have already been set.
265#[doc(alias = "RotTransPers")]
266pub fn project_vertex(v: Vec3I16) -> Projected {
267    write_data!(0, v.xy_packed());
268    write_data!(1, v.z_packed());
269    // SAFETY: V0 has just been loaded; RT / TR / H / OFX / OFY are
270    // assumed to be set by the caller's scene setup.
271    unsafe { ops::project_single() };
272    let sxy = read_data!(14);
273    let sz = read_data!(19) as u16;
274    Projected {
275        sx: sxy as i16,
276        sy: (sxy >> 16) as i16,
277        sz,
278    }
279}
280
281/// Project three vertices as a batch via RTPT -- one GTE call, three
282/// results out of the SXY FIFO + SZ FIFO. Slightly faster than three
283/// successive [`project_vertex`] calls because RTPT shares setup.
284///
285/// The returned array is `[v0_result, v1_result, v2_result]`.
286#[doc(alias = "RotTransPers3")]
287pub fn project_triangle(v0: Vec3I16, v1: Vec3I16, v2: Vec3I16) -> [Projected; 3] {
288    // Load all three vertices first (data regs 0..=5), then fire RTPT.
289    write_data!(0, v0.xy_packed());
290    write_data!(1, v0.z_packed());
291    write_data!(2, v1.xy_packed());
292    write_data!(3, v1.z_packed());
293    write_data!(4, v2.xy_packed());
294    write_data!(5, v2.z_packed());
295    // SAFETY: all three vertices are loaded; scene-setup registers
296    // are the caller's responsibility.
297    unsafe { ops::project_triple() };
298    // After RTPT, SXY FIFO holds (v0, v1, v2) in slots 0/1/2, and
299    // SZ FIFO holds them in SZ1/SZ2/SZ3.
300    let sxy0 = read_data!(12);
301    let sxy1 = read_data!(13);
302    let sxy2 = read_data!(14);
303    let sz1 = read_data!(17) as u16;
304    let sz2 = read_data!(18) as u16;
305    let sz3 = read_data!(19) as u16;
306    [
307        Projected {
308            sx: sxy0 as i16,
309            sy: (sxy0 >> 16) as i16,
310            sz: sz1,
311        },
312        Projected {
313            sx: sxy1 as i16,
314            sy: (sxy1 >> 16) as i16,
315            sz: sz2,
316        },
317        Projected {
318            sx: sxy2 as i16,
319            sy: (sxy2 >> 16) as i16,
320            sz: sz3,
321        },
322    ]
323}
324
325/// Transform one vertex by the currently loaded RT/TR matrix without
326/// perspective projection. Returns MAC1/2/3 in view-space units.
327///
328/// Assumes the rotation matrix and translation have already been set.
329#[doc(alias = "RotTrans")]
330pub fn transform_vertex(v: Vec3I16) -> Vec3I32 {
331    write_data!(0, v.xy_packed());
332    write_data!(1, v.z_packed());
333    // SAFETY: V0 has just been loaded; RT/TR are set by scene setup.
334    unsafe { ops::rotate_translate_v0() };
335    Vec3I32::new(
336        read_data!(25) as i32,
337        read_data!(26) as i32,
338        read_data!(27) as i32,
339    )
340}
341
342/// Transform one vertex with a lower-overhead MIPS register schedule.
343///
344/// Keep the default helper compact; use this variant in measured hot
345/// paths that already keep the relevant GTE camera matrix loaded.
346#[inline(always)]
347pub fn transform_vertex_scheduled(v: Vec3I16) -> Vec3I32 {
348    #[cfg(target_arch = "mips")]
349    {
350        transform_vertex_mips(v)
351    }
352    #[cfg(not(target_arch = "mips"))]
353    {
354        transform_vertex(v)
355    }
356}
357
358/// Compose two Q12 rotation/scale matrices with the GTE's scheduled MVMVA
359/// path.
360///
361/// The left matrix is loaded into the rotation registers and each column of
362/// `right` is transformed in turn. Translation is forced to zero, so the
363/// result is exactly the rotation/scale product. This clobbers the live GTE
364/// rotation and translation state; callers normally load the returned scene
365/// matrix immediately afterward.
366#[inline]
367pub fn compose_rotation_scheduled(left: &Mat3I16, right: &Mat3I16) -> Mat3I16 {
368    load_rotation(left);
369    load_translation(Vec3I32::ZERO);
370
371    let c0 = transform_vertex_scheduled(Vec3I16::new(right.m[0][0], right.m[1][0], right.m[2][0]));
372    let c1 = transform_vertex_scheduled(Vec3I16::new(right.m[0][1], right.m[1][1], right.m[2][1]));
373    let c2 = transform_vertex_scheduled(Vec3I16::new(right.m[0][2], right.m[1][2], right.m[2][2]));
374    let clamp = |value: i32| value.clamp(i16::MIN as i32, i16::MAX as i32) as i16;
375
376    Mat3I16 {
377        m: [
378            [clamp(c0.x), clamp(c1.x), clamp(c2.x)],
379            [clamp(c0.y), clamp(c1.y), clamp(c2.y)],
380            [clamp(c0.z), clamp(c1.z), clamp(c2.z)],
381        ],
382    }
383}
384
385/// Project one vertex with a lower-overhead MIPS register schedule.
386///
387/// This is intended for very hot batched paths that have been benchmarked
388/// with the larger inlined code shape. The portable path delegates to
389/// [`project_vertex`] so host preview/emulator tests remain identical.
390#[inline(always)]
391pub fn project_vertex_scheduled(v: Vec3I16) -> Projected {
392    #[cfg(target_arch = "mips")]
393    {
394        project_vertex_mips(v)
395    }
396    #[cfg(not(target_arch = "mips"))]
397    {
398        project_vertex(v)
399    }
400}
401
402/// Project three vertices with a lower-overhead MIPS register schedule.
403///
404/// The normal [`project_triangle`] helper stays compact for general users;
405/// this variant is used only by renderer loops where profiling shows that
406/// shaving COP2 register wrapper overhead pays for the extra code size.
407#[inline(always)]
408pub fn project_triangle_scheduled(v0: Vec3I16, v1: Vec3I16, v2: Vec3I16) -> [Projected; 3] {
409    #[cfg(target_arch = "mips")]
410    {
411        project_triangle_mips(v0, v1, v2)
412    }
413    #[cfg(not(target_arch = "mips"))]
414    {
415        project_triangle(v0, v1, v2)
416    }
417}
418
419/// In-flight RTPT kicked by [`start_project_triple`]; [`read`](Self::read)
420/// collects the three projected results.
421///
422/// Between kick and read the caller must not issue any other GTE op
423/// or touch GTE registers; arbitrary scalar CPU work is fine and is
424/// the whole point -- it runs while the GTE projects. On the host
425/// build the projection happens eagerly at kick and `read` just
426/// returns it.
427#[must_use = "call read() to collect the projected triple"]
428#[doc(alias = "RTPT")]
429pub struct ProjectTripleInFlight(#[cfg(not(target_arch = "mips"))] [Projected; 3]);
430
431/// Load V0..V2 and issue RTPT without reading results, so the caller
432/// can overlap the GTE op with scalar work for the previous triple.
433///
434/// The MTC2 order matches [`project_triangle_scheduled`]: V0 is
435/// written 6 instructions before RTPT issues and RTPT consumes V2
436/// last, so the HWB-010/011 commit-slip hazard profile is unchanged.
437#[inline(always)]
438#[doc(alias = "RTPT")]
439pub fn start_project_triple(v0: Vec3I16, v1: Vec3I16, v2: Vec3I16) -> ProjectTripleInFlight {
440    #[cfg(target_arch = "mips")]
441    {
442        let v0_xy = v0.xy_packed();
443        let v0_z = v0.z_packed();
444        let v1_xy = v1.xy_packed();
445        let v1_z = v1.z_packed();
446        let v2_xy = v2.xy_packed();
447        let v2_z = v2.z_packed();
448        // SAFETY: the six words are MTC2 $8..$13 into data regs 0..5 (V0..V2),
449        // two NOPs, then RTPT. Each MTC2 only reads its declared `in` register,
450        // RTPT only touches GTE registers, and no CPU register is written, so
451        // `nomem`/`nostack` with no outputs is accurate.
452        unsafe {
453            asm!(
454                // MTC2 $8..$13 into V0/V1/V2 input registers.
455                ".word {w0}",
456                ".word {w1}",
457                ".word {w2}",
458                ".word {w3}",
459                ".word {w4}",
460                ".word {w5}",
461                // Conservative HWB-010/011 input-commit gap for the final V2
462                // write. The original console failure proved the rule for
463                // MVMVA/RTPS, not RTPT; hardware-tests v1.20 records 0xC0-C3
464                // explicitly arbitrate whether RTPT needs these two slots.
465                ".word 0",
466                ".word 0",
467                // RTPT.
468                ".word {w6}",
469                w0 = const psx_hw::gte::mtc2(8, 0),
470                w1 = const psx_hw::gte::mtc2(9, 1),
471                w2 = const psx_hw::gte::mtc2(10, 2),
472                w3 = const psx_hw::gte::mtc2(11, 3),
473                w4 = const psx_hw::gte::mtc2(12, 4),
474                w5 = const psx_hw::gte::mtc2(13, 5),
475                w6 = const psx_hw::gte::command::RTPT,
476                in("$8") v0_xy,
477                in("$9") v0_z,
478                in("$10") v1_xy,
479                in("$11") v1_z,
480                in("$12") v2_xy,
481                in("$13") v2_z,
482                options(nostack, nomem, preserves_flags),
483            );
484        }
485        ProjectTripleInFlight()
486    }
487    #[cfg(not(target_arch = "mips"))]
488    {
489        ProjectTripleInFlight(project_triangle(v0, v1, v2))
490    }
491}
492
493impl ProjectTripleInFlight {
494    /// Collect the projected triple.
495    ///
496    /// MFC2 does not provide a general GTE-busy interlock: the console result
497    /// in hardware-tests record 0xB0 disproved that older assumption for
498    /// NCLIP/MAC0. This RTPT sequence is safe only if its first result is ready
499    /// by the read issue point; v1.20 records 0xC4-C7 measure that exact window.
500    /// Until silicon answers them, callers must not treat a short overlap as a
501    /// guaranteed blocking wait.
502    #[inline(always)]
503    pub fn read(self) -> [Projected; 3] {
504        #[cfg(target_arch = "mips")]
505        {
506            let sxy0: u32;
507            let sxy1: u32;
508            let sxy2: u32;
509            let sz1: u32;
510            let sz2: u32;
511            let sz3: u32;
512            // SAFETY: six MFC2s copy SXY0..SXY2 (data 12..14) and SZ1..SZ3 (17..19)
513            // into $8..$13, all declared as outputs; each read's load-delay slot is
514            // covered by the next MFC2 and the final NOP. No memory or stack is
515            // touched. Reading before RTPT finishes yields stale values, not UB (see
516            // the doc comment above).
517            unsafe {
518                asm!(
519                    // Read SXY0/SXY1/SXY2/SZ1/SZ2/SZ3; each MFC2's
520                    // load-delay slot is filled by the next, so only
521                    // the final read needs the explicit NOP.
522                    ".word {w0}",
523                    ".word {w1}",
524                    ".word {w2}",
525                    ".word {w3}",
526                    ".word {w4}",
527                    ".word {w5}",
528                    ".word 0",
529                    w0 = const psx_hw::gte::mfc2(8, 12),
530                    w1 = const psx_hw::gte::mfc2(9, 13),
531                    w2 = const psx_hw::gte::mfc2(10, 14),
532                    w3 = const psx_hw::gte::mfc2(11, 17),
533                    w4 = const psx_hw::gte::mfc2(12, 18),
534                    w5 = const psx_hw::gte::mfc2(13, 19),
535                    out("$8") sxy0,
536                    out("$9") sxy1,
537                    out("$10") sxy2,
538                    out("$11") sz1,
539                    out("$12") sz2,
540                    out("$13") sz3,
541                    options(nostack, nomem, preserves_flags),
542                );
543            }
544            [
545                Projected {
546                    sx: sxy0 as i16,
547                    sy: (sxy0 >> 16) as i16,
548                    sz: sz1 as u16,
549                },
550                Projected {
551                    sx: sxy1 as i16,
552                    sy: (sxy1 >> 16) as i16,
553                    sz: sz2 as u16,
554                },
555                Projected {
556                    sx: sxy2 as i16,
557                    sy: (sxy2 >> 16) as i16,
558                    sz: sz3 as u16,
559                },
560            ]
561        }
562        #[cfg(not(target_arch = "mips"))]
563        {
564            self.0
565        }
566    }
567}
568
569#[cfg(target_arch = "mips")]
570#[inline(always)]
571fn project_vertex_mips(v: Vec3I16) -> Projected {
572    let mut sxy = v.xy_packed();
573    let mut sz = v.z_packed();
574    // SAFETY: MTC2 $8/$9 into V0, two NOPs, RTPS, then MFC2 SXY2 (data 14)
575    // into $8 and SZ3 (data 19) into $9 plus a load-delay NOP. Only $8 and $9
576    // are written and both are `inlateout`; no memory or stack is touched.
577    unsafe {
578        asm!(
579            // MTC2 $8,VXY0 and $9,VZ0.
580            ".word {w0}",
581            ".word {w1}",
582            // HWB-010/011 input-commit gap. The single-vertex path used to
583            // issue RTPS immediately here, leaving VXY0 at the same two-tick
584            // distance as the console-confirmed MVMVA vertex-explosion case.
585            // Two NOPs move it to the known-safe four-instruction distance.
586            ".word 0",
587            ".word 0",
588            // RTPS.
589            ".word {w2}",
590            // Read SXY2 and SZ3. Two MFC2s can share one final
591            // load-delay NOP instead of one NOP per wrapper call.
592            ".word {w3}",
593            ".word {w4}",
594            ".word 0",
595            w0 = const psx_hw::gte::mtc2(8, 0),
596            w1 = const psx_hw::gte::mtc2(9, 1),
597            w2 = const psx_hw::gte::command::RTPS,
598            w3 = const psx_hw::gte::mfc2(8, 14),
599            w4 = const psx_hw::gte::mfc2(9, 19),
600            inlateout("$8") sxy,
601            inlateout("$9") sz,
602            options(nostack, nomem, preserves_flags),
603        );
604    }
605    Projected {
606        sx: sxy as i16,
607        sy: (sxy >> 16) as i16,
608        sz: sz as u16,
609    }
610}
611
612#[cfg(target_arch = "mips")]
613#[inline(always)]
614fn project_triangle_mips(v0: Vec3I16, v1: Vec3I16, v2: Vec3I16) -> [Projected; 3] {
615    let v0_xy = v0.xy_packed();
616    let v0_z = v0.z_packed();
617    let v1_xy = v1.xy_packed();
618    let v1_z = v1.z_packed();
619    let v2_xy = v2.xy_packed();
620    let v2_z = v2.z_packed();
621    let sxy0: u32;
622    let sxy1: u32;
623    let sxy2: u32;
624    let sz1: u32;
625    let sz2: u32;
626    let sz3: u32;
627    // SAFETY: MTC2 $8..$13 into V0..V2, two NOPs, RTPT, then MFC2s of SXY0..2
628    // and SZ1..3 back into $8..$13 with a final load-delay NOP. Exactly those
629    // six registers are written, each declared `inlateout`; no memory or
630    // stack is touched.
631    unsafe {
632        asm!(
633            // MTC2 $8..$13 into V0/V1/V2 input registers.
634            ".word {w0}",
635            ".word {w1}",
636            ".word {w2}",
637            ".word {w3}",
638            ".word {w4}",
639            ".word {w5}",
640            // Conservative HWB-010/011 input-commit gap. The original
641            // console failure proved MVMVA/RTPS; hardware-tests v1.20 records
642            // 0xC0-C3 measure RTPT directly before we remove these slots.
643            // Keep this in sync with start_project_triple.
644            ".word 0",
645            ".word 0",
646            // RTPT.
647            ".word {w6}",
648            // Read SXY0/SXY1/SXY2/SZ1/SZ2/SZ3. Each MFC2's
649            // load-delay slot is filled by the next MFC2, so only the
650            // final read needs an explicit NOP before Rust observes
651            // the output registers.
652            ".word {w7}",
653            ".word {w8}",
654            ".word {w9}",
655            ".word {w10}",
656            ".word {w11}",
657            ".word {w12}",
658            ".word 0",
659            w0 = const psx_hw::gte::mtc2(8, 0),
660            w1 = const psx_hw::gte::mtc2(9, 1),
661            w2 = const psx_hw::gte::mtc2(10, 2),
662            w3 = const psx_hw::gte::mtc2(11, 3),
663            w4 = const psx_hw::gte::mtc2(12, 4),
664            w5 = const psx_hw::gte::mtc2(13, 5),
665            w6 = const psx_hw::gte::command::RTPT,
666            w7 = const psx_hw::gte::mfc2(8, 12),
667            w8 = const psx_hw::gte::mfc2(9, 13),
668            w9 = const psx_hw::gte::mfc2(10, 14),
669            w10 = const psx_hw::gte::mfc2(11, 17),
670            w11 = const psx_hw::gte::mfc2(12, 18),
671            w12 = const psx_hw::gte::mfc2(13, 19),
672            inlateout("$8") v0_xy => sxy0,
673            inlateout("$9") v0_z => sxy1,
674            inlateout("$10") v1_xy => sxy2,
675            inlateout("$11") v1_z => sz1,
676            inlateout("$12") v2_xy => sz2,
677            inlateout("$13") v2_z => sz3,
678            options(nostack, nomem, preserves_flags),
679        );
680    }
681    [
682        Projected {
683            sx: sxy0 as i16,
684            sy: (sxy0 >> 16) as i16,
685            sz: sz1 as u16,
686        },
687        Projected {
688            sx: sxy1 as i16,
689            sy: (sxy1 >> 16) as i16,
690            sz: sz2 as u16,
691        },
692        Projected {
693            sx: sxy2 as i16,
694            sy: (sxy2 >> 16) as i16,
695            sz: sz3 as u16,
696        },
697    ]
698}
699
700#[cfg(target_arch = "mips")]
701#[inline(always)]
702fn transform_vertex_mips(v: Vec3I16) -> Vec3I32 {
703    let xy = v.xy_packed();
704    let z = v.z_packed();
705    let mac1: u32;
706    let mac2: u32;
707    let mac3: u32;
708    // SAFETY: MTC2 $8/$9 into V0, two NOPs, MVMVA (RT, V0, TR), then MFC2
709    // MAC1..MAC3 (data 25..27) into $8..$10 with a final load-delay NOP. Only
710    // $8..$10 are written and all are declared outputs; no memory or stack is
711    // touched.
712    unsafe {
713        asm!(
714            // MTC2 $8,VXY0 and $9,VZ0.
715            ".word {w0}",
716            ".word {w1}",
717            // HWB-010/011 hazard gap (console-confirmed fix): two buffer
718            // NOPs push the VXY0 write's commit distance from 2 to 4
719            // instructions. Without them, real silicon can commit the
720            // write BETWEEN the MVMVA's sequential MAC1 and MAC2 compute
721            // phases, so MAC1 reads the previous V0.x -- the cortex
722            // vertex-explosion mechanism seen in the HWB-010 live capture.
723            ".word 0",
724            ".word 0",
725            // MVMVA RT,V0,TR,sf=1.
726            ".word {w2}",
727            // Read MAC1/MAC2/MAC3. Consecutive MFC2 instructions fill
728            // each other's load-delay slot; only the final read needs
729            // an explicit NOP before Rust observes the outputs.
730            ".word {w3}",
731            ".word {w4}",
732            ".word {w5}",
733            ".word 0",
734            w0 = const psx_hw::gte::mtc2(8, 0),
735            w1 = const psx_hw::gte::mtc2(9, 1),
736            w2 = const psx_hw::gte::command::ROTATE_TRANSLATE_V0,
737            w3 = const psx_hw::gte::mfc2(8, 25),
738            w4 = const psx_hw::gte::mfc2(9, 26),
739            w5 = const psx_hw::gte::mfc2(10, 27),
740            inlateout("$8") xy => mac1,
741            inlateout("$9") z => mac2,
742            lateout("$10") mac3,
743            options(nostack, nomem, preserves_flags),
744        );
745    }
746    Vec3I32::new(mac1 as i32, mac2 as i32, mac3 as i32)
747}
748
749/// Result of [`transform_vertex_probed`]: the live-schedule transform
750/// output plus post-op hazard evidence.
751#[derive(Clone, Copy)]
752pub struct TransformProbe {
753    /// The transform result exactly as the hot path reads it (the
754    /// IMMEDIATE MAC1/2/3 reads, same schedule as
755    /// `transform_vertex_mips`). Consumers keep using this so the
756    /// probed build behaves identically to the live engine.
757    pub out: Vec3I32,
758    /// MAC1 re-read after a 4-NOP settle gap. Differs from `out.x`
759    /// only if the immediate MAC1 read was served stale.
760    pub x_settled: i32,
761    /// Translation control regs (TRX/TRY/TRZ, cr5..cr7) read back
762    /// AFTER the op (nothing writes them during, so this is the value
763    /// in effect while the MVMVA executed). The compose path loads
764    /// zero here; nonzero = the zero write did not land for this op.
765    pub tr: [i32; 3],
766}
767
768/// Hazard-hunt instrument (keep): one MVMVA on the DELIBERATELY
769/// UNPADDED pre-HWB-011 schedule (V0 writes 1-2 instructions before
770/// the op -- the schedule that trips the silicon MTC2-commit hazard),
771/// with evidence reads appended strictly AFTER the op: a settled MAC1
772/// re-read and a TRX/TRY/TRZ readback. This is the live evidence
773/// channel that decoded the vertex explosion; it stays in the SDK so the
774/// next hardware mystery starts from a proven instrument. Not for production paths -- use
775/// [`transform_vertex_scheduled`], whose schedule carries the
776/// console-confirmed hazard gap.
777#[inline(always)]
778pub fn transform_vertex_probed(v: Vec3I16) -> TransformProbe {
779    #[cfg(target_arch = "mips")]
780    {
781        let xy = v.xy_packed();
782        let z = v.z_packed();
783        let mac1: u32;
784        let mac2: u32;
785        let mac3: u32;
786        let mac1_settled: u32;
787        let trx: u32;
788        let try_: u32;
789        let trz: u32;
790        // SAFETY: same MTC2/MVMVA/MFC2 shape as `transform_vertex_mips` minus the
791        // input gap, then a MAC1 re-read into $11 and CFC2 TRX/TRY/TRZ (control
792        // 5..7) into $12..$14. Every written register ($8..$14) is a declared
793        // output and no memory or stack is touched. The deliberately unpadded
794        // schedule can return stale MAC values; that is a data hazard, not UB.
795        unsafe {
796            asm!(
797                // Live schedule, byte-identical to transform_vertex_mips:
798                // MTC2 $8,VXY0 / MTC2 $9,VZ0 / MVMVA / MAC1,2,3 reads.
799                ".word {w0}",
800                ".word {w1}",
801                ".word {w2}",
802                ".word {w3}",
803                ".word {w4}",
804                ".word {w5}",
805                ".word 0",
806                // Probe tail, strictly AFTER the live reads: 4-NOP
807                // settle gap, MAC1 re-read ($11), then TRX/TRY/TRZ
808                // (cr5..cr7) read-back; chained CFC2s share delay
809                // slots, final NOP covers the last one.
810                ".word 0",
811                ".word 0",
812                ".word 0",
813                ".word 0",
814                ".word {w6}",
815                ".word {w7}",
816                ".word {w8}",
817                ".word {w9}",
818                ".word 0",
819                w0 = const psx_hw::gte::mtc2(8, 0),
820                w1 = const psx_hw::gte::mtc2(9, 1),
821                w2 = const psx_hw::gte::command::ROTATE_TRANSLATE_V0,
822                w3 = const psx_hw::gte::mfc2(8, 25),
823                w4 = const psx_hw::gte::mfc2(9, 26),
824                w5 = const psx_hw::gte::mfc2(10, 27),
825                w6 = const psx_hw::gte::mfc2(11, 25),
826                w7 = const psx_hw::gte::cfc2(12, 5),
827                w8 = const psx_hw::gte::cfc2(13, 6),
828                w9 = const psx_hw::gte::cfc2(14, 7),
829                inlateout("$8") xy => mac1,
830                inlateout("$9") z => mac2,
831                lateout("$10") mac3,
832                lateout("$11") mac1_settled,
833                lateout("$12") trx,
834                lateout("$13") try_,
835                lateout("$14") trz,
836                options(nostack, nomem, preserves_flags),
837            );
838        }
839        TransformProbe {
840            out: Vec3I32::new(mac1 as i32, mac2 as i32, mac3 as i32),
841            x_settled: mac1_settled as i32,
842            tr: [trx as i32, try_ as i32, trz as i32],
843        }
844    }
845    #[cfg(not(target_arch = "mips"))]
846    {
847        let out = transform_vertex(v);
848        TransformProbe {
849            out,
850            x_settled: out.x,
851            tr: [
852                read_control!(5) as i32,
853                read_control!(6) as i32,
854                read_control!(7) as i32,
855            ],
856        }
857    }
858}
859
860/// Read the last three projected Z values and compute their average
861/// via AVSZ3 (weighted by ZSF3). Returns OTZ -- the depth key most
862/// renderers use for ordering-table inserts.
863pub fn average_z_triangle() -> u16 {
864    // SAFETY: no input registers to prepare -- AVSZ3 reads SZ1..SZ3
865    // which were populated by the most recent RTPT / project_triangle.
866    unsafe { ops::average_z3() };
867    read_data!(7) as u16
868}
869
870/// Reload three cached projected depths into the GTE SZ FIFO and compute OTZ.
871///
872/// This is the indexed-mesh counterpart to [`average_z_triangle`]. It keeps
873/// cached vertex projection while using the PS1's AVSZ3 unit instead of a
874/// software 64-bit multiply for every face. The configured ZSF3 weight is
875/// read from GTE control register 29.
876#[inline(always)]
877pub fn average_cached_z3(depths: [u16; 3]) -> u16 {
878    #[cfg(target_arch = "mips")]
879    {
880        let mut otz = depths[0] as u32;
881        // SAFETY: MTC2 $8..$10 into SZ1..SZ3 (data 17..19), two NOPs, AVSZ3,
882        // then MFC2 OTZ (data 7) into $8 plus a load-delay NOP. Only $8 is written
883        // (`inlateout`); $9/$10 are read-only inputs; no memory or stack is
884        // touched.
885        unsafe {
886            asm!(
887                // Load SZ1..SZ3, then leave the hardware-safe two-slot MTC2
888                // commit gap before AVSZ3 consumes the final write.
889                ".word {w0}",
890                ".word {w1}",
891                ".word {w2}",
892                ".word 0",
893                ".word 0",
894                ".word {w3}",
895                // MFC2 has one CPU load-delay slot.
896                ".word {w4}",
897                ".word 0",
898                w0 = const psx_hw::gte::mtc2(8, 17),
899                w1 = const psx_hw::gte::mtc2(9, 18),
900                w2 = const psx_hw::gte::mtc2(10, 19),
901                w3 = const psx_hw::gte::command::AVSZ3,
902                w4 = const psx_hw::gte::mfc2(8, 7),
903                inlateout("$8") otz,
904                in("$9") depths[1] as u32,
905                in("$10") depths[2] as u32,
906                options(nostack, nomem, preserves_flags),
907            );
908        }
909        otz as u16
910    }
911    #[cfg(not(target_arch = "mips"))]
912    {
913        write_data!(17, depths[0] as u32);
914        write_data!(18, depths[1] as u32);
915        write_data!(19, depths[2] as u32);
916        // SAFETY: SZ1, SZ2 and SZ3 were loaded immediately above.
917        unsafe { ops::average_z3() };
918        read_data!(7) as u16
919    }
920}
921
922/// Scale a three-depth sum into the classic 2,048-slot OTZ domain.
923///
924/// This is exactly `(sum * 0x155) >> 12`. The MIPS sequence factors 0x155 as
925/// `5 * 17 * 4 + 1`, avoiding two shifts and additions emitted for the flat
926/// constant multiply on MIPS I.
927#[inline(always)]
928#[doc(alias = "OTZ")]
929pub fn classic_ordering_depth3_from_sum(sum: u32) -> u16 {
930    #[cfg(target_arch = "mips")]
931    {
932        let mut otz = sum;
933        // SAFETY: pure ALU shift-add on $8..$10. $8 is `inlateout` and the
934        // $9/$10 scratch registers are declared `lateout(_)`; no memory or stack
935        // is touched and `addu`/`sll`/`srl` never trap.
936        unsafe {
937            asm!(
938                "sll $9, $8, 2",
939                "addu $9, $9, $8",
940                "sll $10, $9, 4",
941                "addu $9, $10, $9",
942                "sll $9, $9, 2",
943                "addu $9, $9, $8",
944                "srl $8, $9, 12",
945                inlateout("$8") otz,
946                lateout("$9") _,
947                lateout("$10") _,
948                options(nostack, nomem, preserves_flags),
949            );
950        }
951        otz as u16
952    }
953    #[cfg(not(target_arch = "mips"))]
954    {
955        ((sum * 0x155) >> 12) as u16
956    }
957}
958
959/// Reload four cached projected depths into the GTE SZ FIFO and compute OTZ.
960///
961/// This is the AVSZ4 counterpart to [`average_cached_z3`]. The configured
962/// ZSF4 weight is read from GTE control register 30.
963#[inline(always)]
964pub fn average_cached_z4(depths: [u16; 4]) -> u16 {
965    #[cfg(target_arch = "mips")]
966    {
967        let mut otz = depths[0] as u32;
968        // SAFETY: MTC2 $8..$11 into SZ0..SZ3 (data 16..19), two NOPs, AVSZ4,
969        // then MFC2 OTZ (data 7) into $8 plus a load-delay NOP. Only $8 is written
970        // (`inlateout`); $9..$11 are read-only inputs; no memory or stack is
971        // touched.
972        unsafe {
973            asm!(
974                // Load SZ0..SZ3, then leave the hardware-safe two-slot MTC2
975                // commit gap before AVSZ4 consumes the final write.
976                ".word {w0}",
977                ".word {w1}",
978                ".word {w2}",
979                ".word {w3}",
980                ".word 0",
981                ".word 0",
982                ".word {w4}",
983                // MFC2 has one CPU load-delay slot.
984                ".word {w5}",
985                ".word 0",
986                w0 = const psx_hw::gte::mtc2(8, 16),
987                w1 = const psx_hw::gte::mtc2(9, 17),
988                w2 = const psx_hw::gte::mtc2(10, 18),
989                w3 = const psx_hw::gte::mtc2(11, 19),
990                w4 = const psx_hw::gte::command::AVSZ4,
991                w5 = const psx_hw::gte::mfc2(8, 7),
992                inlateout("$8") otz,
993                in("$9") depths[1] as u32,
994                in("$10") depths[2] as u32,
995                in("$11") depths[3] as u32,
996                options(nostack, nomem, preserves_flags),
997            );
998        }
999        otz as u16
1000    }
1001    #[cfg(not(target_arch = "mips"))]
1002    {
1003        write_data!(16, depths[0] as u32);
1004        write_data!(17, depths[1] as u32);
1005        write_data!(18, depths[2] as u32);
1006        write_data!(19, depths[3] as u32);
1007        // SAFETY: SZ0 through SZ3 were loaded immediately above.
1008        unsafe { ops::average_z4() };
1009        read_data!(7) as u16
1010    }
1011}
1012
1013/// Compute AVSZ3's saturated OTZ result from three cached projected depths.
1014///
1015/// This pure-software form is useful for host processing and for callers that
1016/// cannot disturb the live GTE FIFO. MIPS render loops should normally prefer
1017/// [`average_cached_z3`]. The arithmetic is exactly the GTE operation: sum the
1018/// unsigned 16-bit depths, multiply by signed `ZSF3`, shift right by 12, then
1019/// saturate to OTZ's unsigned 16-bit range.
1020#[inline]
1021#[doc(alias = "OTZ")]
1022#[doc(alias = "AverageZ3")]
1023pub fn average_z3_ordering_depth(depths: [u16; 3], zsf3: i16) -> u16 {
1024    // ZSF3 is i16 and each depth is u16, so the product reaches ~2^41: the
1025    // hardware AVSZ3 accumulates in the GTE's own wide register and this is
1026    // the software mirror of it. An i32 accumulator would wrap and hand the
1027    // ordering table a near OTZ for far geometry.
1028    // psx-numeric-allow-next-line: AVSZ3 wide accumulator, see above
1029    let sum = depths[0] as i64 + depths[1] as i64 + depths[2] as i64;
1030    // psx-numeric-allow-next-line: AVSZ3 wide accumulator
1031    ((sum * zsf3 as i64) >> 12).clamp(0, u16::MAX as i64) as u16
1032}
1033
1034/// Compute AVSZ4's saturated OTZ result from four cached projected depths.
1035///
1036/// This is the four-vertex counterpart to [`average_z3_ordering_depth`] and matches the
1037/// GTE's `AVSZ4` operation with the supplied `ZSF4` value. MIPS render loops
1038/// should normally prefer [`average_cached_z4`].
1039#[inline]
1040#[doc(alias = "OTZ")]
1041#[doc(alias = "AverageZ4")]
1042pub fn average_z4_ordering_depth(depths: [u16; 4], zsf4: i16) -> u16 {
1043    // psx-numeric-allow-next-line: AVSZ4 wide accumulator, same reasoning as average_z3_ordering_depth
1044    let sum = depths[0] as i64 + depths[1] as i64 + depths[2] as i64 + depths[3] as i64;
1045    // psx-numeric-allow-next-line: AVSZ4 wide accumulator
1046    ((sum * zsf4 as i64) >> 12).clamp(0, u16::MAX as i64) as u16
1047}
1048
1049#[inline(always)]
1050fn aabb_outer_support(mins: [i16; 3], maxs: [i16; 3], signbits: u8) -> Vec3I16 {
1051    Vec3I16::new(
1052        if signbits & 1 != 0 { mins[0] } else { maxs[0] },
1053        if signbits & 2 != 0 { mins[1] } else { maxs[1] },
1054        if signbits & 4 != 0 { mins[2] } else { maxs[2] },
1055    )
1056}
1057
1058/// `MVMVA` of V0 by the rotation matrix, no translation, `sf` clear.
1059#[cfg(target_arch = "mips")]
1060const RT_V0_NO_TRANSLATION: u32 = psx_hw::gte::mvmva(
1061    psx_hw::gte::Matrix::Rotation,
1062    psx_hw::gte::Vector::V0,
1063    psx_hw::gte::Translation::None,
1064);
1065
1066/// `MVMVA` of V0 by the light matrix, no translation, `sf` clear.
1067#[cfg(target_arch = "mips")]
1068const LLM_V0_NO_TRANSLATION: u32 = psx_hw::gte::mvmva(
1069    psx_hw::gte::Matrix::Light,
1070    psx_hw::gte::Vector::V0,
1071    psx_hw::gte::Translation::None,
1072);
1073
1074/// `MFC2 $8, MAC1 + n`.
1075#[cfg(target_arch = "mips")]
1076const fn read_mac(n: u32) -> u32 {
1077    psx_hw::gte::mfc2(8, 25 + n)
1078}
1079
1080#[cfg(target_arch = "mips")]
1081#[inline(always)]
1082fn aabb_dot_mvmva<const OP: u32, const READ_MAC: u32>(v: Vec3I16) -> i32 {
1083    let mut dot = v.xy_packed();
1084    // SAFETY: MTC2 $8/$9 into V0, two NOPs, then `OP` and `READ_MAC`. The
1085    // only instantiations (`aabb_clip_dot`) pass MVMVA encodings (`0x4a00_6012`
1086    // RT, `0x4a02_6012` LLM; cv=none, sf=0) and MFC2 of MAC1..MAC3 into $8,
1087    // so only $8 is written (`inlateout`) and no memory or stack is touched.
1088    // This private fn trusts its const arguments; any new caller must keep
1089    // `READ_MAC` writing $8 only.
1090    unsafe {
1091        asm!(
1092            ".word {w0}",
1093            ".word {w1}",
1094            // Same console-confirmed V0 commit distance as
1095            // transform_vertex_mips.
1096            ".word 0",
1097            ".word 0",
1098            ".word {op}",
1099            ".word {read_mac}",
1100            ".word 0",
1101            w0 = const psx_hw::gte::mtc2(8, 0),
1102            w1 = const psx_hw::gte::mtc2(9, 1),
1103            op = const OP,
1104            read_mac = const READ_MAC,
1105            inlateout("$8") dot,
1106            in("$9") v.z_packed(),
1107            options(nostack, nomem, preserves_flags),
1108        );
1109    }
1110    dot as i32
1111}
1112
1113#[inline(always)]
1114fn aabb_clip_dot(v: Vec3I16, _plane: &AabbClipPlane, index: usize) -> i32 {
1115    #[cfg(target_arch = "mips")]
1116    {
1117        match index {
1118            0 => aabb_dot_mvmva::<{ RT_V0_NO_TRANSLATION }, { read_mac(0) }>(v),
1119            1 => aabb_dot_mvmva::<{ RT_V0_NO_TRANSLATION }, { read_mac(1) }>(v),
1120            2 => aabb_dot_mvmva::<{ RT_V0_NO_TRANSLATION }, { read_mac(2) }>(v),
1121            3 => aabb_dot_mvmva::<{ LLM_V0_NO_TRANSLATION }, { read_mac(0) }>(v),
1122            _ => 0,
1123        }
1124    }
1125    #[cfg(not(target_arch = "mips"))]
1126    {
1127        let _ = index;
1128        _plane.normal[0] as i32 * v.x as i32
1129            + _plane.normal[1] as i32 * v.y as i32
1130            + _plane.normal[2] as i32 * v.z as i32
1131    }
1132}
1133
1134/// Classify a signed-integer AABB against four planes loaded by
1135/// [`load_aabb_clip4`].
1136///
1137/// `clip_flags` selects active planes in bits zero through three. Returns
1138/// `-1` when the box is fully outside any active plane; otherwise returns the
1139/// remaining intersecting-plane flags after fully-inside planes are cleared.
1140/// The GTE path computes the same unshifted signed Q12 dot products as six
1141/// scalar MIPS multiplications per active plane.
1142#[inline]
1143pub fn classify_aabb_clip4(
1144    mins: [i16; 3],
1145    maxs: [i16; 3],
1146    planes: &[AabbClipPlane; 4],
1147    mut clip_flags: u8,
1148) -> i32 {
1149    let mut index = 0usize;
1150    while index < 4 {
1151        let flag = 1u8 << index;
1152        if clip_flags & flag != 0 {
1153            let plane = &planes[index];
1154            let outer = aabb_outer_support(mins, maxs, plane.signbits);
1155            if aabb_clip_dot(outer, plane, index) < plane.distance {
1156                return -1;
1157            }
1158            let inner = aabb_outer_support(maxs, mins, plane.signbits);
1159            if aabb_clip_dot(inner, plane, index) >= plane.distance {
1160                clip_flags &= !flag;
1161            }
1162        }
1163        index += 1;
1164    }
1165    clip_flags as i32
1166}
1167
1168/// Return whether a signed-integer AABB is outside any selected plane loaded
1169/// by [`load_aabb_clip4`].
1170///
1171/// Always inlined: renderers call this once per candidate face inside their
1172/// selection loop, and as an out-of-line call it spent a third of its cycles
1173/// on the call itself (two arrays by value plus the plane pointer).
1174#[inline(always)]
1175pub fn is_aabb_outside_clip4(
1176    mins: [i16; 3],
1177    maxs: [i16; 3],
1178    planes: &[AabbClipPlane; 4],
1179    clip_flags: u8,
1180) -> bool {
1181    let mut index = 0usize;
1182    while index < 4 {
1183        let flag = 1u8 << index;
1184        if clip_flags & flag != 0 {
1185            let plane = &planes[index];
1186            let outer = aabb_outer_support(mins, maxs, plane.signbits);
1187            if aabb_clip_dot(outer, plane, index) < plane.distance {
1188                return true;
1189            }
1190        }
1191        index += 1;
1192    }
1193    false
1194}
1195
1196/// Signed screen-space area of a triangle -- the same value GTE `NCLIP`
1197/// writes to MAC0: `SX0*(SY1-SY2) + SX1*(SY2-SY0) + SX2*(SY0-SY1)`.
1198/// Positive = front-facing, `<= 0` = back-facing/degenerate.
1199///
1200/// Computed in software rather than via `NCLIP` on purpose: reading MAC0
1201/// immediately after `NCLIP` returns a STALE value on real PS1 hardware
1202/// (the GTE result-read hazard -- MAC0 settles a few cycles later than the
1203/// CPU reads it), which mis-culls and drops wall faces on silicon while
1204/// looking fine on every emulator. The i32 cross product is exact for
1205/// screen coordinates (|coord| <= 0x400 after clamping) and has no read
1206/// latency. Confirmed against real hardware (cortex GTE disc 2026-06-09:
1207/// NCLIP MAC0 back-to-back read is stale, +8 nops reads correct).
1208#[inline]
1209#[doc(alias = "NCLIP")]
1210#[doc(alias = "MAC0")]
1211pub fn screen_area(vertices: [(i16, i16); 3]) -> i32 {
1212    let (sx0, sy0) = (vertices[0].0 as i32, vertices[0].1 as i32);
1213    let (sx1, sy1) = (vertices[1].0 as i32, vertices[1].1 as i32);
1214    let (sx2, sy2) = (vertices[2].0 as i32, vertices[2].1 as i32);
1215    // Algebraically identical to the three-product NCLIP expansion above,
1216    // but expressed as one 2D cross product. On MIPS-I this removes one MULT
1217    // from every cached-room and model-face backface test.
1218    (sx1 - sx0) * (sy2 - sy0) - (sy1 - sy0) * (sx2 - sx0)
1219}
1220
1221/// Run a hardware-safe `NCLIP` for an already-projected triangle.
1222///
1223/// The two input NOPs and eight-instruction result distance are both required
1224/// by the console measurements documented on [`screen_area`]. This is
1225/// useful in tight indexed-model loops where the GTE would otherwise be idle.
1226#[inline(always)]
1227#[doc(alias = "NCLIP")]
1228#[doc(alias = "MAC0")]
1229pub fn screen_area_scheduled(vertices: [(i16, i16); 3]) -> i32 {
1230    #[cfg(target_arch = "mips")]
1231    {
1232        let sxy0 = pack_xy(vertices[0].0, vertices[0].1);
1233        let sxy1 = pack_xy(vertices[1].0, vertices[1].1);
1234        let mut area = pack_xy(vertices[2].0, vertices[2].1);
1235        // SAFETY: MTC2 $8..$10 into SXY0..SXY2 (data 12..14), two NOPs, NCLIP,
1236        // eight NOPs, then MFC2 MAC0 (data 24) into $10 plus a load-delay NOP.
1237        // Only $10 is written (`inlateout`); no memory or stack is touched.
1238        unsafe {
1239            asm!(
1240                // MTC2 $8/$9/$10,SXY0/SXY1/SXY2.
1241                ".word {w0}",
1242                ".word {w1}",
1243                ".word {w2}",
1244                // HWB-010/011 input-commit gap before NCLIP consumes SXY2.
1245                ".word 0",
1246                ".word 0",
1247                // NCLIP plus its hardware-confirmed MAC0 result gap.
1248                ".word {w3}",
1249                ".word 0",
1250                ".word 0",
1251                ".word 0",
1252                ".word 0",
1253                ".word 0",
1254                ".word 0",
1255                ".word 0",
1256                ".word 0",
1257                // MFC2 $10,MAC0 plus its CPU load-delay slot.
1258                ".word {w4}",
1259                ".word 0",
1260                w0 = const psx_hw::gte::mtc2(8, 12),
1261                w1 = const psx_hw::gte::mtc2(9, 13),
1262                w2 = const psx_hw::gte::mtc2(10, 14),
1263                w3 = const psx_hw::gte::command::NCLIP,
1264                w4 = const psx_hw::gte::mfc2(10, 24),
1265                in("$8") sxy0,
1266                in("$9") sxy1,
1267                inlateout("$10") area,
1268                options(nostack, nomem, preserves_flags),
1269            );
1270        }
1271        area as i32
1272    }
1273    #[cfg(not(target_arch = "mips"))]
1274    {
1275        screen_area(vertices)
1276    }
1277}
1278
1279/// Run hardware-safe `NCLIP` while unpacking one aligned model-face record.
1280///
1281/// Runtime model faces already carry three `vertex | uv << 16` corner words,
1282/// with a two-bit palette selector in bits 14..15 of the first vertex word.
1283/// The five register-only unpack instructions occupy five of NCLIP's eight
1284/// mandatory MAC0 result slots. No GTE input or result hazard is shortened.
1285#[inline(always)]
1286pub fn screen_area_and_unpack_model_face_scheduled(
1287    vertices: [(i16, i16); 3],
1288    corner_words: [u32; 3],
1289) -> (i32, [u16; 3], u8) {
1290    #[cfg(target_arch = "mips")]
1291    {
1292        let sxy0 = pack_xy(vertices[0].0, vertices[0].1);
1293        let sxy1 = pack_xy(vertices[1].0, vertices[1].1);
1294        let mut area = pack_xy(vertices[2].0, vertices[2].1);
1295        let mut uv0 = corner_words[0];
1296        let mut uv1 = corner_words[1];
1297        let mut uv2 = corner_words[2];
1298        let palette_bank: u32;
1299        // SAFETY: MTC2 $8..$10 into SXY0..SXY2, NCLIP, register-only `srl`/`andi`
1300        // on $11..$14, then MFC2 MAC0 into $10. The written registers ($10..$14)
1301        // are all declared `inlateout`/`lateout`; no memory or stack is touched.
1302        unsafe {
1303            asm!(
1304                // MTC2 SXY0..SXY2 and the hardware-confirmed input gap.
1305                ".word {w0}",
1306                ".word {w1}",
1307                ".word {w2}",
1308                ".word 0",
1309                ".word 0",
1310                ".word {w3}",
1311                // Register-only face unpacking inside NCLIP's complete
1312                // eight-instruction MAC0 result gap.
1313                "srl $14, $11, 14",
1314                "andi $14, $14, 3",
1315                "srl $11, $11, 16",
1316                "srl $12, $12, 16",
1317                "srl $13, $13, 16",
1318                ".word 0",
1319                ".word 0",
1320                ".word 0",
1321                // MFC2 MAC0 plus the CPU load-delay slot.
1322                ".word {w4}",
1323                ".word 0",
1324                w0 = const psx_hw::gte::mtc2(8, 12),
1325                w1 = const psx_hw::gte::mtc2(9, 13),
1326                w2 = const psx_hw::gte::mtc2(10, 14),
1327                w3 = const psx_hw::gte::command::NCLIP,
1328                w4 = const psx_hw::gte::mfc2(10, 24),
1329                in("$8") sxy0,
1330                in("$9") sxy1,
1331                inlateout("$10") area,
1332                inlateout("$11") uv0,
1333                inlateout("$12") uv1,
1334                inlateout("$13") uv2,
1335                lateout("$14") palette_bank,
1336                options(nostack, nomem, preserves_flags),
1337            );
1338        }
1339        (
1340            area as i32,
1341            [uv0 as u16, uv1 as u16, uv2 as u16],
1342            palette_bank as u8,
1343        )
1344    }
1345    #[cfg(not(target_arch = "mips"))]
1346    {
1347        (
1348            screen_area(vertices),
1349            [
1350                (corner_words[0] >> 16) as u16,
1351                (corner_words[1] >> 16) as u16,
1352                (corner_words[2] >> 16) as u16,
1353            ],
1354            ((corner_words[0] >> 14) & 3) as u8,
1355        )
1356    }
1357}
1358
1359/// Run hardware-safe `NCLIP` and `AVSZ3` for an already-projected indexed
1360/// triangle.
1361///
1362/// The cached screen coordinates and depths are loaded together. The three
1363/// SZ writes occupy part of the silicon-required NCLIP result gap, so callers
1364/// that need both winding and an OT key avoid paying two independent GTE
1365/// schedules. The returned area is identical to [`screen_area`], and the
1366/// depth is identical to [`average_cached_z3`] with the installed ZSF3.
1367#[inline(always)]
1368pub fn screen_area_and_average_cached_z3_scheduled(
1369    vertices: [(i16, i16); 3],
1370    depths: [u16; 3],
1371) -> (i32, u16) {
1372    #[cfg(target_arch = "mips")]
1373    {
1374        let sxy0 = pack_xy(vertices[0].0, vertices[0].1);
1375        let sxy1 = pack_xy(vertices[1].0, vertices[1].1);
1376        let mut area = pack_xy(vertices[2].0, vertices[2].1);
1377        let mut otz = depths[0] as u32;
1378        // SAFETY: MTC2 $8..$10 into SXY0..SXY2, NCLIP, MTC2 $11..$13 into
1379        // SZ1..SZ3, then MFC2 MAC0 into $10, AVSZ3, and MFC2 OTZ into $11 with a
1380        // final load-delay NOP. Only $10 and $11 are written (`inlateout`);
1381        // $12/$13 are read-only; no memory or stack is touched.
1382        unsafe {
1383            asm!(
1384                // Load SXY0..SXY2 and leave the measured input-commit gap.
1385                ".word {w0}",
1386                ".word {w1}",
1387                ".word {w2}",
1388                ".word 0",
1389                ".word 0",
1390                ".word {w3}",
1391                // Loading SZ1..SZ3 is independent work inside NCLIP's
1392                // hardware-confirmed eight-instruction MAC0 result gap.
1393                ".word {w4}",
1394                ".word {w5}",
1395                ".word {w6}",
1396                ".word 0",
1397                ".word 0",
1398                ".word 0",
1399                ".word 0",
1400                ".word 0",
1401                // Capture NCLIP's MAC0 before AVSZ3 overwrites it. AVSZ3 is
1402                // independent of the CPU load-delay result.
1403                ".word {w7}",
1404                ".word {w8}",
1405                ".word {w9}",
1406                ".word 0",
1407                w0 = const psx_hw::gte::mtc2(8, 12),
1408                w1 = const psx_hw::gte::mtc2(9, 13),
1409                w2 = const psx_hw::gte::mtc2(10, 14),
1410                w3 = const psx_hw::gte::command::NCLIP,
1411                w4 = const psx_hw::gte::mtc2(11, 17),
1412                w5 = const psx_hw::gte::mtc2(12, 18),
1413                w6 = const psx_hw::gte::mtc2(13, 19),
1414                w7 = const psx_hw::gte::mfc2(10, 24),
1415                w8 = const psx_hw::gte::command::AVSZ3,
1416                w9 = const psx_hw::gte::mfc2(11, 7),
1417                in("$8") sxy0,
1418                in("$9") sxy1,
1419                inlateout("$10") area,
1420                inlateout("$11") otz,
1421                in("$12") depths[1] as u32,
1422                in("$13") depths[2] as u32,
1423                options(nostack, nomem, preserves_flags),
1424            );
1425        }
1426        (area as i32, otz as u16)
1427    }
1428    #[cfg(not(target_arch = "mips"))]
1429    {
1430        (screen_area(vertices), average_cached_z3(depths))
1431    }
1432}
1433
1434/// Run hardware-safe `NCLIP` and compute the classic 0x155-scaled OTZ from
1435/// three cached depths without disturbing the GTE depth FIFO.
1436///
1437/// `ZSF3 = 0x155` is the historical 2,048-slot ordering-table scale used by
1438/// the classic affine path. The CPU shift-add sequence is placed entirely in
1439/// NCLIP's required MAC0 result gap, so it replaces the later AVSZ3 command
1440/// without extending the hazard schedule.
1441#[inline(always)]
1442#[doc(alias = "OTZ")]
1443pub fn screen_area_and_classic_ordering_depth3_scheduled(
1444    vertices: [(i16, i16); 3],
1445    depths: [u16; 3],
1446) -> (i32, u16) {
1447    #[cfg(target_arch = "mips")]
1448    {
1449        let sxy0 = pack_xy(vertices[0].0, vertices[0].1);
1450        let sxy1 = pack_xy(vertices[1].0, vertices[1].1);
1451        let mut area = pack_xy(vertices[2].0, vertices[2].1);
1452        let mut otz = depths[0] as u32;
1453        let depth1 = depths[1] as u32;
1454        let depth2 = depths[2] as u32;
1455        // SAFETY: MTC2 $8..$10 into SXY0..SXY2, NCLIP, ALU shift-add on
1456        // $11..$13, MFC2 MAC0 into $10 and a final `srl` into $11. Every written
1457        // register ($10..$13) is declared `inlateout` (scratch outputs discarded);
1458        // no memory or stack is touched and the ALU ops never trap.
1459        unsafe {
1460            asm!(
1461                // Load SXY0..SXY2 and leave the measured input-commit gap.
1462                ".word {w0}",
1463                ".word {w1}",
1464                ".word {w2}",
1465                ".word 0",
1466                ".word 0",
1467                // NCLIP.
1468                ".word {w3}",
1469                // Fill NCLIP's eight-instruction MAC0 result gap with the
1470                // exact sum * 0x155 sequence: 5x, 85x, then 341x.
1471                "addu $11, $11, $12",
1472                "addu $11, $11, $13",
1473                "sll $12, $11, 2",
1474                "addu $12, $12, $11",
1475                "sll $13, $12, 4",
1476                "addu $12, $13, $12",
1477                "sll $12, $12, 2",
1478                "addu $12, $12, $11",
1479                // Read MAC0 and use its CPU load-delay slot for the OTZ
1480                // scale. Neither instruction depends on the other's result.
1481                ".word {w4}",
1482                "srl $11, $12, 12",
1483                w0 = const psx_hw::gte::mtc2(8, 12),
1484                w1 = const psx_hw::gte::mtc2(9, 13),
1485                w2 = const psx_hw::gte::mtc2(10, 14),
1486                w3 = const psx_hw::gte::command::NCLIP,
1487                w4 = const psx_hw::gte::mfc2(10, 24),
1488                in("$8") sxy0,
1489                in("$9") sxy1,
1490                inlateout("$10") area,
1491                inlateout("$11") otz,
1492                inlateout("$12") depth1 => _,
1493                inlateout("$13") depth2 => _,
1494                options(nostack, nomem, preserves_flags),
1495            );
1496        }
1497        (area as i32, otz as u16)
1498    }
1499    #[cfg(not(target_arch = "mips"))]
1500    {
1501        let sum = depths[0] as u32 + depths[1] as u32 + depths[2] as u32;
1502        (screen_area(vertices), ((sum * 0x155) >> 12) as u16)
1503    }
1504}
1505
1506/// Back-face test for three already-projected screen-space vertices.
1507///
1508/// Useful when a renderer cached/projected vertices first and later wants
1509/// the signed screen-space area test for arbitrary indexed faces. Uses the
1510/// software [`screen_area`] (see its note on the NCLIP MAC0 hazard).
1511pub fn is_screen_triangle_back_facing(vertices: [(i16, i16); 3]) -> bool {
1512    screen_area(vertices) <= 0
1513}
1514
1515/// Read the GTE FLAG register. Non-zero indicates at least one error
1516/// bit fired during the last op (overflow, saturation, divide
1517/// overflow). Useful for debug prints on a frame that looks wrong.
1518#[doc(alias = "FLAG")]
1519pub fn error_flags() -> u32 {
1520    read_control!(31)
1521}
1522
1523/// Renamed to [`start_project_triple`].
1524#[deprecated(note = "renamed to `start_project_triple`")]
1525#[inline(always)]
1526pub fn rtpt_kick(v0: Vec3I16, v1: Vec3I16, v2: Vec3I16) -> ProjectTripleInFlight {
1527    start_project_triple(v0, v1, v2)
1528}
1529
1530/// Renamed to [`classic_ordering_depth3_from_sum`].
1531#[deprecated(note = "renamed to `classic_ordering_depth3_from_sum`")]
1532#[inline(always)]
1533pub fn classic_otz3_from_sum(sum: u32) -> u16 {
1534    classic_ordering_depth3_from_sum(sum)
1535}
1536
1537/// Renamed to [`is_aabb_outside_clip4`].
1538#[deprecated(note = "renamed to `is_aabb_outside_clip4`")]
1539#[inline(always)]
1540pub fn aabb_outside_clip4(
1541    mins: [i16; 3],
1542    maxs: [i16; 3],
1543    planes: &[AabbClipPlane; 4],
1544    clip_flags: u8,
1545) -> bool {
1546    is_aabb_outside_clip4(mins, maxs, planes, clip_flags)
1547}
1548
1549/// Renamed to [`screen_area_scheduled`].
1550#[deprecated(note = "renamed to `screen_area_scheduled`")]
1551#[inline(always)]
1552pub fn screen_area_mac0_scheduled(vertices: [(i16, i16); 3]) -> i32 {
1553    screen_area_scheduled(vertices)
1554}
1555
1556#[cfg(all(test, not(target_arch = "mips")))]
1557mod host_smoke {
1558    //! Smoke tests for the host-side software-GTE shim.
1559    //!
1560    //! On hardware these helpers compile to inline COP2 instructions,
1561    //! so testing them via Rust integration would require running on
1562    //! a PS1. On host they route through the per-thread Gte from
1563    //! `psx-gte-core`, which we *can* poke at directly to confirm the
1564    //! routing produces matching output.
1565    use super::*;
1566    use crate::host;
1567
1568    fn install_identity() {
1569        load_rotation(&Mat3I16::IDENTITY);
1570        load_translation(Vec3I32::ZERO);
1571        set_screen_offset(160 << 16, 120 << 16);
1572        set_projection_plane(200);
1573    }
1574
1575    #[test]
1576    fn rtps_through_host_shim_projects_an_in_front_vertex() {
1577        host::reset();
1578        install_identity();
1579        // V0 = (0, 0, 1024) -- straight ahead, depth 1024. With H=200
1580        // the GTE divides 200/sz3 (≈0x4000/sz3 internally), giving an
1581        // X/Y near the screen offset for a vertex at the origin.
1582        let projected = project_vertex(Vec3I16::new(0, 0, 1024));
1583        assert_eq!(projected.sx, 160);
1584        assert_eq!(projected.sy, 120);
1585        assert!(
1586            projected.sz > 0,
1587            "near-plane vertex must yield non-zero depth"
1588        );
1589    }
1590
1591    #[test]
1592    fn rtpt_through_host_shim_matches_three_separate_rtps_calls() {
1593        host::reset();
1594        install_identity();
1595        let a = Vec3I16::new(-256, 0, 1024);
1596        let b = Vec3I16::new(256, 0, 1024);
1597        let c = Vec3I16::new(0, 256, 1024);
1598
1599        let batch = project_triangle(a, b, c);
1600
1601        host::reset();
1602        install_identity();
1603        let p_a = project_vertex(a);
1604        let p_b = project_vertex(b);
1605        let p_c = project_vertex(c);
1606
1607        assert_eq!(batch[0], p_a);
1608        assert_eq!(batch[1], p_b);
1609        assert_eq!(batch[2], p_c);
1610    }
1611
1612    #[test]
1613    fn mvmva_transform_through_host_shim_applies_rt_and_tr() {
1614        host::reset();
1615        load_rotation(&Mat3I16::IDENTITY);
1616        load_translation(Vec3I32::new(10, -20, 30));
1617
1618        let transformed = transform_vertex(Vec3I16::new(100, 200, 300));
1619
1620        assert_eq!(transformed, Vec3I32::new(110, 180, 330));
1621    }
1622
1623    #[test]
1624    fn scheduled_rotation_compose_matches_cpu_matrix_product() {
1625        host::reset();
1626        let left = Mat3I16::rotate_z(37).mul(&Mat3I16::rotate_y(91));
1627        let right = Mat3I16::rotate_y(13)
1628            .mul(&Mat3I16::rotate_x(55))
1629            .scale_columns_q12([3072, 4096, 5120]);
1630
1631        assert_eq!(compose_rotation_scheduled(&left, &right), left.mul(&right));
1632    }
1633
1634    #[test]
1635    fn classic_normalize_matches_reference_table_results() {
1636        for (input, vector, xy_squared, squared) in [
1637            ([1, 0, 0], [4096, 0, 0], 1, 1),
1638            ([3, 4, 0], [2457, 3276, 0], 25, 25),
1639            ([10, 20, 30], [1097, 2195, 3293], 500, 1400),
1640            ([-10, 20, 30], [-1098, 2195, 3293], 500, 1400),
1641            ([100, 50, -20], [3610, 1805, -723], 12_500, 12_900),
1642            ([600, 0, 200], [3898, 0, 1299], 360_000, 400_000),
1643        ] {
1644            host::reset();
1645            let result = normalize_classic_q12_scheduled(Vec3I32::new(
1646                input[0] << 12,
1647                input[1] << 12,
1648                input[2] << 12,
1649            ));
1650            assert_eq!(
1651                result,
1652                ClassicNormalizedVector {
1653                    vector: Vec3I16::new(vector[0], vector[1], vector[2]),
1654                    xy_squared,
1655                    squared,
1656                }
1657            );
1658        }
1659
1660        host::reset();
1661        assert_eq!(
1662            normalize_classic_q12_scheduled(Vec3I32::ZERO),
1663            ClassicNormalizedVector::default()
1664        );
1665    }
1666
1667    #[test]
1668    fn scheduled_nclip_matches_software_area_on_host() {
1669        let vertices = [(-320, 112), (47, -91), (511, 230)];
1670        assert_eq!(screen_area_scheduled(vertices), screen_area(vertices));
1671    }
1672
1673    #[test]
1674    fn scheduled_nclip_face_unpack_matches_packed_record() {
1675        let vertices = [(-320, 112), (47, -91), (511, 230)];
1676        let corners = [0xabcd_c123, 0x0123_4567, 0xfedc_89ab];
1677        assert_eq!(
1678            screen_area_and_unpack_model_face_scheduled(vertices, corners),
1679            (
1680                screen_area(vertices),
1681                [0xabcd, 0x0123, 0xfedc],
1682                ((0xc123 >> 14) & 3) as u8,
1683            ),
1684        );
1685    }
1686
1687    #[test]
1688    fn cached_average_z_matches_avsz_saturation_rules() {
1689        assert_eq!(average_z3_ordering_depth([100, 200, 300], 1_365), 199);
1690        assert_eq!(average_z4_ordering_depth([100, 200, 300, 400], 1_024), 250);
1691        assert_eq!(average_z3_ordering_depth([u16::MAX; 3], i16::MAX), u16::MAX);
1692        assert_eq!(average_z4_ordering_depth([u16::MAX; 4], -1), 0);
1693
1694        set_average_z_weights(1_365, 1_024);
1695        assert_eq!(average_cached_z3([100, 200, 300]), 199);
1696        assert_eq!(average_cached_z4([100, 200, 300, 400]), 250);
1697        assert_eq!(classic_ordering_depth3_from_sum(100 + 200 + 300), 49);
1698
1699        let vertices = [(-320, 112), (47, -91), (511, 230)];
1700        assert_eq!(
1701            screen_area_and_average_cached_z3_scheduled(vertices, [100, 200, 300]),
1702            (screen_area(vertices), 199),
1703        );
1704        assert_eq!(
1705            screen_area_and_classic_ordering_depth3_scheduled(vertices, [100, 200, 300]),
1706            (screen_area(vertices), 49),
1707        );
1708    }
1709
1710    #[test]
1711    fn four_plane_aabb_clip_matches_scalar_support_points() {
1712        let plane = |normal: [i16; 3], distance| AabbClipPlane {
1713            normal,
1714            kind: 0,
1715            signbits: (normal[0] < 0) as u8
1716                | (((normal[1] < 0) as u8) << 1)
1717                | (((normal[2] < 0) as u8) << 2),
1718            distance,
1719        };
1720        let planes = [
1721            plane([4096, 1024, -512], -3000),
1722            plane([-2048, 4096, 256], 7000),
1723            plane([300, -900, 4096], -12000),
1724            plane([-700, -500, -4096], 16000),
1725        ];
1726        load_aabb_clip4(&planes);
1727
1728        let scalar = |mins: [i16; 3], maxs: [i16; 3], mut flags: u8| {
1729            for (index, plane) in planes.iter().enumerate() {
1730                let flag = 1u8 << index;
1731                if flags & flag == 0 {
1732                    continue;
1733                }
1734                let outer = [
1735                    if plane.normal[0] < 0 {
1736                        mins[0]
1737                    } else {
1738                        maxs[0]
1739                    },
1740                    if plane.normal[1] < 0 {
1741                        mins[1]
1742                    } else {
1743                        maxs[1]
1744                    },
1745                    if plane.normal[2] < 0 {
1746                        mins[2]
1747                    } else {
1748                        maxs[2]
1749                    },
1750                ];
1751                let inner = [
1752                    if plane.normal[0] < 0 {
1753                        maxs[0]
1754                    } else {
1755                        mins[0]
1756                    },
1757                    if plane.normal[1] < 0 {
1758                        maxs[1]
1759                    } else {
1760                        mins[1]
1761                    },
1762                    if plane.normal[2] < 0 {
1763                        maxs[2]
1764                    } else {
1765                        mins[2]
1766                    },
1767                ];
1768                let dot = |point: [i16; 3]| {
1769                    plane.normal[0] as i32 * point[0] as i32
1770                        + plane.normal[1] as i32 * point[1] as i32
1771                        + plane.normal[2] as i32 * point[2] as i32
1772                };
1773                if dot(outer) < plane.distance {
1774                    return -1;
1775                }
1776                if dot(inner) >= plane.distance {
1777                    flags &= !flag;
1778                }
1779            }
1780            flags as i32
1781        };
1782
1783        for (mins, maxs, flags) in [
1784            ([-10, -20, -30], [40, 50, 60], 0x0f),
1785            ([100, 200, 300], [120, 240, 360], 0x0f),
1786            ([-32000, -100, 20], [-30000, 100, 80], 0x05),
1787        ] {
1788            let expected = scalar(mins, maxs, flags);
1789            assert_eq!(classify_aabb_clip4(mins, maxs, &planes, flags), expected);
1790            assert_eq!(
1791                is_aabb_outside_clip4(mins, maxs, &planes, flags),
1792                expected < 0,
1793            );
1794        }
1795        assert_eq!(core::mem::size_of::<AabbClipPlane>(), 12);
1796        assert_eq!(core::mem::align_of::<AabbClipPlane>(), 4);
1797    }
1798
1799    /// FNV-1a 64 of `normalize_classic_q12_scheduled` over 40,000 inputs
1800    /// spread across every magnitude, including ones whose squares wrap.
1801    /// Recorded from the implementation that came before the generated
1802    /// table; the rewrite has to land on the same digest.
1803    #[test]
1804    fn classic_normalize_matches_previous_results_digest() {
1805        let mut seed = 0x1234_5678u32;
1806        let mut next = move || {
1807            seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
1808            seed
1809        };
1810        let mut hash = 0xcbf2_9ce4_8422_2325u64;
1811        let mut eat = |value: i32| {
1812            for byte in value.to_le_bytes() {
1813                hash ^= u64::from(byte);
1814                hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
1815            }
1816        };
1817        for i in 0..40_000u32 {
1818            // Shift each component right by 0..=31 bits so small, medium,
1819            // large and wrapping magnitudes all show up.
1820            let mut component = || (next() as i32) >> (next() % 32);
1821            let input = Vec3I32::new(component(), component(), component());
1822            let input = if i % 7 == 0 {
1823                Vec3I32::new(input.x, 0, 0)
1824            } else {
1825                input
1826            };
1827            host::reset();
1828            let out = normalize_classic_q12_scheduled(input);
1829            eat(i32::from(out.vector.x));
1830            eat(i32::from(out.vector.y));
1831            eat(i32::from(out.vector.z));
1832            eat(out.xy_squared);
1833            eat(out.squared);
1834        }
1835        assert_eq!(hash, 0x803b_4a0d_7ea1_0cb5);
1836    }
1837
1838    /// The table the previous implementation used, captured by running it.
1839    const PREVIOUS_TABLE: [i16; 192] = [
1840        4096, 4064, 4033, 4003, 3973, 3944, 3916, 3888, 3861, 3835, 3809, 3783, 3758, 3734, 3710,
1841        3686, 3663, 3640, 3618, 3596, 3575, 3554, 3533, 3513, 3493, 3473, 3454, 3435, 3416, 3397,
1842        3379, 3361, 3344, 3327, 3310, 3293, 3276, 3260, 3244, 3228, 3213, 3197, 3182, 3167, 3153,
1843        3138, 3124, 3110, 3096, 3082, 3069, 3055, 3042, 3029, 3016, 3003, 2991, 2978, 2966, 2954,
1844        2942, 2930, 2919, 2907, 2896, 2885, 2873, 2862, 2852, 2841, 2830, 2820, 2809, 2799, 2789,
1845        2779, 2769, 2759, 2749, 2740, 2730, 2721, 2711, 2702, 2693, 2684, 2675, 2666, 2657, 2649,
1846        2640, 2631, 2623, 2615, 2606, 2598, 2590, 2582, 2574, 2566, 2558, 2550, 2543, 2535, 2528,
1847        2520, 2513, 2505, 2498, 2491, 2484, 2477, 2469, 2462, 2456, 2449, 2442, 2435, 2428, 2422,
1848        2415, 2409, 2402, 2396, 2389, 2383, 2377, 2371, 2364, 2358, 2352, 2346, 2340, 2334, 2328,
1849        2322, 2317, 2311, 2305, 2299, 2294, 2288, 2283, 2277, 2272, 2266, 2261, 2255, 2250, 2245,
1850        2239, 2234, 2229, 2224, 2219, 2214, 2209, 2204, 2199, 2194, 2189, 2184, 2179, 2174, 2170,
1851        2165, 2160, 2155, 2151, 2146, 2142, 2137, 2133, 2128, 2124, 2119, 2115, 2110, 2106, 2102,
1852        2097, 2093, 2089, 2084, 2080, 2076, 2072, 2068, 2064, 2060, 2056, 2052,
1853    ];
1854
1855    #[test]
1856    fn generated_rsqrt_table_matches_the_previous_table() {
1857        assert_eq!(RSQRT_Q12_FROM_64, PREVIOUS_TABLE);
1858    }
1859}