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

psx_asset/
lib.rs

1// SPDX-License-Identifier: GPL-2.0-or-later
2#![cfg_attr(target_arch = "mips", feature(asm_experimental_arch))]
3//! Runtime parsers for PSoXide cooked-asset blobs.
4//!
5//! Pairs with `editor/crates/psxed`, the host-side tool that
6//! produces these files. Format structs live in `psxed-format`
7//! (shared by both sides so drift is impossible).
8//!
9//! Usage pattern:
10//!
11//! ```ignore
12//! // At compile time, embed the cooked blob into the MIPS binary.
13//! static TEAPOT: &[u8] = include_bytes!("assets/teapot.psxm");
14//!
15//! // At runtime, parse into a typed view. Zero-copy -- the view
16//! // just borrows slices into the original byte stream.
17//! let mesh = psx_asset::Mesh::from_bytes(TEAPOT).expect("cooked mesh");
18//! for tri_idx in 0..mesh.face_count() {
19//!     let (ia, ib, ic) = mesh.face(tri_idx);
20//!     let v0 = mesh.vertex(ia);
21//!     let v1 = mesh.vertex(ib);
22//!     let v2 = mesh.vertex(ic);
23//!     let (r, g, b) = mesh.face_color(tri_idx).unwrap_or((128, 128, 128));
24//!     // project + draw …
25//! }
26//! ```
27//!
28//! Design:
29//!
30//! - **Zero-copy**: `Mesh::from_bytes` borrows into the caller's
31//!   byte slice. No allocation, no memcpy; the static blob stays
32//!   where it was embedded.
33//! - **`no_std`-clean**: all parsing is manual LE decode, no
34//!   `std::io`.
35//! - **Bounds-checked**: every accessor validates its index
36//!   against the counts in the header. Malformed blobs produce
37//!   `None` rather than panics at integer level, so consumers
38//!   see errors at load time, not in the render loop.
39
40#![no_std]
41#![deny(unsafe_op_in_unsafe_fn)]
42#![warn(missing_docs)]
43
44pub mod hma1;
45pub mod hmd8;
46pub mod tracks;
47
48use psx_gte::math::{Vec3I16, Vec3I32};
49
50const MESH_VERSION_U8_INDICES: u16 = 1;
51const MESH_U8_INDEX_STRIDE: usize = 3;
52const MESH_U16_INDEX_STRIDE: usize = 6;
53
54/// Shared topology helpers for cooked world quads and wall shapes.
55pub mod world_topology {
56    pub use psxed_format::world::topology::{
57        horizontal_triangle_at_local, split_triangle, split_triangles, triangle_contains_corner,
58        wall_shape_for_dropped_corner, wall_shape_triangle, wall_shape_triangle_corners,
59        SplitTriangles, TriangleCorners, HORIZONTAL_NE_SW_TRIANGLES, HORIZONTAL_NW_SE_TRIANGLES,
60        SPLIT_ONE_THREE_TRIANGLES, SPLIT_ZERO_TWO_TRIANGLES, WHOLE_QUAD_TRIANGLE_INDEX,
61    };
62}
63
64/// World split id from north-west to south-east.
65pub const WORLD_SPLIT_NORTH_WEST_SOUTH_EAST: u8 = psxed_format::world::split::NORTH_WEST_SOUTH_EAST;
66
67/// World split id from north-east to south-west.
68pub const WORLD_SPLIT_NORTH_EAST_SOUTH_WEST: u8 = psxed_format::world::split::NORTH_EAST_SOUTH_WEST;
69
70/// Full four-corner world-wall shape.
71pub const WORLD_WALL_SHAPE_QUAD: u16 = psxed_format::world::wall_shape::QUAD;
72
73/// World-wall shape with the bottom-left corner removed.
74pub const WORLD_WALL_SHAPE_DROP_BOTTOM_LEFT: u16 =
75    psxed_format::world::wall_shape::DROP_BOTTOM_LEFT;
76
77/// World-wall shape with the bottom-right corner removed.
78pub const WORLD_WALL_SHAPE_DROP_BOTTOM_RIGHT: u16 =
79    psxed_format::world::wall_shape::DROP_BOTTOM_RIGHT;
80
81/// World-wall shape with the top-right corner removed.
82pub const WORLD_WALL_SHAPE_DROP_TOP_RIGHT: u16 = psxed_format::world::wall_shape::DROP_TOP_RIGHT;
83
84/// World-wall shape with the top-left corner removed.
85pub const WORLD_WALL_SHAPE_DROP_TOP_LEFT: u16 = psxed_format::world::wall_shape::DROP_TOP_LEFT;
86
87/// Errors `Mesh::from_bytes` can return for a malformed blob.
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub enum ParseError {
90    /// Blob shorter than the minimum header sizes.
91    Truncated,
92    /// `AssetHeader::magic` doesn't match the expected asset kind.
93    WrongMagic,
94    /// Format version newer than this parser supports.
95    UnsupportedVersion(u16),
96    /// Declared payload_len disagrees with the actual byte length.
97    InvalidPayloadLen {
98        /// Payload length declared in the common asset header.
99        declared: u32,
100        /// Actual payload byte count after the common asset header.
101        actual: usize,
102    },
103    /// Vertex or face table wouldn't fit in the remaining payload.
104    TableOverflow,
105    /// World-grid header fields are inconsistent.
106    InvalidWorldLayout,
107    /// Model header/table fields are inconsistent.
108    InvalidModelLayout,
109    /// Animation header/table fields are inconsistent.
110    InvalidAnimationLayout,
111    /// Audio header/table fields are inconsistent.
112    InvalidAudioLayout,
113}
114
115/// A parsed 3D mesh backed by slices into the caller's cooked blob.
116///
117/// Cheap to construct (just bounds-checks the header + computes
118/// sub-slice offsets). Cheap to pass around -- table `&[u8]` slices,
119/// an index stride, a flags `u16`, and the counts.
120#[derive(Copy, Clone, Debug)]
121pub struct Mesh<'a> {
122    verts: &'a [u8],
123    indices: &'a [u8],
124    face_colors: Option<&'a [u8]>,
125    vertex_normals: Option<&'a [u8]>,
126    index_stride: u8,
127    vert_count: u16,
128    face_count: u16,
129    flags: u16,
130}
131
132impl<'a> Mesh<'a> {
133    /// Parse a cooked `.psxm` blob. Returns a `Mesh` view that
134    /// borrows into `bytes`.
135    pub fn from_bytes(bytes: &'a [u8]) -> Result<Self, ParseError> {
136        // AssetHeader.
137        if bytes.len() < psxed_format::AssetHeader::SIZE {
138            return Err(ParseError::Truncated);
139        }
140        let magic: [u8; 4] = [bytes[0], bytes[1], bytes[2], bytes[3]];
141        if magic != psxed_format::mesh::MAGIC {
142            return Err(ParseError::WrongMagic);
143        }
144        let version = u16::from_le_bytes([bytes[4], bytes[5]]);
145        let index_stride = match version {
146            MESH_VERSION_U8_INDICES => MESH_U8_INDEX_STRIDE,
147            psxed_format::mesh::VERSION => MESH_U16_INDEX_STRIDE,
148            _ => return Err(ParseError::UnsupportedVersion(version)),
149        };
150        let flags = u16::from_le_bytes([bytes[6], bytes[7]]);
151        let payload_len = u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]);
152        let payload_start = psxed_format::AssetHeader::SIZE;
153        let actual_payload = bytes.len().saturating_sub(payload_start);
154        if (payload_len as usize) != actual_payload {
155            return Err(ParseError::InvalidPayloadLen {
156                declared: payload_len,
157                actual: actual_payload,
158            });
159        }
160
161        // MeshHeader.
162        if actual_payload < psxed_format::mesh::MeshHeader::SIZE {
163            return Err(ParseError::Truncated);
164        }
165        let mh = &bytes[payload_start..];
166        let vert_count = u16::from_le_bytes([mh[0], mh[1]]);
167        let face_count = u16::from_le_bytes([mh[2], mh[3]]);
168        // Skip _reserved (4 bytes).
169
170        // Slice the vertex + index + optional colour tables out.
171        let mut off = payload_start + psxed_format::mesh::MeshHeader::SIZE;
172        let vert_bytes = (vert_count as usize) * 6;
173        if off + vert_bytes > bytes.len() {
174            return Err(ParseError::TableOverflow);
175        }
176        let verts = &bytes[off..off + vert_bytes];
177        off += vert_bytes;
178
179        let index_bytes = (face_count as usize) * index_stride;
180        if off + index_bytes > bytes.len() {
181            return Err(ParseError::TableOverflow);
182        }
183        let indices = &bytes[off..off + index_bytes];
184        off += index_bytes;
185
186        let face_colors = if flags & psxed_format::mesh::flags::HAS_FACE_COLORS != 0 {
187            let color_bytes = (face_count as usize) * 3;
188            if off + color_bytes > bytes.len() {
189                return Err(ParseError::TableOverflow);
190            }
191            let slice = &bytes[off..off + color_bytes];
192            off += color_bytes;
193            Some(slice)
194        } else {
195            None
196        };
197
198        let vertex_normals = if flags & psxed_format::mesh::flags::HAS_NORMALS != 0 {
199            let normal_bytes = (vert_count as usize) * 6;
200            if off + normal_bytes > bytes.len() {
201                return Err(ParseError::TableOverflow);
202            }
203            let slice = &bytes[off..off + normal_bytes];
204            Some(slice)
205        } else {
206            None
207        };
208
209        Ok(Self {
210            verts,
211            indices,
212            face_colors,
213            vertex_normals,
214            index_stride: index_stride as u8,
215            vert_count,
216            face_count,
217            flags,
218        })
219    }
220
221    /// Vertex count.
222    #[inline]
223    pub fn vertex_count(&self) -> u16 {
224        self.vert_count
225    }
226
227    /// Renamed to [`Self::vertex_count`].
228    #[deprecated(note = "renamed to `vertex_count`")]
229    #[inline(always)]
230    pub fn vert_count(&self) -> u16 {
231        self.vertex_count()
232    }
233
234    /// Triangle count.
235    #[inline]
236    pub fn face_count(&self) -> u16 {
237        self.face_count
238    }
239
240    /// Mesh feature flags (see [`psxed_format::mesh::flags`]).
241    #[inline]
242    pub fn flags(&self) -> u16 {
243        self.flags
244    }
245
246    /// Does the blob carry a face-colour table?
247    #[inline]
248    pub fn has_face_colors(&self) -> bool {
249        self.flags & psxed_format::mesh::flags::HAS_FACE_COLORS != 0
250    }
251
252    /// Does the blob carry per-vertex normals? Required for any
253    /// GTE- or CPU-lit rendering path.
254    #[inline]
255    pub fn has_normals(&self) -> bool {
256        self.flags & psxed_format::mesh::flags::HAS_NORMALS != 0
257    }
258
259    /// Decode vertex `i` as a Q3.12 [`Vec3I16`]. Returns
260    /// [`Vec3I16::ZERO`] if the index is out of range -- keeps
261    /// the render path branch-free, callers who care can
262    /// check against [`Self::vertex_count`] first.
263    #[inline]
264    pub fn vertex(&self, i: u16) -> Vec3I16 {
265        let idx = i as usize;
266        if idx >= self.vert_count as usize {
267            return Vec3I16::ZERO;
268        }
269        let base = idx * 6;
270        let x = i16::from_le_bytes([self.verts[base], self.verts[base + 1]]);
271        let y = i16::from_le_bytes([self.verts[base + 2], self.verts[base + 3]]);
272        let z = i16::from_le_bytes([self.verts[base + 4], self.verts[base + 5]]);
273        Vec3I16::new(x, y, z)
274    }
275
276    /// Triangle `i`'s three vertex indices. Returns `(0, 0, 0)`
277    /// for an out-of-range index.
278    #[inline]
279    pub fn face(&self, i: u16) -> (u16, u16, u16) {
280        let idx = i as usize;
281        if idx >= self.face_count as usize {
282            return (0, 0, 0);
283        }
284        let base = idx * self.index_stride as usize;
285        if self.index_stride as usize == MESH_U16_INDEX_STRIDE {
286            (
287                u16::from_le_bytes([self.indices[base], self.indices[base + 1]]),
288                u16::from_le_bytes([self.indices[base + 2], self.indices[base + 3]]),
289                u16::from_le_bytes([self.indices[base + 4], self.indices[base + 5]]),
290            )
291        } else {
292            (
293                self.indices[base] as u16,
294                self.indices[base + 1] as u16,
295                self.indices[base + 2] as u16,
296            )
297        }
298    }
299
300    /// Triangle `i`'s flat colour, or `None` if the blob doesn't
301    /// carry a face-colour table.
302    #[inline]
303    pub fn face_color(&self, i: u16) -> Option<(u8, u8, u8)> {
304        let colors = self.face_colors?;
305        let idx = i as usize;
306        if idx >= self.face_count as usize {
307            return None;
308        }
309        let base = idx * 3;
310        Some((colors[base], colors[base + 1], colors[base + 2]))
311    }
312
313    /// Per-vertex Q3.12 normal. Returns `None` if the blob lacks
314    /// a normal table (`HAS_NORMALS` flag clear) or `i` is out of
315    /// range. Components are unit-length-ish (Q3.12 quantisation
316    /// introduces sub-ULP error but the GTE lighting path is
317    /// tolerant).
318    #[inline]
319    pub fn vertex_normal(&self, i: u16) -> Option<Vec3I16> {
320        let normals = self.vertex_normals?;
321        let idx = i as usize;
322        if idx >= self.vert_count as usize {
323            return None;
324        }
325        let base = idx * 6;
326        let x = i16::from_le_bytes([normals[base], normals[base + 1]]);
327        let y = i16::from_le_bytes([normals[base + 2], normals[base + 3]]);
328        let z = i16::from_le_bytes([normals[base + 4], normals[base + 5]]);
329        Some(Vec3I16::new(x, y, z))
330    }
331}
332
333/// A parsed textured 3D model backed by slices into the caller's
334/// cooked `.psxmdl` blob.
335///
336/// This is intentionally a low-level view. It exposes the tables the
337/// renderer needs -- joints, materials, rigid parts, vertices, and
338/// faces -- without allocating or converting the whole model at load
339/// time.
340#[derive(Copy, Clone, Debug)]
341pub struct Model<'a> {
342    joints: &'a [u8],
343    materials: &'a [u8],
344    parts: &'a [u8],
345    vertices: &'a [u8],
346    faces: &'a [u8],
347    face_palette_banks: Option<&'a [u8]>,
348    joint_count: u16,
349    material_count: u16,
350    part_count: u16,
351    vertex_count: u16,
352    face_count: u16,
353    texture_width: u16,
354    texture_height: u16,
355    local_to_world_q12: u16,
356    flags: u16,
357}
358
359impl<'a> Model<'a> {
360    /// Parse a cooked `.psxmdl` blob.
361    pub fn from_bytes(bytes: &'a [u8]) -> Result<Self, ParseError> {
362        use psxed_format::model::{
363            JointRecord, MaterialRecord, ModelHeader, PartRecord, FACE_RECORD_SIZE, LEGACY_VERSION,
364            MAGIC, VERSION, VERTEX_RECORD_SIZE,
365        };
366
367        if bytes.len() < psxed_format::AssetHeader::SIZE {
368            return Err(ParseError::Truncated);
369        }
370        let magic = [bytes[0], bytes[1], bytes[2], bytes[3]];
371        if magic != MAGIC {
372            return Err(ParseError::WrongMagic);
373        }
374        let version = read_u16(bytes, 4);
375        if version != LEGACY_VERSION && version != VERSION {
376            return Err(ParseError::UnsupportedVersion(version));
377        }
378        let flags = read_u16(bytes, 6);
379        let payload_len = u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]);
380        let payload_start = psxed_format::AssetHeader::SIZE;
381        let actual_payload = bytes.len().saturating_sub(payload_start);
382        if payload_len as usize != actual_payload {
383            return Err(ParseError::InvalidPayloadLen {
384                declared: payload_len,
385                actual: actual_payload,
386            });
387        }
388        if actual_payload < ModelHeader::SIZE {
389            return Err(ParseError::Truncated);
390        }
391
392        let mh = &bytes[payload_start..payload_start + ModelHeader::SIZE];
393        let joint_count = read_u16(mh, 0);
394        let part_count = read_u16(mh, 2);
395        let vertex_count = read_u16(mh, 4);
396        let face_count = read_u16(mh, 6);
397        let material_count = read_u16(mh, 8);
398        let texture_width = read_u16(mh, 10);
399        let texture_height = read_u16(mh, 12);
400        let local_to_world_q12 = read_u16(mh, 14);
401
402        let mut off = payload_start + ModelHeader::SIZE;
403
404        let joint_bytes = checked_table_bytes(joint_count, JointRecord::SIZE)?;
405        let joints = take_table(bytes, &mut off, joint_bytes)?;
406
407        let material_bytes = checked_table_bytes(material_count, MaterialRecord::SIZE)?;
408        let materials = take_table(bytes, &mut off, material_bytes)?;
409
410        let part_bytes = checked_table_bytes(part_count, PartRecord::SIZE)?;
411        let parts = take_table(bytes, &mut off, part_bytes)?;
412
413        let vertex_bytes = checked_table_bytes(vertex_count, VERTEX_RECORD_SIZE)?;
414        let vertices = take_table(bytes, &mut off, vertex_bytes)?;
415
416        let face_bytes = checked_table_bytes(face_count, FACE_RECORD_SIZE)?;
417        let faces = take_table(bytes, &mut off, face_bytes)?;
418
419        let has_face_palette_banks = flags & psxed_format::model::flags::FACE_PALETTE_BANKS != 0;
420        if version == LEGACY_VERSION && has_face_palette_banks {
421            return Err(ParseError::InvalidModelLayout);
422        }
423        let face_palette_banks = if has_face_palette_banks {
424            let bytes_needed = psxed_format::model::face_palette_bank_bytes(face_count);
425            Some(take_table(bytes, &mut off, bytes_needed)?)
426        } else {
427            None
428        };
429
430        if off != bytes.len() {
431            return Err(ParseError::InvalidModelLayout);
432        }
433        validate_model_parts(parts, joint_count, material_count, vertex_count, face_count)?;
434        validate_model_faces(faces, vertex_count)?;
435
436        Ok(Self {
437            joints,
438            materials,
439            parts,
440            vertices,
441            faces,
442            face_palette_banks,
443            joint_count,
444            material_count,
445            part_count,
446            vertex_count,
447            face_count,
448            texture_width,
449            texture_height,
450            local_to_world_q12,
451            flags,
452        })
453    }
454
455    /// Model feature flags (see [`psxed_format::model::flags`]).
456    #[inline]
457    pub fn flags(&self) -> u16 {
458        self.flags
459    }
460
461    /// Whether this model should render double-sided (no backface
462    /// culling). Set by the cooker for hollow / open-faced models.
463    #[inline]
464    pub fn is_double_sided(&self) -> bool {
465        self.flags & psxed_format::model::flags::DOUBLE_SIDED != 0
466    }
467
468    /// Number of joint records.
469    #[inline]
470    pub fn joint_count(&self) -> u16 {
471        self.joint_count
472    }
473
474    /// Number of material records.
475    #[inline]
476    pub fn material_count(&self) -> u16 {
477        self.material_count
478    }
479
480    /// Number of rigid part records.
481    #[inline]
482    pub fn part_count(&self) -> u16 {
483        self.part_count
484    }
485
486    /// Number of vertex records.
487    #[inline]
488    pub fn vertex_count(&self) -> u16 {
489        self.vertex_count
490    }
491
492    /// Number of triangle records.
493    #[inline]
494    pub fn face_count(&self) -> u16 {
495        self.face_count
496    }
497
498    /// Primary texture width in texels.
499    #[inline]
500    pub fn texture_width(&self) -> u16 {
501        self.texture_width
502    }
503
504    /// Primary texture height in texels.
505    #[inline]
506    pub fn texture_height(&self) -> u16 {
507        self.texture_height
508    }
509
510    /// Distance from the model origin down to the lowest bind-pose vertex,
511    /// in MODEL units (the vertex table's own units). Scale it with the same
512    /// local-to-world scale the mesh is drawn with and the feet land exactly
513    /// on the floor point; scaling it separately (or pre-scaling here) loses
514    /// up to a unit per rounding and leaves the feet hovering.
515    ///
516    /// Model space is Y-up; the origin is wherever the importer normalised it
517    /// (usually near, but not exactly at, mid-height), so this replaces the
518    /// "half of the authored height" guess.
519    pub fn bind_pose_floor_lift(&self) -> i32 {
520        let mut lowest = i32::MAX;
521        let mut i = 0u16;
522        while i < self.vertex_count() {
523            if let Some(vertex) = self.vertex(i) {
524                lowest = lowest.min(vertex.position.y as i32);
525            }
526            i = i.wrapping_add(1);
527            if i == 0 {
528                break;
529            }
530        }
531        if lowest == i32::MAX || lowest >= 0 {
532            return 0;
533        }
534        -lowest
535    }
536
537    /// Suggested uniform scale from model-local units to engine world units.
538    ///
539    /// `0x1000` is identity. Older blobs may store zero in the reserved
540    /// header slot; those are treated as identity.
541    #[inline]
542    pub fn local_to_world_q12(&self) -> u16 {
543        if self.local_to_world_q12 == 0 {
544            psxed_format::model::DEFAULT_LOCAL_TO_WORLD_Q12
545        } else {
546            self.local_to_world_q12
547        }
548    }
549
550    /// Joint record by index.
551    #[inline]
552    pub fn joint(&self, index: u16) -> Option<ModelJoint> {
553        if index >= self.joint_count {
554            return None;
555        }
556        let base = index as usize * psxed_format::model::JointRecord::SIZE;
557        let bytes = self
558            .joints
559            .get(base..base + psxed_format::model::JointRecord::SIZE)?;
560        Some(ModelJoint {
561            parent: read_u16(bytes, 0),
562        })
563    }
564
565    /// Material record by index.
566    #[inline]
567    pub fn material(&self, index: u16) -> Option<ModelMaterial> {
568        if index >= self.material_count {
569            return None;
570        }
571        let base = index as usize * psxed_format::model::MaterialRecord::SIZE;
572        let bytes = self
573            .materials
574            .get(base..base + psxed_format::model::MaterialRecord::SIZE)?;
575        Some(ModelMaterial {
576            texture_index: read_u16(bytes, 0),
577            flags: read_u16(bytes, 2),
578            base_color: [bytes[4], bytes[5], bytes[6], bytes[7]],
579        })
580    }
581
582    /// Rigid part record by index.
583    #[inline]
584    pub fn part(&self, index: u16) -> Option<ModelPart> {
585        if index >= self.part_count {
586            return None;
587        }
588        let base = index as usize * psxed_format::model::PartRecord::SIZE;
589        let bytes = self
590            .parts
591            .get(base..base + psxed_format::model::PartRecord::SIZE)?;
592        Some(ModelPart {
593            joint_index: read_u16(bytes, 0),
594            first_vertex: read_u16(bytes, 2),
595            vertex_count: read_u16(bytes, 4),
596            first_face: read_u16(bytes, 6),
597            face_count: read_u16(bytes, 8),
598            material_index: read_u16(bytes, 10),
599        })
600    }
601
602    /// Vertex record by global vertex index.
603    #[inline]
604    pub fn vertex(&self, index: u16) -> Option<ModelVertex> {
605        if index >= self.vertex_count {
606            return None;
607        }
608        let base = index as usize * psxed_format::model::VERTEX_RECORD_SIZE;
609        let bytes = self
610            .vertices
611            .get(base..base + psxed_format::model::VERTEX_RECORD_SIZE)?;
612        Some(ModelVertex {
613            position: Vec3I16::new(read_i16(bytes, 0), read_i16(bytes, 2), read_i16(bytes, 4)),
614            joint1: bytes[6],
615            blend: bytes[7],
616        })
617    }
618
619    /// Textured triangle by global face index.
620    #[inline]
621    pub fn face(&self, index: u16) -> Option<ModelFace> {
622        if index >= self.face_count {
623            return None;
624        }
625        let base = index as usize * psxed_format::model::FACE_RECORD_SIZE;
626        let bytes = self
627            .faces
628            .get(base..base + psxed_format::model::FACE_RECORD_SIZE)?;
629        Some(ModelFace {
630            corners: [
631                ModelFaceCorner {
632                    vertex_index: read_u16(bytes, 0),
633                    uv: (bytes[2], bytes[3]),
634                },
635                ModelFaceCorner {
636                    vertex_index: read_u16(bytes, 4),
637                    uv: (bytes[6], bytes[7]),
638                },
639                ModelFaceCorner {
640                    vertex_index: read_u16(bytes, 8),
641                    uv: (bytes[10], bytes[11]),
642                },
643            ],
644        })
645    }
646
647    /// 4bpp CLUT bank selected by a model face.
648    ///
649    /// Legacy and ordinary single-palette models return bank zero. `None`
650    /// means the face index is outside the model.
651    #[inline]
652    pub fn face_palette_bank(&self, index: u16) -> Option<u8> {
653        if index >= self.face_count {
654            return None;
655        }
656        let Some(packed) = self.face_palette_banks else {
657            return Some(0);
658        };
659        let byte = *packed.get(index as usize / 4)?;
660        Some((byte >> ((index as usize & 3) * 2)) & 3)
661    }
662
663    /// Number of consecutive 16-entry CLUT banks referenced by this model.
664    pub fn palette_bank_count(&self) -> u8 {
665        let mut highest = 0u8;
666        let mut index = 0u16;
667        while index < self.face_count {
668            highest = highest.max(self.face_palette_bank(index).unwrap_or(0));
669            index += 1;
670        }
671        highest + 1
672    }
673}
674
675/// Decoded model joint record.
676#[derive(Copy, Clone, Debug, PartialEq, Eq)]
677pub struct ModelJoint {
678    parent: u16,
679}
680
681impl ModelJoint {
682    /// Parent joint index, or `None` for a root joint.
683    #[inline]
684    pub fn parent(&self) -> Option<u16> {
685        if self.parent == psxed_format::model::NO_JOINT {
686            None
687        } else {
688            Some(self.parent)
689        }
690    }
691}
692
693/// Decoded model material record.
694#[derive(Copy, Clone, Debug, PartialEq, Eq)]
695pub struct ModelMaterial {
696    texture_index: u16,
697    flags: u16,
698    base_color: [u8; 4],
699}
700
701impl ModelMaterial {
702    /// Texture slot index.
703    #[inline]
704    pub fn texture_index(&self) -> u16 {
705        self.texture_index
706    }
707
708    /// Material flags.
709    #[inline]
710    pub fn flags(&self) -> u16 {
711        self.flags
712    }
713
714    /// Base colour/tint as RGBA8.
715    #[inline]
716    pub fn base_color(&self) -> [u8; 4] {
717        self.base_color
718    }
719}
720
721/// Decoded rigid part record.
722#[derive(Copy, Clone, Debug, PartialEq, Eq)]
723pub struct ModelPart {
724    joint_index: u16,
725    first_vertex: u16,
726    vertex_count: u16,
727    first_face: u16,
728    face_count: u16,
729    material_index: u16,
730}
731
732impl ModelPart {
733    /// Empty part used for fixed static/runtime pools.
734    pub const ZERO: Self = Self {
735        joint_index: 0,
736        first_vertex: 0,
737        vertex_count: 0,
738        first_face: 0,
739        face_count: 0,
740        material_index: 0,
741    };
742
743    /// Joint whose animation pose applies to this part.
744    #[inline]
745    pub fn joint_index(&self) -> u16 {
746        self.joint_index
747    }
748
749    /// First global vertex owned by this part.
750    #[inline]
751    pub fn first_vertex(&self) -> u16 {
752        self.first_vertex
753    }
754
755    /// Number of vertices owned by this part.
756    #[inline]
757    pub fn vertex_count(&self) -> u16 {
758        self.vertex_count
759    }
760
761    /// First global triangle owned by this part.
762    #[inline]
763    pub fn first_face(&self) -> u16 {
764        self.first_face
765    }
766
767    /// Number of triangles owned by this part.
768    #[inline]
769    pub fn face_count(&self) -> u16 {
770        self.face_count
771    }
772
773    /// Material slot used by this part.
774    #[inline]
775    pub fn material_index(&self) -> u16 {
776        self.material_index
777    }
778}
779
780/// Sentinel value for [`ModelVertex::joint1`] meaning "no secondary
781/// blend bone". Re-exported from `psxed_format::model` so runtime
782/// code does not need to depend on the editor crate.
783pub const NO_JOINT8: u8 = psxed_format::model::NO_JOINT8;
784
785/// Decoded textured model vertex.
786/// Word alignment lets the GTE projection path load XY in one MIPS load.
787/// These are decoded records, not a view into the cooked byte format.
788#[repr(C, align(4))]
789#[derive(Copy, Clone, Debug, PartialEq, Eq)]
790pub struct ModelVertex {
791    /// Model-local position. The cooked importer may use a much denser
792    /// scale here than world/grid units; use [`Model::local_to_world_q12`]
793    /// when placing the model directly into world space.
794    pub position: Vec3I16,
795    /// Secondary blend joint, or [`NO_JOINT8`] when this vertex is
796    /// single-bone.
797    pub joint1: u8,
798    /// Weight of `joint1` for view-space blending (0..=255). Zero
799    /// signals the renderer to stay on the single-bone GTE fast path.
800    pub blend: u8,
801}
802
803// Alignment must not grow the resident vertex pools.
804const _: () = assert!(core::mem::size_of::<ModelVertex>() == 8);
805
806impl ModelVertex {
807    /// Empty vertex record used by fixed-size runtime decode pools.
808    pub const ZERO: Self = Self {
809        position: Vec3I16::ZERO,
810        joint1: NO_JOINT8,
811        blend: 0,
812    };
813
814    /// `true` when this vertex needs the two-bone blend render path.
815    #[inline]
816    pub fn is_blend(&self) -> bool {
817        self.blend != 0 && self.joint1 != NO_JOINT8
818    }
819}
820
821/// One textured triangle corner in a cooked model face.
822#[derive(Copy, Clone, Debug, PartialEq, Eq)]
823pub struct ModelFaceCorner {
824    /// Global skinned vertex index.
825    pub vertex_index: u16,
826    /// 8-bit texture coordinate for this face corner.
827    pub uv: (u8, u8),
828}
829
830/// Decoded textured model face.
831#[derive(Copy, Clone, Debug, PartialEq, Eq)]
832pub struct ModelFace {
833    /// Three triangle corners in packet order.
834    pub corners: [ModelFaceCorner; 3],
835}
836
837/// A parsed rigid-skeletal animation backed by slices into the
838/// caller's cooked `.psxanim` blob.
839#[derive(Copy, Clone, Debug)]
840pub struct Animation<'a> {
841    pose_indices: &'a [u8],
842    /// Pose table of v1 to v5 clips; the whole blob for a v6 clip.
843    poses: &'a [u8],
844    joint_count: u16,
845    frame_count: u16,
846    sample_rate_hz: u16,
847    /// Bytes of one pose record, or [`TRACKS_MARK`] for a v6 keyed-track clip.
848    pose_record_size: usize,
849    translation_shift: u8,
850    tracks: Option<tracks::Tracks>,
851}
852
853/// `pose_record_size` of a v6 clip, which has no pose records.
854const TRACKS_MARK: usize = 0;
855
856impl<'a> Animation<'a> {
857    /// Parse a cooked `.psxanim` blob.
858    pub fn from_bytes(bytes: &'a [u8]) -> Result<Self, ParseError> {
859        use psxed_format::animation::{
860            AnimationHeader, MAGIC, POSE_RECORD_SIZE, POSE_RECORD_SIZE_V1, POSE_RECORD_SIZE_V3,
861            POSE_RECORD_SIZE_V4, VERSION, VERSION_V1, VERSION_V3, VERSION_V4, VERSION_V5,
862            VERSION_V6,
863        };
864
865        if bytes.len() < psxed_format::AssetHeader::SIZE {
866            return Err(ParseError::Truncated);
867        }
868        let magic = [bytes[0], bytes[1], bytes[2], bytes[3]];
869        if magic != MAGIC {
870            return Err(ParseError::WrongMagic);
871        }
872        let version = read_u16(bytes, 4);
873        let pose_record_size = match version {
874            VERSION => POSE_RECORD_SIZE,
875            VERSION_V1 => POSE_RECORD_SIZE_V1,
876            VERSION_V3 => POSE_RECORD_SIZE_V3,
877            VERSION_V4 | VERSION_V5 => POSE_RECORD_SIZE_V4,
878            VERSION_V6 => TRACKS_MARK,
879            _ => {
880                return Err(ParseError::UnsupportedVersion(version));
881            }
882        };
883        let payload_len = u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]);
884        let payload_start = psxed_format::AssetHeader::SIZE;
885        let actual_payload = bytes.len().saturating_sub(payload_start);
886        if payload_len as usize != actual_payload {
887            return Err(ParseError::InvalidPayloadLen {
888                declared: payload_len,
889                actual: actual_payload,
890            });
891        }
892        if actual_payload < AnimationHeader::SIZE {
893            return Err(ParseError::Truncated);
894        }
895
896        let ah = &bytes[payload_start..payload_start + AnimationHeader::SIZE];
897        let joint_count = read_u16(ah, 0);
898        let frame_count = read_u16(ah, 2);
899        let sample_rate_hz = read_u16(ah, 4);
900        let translation_shift = if version == VERSION
901            || version == VERSION_V3
902            || version == VERSION_V4
903            || version == VERSION_V5
904            || version == VERSION_V6
905        {
906            let shift = read_u16(ah, 6);
907            if shift > 15 {
908                return Err(ParseError::InvalidAnimationLayout);
909            }
910            shift as u8
911        } else {
912            0
913        };
914        if joint_count == 0 || frame_count == 0 || sample_rate_hz == 0 {
915            return Err(ParseError::InvalidAnimationLayout);
916        }
917
918        if version == VERSION_V6 {
919            let tracks = tracks::validate(bytes, joint_count, frame_count, translation_shift)?;
920            return Ok(Self {
921                pose_indices: &[],
922                poses: bytes,
923                joint_count,
924                frame_count,
925                sample_rate_hz,
926                pose_record_size: TRACKS_MARK,
927                translation_shift,
928                tracks: Some(tracks),
929            });
930        }
931
932        let mut off = payload_start + AnimationHeader::SIZE;
933        let pose_count = (joint_count as usize)
934            .checked_mul(frame_count as usize)
935            .ok_or(ParseError::TableOverflow)?;
936        let (pose_indices, poses) = if version == VERSION_V5 {
937            let index_bytes = pose_count.checked_mul(2).ok_or(ParseError::TableOverflow)?;
938            let indices = take_table(bytes, &mut off, index_bytes)?;
939            off = (off + 3) & !3;
940            let poses = bytes.get(off..).ok_or(ParseError::Truncated)?;
941            if poses.is_empty() || poses.len() % POSE_RECORD_SIZE_V4 != 0 {
942                return Err(ParseError::InvalidAnimationLayout);
943            }
944            let records = poses.len() / POSE_RECORD_SIZE_V4;
945            for index in indices.chunks_exact(2) {
946                if read_u16(index, 0) as usize >= records {
947                    return Err(ParseError::InvalidAnimationLayout);
948                }
949            }
950            (indices, poses)
951        } else {
952            let pose_bytes = pose_count
953                .checked_mul(pose_record_size)
954                .ok_or(ParseError::TableOverflow)?;
955            let poses = take_table(bytes, &mut off, pose_bytes)?;
956            if off != bytes.len() {
957                return Err(ParseError::InvalidAnimationLayout);
958            }
959            (&[][..], poses)
960        };
961
962        Ok(Self {
963            pose_indices,
964            poses,
965            joint_count,
966            frame_count,
967            sample_rate_hz,
968            pose_record_size,
969            translation_shift,
970            tracks: None,
971        })
972    }
973
974    /// `true` for a v6 clip of per-joint keyed tracks.
975    #[inline]
976    pub fn is_keyed_tracks(&self) -> bool {
977        self.tracks.is_some()
978    }
979
980    /// Number of joint poses per frame.
981    #[inline]
982    pub fn joint_count(&self) -> u16 {
983        self.joint_count
984    }
985
986    /// Number of sampled frames.
987    #[inline]
988    pub fn frame_count(&self) -> u16 {
989        self.frame_count
990    }
991
992    /// Integer sample rate in Hz.
993    #[inline]
994    pub fn sample_rate_hz(&self) -> u16 {
995        self.sample_rate_hz
996    }
997
998    /// Byte size of one stored pose record.
999    #[inline]
1000    pub fn pose_record_size(&self) -> usize {
1001        self.pose_record_size
1002    }
1003
1004    /// Shared right shift used by compact v2 stored translations.
1005    #[inline]
1006    pub fn translation_shift(&self) -> u8 {
1007        self.translation_shift
1008    }
1009
1010    /// Q12 sampled-frame phase advance for one playback tick.
1011    ///
1012    /// `playback_hz` is the caller's update cadence. For example,
1013    /// a 15 Hz cooked clip played by a 30 Hz update loop advances by
1014    /// half a sampled frame per tick (`0x0800`).
1015    #[inline]
1016    pub fn phase_step_q12(&self, playback_hz: u16) -> u32 {
1017        ((self.sample_rate_hz as u32) << 12) / playback_hz.max(1) as u32
1018    }
1019
1020    /// Convert a fixed-rate playback tick to a Q12 sampled-frame phase.
1021    ///
1022    /// This is a convenience for frame-locked demos. More advanced
1023    /// scenes can accumulate [`Animation::phase_step_q12`] themselves
1024    /// when playback speed, pausing, or elapsed-time correction matters.
1025    #[inline]
1026    pub fn phase_at_tick_q12(&self, playback_tick: u32, playback_hz: u16) -> u32 {
1027        playback_tick.wrapping_mul(self.phase_step_q12(playback_hz))
1028    }
1029
1030    /// Like [`Animation::phase_at_tick_q12`] but scales the advance by a
1031    /// Q8 speed multiplier (`256 = 1.0x`): `< 256` plays slower, `> 256`
1032    /// faster. Scaling the per-tick step rather than the accumulated
1033    /// phase keeps looping wrap-around identical to unscaled playback.
1034    #[inline]
1035    pub fn phase_at_tick_scaled_q12(
1036        &self,
1037        playback_tick: u32,
1038        playback_hz: u16,
1039        speed_q8: u16,
1040    ) -> u32 {
1041        // `step * speed_q8 / 256` in u32: the high byte of the step scales
1042        // whole, the low byte contributes its floored share, and the sum
1043        // equals the floor of the full product over 256 (wrapping like the
1044        // former u64 form's `as u32`).
1045        let step = self.phase_step_q12(playback_hz);
1046        let speed = u32::from(speed_q8);
1047        let scaled_step = (step >> 8)
1048            .wrapping_mul(speed)
1049            .wrapping_add(((step & 0xff) * speed) >> 8);
1050        playback_tick.wrapping_mul(scaled_step)
1051    }
1052
1053    /// Joint pose at `frame_index`, `joint_index`.
1054    pub fn pose(&self, frame_index: u16, joint_index: u16) -> Option<JointPose> {
1055        if frame_index >= self.frame_count || joint_index >= self.joint_count {
1056            return None;
1057        }
1058        if let Some(tracks) = &self.tracks {
1059            let pos = tracks::track_pos(self.poses, u32::from(frame_index) << 8);
1060            // SAFETY: `tracks` came from `validate` for this blob and the joint
1061            // index was checked above.
1062            return Some(unsafe { tracks::joint_pose(tracks, joint_index as usize, &pos) });
1063        }
1064        let base = frame_index as usize * self.joint_count as usize * self.pose_record_size;
1065        // SAFETY: both indices were checked above. `from_bytes` validates
1066        // the complete frame/joint table before constructing `Animation`.
1067        Some(unsafe { self.pose_at_frame_offset_unchecked(base, joint_index) })
1068    }
1069
1070    #[inline]
1071    fn record_offset(&self, logical_offset: usize) -> usize {
1072        if self.pose_indices.is_empty() {
1073            logical_offset
1074        } else {
1075            // Dictionary clips use 16-byte records. The parser checked every
1076            // index before any unchecked pose sampling can reach this table.
1077            usize::from(read_u16(self.pose_indices, logical_offset >> 3)) << 4
1078        }
1079    }
1080
1081    /// Decode the joint record `joint_index` of the frame starting at
1082    /// logical byte offset `frame_offset`.
1083    ///
1084    /// # Safety
1085    /// `frame_offset` must be `frame * joint_count * pose_record_size` for a
1086    /// frame `< frame_count`, and `joint_index < joint_count`. `from_bytes`
1087    /// sized `poses` (or validated every dictionary index) so that such a
1088    /// record lies wholly inside `poses`.
1089    #[inline]
1090    unsafe fn pose_at_frame_offset_unchecked(
1091        &self,
1092        frame_offset: usize,
1093        joint_index: u16,
1094    ) -> JointPose {
1095        let base = self.record_offset(frame_offset + joint_index as usize * self.pose_record_size);
1096        if self.poses.as_ptr() as usize & 1 != 0 {
1097            // SAFETY: per this fn's `# Safety` section the whole record at
1098            // `base` is inside `poses`; the byte decoder needs no alignment.
1099            return unsafe { self.pose_at_byte_offset_unaligned(base) };
1100        }
1101        if self.pose_record_size == psxed_format::animation::POSE_RECORD_SIZE_V4 {
1102            // SAFETY: the record is `POSE_RECORD_SIZE_V4` (16) bytes and lies
1103            // inside `poses` per this fn's `# Safety` section, so `base + 16`
1104            // is in bounds; `pose_v4_unchecked` checks alignment itself.
1105            return unsafe { self.pose_v4_unchecked(base) };
1106        }
1107        if self.pose_record_size == psxed_format::animation::POSE_RECORD_SIZE_V3 {
1108            // SAFETY: the record is `POSE_RECORD_SIZE_V3` (20) bytes and lies
1109            // inside `poses` per this fn's `# Safety` section, so `base + 20`
1110            // is in bounds; `pose_v3_unchecked` checks alignment itself.
1111            return unsafe { self.pose_v3_unchecked(base) };
1112        }
1113        // Only v1 (30-byte) and v2 (24-byte) records reach here. Both are
1114        // non-dictionary, so `base` is a multiple of an even record size,
1115        // and `poses` is 2-byte aligned (checked above): every i16 below is
1116        // aligned. The record covers bytes `base..base + 24` at least.
1117        // SAFETY: the 18-byte matrix at `base` is inside the in-bounds record
1118        // (this fn's `# Safety` section) and 2-byte aligned as argued above.
1119        let matrix = unsafe { read_pose_matrix_aligned_unchecked(self.poses, base) };
1120        let off = 18;
1121        let translation = if self.pose_record_size == psxed_format::animation::POSE_RECORD_SIZE {
1122            // v2 records are 24 bytes, so `base + 18..base + 24` is inside
1123            // the in-bounds record, and each offset is even on a 2-byte-aligned
1124            // pool.
1125            Vec3I32::new(
1126                decode_packed_translation(
1127                    // SAFETY: bytes `base + 18..base + 20` of the 24-byte record, even offset.
1128                    unsafe { read_i16_aligned_unchecked(self.poses, base + off) },
1129                    self.translation_shift,
1130                ),
1131                decode_packed_translation(
1132                    // SAFETY: bytes `base + 20..base + 22` of the 24-byte record, even offset.
1133                    unsafe { read_i16_aligned_unchecked(self.poses, base + off + 2) },
1134                    self.translation_shift,
1135                ),
1136                decode_packed_translation(
1137                    // SAFETY: bytes `base + 22..base + 24` of the 24-byte record, even offset.
1138                    unsafe { read_i16_aligned_unchecked(self.poses, base + off + 4) },
1139                    self.translation_shift,
1140                ),
1141            )
1142        } else {
1143            // v1 records are 30 bytes: three byte-wise i32 reads at
1144            // `base + 18..base + 30`, all inside the in-bounds record.
1145            Vec3I32::new(
1146                // SAFETY: bytes `base + 18..base + 22` of the v1 record.
1147                unsafe { read_i32_unchecked(self.poses, base + off) },
1148                // SAFETY: bytes `base + 22..base + 26` of the v1 record.
1149                unsafe { read_i32_unchecked(self.poses, base + off + 4) },
1150                // SAFETY: bytes `base + 26..base + 30` of the v1 record.
1151                unsafe { read_i32_unchecked(self.poses, base + off + 8) },
1152            )
1153        };
1154        JointPose {
1155            matrix,
1156            translation,
1157        }
1158    }
1159
1160    /// Decode one v3 (Q11-packed) record: rotation block at +0,
1161    /// shifted i16 translations at +14.
1162    ///
1163    /// Shipping assets are word-aligned by both the generated static wrapper
1164    /// and the persistent CD asset pool. That path reads the complete 20-byte
1165    /// record as five words; generic callers can still pass an arbitrarily
1166    /// aligned byte slice and use the byte-exact fallback.
1167    ///
1168    /// # Safety
1169    /// `base + 20` must be in bounds.
1170    unsafe fn pose_v3_unchecked(&self, base: usize) -> JointPose {
1171        // SAFETY: `base + 20 <= poses.len()` (this fn's `# Safety` section),
1172        // so `base` is within the allocation.
1173        let record = unsafe { self.poses.as_ptr().add(base) };
1174        let (matrix, packed_translation) = if record as usize & 3 == 0 {
1175            // SAFETY: `base + 20` is in bounds and the record pointer was just
1176            // checked to be word aligned.
1177            unsafe { read_pose_v3_word_aligned_unchecked(self.poses, base) }
1178        } else {
1179            // SAFETY: needs `base + 14` in bounds; `base + 20` is.
1180            let matrix = unsafe { read_pose_matrix_q11_unchecked(self.poses, base) };
1181            let off = psxed_format::animation::POSE_ROTATION_BLOCK_SIZE_V3;
1182            let translation = Vec3I16::new(
1183                // SAFETY: bytes `base + 14..base + 16`, inside `base + 20`.
1184                unsafe { read_i16_unchecked(self.poses, base + off) },
1185                // SAFETY: bytes `base + 16..base + 18`, inside `base + 20`.
1186                unsafe { read_i16_unchecked(self.poses, base + off + 2) },
1187                // SAFETY: bytes `base + 18..base + 20`, inside `base + 20`.
1188                unsafe { read_i16_unchecked(self.poses, base + off + 4) },
1189            );
1190            (matrix, translation)
1191        };
1192        let translation = Vec3I32::new(
1193            decode_packed_translation(packed_translation.x, self.translation_shift),
1194            decode_packed_translation(packed_translation.y, self.translation_shift),
1195            decode_packed_translation(packed_translation.z, self.translation_shift),
1196        );
1197        JointPose {
1198            matrix,
1199            translation,
1200        }
1201    }
1202
1203    /// Decode one v4 record: two packed basis vectors plus correction at +0,
1204    /// followed by shifted `i16` translations at +10.
1205    ///
1206    /// # Safety
1207    /// `base + 16` must be in bounds.
1208    unsafe fn pose_v4_unchecked(&self, base: usize) -> JointPose {
1209        // SAFETY: `base + 16 <= poses.len()` (this fn's `# Safety` section),
1210        // so `base` is within the allocation.
1211        let record = unsafe { self.poses.as_ptr().add(base) };
1212        let (matrix, packed_translation) = if record as usize & 3 == 0 {
1213            // SAFETY: `base + 16` is in bounds and the record pointer was just
1214            // checked to be word aligned.
1215            unsafe { read_pose_v4_word_aligned_unchecked(self.poses, base) }
1216        } else {
1217            // SAFETY: needs `base + 10` in bounds; `base + 16` is.
1218            let matrix = unsafe { read_pose_matrix_q11_cross_unchecked(self.poses, base) };
1219            let off = psxed_format::animation::POSE_ROTATION_BLOCK_SIZE_V4;
1220            let translation = Vec3I16::new(
1221                // SAFETY: bytes `base + 10..base + 12`, inside `base + 16`.
1222                unsafe { read_i16_unchecked(self.poses, base + off) },
1223                // SAFETY: bytes `base + 12..base + 14`, inside `base + 16`.
1224                unsafe { read_i16_unchecked(self.poses, base + off + 2) },
1225                // SAFETY: bytes `base + 14..base + 16`, inside `base + 16`.
1226                unsafe { read_i16_unchecked(self.poses, base + off + 4) },
1227            );
1228            (matrix, translation)
1229        };
1230        JointPose {
1231            matrix,
1232            translation: Vec3I32::new(
1233                decode_packed_translation(packed_translation.x, self.translation_shift),
1234                decode_packed_translation(packed_translation.y, self.translation_shift),
1235                decode_packed_translation(packed_translation.z, self.translation_shift),
1236            ),
1237        }
1238    }
1239
1240    /// Byte-wise decode of the record at `base`, for pools with no
1241    /// alignment guarantee.
1242    ///
1243    /// # Safety
1244    /// The whole `pose_record_size`-byte record at `base` must lie inside
1245    /// `poses`.
1246    #[inline(never)]
1247    unsafe fn pose_at_byte_offset_unaligned(&self, base: usize) -> JointPose {
1248        if self.pose_record_size == psxed_format::animation::POSE_RECORD_SIZE_V4 {
1249            // SAFETY: the 16-byte record is in bounds per this fn's `# Safety`.
1250            return unsafe { self.pose_v4_unchecked(base) };
1251        }
1252        if self.pose_record_size == psxed_format::animation::POSE_RECORD_SIZE_V3 {
1253            // SAFETY: the 20-byte record is in bounds per this fn's `# Safety`.
1254            return unsafe { self.pose_v3_unchecked(base) };
1255        }
1256        // Only v1 (30-byte) and v2 (24-byte) records reach here.
1257        // SAFETY: the 18-byte matrix lies inside the in-bounds record;
1258        // `read_pose_matrix_unchecked` reads byte-wise, no alignment needed.
1259        let matrix = unsafe { read_pose_matrix_unchecked(self.poses, base) };
1260        let off = 18;
1261        let translation = if self.pose_record_size == psxed_format::animation::POSE_RECORD_SIZE {
1262            Vec3I32::new(
1263                decode_packed_translation(
1264                    // SAFETY: bytes `base + 18..base + 20` of the 24-byte record.
1265                    unsafe { read_i16_unchecked(self.poses, base + off) },
1266                    self.translation_shift,
1267                ),
1268                decode_packed_translation(
1269                    // SAFETY: bytes `base + 20..base + 22` of the 24-byte record.
1270                    unsafe { read_i16_unchecked(self.poses, base + off + 2) },
1271                    self.translation_shift,
1272                ),
1273                decode_packed_translation(
1274                    // SAFETY: bytes `base + 22..base + 24` of the 24-byte record.
1275                    unsafe { read_i16_unchecked(self.poses, base + off + 4) },
1276                    self.translation_shift,
1277                ),
1278            )
1279        } else {
1280            Vec3I32::new(
1281                // SAFETY: bytes `base + 18..base + 22` of the 30-byte v1 record.
1282                unsafe { read_i32_unchecked(self.poses, base + off) },
1283                // SAFETY: bytes `base + 22..base + 26` of the 30-byte v1 record.
1284                unsafe { read_i32_unchecked(self.poses, base + off + 4) },
1285                // SAFETY: bytes `base + 26..base + 30` of the 30-byte v1 record.
1286                unsafe { read_i32_unchecked(self.poses, base + off + 8) },
1287            )
1288        };
1289        JointPose {
1290            matrix,
1291            translation,
1292        }
1293    }
1294
1295    #[inline]
1296    fn packed_pose_at_frame_offset(
1297        &self,
1298        frame_offset: usize,
1299        joint_index: u16,
1300    ) -> Option<GteJointPose> {
1301        let v3 = self.pose_record_size == psxed_format::animation::POSE_RECORD_SIZE_V3;
1302        let v4 = self.pose_record_size == psxed_format::animation::POSE_RECORD_SIZE_V4;
1303        if joint_index >= self.joint_count
1304            || !(v3 || v4 || self.pose_record_size == psxed_format::animation::POSE_RECORD_SIZE)
1305        {
1306            return None;
1307        }
1308        let base = frame_offset.checked_add(joint_index as usize * self.pose_record_size)?;
1309        let base = self.record_offset(base);
1310        let bytes = self.poses.get(base..base + self.pose_record_size)?;
1311        if v4 {
1312            let (matrix, translation) = if bytes.as_ptr() as usize & 3 == 0 {
1313                // SAFETY: `bytes` is a checked `get` of exactly the 16-byte v4
1314                // record and its pointer was just checked to be word aligned.
1315                unsafe { read_pose_v4_word_aligned_unchecked(bytes, 0) }
1316            } else {
1317                // SAFETY: the 16-byte checked slice covers the 10 bytes needed.
1318                let matrix = unsafe { read_pose_matrix_q11_cross_unchecked(bytes, 0) };
1319                let off = psxed_format::animation::POSE_ROTATION_BLOCK_SIZE_V4;
1320                let translation = Vec3I16::new(
1321                    read_i16(bytes, off),
1322                    read_i16(bytes, off + 2),
1323                    read_i16(bytes, off + 4),
1324                );
1325                (matrix, translation)
1326            };
1327            return Some(GteJointPose {
1328                matrix,
1329                translation,
1330                translation_shift: self.translation_shift,
1331            });
1332        }
1333        if v3 {
1334            // SAFETY: the slice covers the whole 20-byte record. Shipping
1335            // storage is word-aligned; retain the byte decoder for arbitrary
1336            // slices accepted by the public parser.
1337            let (matrix, translation) = if bytes.as_ptr() as usize & 3 == 0 {
1338                // SAFETY: as stated above, plus the word alignment just checked.
1339                unsafe { read_pose_v3_word_aligned_unchecked(bytes, 0) }
1340            } else {
1341                // SAFETY: the 20-byte checked slice covers the 14 bytes needed.
1342                let matrix = unsafe { read_pose_matrix_q11_unchecked(bytes, 0) };
1343                let off = psxed_format::animation::POSE_ROTATION_BLOCK_SIZE_V3;
1344                let translation = Vec3I16::new(
1345                    read_i16(bytes, off),
1346                    read_i16(bytes, off + 2),
1347                    read_i16(bytes, off + 4),
1348                );
1349                (matrix, translation)
1350            };
1351            return Some(GteJointPose {
1352                matrix,
1353                translation,
1354                translation_shift: self.translation_shift,
1355            });
1356        }
1357        Some(GteJointPose {
1358            matrix: read_pose_matrix(bytes),
1359            translation: Vec3I16::new(
1360                read_i16(bytes, 18),
1361                read_i16(bytes, 20),
1362                read_i16(bytes, 22),
1363            ),
1364            translation_shift: self.translation_shift,
1365        })
1366    }
1367
1368    /// Interpolated looping joint pose at a Q12 fixed-point frame phase.
1369    ///
1370    /// `frame_q12` uses sampled animation frames as the integer unit
1371    /// and 12 fractional bits. For example, `1 << 12` samples frame
1372    /// 1 exactly, while `1 << 11` samples halfway between frames 0
1373    /// and 1. The cooker writes endpoint-inclusive clips, so looping
1374    /// playback treats the final stored frame as the duplicate of
1375    /// frame 0 and blends `frame_count - 2` back to frame 0.
1376    pub fn pose_looped_q12(&self, frame_q12: u32, joint_index: u16) -> Option<JointPose> {
1377        self.looped_pose_sample_q12(frame_q12)?.pose(joint_index)
1378    }
1379
1380    /// Precomputed looping frame pair for sampling multiple joints at
1381    /// the same animation phase.
1382    ///
1383    /// Renderers should prefer this when walking every joint in a
1384    /// model: the expensive loop-frame modulo and alpha calculation
1385    /// happens once per draw instead of once per joint.
1386    pub fn looped_pose_sample_q12(&self, frame_q12: u32) -> Option<AnimationPoseSample<'a>> {
1387        if self.frame_count == 0 {
1388            return None;
1389        }
1390
1391        let cycle_frames = self.frame_count.saturating_sub(1).max(1);
1392        let base_frame = ((frame_q12 >> 12) % cycle_frames as u32) as u16;
1393        let next_frame = if cycle_frames <= 1 || base_frame + 1 >= cycle_frames {
1394            0
1395        } else {
1396            base_frame + 1
1397        };
1398        let alpha_q12 = (frame_q12 & 0x0fff) as u16;
1399        let track_pos = if self.tracks.is_some() {
1400            tracks::track_pos(
1401                self.poses,
1402                (u32::from(base_frame) << 8) | u32::from(alpha_q12 >> 4),
1403            )
1404        } else {
1405            tracks::TrackPos::ZERO
1406        };
1407        Some(AnimationPoseSample {
1408            animation: *self,
1409            base_frame,
1410            next_frame,
1411            base_frame_offset: base_frame as usize
1412                * self.joint_count as usize
1413                * self.pose_record_size,
1414            next_frame_offset: next_frame as usize
1415                * self.joint_count as usize
1416                * self.pose_record_size,
1417            alpha_q12,
1418            track_pos,
1419        })
1420    }
1421}
1422
1423/// Reusable frame-pair sampler for one animation phase.
1424#[derive(Copy, Clone, Debug)]
1425pub struct AnimationPoseSample<'a> {
1426    animation: Animation<'a>,
1427    base_frame: u16,
1428    next_frame: u16,
1429    base_frame_offset: usize,
1430    next_frame_offset: usize,
1431    alpha_q12: u16,
1432    /// Key positions of a v6 clip; zero for every other version.
1433    track_pos: tracks::TrackPos,
1434}
1435
1436impl AnimationPoseSample<'_> {
1437    /// Joint pose at this sample's precomputed looping phase.
1438    #[inline]
1439    pub fn pose(&self, joint_index: u16) -> Option<JointPose> {
1440        if joint_index >= self.animation.joint_count {
1441            return None;
1442        }
1443        if let Some(tracks) = &self.animation.tracks {
1444            // SAFETY: `tracks` came from `validate` for this animation's blob
1445            // and the joint index was checked above.
1446            return Some(unsafe {
1447                tracks::joint_pose(tracks, joint_index as usize, &self.track_pos)
1448            });
1449        }
1450        if self.alpha_q12 == 0 || self.base_frame == self.next_frame {
1451            // SAFETY: the joint index was checked above and the frame offset
1452            // was computed from a validated animation frame.
1453            return Some(unsafe {
1454                self.animation
1455                    .pose_at_frame_offset_unchecked(self.base_frame_offset, joint_index)
1456            });
1457        }
1458
1459        // Shipping clips are v4 records inside a word-aligned pool, which is
1460        // the one shape every skinned draw walks joint by joint. Decoding both
1461        // frames in one body instead of two outlined calls plus an outlined
1462        // lerp removes two 32-byte `JointPose` temporaries that the R3000A,
1463        // having no data cache, would otherwise write to and read back from
1464        // main RAM, and it loads the record base and the shared translation
1465        // shift once instead of twice. The values are bit-identical to the
1466        // generic path below: `pose_record_size == V4` and a word-aligned pool
1467        // select exactly the same decoder, and every v4 record offset is a
1468        // multiple of 16, so the whole-pool alignment test settles both
1469        // records at once.
1470        if self.animation.pose_record_size == psxed_format::animation::POSE_RECORD_SIZE_V4 {
1471            let pool = self.animation.poses.as_ptr();
1472            if pool as usize & 3 == 0 {
1473                let joint_offset =
1474                    joint_index as usize * psxed_format::animation::POSE_RECORD_SIZE_V4;
1475                // SAFETY: the joint index was checked above and both frame
1476                // offsets were computed from validated animation frames, so
1477                // both records lie wholly inside `poses`; the pool is word
1478                // aligned and both offsets are multiples of the 16-byte record.
1479                return Some(unsafe {
1480                    lerp_v4_pair_word_aligned(
1481                        pool.add(
1482                            self.animation
1483                                .record_offset(self.base_frame_offset + joint_offset),
1484                        ),
1485                        pool.add(
1486                            self.animation
1487                                .record_offset(self.next_frame_offset + joint_offset),
1488                        ),
1489                        self.animation.translation_shift,
1490                        self.alpha_q12,
1491                    )
1492                });
1493            }
1494        }
1495
1496        // SAFETY: the joint index was checked above and both frame offsets
1497        // were computed from validated animation frames.
1498        let a = unsafe {
1499            self.animation
1500                .pose_at_frame_offset_unchecked(self.base_frame_offset, joint_index)
1501        };
1502        // SAFETY: as for `a`: `next_frame < frame_count` by construction in
1503        // `looped_pose_sample_q12`, and the joint index was checked above.
1504        let b = unsafe {
1505            self.animation
1506                .pose_at_frame_offset_unchecked(self.next_frame_offset, joint_index)
1507        };
1508        Some(lerp_pose_q12(a, b, self.alpha_q12))
1509    }
1510
1511    /// Packed GTE-friendly joint pose at this sample's phase.
1512    ///
1513    /// This is available for current v2 `.psxanim` files. Legacy v1
1514    /// files return `None` and callers can fall back to [`Self::pose`].
1515    #[inline]
1516    pub fn gte_pose(&self, joint_index: u16) -> Option<GteJointPose> {
1517        if self.alpha_q12 == 0 || self.base_frame == self.next_frame {
1518            return self
1519                .animation
1520                .packed_pose_at_frame_offset(self.base_frame_offset, joint_index);
1521        }
1522
1523        let a = self
1524            .animation
1525            .packed_pose_at_frame_offset(self.base_frame_offset, joint_index)?;
1526        let b = self
1527            .animation
1528            .packed_pose_at_frame_offset(self.next_frame_offset, joint_index)?;
1529        Some(lerp_gte_pose_q12(a, b, self.alpha_q12))
1530    }
1531}
1532
1533/// Crossfade source: a second animation sample blended toward a
1534/// primary pose.
1535///
1536/// Used for clip-transition crossfades: the outgoing clip's frozen
1537/// sample sits here while the incoming clip plays as the primary.
1538/// `alpha_q12` is the Q12 weight of the PRIMARY pose (0 shows this
1539/// source, `1 << 12` shows the primary alone).
1540///
1541/// The blend is a linear matrix lerp, not a rotation-correct slerp:
1542/// mid-blend joints shrink slightly when the two poses differ a lot.
1543/// Short crossfade windows keep that invisible; renormalize later if
1544/// a long blend ever makes it visible.
1545#[derive(Copy, Clone, Debug)]
1546pub struct ModelPoseBlend<'a> {
1547    /// Outgoing pose sample (frame pair + intra-frame alpha).
1548    pub sample: AnimationPoseSample<'a>,
1549    /// Q12 weight of the primary pose this source blends toward.
1550    pub alpha_q12: u16,
1551}
1552
1553impl ModelPoseBlend<'_> {
1554    /// Blend this source's joint pose toward `primary`.
1555    ///
1556    /// Falls back to `primary` unchanged when the joint is missing
1557    /// from the outgoing clip (mismatched rigs never corrupt poses).
1558    #[inline]
1559    pub fn blend_toward(&self, primary: JointPose, joint_index: u16) -> JointPose {
1560        if self.alpha_q12 >= 1 << 12 {
1561            return primary;
1562        }
1563        match self.sample.pose(joint_index) {
1564            Some(from) => lerp_pose_q12(from, primary, self.alpha_q12),
1565            None => primary,
1566        }
1567    }
1568}
1569
1570/// Decoded joint pose matrix.
1571#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1572pub struct JointPose {
1573    /// Q3.12 column-major 3×3 transform.
1574    pub matrix: [[i16; 3]; 3],
1575    /// Q3.12 translation vector.
1576    pub translation: Vec3I32,
1577}
1578
1579/// Compact joint pose that can feed GTE vector inputs directly.
1580#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1581pub struct GteJointPose {
1582    /// Q3.12 column-major 3×3 transform.
1583    pub matrix: [[i16; 3]; 3],
1584    /// Packed model-local translation vector.
1585    pub translation: Vec3I16,
1586    /// Shared left shift used to reconstruct model-local units.
1587    pub translation_shift: u8,
1588}
1589
1590/// A parsed `.psau` SPU audio sample backed by the caller's cooked blob.
1591#[derive(Copy, Clone, Debug)]
1592pub struct Audio<'a> {
1593    adpcm: &'a [u8],
1594    flags: u16,
1595    sample_rate_hz: u32,
1596    sample_count: u32,
1597    adpcm_block_count: u32,
1598    loop_start_block: u32,
1599}
1600
1601impl<'a> Audio<'a> {
1602    /// Parse a cooked `.psau` blob.
1603    pub fn from_bytes(bytes: &'a [u8]) -> Result<Self, ParseError> {
1604        use psxed_format::audio::{self, AudioHeader};
1605
1606        if bytes.len() < psxed_format::AssetHeader::SIZE {
1607            return Err(ParseError::Truncated);
1608        }
1609        let magic = [bytes[0], bytes[1], bytes[2], bytes[3]];
1610        if magic != audio::MAGIC {
1611            return Err(ParseError::WrongMagic);
1612        }
1613        let version = read_u16(bytes, 4);
1614        if version != audio::VERSION {
1615            return Err(ParseError::UnsupportedVersion(version));
1616        }
1617        let flags = read_u16(bytes, 6);
1618        let payload_len = read_u32(bytes, 8);
1619        let payload_start = psxed_format::AssetHeader::SIZE;
1620        let actual_payload = bytes.len().saturating_sub(payload_start);
1621        if payload_len as usize != actual_payload {
1622            return Err(ParseError::InvalidPayloadLen {
1623                declared: payload_len,
1624                actual: actual_payload,
1625            });
1626        }
1627        if actual_payload < AudioHeader::SIZE {
1628            return Err(ParseError::Truncated);
1629        }
1630
1631        let ah = &bytes[payload_start..payload_start + AudioHeader::SIZE];
1632        let codec = ah[0];
1633        let channel_count = ah[1];
1634        let sample_rate_hz = read_u32(ah, 4);
1635        let sample_count = read_u32(ah, 8);
1636        let adpcm_block_count = read_u32(ah, 12);
1637        let loop_start_block = read_u32(ah, 16);
1638        let decoded_capacity = adpcm_block_count
1639            .checked_mul(28)
1640            .ok_or(ParseError::TableOverflow)?;
1641        let min_samples_for_blocks = adpcm_block_count.saturating_sub(1) * 28 + 1;
1642        if codec != audio::CODEC_SPU_ADPCM
1643            || channel_count != 1
1644            || flags & audio::flags::MONO == 0
1645            || flags & audio::flags::ONE_SHOT == 0
1646            || sample_rate_hz == 0
1647            || sample_count == 0
1648            || adpcm_block_count == 0
1649            || sample_count > decoded_capacity
1650            || sample_count < min_samples_for_blocks
1651            || loop_start_block != AudioHeader::NO_LOOP
1652        {
1653            return Err(ParseError::InvalidAudioLayout);
1654        }
1655
1656        let adpcm_bytes = (adpcm_block_count as usize)
1657            .checked_mul(16)
1658            .ok_or(ParseError::TableOverflow)?;
1659        let adpcm_start = payload_start + AudioHeader::SIZE;
1660        let adpcm_end = adpcm_start
1661            .checked_add(adpcm_bytes)
1662            .ok_or(ParseError::TableOverflow)?;
1663        if adpcm_end != bytes.len() {
1664            return Err(ParseError::InvalidAudioLayout);
1665        }
1666
1667        Ok(Self {
1668            adpcm: &bytes[adpcm_start..adpcm_end],
1669            flags,
1670            sample_rate_hz,
1671            sample_count,
1672            adpcm_block_count,
1673            loop_start_block,
1674        })
1675    }
1676
1677    /// Playback sample rate in Hz.
1678    #[inline]
1679    pub fn sample_rate_hz(&self) -> u32 {
1680        self.sample_rate_hz
1681    }
1682
1683    /// Audible mono sample count before encoder padding.
1684    #[inline]
1685    pub fn sample_count(&self) -> u32 {
1686        self.sample_count
1687    }
1688
1689    /// Number of 16-byte SPU ADPCM blocks.
1690    #[inline]
1691    pub fn adpcm_block_count(&self) -> u32 {
1692        self.adpcm_block_count
1693    }
1694
1695    /// Loop-start block, or `None` for one-shot samples.
1696    #[inline]
1697    pub fn loop_start_block(&self) -> Option<u32> {
1698        if self.loop_start_block == psxed_format::audio::AudioHeader::NO_LOOP {
1699            None
1700        } else {
1701            Some(self.loop_start_block)
1702        }
1703    }
1704
1705    /// Raw SPU ADPCM bytes ready for upload.
1706    #[inline]
1707    pub fn adpcm_bytes(&self) -> &'a [u8] {
1708        self.adpcm
1709    }
1710
1711    /// Whether this sample is a non-looping one-shot.
1712    #[inline]
1713    pub fn is_one_shot(&self) -> bool {
1714        self.flags & psxed_format::audio::flags::ONE_SHOT != 0
1715    }
1716}
1717
1718#[inline]
1719fn lerp_pose_q12(a: JointPose, b: JointPose, alpha_q12: u16) -> JointPose {
1720    let mut matrix = [[0i16; 3]; 3];
1721    let mut col = 0;
1722    while col < 3 {
1723        let mut row = 0;
1724        while row < 3 {
1725            matrix[col][row] = lerp_i16_q12(a.matrix[col][row], b.matrix[col][row], alpha_q12);
1726            row += 1;
1727        }
1728        col += 1;
1729    }
1730
1731    JointPose {
1732        matrix,
1733        translation: Vec3I32::new(
1734            lerp_i32_q12(a.translation.x, b.translation.x, alpha_q12),
1735            lerp_i32_q12(a.translation.y, b.translation.y, alpha_q12),
1736            lerp_i32_q12(a.translation.z, b.translation.z, alpha_q12),
1737        ),
1738    }
1739}
1740
1741#[inline]
1742fn lerp_gte_pose_q12(a: GteJointPose, b: GteJointPose, alpha_q12: u16) -> GteJointPose {
1743    let mut matrix = [[0i16; 3]; 3];
1744    let mut col = 0;
1745    while col < 3 {
1746        let mut row = 0;
1747        while row < 3 {
1748            matrix[col][row] = lerp_i16_q12(a.matrix[col][row], b.matrix[col][row], alpha_q12);
1749            row += 1;
1750        }
1751        col += 1;
1752    }
1753
1754    GteJointPose {
1755        matrix,
1756        translation: Vec3I16::new(
1757            lerp_i16_q12(a.translation.x, b.translation.x, alpha_q12),
1758            lerp_i16_q12(a.translation.y, b.translation.y, alpha_q12),
1759            lerp_i16_q12(a.translation.z, b.translation.z, alpha_q12),
1760        ),
1761        translation_shift: a.translation_shift,
1762    }
1763}
1764
1765/// Decode one 12-bit Q11 rotation code to a Q3.12 element.
1766///
1767/// Ported from hl-psx's silicon-proven decoder: value = code * 2, with
1768/// the reserved positive-max code 0x7FF decoding to exactly 4096. The decoder
1769/// itself lives in [`decode_q11_element_wide`], including the branchless MIPS
1770/// form that avoids the select branch LLVM would otherwise emit; this is that
1771/// value narrowed, which is exact because the range is `+/-4096`.
1772#[inline(always)]
1773fn decode_q11_element(raw: u16) -> i16 {
1774    decode_q11_element_wide(raw) as i16
1775}
1776
1777/// Q11 rotation decode that keeps its result 32-bit.
1778///
1779/// Identical value to [`decode_q11_element`]: the decoder's range is
1780/// `+/-4096`, so the `i16` narrowing there is exact and re-widening it for
1781/// arithmetic is pure loss. Every use in the v4 path is arithmetic, and on MIPS
1782/// each round trip through `i16` costs an `sll`/`sra` pair.
1783#[inline(always)]
1784fn decode_q11_element_wide(raw: u16) -> i32 {
1785    #[cfg(target_arch = "mips")]
1786    {
1787        let decoded: u32;
1788        // SAFETY: pure register arithmetic: no memory access (`nomem`), no
1789        // stack use (`nostack`), no branches, and `$at` is never named, so
1790        // `.set noat` only silences the assembler. `scratch` is a lateout,
1791        // but the only input lives in `decoded`'s own inlateout register,
1792        // which an output can never share, so the first write to `scratch`
1793        // cannot clobber the input.
1794        unsafe {
1795            core::arch::asm!(
1796                ".set push",
1797                ".set noat",
1798                "xori {scratch}, {decoded}, 0x07ff",
1799                "sltiu {scratch}, {scratch}, 1",
1800                "sll {decoded}, {decoded}, 20",
1801                "sra {decoded}, {decoded}, 19",
1802                "sll {scratch}, {scratch}, 1",
1803                "addu {decoded}, {decoded}, {scratch}",
1804                ".set pop",
1805                decoded = inlateout(reg) raw as u32 => decoded,
1806                scratch = lateout(reg) _,
1807                options(nomem, nostack, preserves_flags),
1808            );
1809        }
1810        decoded as i32
1811    }
1812
1813    #[cfg(not(target_arch = "mips"))]
1814    {
1815        let signed = ((raw << 4) as i16) >> 4;
1816        signed
1817            .wrapping_shl(1)
1818            .wrapping_add((((raw & 0x0fff) == 0x07ff) as i16) << 1) as i32
1819    }
1820}
1821
1822/// Decode a v3 packed rotation block (nine 12-bit Q11 codes in
1823/// fourteen bytes) into the row-major pose matrix. Byte-wise loads:
1824/// the block is not alignment-guaranteed and the R3000 has no D-cache
1825/// penalty for it.
1826///
1827/// # Safety
1828/// `offset + 14` must be in bounds (v3 records are 20 bytes, so any
1829/// in-bounds record satisfies this).
1830#[inline]
1831unsafe fn read_pose_matrix_q11_unchecked(bytes: &[u8], offset: usize) -> [[i16; 3]; 3] {
1832    let mut flat = [0i16; 9];
1833    let mut pair = 0;
1834    while pair < 4 {
1835        let o = offset + pair * 3;
1836        // SAFETY: `pair < 4`, so the highest byte read is `offset + 11`,
1837        // inside the `offset + 14` the caller guarantees; `u8` reads need no
1838        // alignment.
1839        let packed = unsafe {
1840            (bytes.as_ptr().add(o).read() as u32)
1841                | ((bytes.as_ptr().add(o + 1).read() as u32) << 8)
1842                | ((bytes.as_ptr().add(o + 2).read() as u32) << 16)
1843        };
1844        flat[pair * 2] = decode_q11_element((packed & 0x0fff) as u16);
1845        flat[pair * 2 + 1] = decode_q11_element(((packed >> 12) & 0x0fff) as u16);
1846        pair += 1;
1847    }
1848    // SAFETY: bytes `offset + 12` and `offset + 13` are inside the
1849    // `offset + 14` the caller guarantees.
1850    let last = unsafe {
1851        (bytes.as_ptr().add(offset + 12).read() as u16)
1852            | ((bytes.as_ptr().add(offset + 13).read() as u16) << 8)
1853    };
1854    flat[8] = decode_q11_element(last & 0x0fff);
1855    [
1856        [flat[0], flat[1], flat[2]],
1857        [flat[3], flat[4], flat[5]],
1858        [flat[6], flat[7], flat[8]],
1859    ]
1860}
1861
1862/// Largest magnitude a v4 cross-product accumulator can reach.
1863///
1864/// Every operand is a [`decode_q11_element`] output, which is bounded to
1865/// `+/-4096`, so `a*b - c*d` cannot leave `+/-2*4096*4096`. Two facts follow
1866/// and [`v4_third_basis_q12`] relies on both: the saturating arithmetic the
1867/// original reconstruction used could never fire, and the rounded result
1868/// cannot leave `+/-8192`, which the shared `+/-4096` clamp already covers.
1869const V4_CROSS_LIMIT: i32 = 2 * 4096 * 4096;
1870
1871/// Round one Q3.12 cross-product accumulator, half away from zero.
1872///
1873/// The branchless `(v ^ sign) - sign` form of this was measured and is not
1874/// worth it here: identical values, +0.20% frame cycles and three frames lost,
1875/// because the two arms are small enough that LLVM fills the delay slots.
1876#[inline(always)]
1877fn cross_round_q12(value: i32) -> i32 {
1878    debug_assert!((-V4_CROSS_LIMIT..=V4_CROSS_LIMIT).contains(&value));
1879    if value >= 0 {
1880        (value + (1 << 11)) >> 12
1881    } else {
1882        -((-value + (1 << 11)) >> 12)
1883    }
1884}
1885
1886/// Reconstruct a v4 record's third basis row from the two stored rows and the
1887/// packed correction byte.
1888///
1889/// Bit-identical to the `apply_v4_basis_correction(reconstruct_third_basis_q12(
1890/// first, second), correction_byte)` pair this replaced, over the whole domain
1891/// those two could ever see (see [`V4_CROSS_LIMIT`]); the tests hold both forms
1892/// side by side and sweep it. Three things went away, all of them dead work
1893/// rather than accuracy:
1894///
1895/// * the per-component clamp to the `i16` range, subsumed by the `+/-4096`
1896///   clamp that immediately followed it;
1897/// * the `saturating_add`/`saturating_neg`/`saturating_add` triple in the
1898///   rounding, each of which compiles to an overflow test that can never take
1899///   its other arm at this magnitude;
1900/// * the runtime-indexed array write `third[axis] = ..`, which forced all three
1901///   components onto the stack and back. The R3000A has no data cache, so that
1902///   was six uncached accesses on every decoded record.
1903#[inline(always)]
1904fn v4_third_basis_q12(first: [i32; 3], second: [i32; 3], correction_byte: u8) -> [i32; 3] {
1905    let ([f0, f1, f2], [s0, s1, s2]) = (first, second);
1906    let x = cross_round_q12(f1 * s2 - f2 * s1);
1907    let y = cross_round_q12(f2 * s0 - f0 * s2);
1908    let z = cross_round_q12(f0 * s1 - f1 * s0);
1909    let correction = ((((correction_byte >> 2) << 2) as i8) >> 2) as i32;
1910    // Axis 3 is the "no correction" encoding, matching the `axis < 3` guard the
1911    // array form used.
1912    let (x, y, z) = match correction_byte & 0x03 {
1913        0 => (x + correction, y, z),
1914        1 => (x, y + correction, z),
1915        2 => (x, y, z + correction),
1916        _ => (x, y, z),
1917    };
1918    [
1919        x.clamp(-4096, 4096),
1920        y.clamp(-4096, 4096),
1921        z.clamp(-4096, 4096),
1922    ]
1923}
1924
1925/// Decode a v4 packed rotation block. Its first nine bytes contain six Q11
1926/// codes and byte nine corrects the cross-product reconstruction.
1927///
1928/// # Safety
1929/// `offset + 10` must be in bounds.
1930#[inline]
1931unsafe fn read_pose_matrix_q11_cross_unchecked(bytes: &[u8], offset: usize) -> [[i16; 3]; 3] {
1932    let mut flat = [0i32; 6];
1933    let mut pair = 0usize;
1934    while pair < 3 {
1935        let o = offset + pair * 3;
1936        // SAFETY: `pair < 3`, so the highest byte read is `offset + 8`,
1937        // inside the `offset + 10` the caller guarantees.
1938        let packed = unsafe {
1939            (bytes.as_ptr().add(o).read() as u32)
1940                | ((bytes.as_ptr().add(o + 1).read() as u32) << 8)
1941                | ((bytes.as_ptr().add(o + 2).read() as u32) << 16)
1942        };
1943        flat[pair * 2] = decode_q11_element_wide((packed & 0x0fff) as u16);
1944        flat[pair * 2 + 1] = decode_q11_element_wide(((packed >> 12) & 0x0fff) as u16);
1945        pair += 1;
1946    }
1947    let first = [flat[0], flat[1], flat[2]];
1948    let second = [flat[3], flat[4], flat[5]];
1949    // SAFETY: `offset + 9` is inside the `offset + 10` the caller guarantees.
1950    let correction = unsafe { bytes.as_ptr().add(offset + 9).read() };
1951    let third = v4_third_basis_q12(first, second, correction);
1952    [
1953        narrow_q12_row(first),
1954        narrow_q12_row(second),
1955        narrow_q12_row(third),
1956    ]
1957}
1958
1959/// Decode one word-aligned v4 record with four aligned loads.
1960///
1961/// # Safety
1962/// `offset + 16` must be in bounds and the record must be word aligned.
1963#[inline]
1964unsafe fn read_pose_v4_word_aligned_unchecked(
1965    bytes: &[u8],
1966    offset: usize,
1967) -> ([[i16; 3]; 3], Vec3I16) {
1968    // SAFETY: the caller guarantees `offset + 16` is in bounds and the record
1969    // is word aligned, which is exactly the pointer form's contract.
1970    unsafe { read_pose_v4_word_aligned_ptr(bytes.as_ptr().add(offset)) }
1971}
1972
1973/// Pointer form of [`read_pose_v4_word_aligned_unchecked`], so a caller that
1974/// already holds the record address does not carry a slice length it cannot
1975/// use. Identical decode.
1976///
1977/// # Safety
1978/// `record` must be word aligned with 16 readable bytes.
1979#[inline(always)]
1980unsafe fn read_pose_v4_word_aligned_ptr(record: *const u8) -> ([[i16; 3]; 3], Vec3I16) {
1981    // SAFETY: same contract as this fn: word aligned, 16 readable bytes.
1982    let (rows, translation) = unsafe { read_pose_v4_rows_word_aligned(record) };
1983    (
1984        [
1985            narrow_q12_row(rows[0]),
1986            narrow_q12_row(rows[1]),
1987            narrow_q12_row(rows[2]),
1988        ],
1989        translation,
1990    )
1991}
1992
1993/// Narrow a reconstructed Q3.12 basis row. Every element is already inside
1994/// `+/-4096`, so this is a truncation the store would have done anyway.
1995#[inline(always)]
1996fn narrow_q12_row(row: [i32; 3]) -> [i16; 3] {
1997    [row[0] as i16, row[1] as i16, row[2] as i16]
1998}
1999
2000/// Decode one word-aligned v4 record into three Q3.12 basis rows held as
2001/// `i32`, plus the record's packed translation.
2002///
2003/// This is the shape the arithmetic wants. The narrow
2004/// [`read_pose_v4_word_aligned_ptr`] is this function plus three truncations,
2005/// which the caller's halfword stores absorb for free; the interpolation in
2006/// [`lerp_v4_pair_word_aligned`] skips them entirely and stays 32-bit from the
2007/// packed code all the way to the stored matrix element.
2008///
2009/// # Safety
2010/// `record` must be word aligned with 16 readable bytes.
2011#[inline(always)]
2012unsafe fn read_pose_v4_rows_word_aligned(record: *const u8) -> ([[i32; 3]; 3], Vec3I16) {
2013    debug_assert_eq!(record as usize & 3, 0);
2014    let words = record.cast::<u32>();
2015    // The caller guarantees `record` is word aligned with 16 readable
2016    // bytes, so words 0..=3 are aligned and in bounds.
2017    // SAFETY: word 0, bytes 0..4.
2018    let w0 = u32::from_le(unsafe { words.add(0).read() });
2019    // SAFETY: word 1, bytes 4..8.
2020    let w1 = u32::from_le(unsafe { words.add(1).read() });
2021    // SAFETY: word 2, bytes 8..12.
2022    let w2 = u32::from_le(unsafe { words.add(2).read() });
2023    // SAFETY: word 3, bytes 12..16.
2024    let w3 = u32::from_le(unsafe { words.add(3).read() });
2025
2026    let p0 = w0 & 0x00ff_ffff;
2027    let p1 = (w0 >> 24) | ((w1 & 0x0000_ffff) << 8);
2028    let p2 = (w1 >> 16) | ((w2 & 0x0000_00ff) << 16);
2029    let first = [
2030        decode_q11_element_wide((p0 & 0x0fff) as u16),
2031        decode_q11_element_wide(((p0 >> 12) & 0x0fff) as u16),
2032        decode_q11_element_wide((p1 & 0x0fff) as u16),
2033    ];
2034    let second = [
2035        decode_q11_element_wide(((p1 >> 12) & 0x0fff) as u16),
2036        decode_q11_element_wide((p2 & 0x0fff) as u16),
2037        decode_q11_element_wide(((p2 >> 12) & 0x0fff) as u16),
2038    ];
2039    let third = v4_third_basis_q12(first, second, ((w2 >> 8) & 0xff) as u8);
2040    let translation = Vec3I16::new(
2041        (w2 >> 16) as u16 as i16,
2042        w3 as u16 as i16,
2043        (w3 >> 16) as u16 as i16,
2044    );
2045    ([first, second, third], translation)
2046}
2047
2048/// Decode both frames of one word-aligned v4 joint record pair and interpolate
2049/// them, in a single body.
2050///
2051/// Bit-identical to decoding each record with [`Animation::pose_v4_unchecked`]
2052/// and feeding the two [`JointPose`] values to [`lerp_pose_q12`]; only the call
2053/// shape differs. Fusing them is what keeps the two decoded poses in registers
2054/// instead of round-tripping 64 bytes through uncached main RAM, which is the
2055/// dominant cost of a skinned joint on the R3000A.
2056///
2057/// # Safety
2058/// `a_record` and `b_record` must each be word aligned with 16 readable bytes.
2059#[inline]
2060unsafe fn lerp_v4_pair_word_aligned(
2061    a_record: *const u8,
2062    b_record: *const u8,
2063    translation_shift: u8,
2064    alpha_q12: u16,
2065) -> JointPose {
2066    // SAFETY: the caller guarantees `a_record` is word aligned with 16
2067    // readable bytes.
2068    let (a_rows, a_packed) = unsafe { read_pose_v4_rows_word_aligned(a_record) };
2069    // SAFETY: likewise for `b_record`.
2070    let (b_rows, b_packed) = unsafe { read_pose_v4_rows_word_aligned(b_record) };
2071
2072    let mut matrix = [[0i16; 3]; 3];
2073    let mut col = 0;
2074    while col < 3 {
2075        let mut row = 0;
2076        while row < 3 {
2077            matrix[col][row] = lerp_q12_wide_to_i16(a_rows[col][row], b_rows[col][row], alpha_q12);
2078            row += 1;
2079        }
2080        col += 1;
2081    }
2082
2083    JointPose {
2084        matrix,
2085        translation: Vec3I32::new(
2086            lerp_packed_translation_q12(a_packed.x, b_packed.x, translation_shift, alpha_q12),
2087            lerp_packed_translation_q12(a_packed.y, b_packed.y, translation_shift, alpha_q12),
2088            lerp_packed_translation_q12(a_packed.z, b_packed.z, translation_shift, alpha_q12),
2089        ),
2090    }
2091}
2092
2093/// Interpolate one shift-packed translation component.
2094///
2095/// Bit-identical to `lerp_i32_q12(decode_packed_translation(a, shift),
2096/// decode_packed_translation(b, shift), alpha_q12)` over the whole domain that
2097/// call can reach, and the tests sweep it against exactly that expression.
2098///
2099/// The generic [`lerp_i32_q12`] has to saturate, because v1/v2 records store
2100/// raw `i32` translations of unknown magnitude. A packed record cannot: both
2101/// endpoints are `i16`, and the parser rejects a translation shift above 15, so
2102/// every endpoint fits in `+/-2^30`, every delta in `+/-(2^31 - 2^15)`, and
2103/// every partial product below `i32::MAX`. That makes all four saturating steps
2104/// unreachable, and dropping them matters here because `saturating_mul` on this
2105/// CPU is a `mult` plus a high-word comparison and branch, three times per
2106/// joint.
2107#[inline(always)]
2108fn lerp_packed_translation_q12(a: i16, b: i16, shift: u8, alpha_q12: u16) -> i32 {
2109    debug_assert!(shift <= 15);
2110    debug_assert!(alpha_q12 < 4096);
2111    let base = (a as i32) << shift;
2112    let delta = ((b as i32) << shift) - base;
2113    // Split the Q12 scale exactly as `scale_i32_q12` does: the product of a
2114    // full delta and alpha does not fit in 32 bits, the two halves do.
2115    let alpha = alpha_q12 as i32;
2116    let whole = delta >> 12;
2117    let frac = delta - (whole << 12);
2118    base + whole * alpha + ((frac * alpha) >> 12)
2119}
2120
2121/// Decode one word-aligned v3 pose record with exactly five aligned loads.
2122///
2123/// The rotation occupies bytes 0..14 and the three translations occupy
2124/// bytes 14..20, so words three and four naturally carry both the final
2125/// rotation code and every translation halfword. The returned values are
2126/// identical to [`read_pose_matrix_q11_unchecked`] plus three little-endian
2127/// `i16` reads; only the load shape differs.
2128///
2129/// # Safety
2130/// `offset + 20` must be in bounds and `bytes.as_ptr().add(offset)` must be
2131/// aligned for `u32`.
2132#[inline]
2133unsafe fn read_pose_v3_word_aligned_unchecked(
2134    bytes: &[u8],
2135    offset: usize,
2136) -> ([[i16; 3]; 3], Vec3I16) {
2137    // SAFETY: the caller guarantees `offset + 20 <= bytes.len()`, so
2138    // `offset` is within the allocation.
2139    let record = unsafe { bytes.as_ptr().add(offset) };
2140    debug_assert_eq!(record as usize & 3, 0);
2141    let words = record.cast::<u32>();
2142    // The caller guarantees the record is u32 aligned with 20 readable
2143    // bytes, so words 0..=4 are aligned and in bounds.
2144    // SAFETY: word 0, bytes 0..4 of the record.
2145    let w0 = u32::from_le(unsafe { words.add(0).read() });
2146    // SAFETY: word 1, bytes 4..8 of the record.
2147    let w1 = u32::from_le(unsafe { words.add(1).read() });
2148    // SAFETY: word 2, bytes 8..12 of the record.
2149    let w2 = u32::from_le(unsafe { words.add(2).read() });
2150    // SAFETY: word 3, bytes 12..16 of the record.
2151    let w3 = u32::from_le(unsafe { words.add(3).read() });
2152    // SAFETY: word 4, bytes 16..20 of the record.
2153    let w4 = u32::from_le(unsafe { words.add(4).read() });
2154
2155    let p0 = w0 & 0x00ff_ffff;
2156    let p1 = (w0 >> 24) | ((w1 & 0x0000_ffff) << 8);
2157    let p2 = (w1 >> 16) | ((w2 & 0x0000_00ff) << 16);
2158    let p3 = (w2 >> 8) & 0x00ff_ffff;
2159    let matrix = [
2160        [
2161            decode_q11_element((p0 & 0x0fff) as u16),
2162            decode_q11_element(((p0 >> 12) & 0x0fff) as u16),
2163            decode_q11_element((p1 & 0x0fff) as u16),
2164        ],
2165        [
2166            decode_q11_element(((p1 >> 12) & 0x0fff) as u16),
2167            decode_q11_element((p2 & 0x0fff) as u16),
2168            decode_q11_element(((p2 >> 12) & 0x0fff) as u16),
2169        ],
2170        [
2171            decode_q11_element((p3 & 0x0fff) as u16),
2172            decode_q11_element(((p3 >> 12) & 0x0fff) as u16),
2173            decode_q11_element((w3 & 0x0fff) as u16),
2174        ],
2175    ];
2176    let translation = Vec3I16::new(
2177        (w3 >> 16) as u16 as i16,
2178        w4 as u16 as i16,
2179        (w4 >> 16) as u16 as i16,
2180    );
2181    (matrix, translation)
2182}
2183
2184fn read_pose_matrix(bytes: &[u8]) -> [[i16; 3]; 3] {
2185    [
2186        [read_i16(bytes, 0), read_i16(bytes, 2), read_i16(bytes, 4)],
2187        [read_i16(bytes, 6), read_i16(bytes, 8), read_i16(bytes, 10)],
2188        [
2189            read_i16(bytes, 12),
2190            read_i16(bytes, 14),
2191            read_i16(bytes, 16),
2192        ],
2193    ]
2194}
2195
2196/// Byte-wise read of an 18-byte row-major `i16` pose matrix.
2197///
2198/// # Safety
2199/// `offset + 18` must be `<= bytes.len()`.
2200#[inline]
2201unsafe fn read_pose_matrix_unchecked(bytes: &[u8], offset: usize) -> [[i16; 3]; 3] {
2202    [
2203        [
2204            // SAFETY: bytes `offset..offset + 2`, inside the caller's `offset + 18`.
2205            unsafe { read_i16_unchecked(bytes, offset) },
2206            // SAFETY: bytes `offset + 2..offset + 4`, inside the caller's `offset + 18`.
2207            unsafe { read_i16_unchecked(bytes, offset + 2) },
2208            // SAFETY: bytes `offset + 4..offset + 6`, inside the caller's `offset + 18`.
2209            unsafe { read_i16_unchecked(bytes, offset + 4) },
2210        ],
2211        [
2212            // SAFETY: bytes `offset + 6..offset + 8`, inside the caller's `offset + 18`.
2213            unsafe { read_i16_unchecked(bytes, offset + 6) },
2214            // SAFETY: bytes `offset + 8..offset + 10`, inside the caller's `offset + 18`.
2215            unsafe { read_i16_unchecked(bytes, offset + 8) },
2216            // SAFETY: bytes `offset + 10..offset + 12`, inside the caller's `offset + 18`.
2217            unsafe { read_i16_unchecked(bytes, offset + 10) },
2218        ],
2219        [
2220            // SAFETY: bytes `offset + 12..offset + 14`, inside the caller's `offset + 18`.
2221            unsafe { read_i16_unchecked(bytes, offset + 12) },
2222            // SAFETY: bytes `offset + 14..offset + 16`, inside the caller's `offset + 18`.
2223            unsafe { read_i16_unchecked(bytes, offset + 14) },
2224            // SAFETY: bytes `offset + 16..offset + 18`, inside the caller's `offset + 18`.
2225            unsafe { read_i16_unchecked(bytes, offset + 16) },
2226        ],
2227    ]
2228}
2229
2230/// Halfword-load read of an 18-byte row-major `i16` pose matrix.
2231///
2232/// # Safety
2233/// `offset + 18` must be `<= bytes.len()` and `bytes.as_ptr().add(offset)`
2234/// must be 2-byte aligned.
2235#[inline]
2236unsafe fn read_pose_matrix_aligned_unchecked(bytes: &[u8], offset: usize) -> [[i16; 3]; 3] {
2237    [
2238        [
2239            // SAFETY: bytes `offset..offset + 2`, in bounds and 2-byte aligned.
2240            unsafe { read_i16_aligned_unchecked(bytes, offset) },
2241            // SAFETY: bytes `offset + 2..offset + 4`, in bounds and 2-byte aligned.
2242            unsafe { read_i16_aligned_unchecked(bytes, offset + 2) },
2243            // SAFETY: bytes `offset + 4..offset + 6`, in bounds and 2-byte aligned.
2244            unsafe { read_i16_aligned_unchecked(bytes, offset + 4) },
2245        ],
2246        [
2247            // SAFETY: bytes `offset + 6..offset + 8`, in bounds and 2-byte aligned.
2248            unsafe { read_i16_aligned_unchecked(bytes, offset + 6) },
2249            // SAFETY: bytes `offset + 8..offset + 10`, in bounds and 2-byte aligned.
2250            unsafe { read_i16_aligned_unchecked(bytes, offset + 8) },
2251            // SAFETY: bytes `offset + 10..offset + 12`, in bounds and 2-byte aligned.
2252            unsafe { read_i16_aligned_unchecked(bytes, offset + 10) },
2253        ],
2254        [
2255            // SAFETY: bytes `offset + 12..offset + 14`, in bounds and 2-byte aligned.
2256            unsafe { read_i16_aligned_unchecked(bytes, offset + 12) },
2257            // SAFETY: bytes `offset + 14..offset + 16`, in bounds and 2-byte aligned.
2258            unsafe { read_i16_aligned_unchecked(bytes, offset + 14) },
2259            // SAFETY: bytes `offset + 16..offset + 18`, in bounds and 2-byte aligned.
2260            unsafe { read_i16_aligned_unchecked(bytes, offset + 16) },
2261        ],
2262    ]
2263}
2264
2265#[inline]
2266fn decode_packed_translation(value: i16, shift: u8) -> i32 {
2267    debug_assert!(shift <= 15);
2268    (value as i32) * (1i32 << shift)
2269}
2270
2271/// Interpolate two Q3.12 elements that are already 32-bit.
2272///
2273/// Exactly [`lerp_i16_q12`] with its two sign extensions removed: that function
2274/// widens both endpoints to `i32` before doing anything, so feeding it values
2275/// that never left `i32` computes the identical expression.
2276#[inline(always)]
2277fn lerp_q12_wide_to_i16(a: i32, b: i32, alpha_q12: u16) -> i16 {
2278    debug_assert!(alpha_q12 < 4096);
2279    (a + (((b - a) * alpha_q12 as i32) >> 12)) as i16
2280}
2281
2282#[inline]
2283fn lerp_i16_q12(a: i16, b: i16, alpha_q12: u16) -> i16 {
2284    debug_assert!(alpha_q12 < 4096);
2285    let value = a as i32 + (((b as i32 - a as i32) * alpha_q12 as i32) >> 12);
2286    value as i16
2287}
2288
2289#[inline]
2290fn lerp_i32_q12(a: i32, b: i32, alpha_q12: u16) -> i32 {
2291    let delta = b.saturating_sub(a);
2292    a.saturating_add(scale_i32_q12(delta, alpha_q12 as i32))
2293}
2294
2295#[inline]
2296fn scale_i32_q12(value: i32, scale_q12: i32) -> i32 {
2297    let whole = value >> 12;
2298    let frac = value - (whole << 12);
2299    whole.saturating_mul(scale_q12) + ((frac * scale_q12) >> 12)
2300}
2301
2302/// A parsed 2D texture backed by slices into the caller's cooked
2303/// blob. Pixel data is already packed into the halfword-nibble
2304/// layout the PSX GPU reads; the CLUT (if any) is a slice of
2305/// RGB555 halfwords.
2306///
2307/// Construct by `Texture::from_bytes(&blob)`; upload to VRAM via
2308/// [`Texture::upload`], which returns the matching `TexturePage` + `Clut`
2309/// handles ready to feed into primitive constructors.
2310#[derive(Copy, Clone, Debug)]
2311pub struct Texture<'a> {
2312    /// Packed pixel halfwords -- 4 texels per u16 at 4bpp,
2313    /// 2 at 8bpp, 1 Color555 at 15bpp.
2314    pixel_data: &'a [u8],
2315    /// CLUT halfwords, or empty for 15bpp.
2316    clut_data: &'a [u8],
2317    width_px: u16,
2318    height_px: u16,
2319    depth: psxed_format::texture::Depth,
2320    clut_entries: u16,
2321    flags: u16,
2322}
2323
2324impl<'a> Texture<'a> {
2325    /// Parse a cooked `.psxt` blob. Returns a `Texture` view that
2326    /// borrows into `bytes`. Cheap -- header decode + two slice
2327    /// computations.
2328    pub fn from_bytes(bytes: &'a [u8]) -> Result<Self, ParseError> {
2329        use psxed_format::texture::{Depth, TextureHeader, MAGIC, VERSION};
2330
2331        // AssetHeader.
2332        if bytes.len() < psxed_format::AssetHeader::SIZE {
2333            return Err(ParseError::Truncated);
2334        }
2335        let magic = [bytes[0], bytes[1], bytes[2], bytes[3]];
2336        if magic != MAGIC {
2337            return Err(ParseError::WrongMagic);
2338        }
2339        let version = u16::from_le_bytes([bytes[4], bytes[5]]);
2340        if version != VERSION {
2341            return Err(ParseError::UnsupportedVersion(version));
2342        }
2343        let flags = u16::from_le_bytes([bytes[6], bytes[7]]);
2344        let payload_len = u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]);
2345        let payload_start = psxed_format::AssetHeader::SIZE;
2346        let actual_payload = bytes.len().saturating_sub(payload_start);
2347        if (payload_len as usize) != actual_payload {
2348            return Err(ParseError::InvalidPayloadLen {
2349                declared: payload_len,
2350                actual: actual_payload,
2351            });
2352        }
2353
2354        // TextureHeader.
2355        if actual_payload < TextureHeader::SIZE {
2356            return Err(ParseError::Truncated);
2357        }
2358        let th = &bytes[payload_start..];
2359        let depth = Depth::from_byte(th[0]).ok_or(ParseError::TableOverflow)?;
2360        // th[1] is _pad; skip.
2361        let width_px = u16::from_le_bytes([th[2], th[3]]);
2362        let height_px = u16::from_le_bytes([th[4], th[5]]);
2363        let clut_entries = u16::from_le_bytes([th[6], th[7]]);
2364        let pixel_bytes = u32::from_le_bytes([th[8], th[9], th[10], th[11]]) as usize;
2365        let clut_bytes = u32::from_le_bytes([th[12], th[13], th[14], th[15]]) as usize;
2366
2367        // `take_table` adds with `checked_add`: on the 32-bit console a header claiming
2368        // `0xFFFF_FFF0` pixel bytes wrapped `off + pixel_bytes` past the length test and
2369        // panicked on the slice.
2370        let mut off = payload_start + TextureHeader::SIZE;
2371        let pixel_data = take_table(bytes, &mut off, pixel_bytes)?;
2372        let clut_data = take_table(bytes, &mut off, clut_bytes)?;
2373
2374        Ok(Self {
2375            pixel_data,
2376            clut_data,
2377            width_px,
2378            height_px,
2379            depth,
2380            clut_entries,
2381            flags,
2382        })
2383    }
2384
2385    /// Width in texels.
2386    #[inline]
2387    pub fn width(&self) -> u16 {
2388        self.width_px
2389    }
2390
2391    /// Height in texels.
2392    #[inline]
2393    pub fn height(&self) -> u16 {
2394        self.height_px
2395    }
2396
2397    /// Colour depth.
2398    #[inline]
2399    pub fn depth(&self) -> psxed_format::texture::Depth {
2400        self.depth
2401    }
2402
2403    /// Number of CLUT entries in the blob. Normal textures use 16
2404    /// for 4bpp, 256 for 8bpp, or 0 for 15bpp; specialized 4bpp
2405    /// assets may concatenate multiple 16-entry CLUT rows.
2406    #[inline]
2407    pub fn clut_entries(&self) -> u16 {
2408        self.clut_entries
2409    }
2410
2411    /// Texture feature flags from the shared asset header.
2412    #[inline]
2413    pub fn flags(&self) -> u16 {
2414        self.flags
2415    }
2416
2417    /// True when indexed palette entry 0 should remain transparent.
2418    #[inline]
2419    pub fn is_index_zero_transparent(&self) -> bool {
2420        self.flags & psxed_format::texture::flags::INDEX_ZERO_TRANSPARENT != 0
2421    }
2422
2423    /// Raw packed pixel halfwords, as bytes. Suitable for
2424    /// halfword-level DMA upload; caller pairs this with a `VramRect`
2425    /// describing the *halfword footprint*, not the texel width.
2426    #[inline]
2427    pub fn pixel_bytes(&self) -> &'a [u8] {
2428        self.pixel_data
2429    }
2430
2431    /// Raw CLUT halfwords, as bytes. Empty for 15bpp.
2432    #[inline]
2433    pub fn clut_bytes(&self) -> &'a [u8] {
2434        self.clut_data
2435    }
2436
2437    /// Halfwords-per-row at this texture's depth (rows padded up to
2438    /// a full halfword). Needed when computing the VRAM rect for
2439    /// upload: VRAM measures in halfwords regardless of the texel
2440    /// depth the GPU will fetch them at.
2441    #[inline]
2442    pub fn halfwords_per_row(&self) -> u16 {
2443        psxed_format::texture::TextureHeader::halfwords_per_row(self.depth, self.width_px)
2444    }
2445}
2446
2447/// A parsed `.psxw` grid-world backed by slices into the cooked blob.
2448///
2449/// This is the binary runtime format; engine code wraps it as
2450/// `psx_engine::RuntimeRoom`. It keeps parsing zero-copy and lets engine
2451/// code pull sectors and walls by value as needed.
2452#[derive(Copy, Clone, Debug)]
2453pub struct World<'a> {
2454    sectors: &'a [u8],
2455    walls: &'a [u8],
2456    horizontal_overrides: &'a [u8],
2457    surface_lights: &'a [u8],
2458    sector_record_size: usize,
2459    wall_record_size: usize,
2460    horizontal_override_record_size: usize,
2461    width: u16,
2462    depth: u16,
2463    sector_size: i32,
2464    material_count: u16,
2465    wall_count: u16,
2466    horizontal_override_count: u16,
2467    surface_light_count: u16,
2468    ambient_color: [u8; 3],
2469    flags: u8,
2470    static_vertex_lighting: bool,
2471}
2472
2473/// Four PS1 UV coordinates for one world quad.
2474#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2475pub struct WorldQuadUvs {
2476    corners: [(u8, u8); 4],
2477}
2478
2479impl WorldQuadUvs {
2480    /// Build a quad UV record from face-corner coordinates.
2481    pub const fn new(corners: [(u8, u8); 4]) -> Self {
2482        Self { corners }
2483    }
2484
2485    /// Return UVs as face-corner coordinates.
2486    pub const fn corners(self) -> [(u8, u8); 4] {
2487        self.corners
2488    }
2489}
2490
2491/// Four RGB vertex colours for one world quad.
2492#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2493pub struct WorldSurfaceLight {
2494    vertex_rgb: [[u8; 3]; 4],
2495}
2496
2497impl WorldSurfaceLight {
2498    /// Full-bright neutral lighting for legacy/unlit rooms.
2499    pub const fn white() -> Self {
2500        Self {
2501            vertex_rgb: [[255, 255, 255]; 4],
2502        }
2503    }
2504
2505    /// Build from per-corner RGB values.
2506    pub const fn new(vertex_rgb: [[u8; 3]; 4]) -> Self {
2507        Self { vertex_rgb }
2508    }
2509
2510    /// Return RGB values in face-corner order.
2511    pub const fn vertex_rgb(self) -> [[u8; 3]; 4] {
2512        self.vertex_rgb
2513    }
2514}
2515
2516const WORLD_V1_SECTOR_RECORD_SIZE: usize = 44;
2517const WORLD_V1_WALL_RECORD_SIZE: usize = 24;
2518const WORLD_V2_SECTOR_RECORD_SIZE: usize = 60;
2519const WORLD_V2_WALL_RECORD_SIZE: usize = 32;
2520const WORLD_V3_HEADER_SIZE: usize = 20;
2521const WORLD_V3_SECTOR_RECORD_SIZE: usize = 60;
2522const WORLD_V3_WALL_RECORD_SIZE: usize = 32;
2523const WORLD_V4_HORIZONTAL_OVERRIDE_RECORD_SIZE: usize = 24;
2524
2525impl<'a> World<'a> {
2526    /// Parse a cooked `.psxw` blob.
2527    pub fn from_bytes(bytes: &'a [u8]) -> Result<Self, ParseError> {
2528        use psxed_format::world::{
2529            WorldHeader, MAGIC, VERSION, VERSION_V1, VERSION_V2, VERSION_V3, VERSION_V4,
2530        };
2531
2532        if bytes.len() < psxed_format::AssetHeader::SIZE {
2533            return Err(ParseError::Truncated);
2534        }
2535        let magic = [bytes[0], bytes[1], bytes[2], bytes[3]];
2536        if magic != MAGIC {
2537            return Err(ParseError::WrongMagic);
2538        }
2539        let version = u16::from_le_bytes([bytes[4], bytes[5]]);
2540        if version != VERSION
2541            && version != VERSION_V3
2542            && version != VERSION_V4
2543            && version != VERSION_V2
2544            && version != VERSION_V1
2545        {
2546            return Err(ParseError::UnsupportedVersion(version));
2547        }
2548        let (world_header_size, sector_record_size, wall_record_size) = match version {
2549            VERSION_V1 => (
2550                WORLD_V3_HEADER_SIZE,
2551                WORLD_V1_SECTOR_RECORD_SIZE,
2552                WORLD_V1_WALL_RECORD_SIZE,
2553            ),
2554            VERSION_V2 => (
2555                WORLD_V3_HEADER_SIZE,
2556                WORLD_V2_SECTOR_RECORD_SIZE,
2557                WORLD_V2_WALL_RECORD_SIZE,
2558            ),
2559            VERSION_V3 => (
2560                WORLD_V3_HEADER_SIZE,
2561                WORLD_V3_SECTOR_RECORD_SIZE,
2562                WORLD_V3_WALL_RECORD_SIZE,
2563            ),
2564            VERSION_V4 => (
2565                WorldHeader::SIZE,
2566                psxed_format::world::SectorRecord::SIZE,
2567                psxed_format::world::WallRecord::SIZE,
2568            ),
2569            _ => (
2570                WorldHeader::SIZE,
2571                psxed_format::world::SectorRecord::SIZE,
2572                psxed_format::world::WallRecord::SIZE,
2573            ),
2574        };
2575        let payload_len = u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]);
2576        let payload_start = psxed_format::AssetHeader::SIZE;
2577        let actual_payload = bytes.len().saturating_sub(payload_start);
2578        if payload_len as usize != actual_payload {
2579            return Err(ParseError::InvalidPayloadLen {
2580                declared: payload_len,
2581                actual: actual_payload,
2582            });
2583        }
2584        if actual_payload < world_header_size {
2585            return Err(ParseError::Truncated);
2586        }
2587
2588        let wh = &bytes[payload_start..payload_start + world_header_size];
2589        let width = read_u16(wh, 0);
2590        let depth = read_u16(wh, 2);
2591        let sector_size = read_i32(wh, 4);
2592        let sector_count = read_u16(wh, 8);
2593        let material_count = read_u16(wh, 10);
2594        let wall_count = read_u16(wh, 12);
2595        let ambient_color = [wh[14], wh[15], wh[16]];
2596        let flags = wh[17];
2597        let surface_light_count =
2598            if version == VERSION || version == VERSION_V4 || version == VERSION_V3 {
2599                read_u16(wh, 18)
2600            } else {
2601                0
2602            };
2603        let horizontal_override_count = if version == VERSION || version == VERSION_V4 {
2604            read_u16(wh, 20)
2605        } else {
2606            0
2607        };
2608        let static_vertex_lighting =
2609            (version == VERSION || version == VERSION_V4 || version == VERSION_V3)
2610                && flags & psxed_format::world::world_flags::STATIC_VERTEX_LIGHTING != 0;
2611
2612        let expected_sectors = (width as usize)
2613            .checked_mul(depth as usize)
2614            .ok_or(ParseError::InvalidWorldLayout)?;
2615        if sector_count as usize != expected_sectors {
2616            return Err(ParseError::InvalidWorldLayout);
2617        }
2618        if static_vertex_lighting {
2619            let expected_surface_lights = sector_count
2620                .checked_mul(2)
2621                .and_then(|count| count.checked_add(wall_count))
2622                .ok_or(ParseError::InvalidWorldLayout)?;
2623            if surface_light_count != expected_surface_lights {
2624                return Err(ParseError::InvalidWorldLayout);
2625            }
2626        } else if surface_light_count != 0 {
2627            return Err(ParseError::InvalidWorldLayout);
2628        }
2629
2630        let mut off = payload_start + world_header_size;
2631        let sector_bytes = (sector_count as usize)
2632            .checked_mul(sector_record_size)
2633            .ok_or(ParseError::TableOverflow)?;
2634        if off + sector_bytes > bytes.len() {
2635            return Err(ParseError::TableOverflow);
2636        }
2637        let sectors = &bytes[off..off + sector_bytes];
2638        off += sector_bytes;
2639
2640        let wall_bytes = (wall_count as usize)
2641            .checked_mul(wall_record_size)
2642            .ok_or(ParseError::TableOverflow)?;
2643        if off + wall_bytes > bytes.len() {
2644            return Err(ParseError::TableOverflow);
2645        }
2646        let walls = &bytes[off..off + wall_bytes];
2647        off += wall_bytes;
2648        let horizontal_override_record_size = if version == VERSION_V4 {
2649            WORLD_V4_HORIZONTAL_OVERRIDE_RECORD_SIZE
2650        } else {
2651            psxed_format::world::HorizontalOverrideRecord::SIZE
2652        };
2653        let horizontal_override_bytes = (horizontal_override_count as usize)
2654            .checked_mul(horizontal_override_record_size)
2655            .ok_or(ParseError::TableOverflow)?;
2656        if off + horizontal_override_bytes > bytes.len() {
2657            return Err(ParseError::TableOverflow);
2658        }
2659        let horizontal_overrides = &bytes[off..off + horizontal_override_bytes];
2660        off += horizontal_override_bytes;
2661        let surface_light_bytes = (surface_light_count as usize)
2662            .checked_mul(psxed_format::world::SurfaceLightRecord::SIZE)
2663            .ok_or(ParseError::TableOverflow)?;
2664        if off + surface_light_bytes > bytes.len() {
2665            return Err(ParseError::TableOverflow);
2666        }
2667        let surface_lights = &bytes[off..off + surface_light_bytes];
2668        off += surface_light_bytes;
2669        if off != bytes.len() {
2670            return Err(ParseError::InvalidWorldLayout);
2671        }
2672
2673        validate_sector_wall_ranges(sectors, sector_record_size, wall_count)?;
2674        validate_horizontal_overrides(
2675            horizontal_overrides,
2676            horizontal_override_count,
2677            sector_count,
2678            horizontal_override_record_size,
2679        )?;
2680
2681        Ok(Self {
2682            sectors,
2683            walls,
2684            horizontal_overrides,
2685            surface_lights,
2686            sector_record_size,
2687            wall_record_size,
2688            horizontal_override_record_size,
2689            width,
2690            depth,
2691            sector_size,
2692            material_count,
2693            wall_count,
2694            horizontal_override_count,
2695            surface_light_count,
2696            ambient_color,
2697            flags,
2698            static_vertex_lighting,
2699        })
2700    }
2701
2702    /// Width in grid sectors.
2703    #[inline]
2704    pub fn width(&self) -> u16 {
2705        self.width
2706    }
2707
2708    /// Depth in grid sectors.
2709    #[inline]
2710    pub fn depth(&self) -> u16 {
2711        self.depth
2712    }
2713
2714    /// Engine units per sector.
2715    #[inline]
2716    pub fn sector_size(&self) -> i32 {
2717        self.sector_size
2718    }
2719
2720    /// Number of material slots referenced by the world.
2721    #[inline]
2722    pub fn material_count(&self) -> u16 {
2723        self.material_count
2724    }
2725
2726    /// Number of wall records in the world.
2727    #[inline]
2728    pub fn wall_count(&self) -> u16 {
2729        self.wall_count
2730    }
2731
2732    /// Number of horizontal override records in the world.
2733    #[inline]
2734    pub fn horizontal_override_count(&self) -> u16 {
2735        self.horizontal_override_count
2736    }
2737
2738    /// Number of appended static surface-light records.
2739    #[inline]
2740    pub fn surface_light_count(&self) -> u16 {
2741        self.surface_light_count
2742    }
2743
2744    /// Ambient RGB color.
2745    #[inline]
2746    pub fn ambient_color(&self) -> [u8; 3] {
2747        self.ambient_color
2748    }
2749
2750    /// Whether fog/depth cue is enabled for this world.
2751    #[inline]
2752    pub fn is_fog_enabled(&self) -> bool {
2753        self.flags & psxed_format::world::world_flags::FOG_ENABLED != 0
2754    }
2755
2756    /// Whether face records carry baked static vertex lighting.
2757    #[inline]
2758    pub fn has_static_vertex_lighting(&self) -> bool {
2759        self.static_vertex_lighting
2760    }
2761
2762    /// Sector at a coordinate, returning `None` for empty cells or out of range.
2763    pub fn sector(&self, x: u16, z: u16) -> Option<WorldSector> {
2764        if x >= self.width || z >= self.depth {
2765            return None;
2766        }
2767        let index = x as usize * self.depth as usize + z as usize;
2768        let sector = self.sector_record(index)?;
2769        if sector.has_geometry() {
2770            Some(sector)
2771        } else {
2772            None
2773        }
2774    }
2775
2776    /// Sector at a coordinate without applying horizontal override
2777    /// side-table records. Collision and wall-only queries use this
2778    /// to avoid scanning render-only per-triangle override data.
2779    pub fn sector_without_horizontal_overrides(&self, x: u16, z: u16) -> Option<WorldSector> {
2780        if x >= self.width || z >= self.depth {
2781            return None;
2782        }
2783        let index = x as usize * self.depth as usize + z as usize;
2784        let sector = self.sector_record_without_horizontal_overrides(index)?;
2785        if sector.has_geometry() {
2786            Some(sector)
2787        } else {
2788            None
2789        }
2790    }
2791
2792    /// Minimal collision-probe sector header at a coordinate. This
2793    /// skips horizontal override decoding and only exposes floor
2794    /// presence plus the wall range.
2795    pub fn sector_collision_probe(&self, x: u16, z: u16) -> Option<WorldSectorCollisionProbe> {
2796        if x >= self.width || z >= self.depth {
2797            return None;
2798        }
2799        let index = x as usize * self.depth as usize + z as usize;
2800        let sector = self.sector_collision_probe_record(index)?;
2801        if sector.has_geometry() {
2802            Some(sector)
2803        } else {
2804            None
2805        }
2806    }
2807
2808    /// Decode only the selected floor triangle needed by a collision query.
2809    ///
2810    /// Unlike [`Self::sector`], this does not materialize render materials,
2811    /// UVs, ceiling data, or the unselected triangle.
2812    pub fn sector_floor_collision(
2813        &self,
2814        x: u16,
2815        z: u16,
2816        local_x: i32,
2817        local_z: i32,
2818        sector_size: i32,
2819    ) -> Option<WorldSectorFloorCollision> {
2820        if x >= self.width || z >= self.depth || sector_size <= 0 {
2821            return None;
2822        }
2823        let index = x as usize * self.depth as usize + z as usize;
2824        let size = self.sector_record_size;
2825        let base = index.checked_mul(size)?;
2826        let end = base.checked_add(size)?;
2827        let bytes = self.sectors.get(base..end)?;
2828        let flags = bytes[0];
2829        if flags & psxed_format::world::sector_flags::HAS_FLOOR == 0 {
2830            return None;
2831        }
2832
2833        let split = bytes[1];
2834        let triangle =
2835            world_topology::horizontal_triangle_at_local(split, local_x, local_z, sector_size);
2836        let default_flags = default_horizontal_flags(
2837            true,
2838            flags & psxed_format::world::sector_flags::FLOOR_WALKABLE != 0,
2839        );
2840        let sector_index = u16::try_from(index).ok()?;
2841        let (triangle_flags, override_heights) = self
2842            .horizontal_collision_override(
2843                sector_index,
2844                psxed_format::world::horizontal_surface::FLOOR,
2845                triangle,
2846            )
2847            .unwrap_or((default_flags, None));
2848        if !horizontal_triangle_present(triangle_flags, triangle) {
2849            return None;
2850        }
2851
2852        let floor_heights = read_i32x4(bytes, 12);
2853        let triangle_heights = override_heights
2854            .unwrap_or_else(|| horizontal_triangle_heights(floor_heights, split, triangle));
2855        Some(WorldSectorFloorCollision {
2856            split,
2857            triangle: triangle as u8,
2858            walkable: horizontal_triangle_walkable(triangle_flags, triangle),
2859            floor_heights,
2860            triangle_heights,
2861        })
2862    }
2863
2864    /// Sector record by flat `[x * depth + z]` index, including empty cells.
2865    pub fn sector_record(&self, index: usize) -> Option<WorldSector> {
2866        let size = self.sector_record_size;
2867        let base = index.checked_mul(size)?;
2868        let end = base.checked_add(size)?;
2869        let bytes = self.sectors.get(base..end)?;
2870        let sector_index = if index <= u16::MAX as usize {
2871            index as u16
2872        } else {
2873            return None;
2874        };
2875        let floor_override =
2876            self.horizontal_override(sector_index, psxed_format::world::horizontal_surface::FLOOR);
2877        let ceiling_override = self.horizontal_override(
2878            sector_index,
2879            psxed_format::world::horizontal_surface::CEILING,
2880        );
2881        Some(WorldSector::decode(bytes, floor_override, ceiling_override))
2882    }
2883
2884    fn sector_record_without_horizontal_overrides(&self, index: usize) -> Option<WorldSector> {
2885        let size = self.sector_record_size;
2886        let base = index.checked_mul(size)?;
2887        let end = base.checked_add(size)?;
2888        let bytes = self.sectors.get(base..end)?;
2889        if index > u16::MAX as usize {
2890            return None;
2891        }
2892        Some(WorldSector::decode(bytes, None, None))
2893    }
2894
2895    fn sector_collision_probe_record(&self, index: usize) -> Option<WorldSectorCollisionProbe> {
2896        let size = self.sector_record_size;
2897        let base = index.checked_mul(size)?;
2898        let end = base.checked_add(size)?;
2899        let bytes = self.sectors.get(base..end)?;
2900        if index > u16::MAX as usize {
2901            return None;
2902        }
2903        Some(WorldSectorCollisionProbe {
2904            flags: bytes[0],
2905            first_wall: read_u16(bytes, 8),
2906            wall_count: read_u16(bytes, 10),
2907        })
2908    }
2909
2910    /// Wall record by global wall index.
2911    pub fn wall(&self, index: u16) -> Option<WorldWall> {
2912        if index >= self.wall_count {
2913            return None;
2914        }
2915        let size = self.wall_record_size;
2916        let base = index as usize * size;
2917        let end = base.checked_add(size)?;
2918        let bytes = self.walls.get(base..end)?;
2919        Some(WorldWall::decode(bytes))
2920    }
2921
2922    /// Wall record by sector-local wall index.
2923    pub fn sector_wall(&self, sector: WorldSector, local_index: u16) -> Option<WorldWall> {
2924        if local_index >= sector.wall_count {
2925            return None;
2926        }
2927        self.wall(sector.first_wall.checked_add(local_index)?)
2928    }
2929
2930    /// Static surface-light record by direct table index.
2931    pub fn surface_light(&self, index: u16) -> Option<WorldSurfaceLight> {
2932        if !self.static_vertex_lighting || index >= self.surface_light_count {
2933            return None;
2934        }
2935        let size = psxed_format::world::SurfaceLightRecord::SIZE;
2936        let base = index as usize * size;
2937        let end = base.checked_add(size)?;
2938        let bytes = self.surface_lights.get(base..end)?;
2939        Some(read_world_surface_light(bytes, 0))
2940    }
2941
2942    fn horizontal_override(
2943        &self,
2944        sector_index: u16,
2945        surface: u8,
2946    ) -> Option<WorldHorizontalOverride> {
2947        let size = self.horizontal_override_record_size;
2948        let mut index = 0usize;
2949        while index < self.horizontal_override_count as usize {
2950            let base = index.checked_mul(size)?;
2951            let bytes = self.horizontal_overrides.get(base..base + size)?;
2952            if read_u16(bytes, 0) == sector_index && bytes[2] == surface {
2953                return Some(read_world_horizontal_override(bytes));
2954            }
2955            index += 1;
2956        }
2957        None
2958    }
2959
2960    fn horizontal_collision_override(
2961        &self,
2962        sector_index: u16,
2963        surface: u8,
2964        triangle: usize,
2965    ) -> Option<(u8, Option<[i32; 3]>)> {
2966        let size = self.horizontal_override_record_size;
2967        let mut index = 0usize;
2968        while index < self.horizontal_override_count as usize {
2969            let base = index.checked_mul(size)?;
2970            let bytes = self.horizontal_overrides.get(base..base + size)?;
2971            if read_u16(bytes, 0) == sector_index && bytes[2] == surface {
2972                let heights = (bytes.len() >= psxed_format::world::HorizontalOverrideRecord::SIZE)
2973                    .then(|| {
2974                        let offset = 24 + triangle.min(1) * 12;
2975                        [
2976                            read_i32(bytes, offset),
2977                            read_i32(bytes, offset + 4),
2978                            read_i32(bytes, offset + 8),
2979                        ]
2980                    });
2981                return Some((bytes[3], heights));
2982            }
2983            index += 1;
2984        }
2985        None
2986    }
2987}
2988
2989#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2990struct WorldHorizontalOverride {
2991    flags: u8,
2992    materials: [u16; 2],
2993    uvs: [WorldQuadUvs; 2],
2994    heights: Option<[[i32; 3]; 2]>,
2995}
2996
2997/// Minimal sector data for camera/wall collision probes.
2998#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2999pub struct WorldSectorCollisionProbe {
3000    flags: u8,
3001    first_wall: u16,
3002    wall_count: u16,
3003}
3004
3005/// Minimal decoded floor triangle used by character and camera collision.
3006#[derive(Copy, Clone, Debug, PartialEq, Eq)]
3007pub struct WorldSectorFloorCollision {
3008    split: u8,
3009    triangle: u8,
3010    walkable: bool,
3011    floor_heights: [i32; 4],
3012    triangle_heights: [i32; 3],
3013}
3014
3015impl WorldSectorFloorCollision {
3016    /// Floor diagonal split id.
3017    #[inline]
3018    pub fn split(self) -> u8 {
3019        self.split
3020    }
3021
3022    /// Selected triangle index.
3023    #[inline]
3024    pub fn triangle(self) -> usize {
3025        self.triangle as usize
3026    }
3027
3028    /// Whether the selected floor triangle is walkable.
3029    #[inline]
3030    pub fn is_walkable(self) -> bool {
3031        self.walkable
3032    }
3033
3034    /// Renamed to [`Self::is_walkable`].
3035    #[deprecated(note = "renamed to `is_walkable`")]
3036    #[inline(always)]
3037    pub fn walkable(self) -> bool {
3038        self.is_walkable()
3039    }
3040
3041    /// Floor corner heights `[NW, NE, SE, SW]`.
3042    #[inline]
3043    pub fn floor_heights(self) -> [i32; 4] {
3044        self.floor_heights
3045    }
3046
3047    /// Selected triangle heights in triangle-corner order.
3048    #[inline]
3049    pub fn triangle_heights(self) -> [i32; 3] {
3050        self.triangle_heights
3051    }
3052}
3053
3054impl WorldSectorCollisionProbe {
3055    /// True if this sector contains any floor, ceiling, or wall data.
3056    #[inline]
3057    pub fn has_geometry(self) -> bool {
3058        self.has_floor() || self.has_ceiling() || self.wall_count != 0
3059    }
3060
3061    /// True if this sector has a floor surface.
3062    #[inline]
3063    pub fn has_floor(self) -> bool {
3064        self.flags & psxed_format::world::sector_flags::HAS_FLOOR != 0
3065    }
3066
3067    /// True if this sector has a ceiling surface.
3068    #[inline]
3069    pub fn has_ceiling(self) -> bool {
3070        self.flags & psxed_format::world::sector_flags::HAS_CEILING != 0
3071    }
3072
3073    /// First global wall index for this sector.
3074    #[inline]
3075    pub fn first_wall(self) -> u16 {
3076        self.first_wall
3077    }
3078
3079    /// Number of walls belonging to this sector.
3080    #[inline]
3081    pub fn wall_count(self) -> u16 {
3082        self.wall_count
3083    }
3084}
3085
3086/// One decoded world sector record.
3087#[derive(Copy, Clone, Debug, PartialEq, Eq)]
3088pub struct WorldSector {
3089    flags: u8,
3090    floor_split: u8,
3091    ceiling_split: u8,
3092    floor_material: u16,
3093    ceiling_material: u16,
3094    floor_triangle_flags: u8,
3095    ceiling_triangle_flags: u8,
3096    floor_triangle_materials: [u16; 2],
3097    ceiling_triangle_materials: [u16; 2],
3098    floor_triangle_heights: [[i32; 3]; 2],
3099    ceiling_triangle_heights: [[i32; 3]; 2],
3100    first_wall: u16,
3101    wall_count: u16,
3102    floor_heights: [i32; 4],
3103    ceiling_heights: [i32; 4],
3104    floor_uvs: WorldQuadUvs,
3105    ceiling_uvs: WorldQuadUvs,
3106    floor_triangle_uvs: [WorldQuadUvs; 2],
3107    ceiling_triangle_uvs: [WorldQuadUvs; 2],
3108}
3109
3110impl WorldSector {
3111    fn decode(
3112        bytes: &[u8],
3113        floor_override: Option<WorldHorizontalOverride>,
3114        ceiling_override: Option<WorldHorizontalOverride>,
3115    ) -> Self {
3116        let has_v2_uvs = bytes.len() >= WORLD_V2_SECTOR_RECORD_SIZE;
3117        let flags = bytes[0];
3118        let floor_material = read_u16(bytes, 4);
3119        let ceiling_material = read_u16(bytes, 6);
3120        let floor_heights = read_i32x4(bytes, 12);
3121        let ceiling_heights = read_i32x4(bytes, 28);
3122        let floor_uvs = if has_v2_uvs {
3123            read_world_uvs(bytes, 44)
3124        } else {
3125            WorldQuadUvs::new(psxed_format::world::FLOOR_UVS)
3126        };
3127        let ceiling_uvs = if has_v2_uvs {
3128            read_world_uvs(bytes, 52)
3129        } else {
3130            WorldQuadUvs::new(psxed_format::world::FLOOR_UVS)
3131        };
3132        let floor_default_flags = default_horizontal_flags(
3133            flags & psxed_format::world::sector_flags::HAS_FLOOR != 0,
3134            flags & psxed_format::world::sector_flags::FLOOR_WALKABLE != 0,
3135        );
3136        let ceiling_default_flags = default_horizontal_flags(
3137            flags & psxed_format::world::sector_flags::HAS_CEILING != 0,
3138            flags & psxed_format::world::sector_flags::CEILING_WALKABLE != 0,
3139        );
3140        let floor_triangle_flags =
3141            floor_override.map_or(floor_default_flags, |override_data| override_data.flags);
3142        let ceiling_triangle_flags =
3143            ceiling_override.map_or(ceiling_default_flags, |override_data| override_data.flags);
3144        let floor_triangle_materials = floor_override
3145            .map_or([floor_material, floor_material], |override_data| {
3146                override_data.materials
3147            });
3148        let ceiling_triangle_materials = ceiling_override
3149            .map_or([ceiling_material, ceiling_material], |override_data| {
3150                override_data.materials
3151            });
3152        let floor_triangle_uvs =
3153            floor_override.map_or([floor_uvs, floor_uvs], |override_data| override_data.uvs);
3154        let ceiling_triangle_uvs = ceiling_override
3155            .map_or([ceiling_uvs, ceiling_uvs], |override_data| {
3156                override_data.uvs
3157            });
3158        let floor_triangle_heights = floor_override
3159            .and_then(|override_data| override_data.heights)
3160            .unwrap_or_else(|| {
3161                [
3162                    horizontal_triangle_heights(floor_heights, bytes[1], 0),
3163                    horizontal_triangle_heights(floor_heights, bytes[1], 1),
3164                ]
3165            });
3166        let ceiling_triangle_heights = ceiling_override
3167            .and_then(|override_data| override_data.heights)
3168            .unwrap_or_else(|| {
3169                [
3170                    horizontal_triangle_heights(ceiling_heights, bytes[2], 0),
3171                    horizontal_triangle_heights(ceiling_heights, bytes[2], 1),
3172                ]
3173            });
3174        Self {
3175            flags,
3176            floor_split: bytes[1],
3177            ceiling_split: bytes[2],
3178            floor_material,
3179            ceiling_material,
3180            floor_triangle_flags,
3181            ceiling_triangle_flags,
3182            floor_triangle_materials,
3183            ceiling_triangle_materials,
3184            floor_triangle_heights,
3185            ceiling_triangle_heights,
3186            first_wall: read_u16(bytes, 8),
3187            wall_count: read_u16(bytes, 10),
3188            floor_heights,
3189            ceiling_heights,
3190            floor_uvs,
3191            ceiling_uvs,
3192            floor_triangle_uvs,
3193            ceiling_triangle_uvs,
3194        }
3195    }
3196
3197    /// True if this sector has any floor, ceiling, or wall geometry.
3198    #[inline]
3199    pub fn has_geometry(&self) -> bool {
3200        self.has_floor() || self.has_ceiling() || self.wall_count != 0
3201    }
3202
3203    /// True if this sector has a floor face.
3204    #[inline]
3205    pub fn has_floor(&self) -> bool {
3206        self.flags & psxed_format::world::sector_flags::HAS_FLOOR != 0
3207            && (self.has_floor_triangle(0) || self.has_floor_triangle(1))
3208    }
3209
3210    /// True if this sector has a ceiling face.
3211    #[inline]
3212    pub fn has_ceiling(&self) -> bool {
3213        self.flags & psxed_format::world::sector_flags::HAS_CEILING != 0
3214            && (self.has_ceiling_triangle(0) || self.has_ceiling_triangle(1))
3215    }
3216
3217    /// True if the floor face is walkable.
3218    #[inline]
3219    pub fn is_floor_walkable(&self) -> bool {
3220        self.is_floor_triangle_walkable(0) || self.is_floor_triangle_walkable(1)
3221    }
3222
3223    /// Renamed to [`Self::is_floor_walkable`].
3224    #[deprecated(note = "renamed to `is_floor_walkable`")]
3225    #[inline(always)]
3226    pub fn floor_walkable(&self) -> bool {
3227        self.is_floor_walkable()
3228    }
3229
3230    /// Floor diagonal split id.
3231    #[inline]
3232    pub fn floor_split(&self) -> u8 {
3233        self.floor_split
3234    }
3235
3236    /// Floor material slot.
3237    #[inline]
3238    pub fn floor_material(&self) -> Option<u16> {
3239        self.floor_triangle_material(0)
3240            .or_else(|| self.floor_triangle_material(1))
3241            .or_else(|| material_or_none(self.floor_material))
3242    }
3243
3244    /// Floor corner heights `[NW, NE, SE, SW]`.
3245    #[inline]
3246    pub fn floor_heights(&self) -> [i32; 4] {
3247        self.floor_heights
3248    }
3249
3250    /// Floor UVs `[NW, NE, SE, SW]`.
3251    #[inline]
3252    pub fn floor_uvs(&self) -> WorldQuadUvs {
3253        self.floor_uvs
3254    }
3255
3256    /// `true` if a floor split triangle is present.
3257    #[inline]
3258    pub fn has_floor_triangle(&self, index: usize) -> bool {
3259        horizontal_triangle_present(self.floor_triangle_flags, index)
3260    }
3261
3262    /// Renamed to [`Self::has_floor_triangle`].
3263    #[deprecated(note = "renamed to `has_floor_triangle`")]
3264    #[inline(always)]
3265    pub fn floor_triangle_present(&self, index: usize) -> bool {
3266        self.has_floor_triangle(index)
3267    }
3268
3269    /// Floor split-triangle material slot.
3270    #[inline]
3271    pub fn floor_triangle_material(&self, index: usize) -> Option<u16> {
3272        if self.has_floor_triangle(index) {
3273            material_or_none(self.floor_triangle_materials[index.min(1)])
3274        } else {
3275            None
3276        }
3277    }
3278
3279    /// Floor split-triangle UVs in face-corner order.
3280    #[inline]
3281    pub fn floor_triangle_uvs(&self, index: usize) -> WorldQuadUvs {
3282        self.floor_triangle_uvs[index.min(1)]
3283    }
3284
3285    /// Floor split-triangle heights in that triangle's corner order.
3286    #[inline]
3287    pub fn floor_triangle_heights(&self, index: usize) -> [i32; 3] {
3288        self.floor_triangle_heights[index.min(1)]
3289    }
3290
3291    /// `true` if a floor split triangle is walkable.
3292    #[inline]
3293    pub fn is_floor_triangle_walkable(&self, index: usize) -> bool {
3294        self.has_floor_triangle(index)
3295            && horizontal_triangle_walkable(self.floor_triangle_flags, index)
3296    }
3297
3298    /// Renamed to [`Self::is_floor_triangle_walkable`].
3299    #[deprecated(note = "renamed to `is_floor_triangle_walkable`")]
3300    #[inline(always)]
3301    pub fn floor_triangle_walkable(&self, index: usize) -> bool {
3302        self.is_floor_triangle_walkable(index)
3303    }
3304
3305    /// Ceiling diagonal split id.
3306    #[inline]
3307    pub fn ceiling_split(&self) -> u8 {
3308        self.ceiling_split
3309    }
3310
3311    /// Ceiling material slot.
3312    #[inline]
3313    pub fn ceiling_material(&self) -> Option<u16> {
3314        self.ceiling_triangle_material(0)
3315            .or_else(|| self.ceiling_triangle_material(1))
3316            .or_else(|| material_or_none(self.ceiling_material))
3317    }
3318
3319    /// Ceiling corner heights `[NW, NE, SE, SW]`.
3320    #[inline]
3321    pub fn ceiling_heights(&self) -> [i32; 4] {
3322        self.ceiling_heights
3323    }
3324
3325    /// Ceiling UVs `[NW, NE, SE, SW]`.
3326    #[inline]
3327    pub fn ceiling_uvs(&self) -> WorldQuadUvs {
3328        self.ceiling_uvs
3329    }
3330
3331    /// `true` if a ceiling split triangle is present.
3332    #[inline]
3333    pub fn has_ceiling_triangle(&self, index: usize) -> bool {
3334        horizontal_triangle_present(self.ceiling_triangle_flags, index)
3335    }
3336
3337    /// Renamed to [`Self::has_ceiling_triangle`].
3338    #[deprecated(note = "renamed to `has_ceiling_triangle`")]
3339    #[inline(always)]
3340    pub fn ceiling_triangle_present(&self, index: usize) -> bool {
3341        self.has_ceiling_triangle(index)
3342    }
3343
3344    /// Ceiling split-triangle material slot.
3345    #[inline]
3346    pub fn ceiling_triangle_material(&self, index: usize) -> Option<u16> {
3347        if self.has_ceiling_triangle(index) {
3348            material_or_none(self.ceiling_triangle_materials[index.min(1)])
3349        } else {
3350            None
3351        }
3352    }
3353
3354    /// Ceiling split-triangle UVs in face-corner order.
3355    #[inline]
3356    pub fn ceiling_triangle_uvs(&self, index: usize) -> WorldQuadUvs {
3357        self.ceiling_triangle_uvs[index.min(1)]
3358    }
3359
3360    /// Ceiling split-triangle heights in that triangle's corner order.
3361    #[inline]
3362    pub fn ceiling_triangle_heights(&self, index: usize) -> [i32; 3] {
3363        self.ceiling_triangle_heights[index.min(1)]
3364    }
3365
3366    /// `true` if a ceiling split triangle is walkable.
3367    #[inline]
3368    pub fn is_ceiling_triangle_walkable(&self, index: usize) -> bool {
3369        self.has_ceiling_triangle(index)
3370            && horizontal_triangle_walkable(self.ceiling_triangle_flags, index)
3371    }
3372
3373    /// First global wall index for this sector.
3374    #[inline]
3375    pub fn first_wall(&self) -> u16 {
3376        self.first_wall
3377    }
3378
3379    /// Number of walls belonging to this sector.
3380    #[inline]
3381    pub fn wall_count(&self) -> u16 {
3382        self.wall_count
3383    }
3384}
3385
3386/// One decoded world wall record.
3387#[derive(Copy, Clone, Debug, PartialEq, Eq)]
3388pub struct WorldWall {
3389    direction: u8,
3390    flags: u8,
3391    material: u16,
3392    shape: u16,
3393    heights: [i32; 4],
3394    uvs: WorldQuadUvs,
3395}
3396
3397impl WorldWall {
3398    fn decode(bytes: &[u8]) -> Self {
3399        let has_v2_uvs = bytes.len() >= WORLD_V2_WALL_RECORD_SIZE;
3400        Self {
3401            direction: bytes[0],
3402            flags: bytes[1],
3403            material: read_u16(bytes, 4),
3404            shape: if has_v2_uvs {
3405                read_u16(bytes, 6)
3406            } else {
3407                psxed_format::world::wall_shape::QUAD
3408            },
3409            heights: read_i32x4(bytes, 8),
3410            uvs: if has_v2_uvs {
3411                read_world_uvs(bytes, 24)
3412            } else {
3413                WorldQuadUvs::new(psxed_format::world::WALL_UVS)
3414            },
3415        }
3416    }
3417
3418    /// Direction id, see `psxed_format::world::direction`.
3419    #[inline]
3420    pub fn direction(&self) -> u8 {
3421        self.direction
3422    }
3423
3424    /// Whether this wall blocks collision.
3425    #[inline]
3426    pub fn is_solid(&self) -> bool {
3427        self.flags & psxed_format::world::wall_flags::SOLID != 0
3428    }
3429
3430    /// Material slot.
3431    #[inline]
3432    pub fn material(&self) -> u16 {
3433        self.material
3434    }
3435
3436    /// Wall shape id, see `psxed_format::world::wall_shape`.
3437    #[inline]
3438    pub fn shape(&self) -> u16 {
3439        self.shape
3440    }
3441
3442    /// Wall heights `[bottom-left, bottom-right, top-right, top-left]`.
3443    #[inline]
3444    pub fn heights(&self) -> [i32; 4] {
3445        self.heights
3446    }
3447
3448    /// Wall UVs `[bottom-left, bottom-right, top-right, top-left]`.
3449    #[inline]
3450    pub fn uvs(&self) -> WorldQuadUvs {
3451        self.uvs
3452    }
3453}
3454
3455#[inline]
3456fn material_or_none(material: u16) -> Option<u16> {
3457    if material == psxed_format::world::NO_MATERIAL {
3458        None
3459    } else {
3460        Some(material)
3461    }
3462}
3463
3464const fn default_horizontal_flags(present: bool, walkable: bool) -> u8 {
3465    if !present {
3466        0
3467    } else {
3468        let mut flags = psxed_format::world::horizontal_flags::TRI_A_PRESENT
3469            | psxed_format::world::horizontal_flags::TRI_B_PRESENT;
3470        if walkable {
3471            flags |= psxed_format::world::horizontal_flags::TRI_A_WALKABLE
3472                | psxed_format::world::horizontal_flags::TRI_B_WALKABLE;
3473        }
3474        flags
3475    }
3476}
3477
3478const fn horizontal_triangle_present(flags: u8, index: usize) -> bool {
3479    let bit = if index == 0 {
3480        psxed_format::world::horizontal_flags::TRI_A_PRESENT
3481    } else {
3482        psxed_format::world::horizontal_flags::TRI_B_PRESENT
3483    };
3484    flags & bit != 0
3485}
3486
3487const fn horizontal_triangle_walkable(flags: u8, index: usize) -> bool {
3488    let bit = if index == 0 {
3489        psxed_format::world::horizontal_flags::TRI_A_WALKABLE
3490    } else {
3491        psxed_format::world::horizontal_flags::TRI_B_WALKABLE
3492    };
3493    flags & bit != 0
3494}
3495
3496fn horizontal_triangle_heights(heights: [i32; 4], split: u8, index: usize) -> [i32; 3] {
3497    let corners = psxed_format::world::topology::split_triangle(split, index);
3498    [
3499        heights[corners[0]],
3500        heights[corners[1]],
3501        heights[corners[2]],
3502    ]
3503}
3504
3505fn checked_table_bytes(count: u16, stride: usize) -> Result<usize, ParseError> {
3506    (count as usize)
3507        .checked_mul(stride)
3508        .ok_or(ParseError::TableOverflow)
3509}
3510
3511fn take_table<'a>(bytes: &'a [u8], offset: &mut usize, len: usize) -> Result<&'a [u8], ParseError> {
3512    let end = offset.checked_add(len).ok_or(ParseError::TableOverflow)?;
3513    if end > bytes.len() {
3514        return Err(ParseError::TableOverflow);
3515    }
3516    let table = &bytes[*offset..end];
3517    *offset = end;
3518    Ok(table)
3519}
3520
3521fn validate_model_parts(
3522    parts: &[u8],
3523    joint_count: u16,
3524    material_count: u16,
3525    vertex_count: u16,
3526    face_count: u16,
3527) -> Result<(), ParseError> {
3528    let size = psxed_format::model::PartRecord::SIZE;
3529    let count = parts.len() / size;
3530    for index in 0..count {
3531        let base = index * size;
3532        let joint_index = read_u16(parts, base);
3533        let first_vertex = read_u16(parts, base + 2);
3534        let part_vertex_count = read_u16(parts, base + 4);
3535        let first_face = read_u16(parts, base + 6);
3536        let part_face_count = read_u16(parts, base + 8);
3537        let material_index = read_u16(parts, base + 10);
3538
3539        if joint_index != psxed_format::model::NO_JOINT && joint_index >= joint_count {
3540            return Err(ParseError::InvalidModelLayout);
3541        }
3542        if material_index >= material_count {
3543            return Err(ParseError::InvalidModelLayout);
3544        }
3545        let Some(vertex_end) = first_vertex.checked_add(part_vertex_count) else {
3546            return Err(ParseError::InvalidModelLayout);
3547        };
3548        if vertex_end > vertex_count {
3549            return Err(ParseError::InvalidModelLayout);
3550        }
3551        let Some(face_end) = first_face.checked_add(part_face_count) else {
3552            return Err(ParseError::InvalidModelLayout);
3553        };
3554        if face_end > face_count {
3555            return Err(ParseError::InvalidModelLayout);
3556        }
3557    }
3558    Ok(())
3559}
3560
3561fn validate_model_faces(faces: &[u8], vertex_count: u16) -> Result<(), ParseError> {
3562    let size = psxed_format::model::FACE_RECORD_SIZE;
3563    let count = faces.len() / size;
3564    for index in 0..count {
3565        let base = index * size;
3566        let a = read_u16(faces, base);
3567        let b = read_u16(faces, base + 4);
3568        let c = read_u16(faces, base + 8);
3569        if a >= vertex_count || b >= vertex_count || c >= vertex_count {
3570            return Err(ParseError::InvalidModelLayout);
3571        }
3572    }
3573    Ok(())
3574}
3575
3576#[inline]
3577fn read_u16(bytes: &[u8], offset: usize) -> u16 {
3578    u16::from_le_bytes([bytes[offset], bytes[offset + 1]])
3579}
3580
3581#[inline]
3582fn read_u32(bytes: &[u8], offset: usize) -> u32 {
3583    u32::from_le_bytes([
3584        bytes[offset],
3585        bytes[offset + 1],
3586        bytes[offset + 2],
3587        bytes[offset + 3],
3588    ])
3589}
3590
3591#[inline]
3592fn read_i16(bytes: &[u8], offset: usize) -> i16 {
3593    i16::from_le_bytes([bytes[offset], bytes[offset + 1]])
3594}
3595
3596/// Little-endian `i16` at `offset`, without a bounds check.
3597///
3598/// # Safety
3599/// `offset + 2` must be `<= bytes.len()`.
3600#[inline]
3601unsafe fn read_i16_unchecked(bytes: &[u8], offset: usize) -> i16 {
3602    // SAFETY: `offset` and `offset + 1` are both `< offset + 2 <= len`, as
3603    // the caller guarantees.
3604    let lo = unsafe { *bytes.get_unchecked(offset) };
3605    // SAFETY: as above.
3606    let hi = unsafe { *bytes.get_unchecked(offset + 1) };
3607    i16::from_le_bytes([lo, hi])
3608}
3609
3610/// Little-endian `i16` at `offset` via one halfword load.
3611///
3612/// # Safety
3613/// `offset + 2` must be `<= bytes.len()` and `bytes.as_ptr().add(offset)`
3614/// must be 2-byte aligned.
3615#[inline]
3616unsafe fn read_i16_aligned_unchecked(bytes: &[u8], offset: usize) -> i16 {
3617    // SAFETY: `offset < offset + 2 <= len` per the caller, so the pointer
3618    // stays inside the slice.
3619    debug_assert_eq!((unsafe { bytes.as_ptr().add(offset) } as usize) & 1, 0);
3620    // SAFETY: the caller guarantees two readable bytes at `offset` and 2-byte
3621    // alignment, which is everything an `i16` read needs.
3622    i16::from_le(unsafe { bytes.as_ptr().add(offset).cast::<i16>().read() })
3623}
3624
3625#[inline]
3626fn read_i32(bytes: &[u8], offset: usize) -> i32 {
3627    i32::from_le_bytes([
3628        bytes[offset],
3629        bytes[offset + 1],
3630        bytes[offset + 2],
3631        bytes[offset + 3],
3632    ])
3633}
3634
3635/// Little-endian `i32` at `offset`, read byte-wise without a bounds check.
3636///
3637/// # Safety
3638/// `offset + 4` must be `<= bytes.len()`.
3639#[inline]
3640unsafe fn read_i32_unchecked(bytes: &[u8], offset: usize) -> i32 {
3641    i32::from_le_bytes([
3642        // SAFETY: each index below is `< offset + 4 <= len` per the caller.
3643        unsafe { *bytes.get_unchecked(offset) },
3644        // SAFETY: as above.
3645        unsafe { *bytes.get_unchecked(offset + 1) },
3646        // SAFETY: as above.
3647        unsafe { *bytes.get_unchecked(offset + 2) },
3648        // SAFETY: as above.
3649        unsafe { *bytes.get_unchecked(offset + 3) },
3650    ])
3651}
3652
3653#[inline]
3654fn read_i32x4(bytes: &[u8], offset: usize) -> [i32; 4] {
3655    [
3656        read_i32(bytes, offset),
3657        read_i32(bytes, offset + 4),
3658        read_i32(bytes, offset + 8),
3659        read_i32(bytes, offset + 12),
3660    ]
3661}
3662
3663#[inline]
3664fn read_world_uvs(bytes: &[u8], offset: usize) -> WorldQuadUvs {
3665    WorldQuadUvs::new([
3666        (bytes[offset], bytes[offset + 1]),
3667        (bytes[offset + 2], bytes[offset + 3]),
3668        (bytes[offset + 4], bytes[offset + 5]),
3669        (bytes[offset + 6], bytes[offset + 7]),
3670    ])
3671}
3672
3673#[inline]
3674fn read_world_horizontal_override(bytes: &[u8]) -> WorldHorizontalOverride {
3675    WorldHorizontalOverride {
3676        flags: bytes[3],
3677        materials: [read_u16(bytes, 4), read_u16(bytes, 6)],
3678        uvs: [read_world_uvs(bytes, 8), read_world_uvs(bytes, 16)],
3679        heights: (bytes.len() >= psxed_format::world::HorizontalOverrideRecord::SIZE).then(|| {
3680            [
3681                [
3682                    read_i32(bytes, 24),
3683                    read_i32(bytes, 28),
3684                    read_i32(bytes, 32),
3685                ],
3686                [
3687                    read_i32(bytes, 36),
3688                    read_i32(bytes, 40),
3689                    read_i32(bytes, 44),
3690                ],
3691            ]
3692        }),
3693    }
3694}
3695
3696#[inline]
3697fn read_world_surface_light(bytes: &[u8], offset: usize) -> WorldSurfaceLight {
3698    WorldSurfaceLight::new([
3699        [bytes[offset], bytes[offset + 1], bytes[offset + 2]],
3700        [bytes[offset + 3], bytes[offset + 4], bytes[offset + 5]],
3701        [bytes[offset + 6], bytes[offset + 7], bytes[offset + 8]],
3702        [bytes[offset + 9], bytes[offset + 10], bytes[offset + 11]],
3703    ])
3704}
3705
3706fn validate_horizontal_overrides(
3707    overrides: &[u8],
3708    override_count: u16,
3709    sector_count: u16,
3710    record_size: usize,
3711) -> Result<(), ParseError> {
3712    let size = record_size;
3713    if overrides.len() != override_count as usize * size {
3714        return Err(ParseError::InvalidWorldLayout);
3715    }
3716    for index in 0..override_count as usize {
3717        let base = index * size;
3718        let sector_index = read_u16(overrides, base);
3719        let surface = overrides[base + 2];
3720        if sector_index >= sector_count {
3721            return Err(ParseError::InvalidWorldLayout);
3722        }
3723        if surface != psxed_format::world::horizontal_surface::FLOOR
3724            && surface != psxed_format::world::horizontal_surface::CEILING
3725        {
3726            return Err(ParseError::InvalidWorldLayout);
3727        }
3728    }
3729    Ok(())
3730}
3731
3732fn validate_sector_wall_ranges(
3733    sectors: &[u8],
3734    sector_record_size: usize,
3735    wall_count: u16,
3736) -> Result<(), ParseError> {
3737    let size = sector_record_size;
3738    let count = sectors.len() / size;
3739    for index in 0..count {
3740        let base = index * size;
3741        let first_wall = read_u16(sectors, base + 8);
3742        let sector_wall_count = read_u16(sectors, base + 10);
3743        let Some(end) = first_wall.checked_add(sector_wall_count) else {
3744            return Err(ParseError::InvalidWorldLayout);
3745        };
3746        if end > wall_count {
3747            return Err(ParseError::InvalidWorldLayout);
3748        }
3749    }
3750    Ok(())
3751}
3752
3753#[cfg(test)]
3754extern crate std;
3755
3756#[cfg(test)]
3757mod tests;