Skip to main content

roxlap_formats/
sprite.rs

1//! KV6 sprite — a parsed [`Kv6`] paired with a world-space pose.
2//!
3//! Mirror of voxlap's `vx5sprite` (``) for the kv6
4//! case (`flags & SPRITE_FLAG_KFA == 0`). Pure data — owns the
5//! [`Kv6`] voxel grid plus the four `point3d` fields voxlap calls
6//! `p` (pivot position), `s` (x-basis), `h` (y-basis), `f`
7//! (z-basis), and the bitfield `flags`.
8//!
9//! Rendering lives in `roxlap-core` (`draw_sprite`); this module
10//! only models the data shape so downstream tools (file
11//! converters, model inspectors, asset pipelines) can build and
12//! manipulate sprites without depending on the full renderer.
13//!
14//! Voxlap's 64-byte layout, for reference:
15//!
16//! ```text
17//! point3d p;       // position
18//! int32_t flags;   // bit 0: 0=normal shading
19//!                  // bit 1: 0=kv6data, 1=kfatype
20//!                  // bit 2: 0=normal, 1=invisible
21//!                  // bit 3: 0=z-tested, 1=overlay (no-z)
22//! point3d s;       // x-basis (kv6data.xsiz direction)
23//! kv6data *voxnum; // (or kfatype *kfaptr if flag bit 1 set)
24//! point3d h;       // y-basis
25//! int32_t kfatim;
26//! point3d f;       // z-basis
27//! int32_t okfatim;
28//! ```
29
30use crate::kv6::Kv6;
31
32/// Voxlap's sprite-flags bit 0: disable normal-based face shading.
33pub const SPRITE_FLAG_NO_SHADING: u32 = 1 << 0;
34/// Voxlap's sprite-flags bit 1: voxnum points at a `kfatype`
35/// (animated). When clear (default), points at a `kv6data`.
36pub const SPRITE_FLAG_KFA: u32 = 1 << 1;
37/// Voxlap's sprite-flags bit 2: skip rendering entirely.
38pub const SPRITE_FLAG_INVISIBLE: u32 = 1 << 2;
39/// Voxlap's sprite-flags bit 3: render without z-buffer test.
40pub const SPRITE_FLAG_NO_Z: u32 = 1 << 3;
41/// roxlap extension (XS.4), bit 4: this sprite does **not** cast a hard
42/// shadow onto terrain / other sprites. Clear (the default) ⇒ it casts.
43pub const SPRITE_FLAG_NO_SHADOW_CAST: u32 = 1 << 4;
44/// roxlap extension (XS.4), bit 5: this sprite does **not** receive hard
45/// shadows (it isn't darkened by occluders). Clear (the default) ⇒ it
46/// receives. Both shadow bits default to participating, matching the
47/// dynamic-lighting rig's "shadows on" intent; set a bit to opt a sprite
48/// out (e.g. a glowing effect that shouldn't be shadowed).
49pub const SPRITE_FLAG_NO_SHADOW_RECEIVE: u32 = 1 << 5;
50
51/// roxlap extension (BB.2b), bit 6: light this sprite with a fixed **world-up**
52/// surface normal instead of the DDA hit-face normal — stable directional
53/// shading for a camera-facing billboard (whose face normal would otherwise
54/// track the camera). Clear ⇒ the face normal (default). Ignored if
55/// [`SPRITE_FLAG_LIGHT_AMBIENT_ONLY`] is also set.
56pub const SPRITE_FLAG_LIGHT_WORLD_UP: u32 = 1 << 6;
57/// roxlap extension (BB.2b), bit 7: light this sprite with **ambient only**
58/// (no sun / point-light direct term) — the flattest, most Doom-faithful
59/// billboard look (a flat cutout that ignores the light direction). Clear ⇒
60/// direct lighting applies. Takes precedence over
61/// [`SPRITE_FLAG_LIGHT_WORLD_UP`].
62pub const SPRITE_FLAG_LIGHT_AMBIENT_ONLY: u32 = 1 << 7;
63
64/// The neutral (no-op) value for [`Sprite::tint`] — white, so every channel
65/// multiplies by 1.0.
66pub const NO_TINT: u32 = 0x00FF_FFFF;
67
68/// A KV6 voxel sprite positioned in world space.
69///
70/// Mirror of voxlap's `vx5sprite` for the kv6 case
71/// (`flags & SPRITE_FLAG_KFA == 0`; see [`SPRITE_FLAG_KFA`]).
72/// Owns its [`Kv6`] by value. `p` / `s` / `h` / `f` are voxlap's
73/// per-axis world-space basis: `s` is the `kv6.xsiz` direction,
74/// `h` the `ysiz` direction, `f` the `zsiz` direction. For an
75/// axis-aligned sprite, `s = [1,0,0]`, `h = [0,1,0]`,
76/// `f = [0,0,1]`.
77#[derive(Debug, Clone)]
78pub struct Sprite {
79    /// Voxel data + bounding-box pivots. Loaded from a `.kv6`
80    /// file via [`crate::kv6::parse`] or built procedurally.
81    pub kv6: Kv6,
82    /// World-space position of the sprite's pivot (xpiv, ypiv,
83    /// zpiv inside the kv6 maps to this point).
84    pub p: [f32; 3],
85    /// World-space basis vector for the kv6's local +x. Length
86    /// scales the sprite along that axis (typically `1.0` for
87    /// unit-scale).
88    pub s: [f32; 3],
89    /// World-space basis vector for the kv6's local +y.
90    pub h: [f32; 3],
91    /// World-space basis vector for the kv6's local +z.
92    pub f: [f32; 3],
93    /// Voxlap-style flags bitfield. See [`SPRITE_FLAG_NO_SHADING`],
94    /// [`SPRITE_FLAG_KFA`], [`SPRITE_FLAG_INVISIBLE`],
95    /// [`SPRITE_FLAG_NO_Z`].
96    pub flags: u32,
97    /// Voxel-material id (TV stage) applied uniformly to this sprite's
98    /// voxels — indexes the renderer's global
99    /// [`MaterialTable`](crate::material::MaterialTable) for opacity + blend
100    /// mode. `0` (the default) is opaque, so an un-set sprite renders exactly
101    /// as before. See `PORTING-TRANSPARENCY.md`.
102    pub material: u8,
103    /// Per-instance opacity multiplier (TV stage), `0..=255` (`255` =
104    /// unscaled, the default). Scales the material's alpha so an effect can
105    /// fade out by cheap per-frame updates without re-uploading its volume.
106    pub alpha_mul: u8,
107    /// Per-instance RGB colour tint, packed `0x00RRGGBB`. Each rendered voxel's
108    /// colour is multiplied by this (per channel, `out = c * tint / 255`), so a
109    /// host can recolour instances of one model cheaply. `0x00FF_FFFF` (white,
110    /// the default) is a no-op. Alpha is **not** carried here — use a
111    /// translucent material + [`alpha_mul`](Self::alpha_mul) for transparency.
112    pub tint: u32,
113    /// Per-voxel material colour map (TV.3): `(rgb, material_id)` pairs that
114    /// classify this model's voxels into materials by colour — a mixed model
115    /// (opaque frame + glass, bottle + potion). **Empty** (the default) means
116    /// the whole sprite uses [`material`](Self::material) uniformly (the TV.1
117    /// path). See [`crate::material::material_for_color`].
118    pub material_map: Vec<(u32, u8)>,
119}
120
121impl Sprite {
122    /// Convenience constructor for an axis-aligned sprite at
123    /// world position `pos`. Basis is identity, flags = 0
124    /// (kv6 + normal shading + visible + z-tested).
125    ///
126    /// # Examples
127    ///
128    /// ```
129    /// use roxlap_formats::kv6::Kv6;
130    /// use roxlap_formats::sprite::Sprite;
131    ///
132    /// # let kv6 = Kv6 {
133    /// #     xsiz: 1, ysiz: 1, zsiz: 1,
134    /// #     xpiv: 0.5, ypiv: 0.5, zpiv: 0.5,
135    /// #     voxels: vec![], xlen: vec![0], ylen: vec![vec![0]],
136    /// #     palette: None,
137    /// # };
138    /// // ... after `let kv6 = kv6::parse(&bytes)?;` or similar:
139    /// let sprite = Sprite::axis_aligned(kv6, [1024.0, 1024.0, 100.0]);
140    /// assert_eq!(sprite.flags, 0);
141    /// assert_eq!(sprite.s, [1.0, 0.0, 0.0]);
142    /// ```
143    #[must_use]
144    pub fn axis_aligned(kv6: Kv6, pos: [f32; 3]) -> Self {
145        Self {
146            kv6,
147            p: pos,
148            s: [1.0, 0.0, 0.0],
149            h: [0.0, 1.0, 0.0],
150            f: [0.0, 0.0, 1.0],
151            flags: 0,
152            material: 0,
153            alpha_mul: 255,
154            tint: NO_TINT,
155            material_map: Vec::new(),
156        }
157    }
158
159    /// Set this sprite's RGB colour tint (`0x00RRGGBB`, white = no-op). Returns
160    /// `self` for chaining. See [`tint`](Self::tint).
161    #[must_use]
162    pub fn with_tint(mut self, tint: u32) -> Self {
163        self.tint = tint & 0x00FF_FFFF;
164        self
165    }
166
167    /// XS.4 — whether this sprite casts a hard shadow (the [dynamic-lighting
168    /// stage](../../../PORTING-DYNLIGHT.md) decides it darkens terrain / other
169    /// sprites). `true` unless [`SPRITE_FLAG_NO_SHADOW_CAST`] is set.
170    #[must_use]
171    pub fn casts_shadow(&self) -> bool {
172        self.flags & SPRITE_FLAG_NO_SHADOW_CAST == 0
173    }
174
175    /// XS.4 — whether this sprite receives hard shadows (is darkened by
176    /// occluders). `true` unless [`SPRITE_FLAG_NO_SHADOW_RECEIVE`] is set.
177    #[must_use]
178    pub fn receives_shadow(&self) -> bool {
179        self.flags & SPRITE_FLAG_NO_SHADOW_RECEIVE == 0
180    }
181
182    /// XS.4 — set whether this sprite casts a hard shadow (clears/sets
183    /// [`SPRITE_FLAG_NO_SHADOW_CAST`]). Returns `self` for chaining.
184    #[must_use]
185    pub fn with_casts_shadow(mut self, casts: bool) -> Self {
186        if casts {
187            self.flags &= !SPRITE_FLAG_NO_SHADOW_CAST;
188        } else {
189            self.flags |= SPRITE_FLAG_NO_SHADOW_CAST;
190        }
191        self
192    }
193
194    /// XS.4 — set whether this sprite receives hard shadows (clears/sets
195    /// [`SPRITE_FLAG_NO_SHADOW_RECEIVE`]). Returns `self` for chaining.
196    #[must_use]
197    pub fn with_receives_shadow(mut self, receives: bool) -> Self {
198        if receives {
199            self.flags &= !SPRITE_FLAG_NO_SHADOW_RECEIVE;
200        } else {
201            self.flags |= SPRITE_FLAG_NO_SHADOW_RECEIVE;
202        }
203        self
204    }
205
206    /// Carve a sphere out of this sprite's voxel model, controlling
207    /// the colour of the interior the cut exposes. Thin delegate to
208    /// [`Kv6::carve_sphere_with_colfunc`] — `centre` / `radius`,
209    /// `solid`, and `colfunc` are all in **kv6-local** voxel
210    /// coordinates (the sprite pose `p`/`s`/`h`/`f` is untouched). See
211    /// that method for why the `solid` occupancy predicate is required.
212    pub fn carve_sphere_with_colfunc<S, C>(
213        &mut self,
214        centre: [i32; 3],
215        radius: u32,
216        solid: S,
217        colfunc: C,
218    ) where
219        S: Fn(i32, i32, i32) -> bool,
220        C: Fn(i32, i32, i32) -> u32,
221    {
222        self.kv6
223            .carve_sphere_with_colfunc(centre, radius, solid, colfunc);
224    }
225}
226
227#[cfg(test)]
228mod tests {
229    use super::*;
230
231    /// XS.4 — sprite shadow flags default to participating and toggle cleanly,
232    /// independently of each other.
233    #[test]
234    fn sprite_shadow_flags_default_on_and_toggle() {
235        let kv6 = Kv6::from_fn_shaded(2, 2, 2, |_, _, _| Some(0x8033_4455));
236        let s = Sprite::axis_aligned(kv6, [0.0; 3]);
237        // Default: casts + receives.
238        assert!(s.casts_shadow() && s.receives_shadow());
239
240        let no_cast = s.clone().with_casts_shadow(false);
241        assert!(!no_cast.casts_shadow() && no_cast.receives_shadow());
242        assert_eq!(
243            no_cast.flags & SPRITE_FLAG_NO_SHADOW_CAST,
244            SPRITE_FLAG_NO_SHADOW_CAST
245        );
246
247        let no_recv = s.clone().with_receives_shadow(false);
248        assert!(no_recv.casts_shadow() && !no_recv.receives_shadow());
249
250        // Toggling one bit leaves the other (and unrelated flags) untouched.
251        let neither = s
252            .clone()
253            .with_casts_shadow(false)
254            .with_receives_shadow(false);
255        assert!(!neither.casts_shadow() && !neither.receives_shadow());
256        let back = neither.with_casts_shadow(true);
257        assert!(back.casts_shadow() && !back.receives_shadow());
258    }
259
260    #[test]
261    fn carve_sphere_delegates_to_kv6_and_leaves_pose() {
262        const BASE: u32 = 0x8033_4455;
263        let kv6 = Kv6::from_fn_shaded(16, 16, 16, |_, _, _| Some(BASE));
264        let mut sprite = Sprite::axis_aligned(kv6, [10.0, 20.0, 30.0]);
265        let before = sprite.kv6.voxels.len();
266
267        sprite.carve_sphere_with_colfunc([8, 8, 8], 4, |_, _, _| true, |_, _, _| 0x8000_FF00);
268
269        // The hollowed-out shell has more surface voxels than the
270        // solid hull did, so the model definitely changed.
271        assert_ne!(sprite.kv6.voxels.len(), before);
272        // Pose untouched — carving is kv6-local only.
273        assert_eq!(sprite.p, [10.0, 20.0, 30.0]);
274        assert_eq!(sprite.s, [1.0, 0.0, 0.0]);
275    }
276}