Skip to main content

lactea_render/
sprite.rs

1// SPDX-FileCopyrightText: 2026 Gianluca Boiano
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! MilkDrop 3 preset sprites: the quad draw with the 11 blend modes (MD3 3.37, docs/md3.md "Sprites").
5//!
6//! MD3 draws a sprite with the fixed-function D3D9 pipeline: vertex colour, one texture stage and a blend
7//! state. The stage arithmetic is reproduced by one fragment entry point per mode, the blend factors by the
8//! pipeline's blend state, so each mode is exactly `out = C * SRC + D * DEST` of the table in the docs.
9//! Everything that decides *what* is drawn (sprite state, geometry, GIF frame) is the engine's; this module
10//! only turns a [`SpriteDraw`] into pixels.
11
12use std::collections::HashMap;
13use wgpu::util::DeviceExt;
14
15/// Number of blend modes (`0..=10`).
16pub const SPRITE_MODES: usize = 11;
17
18/// One corner of a sprite quad.
19#[derive(Clone, Copy, Debug, PartialEq)]
20pub struct SpriteVertex {
21    /// Position in MD3's sprite space: `±1` is the target's edge, **y points down** (the D3D 2D projection of
22    /// MilkDrop flips y), z is 0.
23    pub pos: [f32; 2],
24    /// Texture coordinate (row 0 = top of the image); the sampler wraps in both directions.
25    pub uv: [f32; 2],
26}
27
28/// One sprite draw handed to the renderer in [`FrameInput::sprites`](crate::FrameInput::sprites).
29#[derive(Clone, Debug)]
30pub struct SpriteDraw {
31    /// Where it is drawn: `1..=4` into the feedback image (between warp / shapes / waves / main wave, so it
32    /// goes through the composite and is warped next frame), `0` onto the composited output. Other values are
33    /// not drawn.
34    pub layer: u8,
35    /// Image id given to [`Renderer::set_sprite_image`](crate::Renderer::set_sprite_image).
36    pub image: u32,
37    /// Frame of that image (animated GIFs); out of range draws nothing.
38    pub frame: usize,
39    /// Blend mode `0..=10`; any other value behaves as mode 0.
40    pub blend: i32,
41    /// `r, g, b` clamped to `0..1`; `a` is the per-frame alpha times the preset's `SpriteAlpha`, **not**
42    /// clamped (the vertex colour byte wraps like `trunc(255 a) & 0xFF`).
43    pub rgba: [f32; 4],
44    /// Triangle-strip order.
45    pub quad: [SpriteVertex; 4],
46    /// Layer 0: the sprite is also drawn into the feedback image after the composite has read it. Layers 1..4
47    /// already draw into the feedback image; there a burning sprite is drawn twice
48    /// (`CompatRules::md3_sprite_burn_twice`).
49    pub burn: bool,
50}
51
52/// The mode a `blend` value selects (`0` for anything outside `0..=10`).
53pub fn sprite_mode(blend: i32) -> usize {
54    if (0..SPRITE_MODES as i32).contains(&blend) {
55        blend as usize
56    } else {
57        0
58    }
59}
60
61/// `trunc(255 x) & 0xFF`: how D3D packs a float vertex colour channel.
62fn q8(x: f32) -> u8 {
63    ((x * 255.0) as i32 & 0xFF) as u8
64}
65
66/// The vertex colour `(r, g, b, a)` of a sprite in `mode`, after the byte quantisation of `D3DCOLOR`.
67///
68/// Modes 1 and 2 premultiply the colour by `a` and force alpha 1, mode 3 is plain white, mode 7 has a white
69/// colour (its colour comes from the texture and `TFACTOR`), mode 8 folds the colour `c` to `c > 0.5 ? 1 - c : c`.
70pub fn sprite_vertex_color(mode: usize, rgba: [f32; 4]) -> [u8; 4] {
71    let [r, g, b, a] = rgba;
72    match mode {
73        1 | 2 => [q8(r * a), q8(g * a), q8(b * a), 255],
74        3 => [255; 4],
75        7 => [255, 255, 255, q8(a)],
76        8 => {
77            let f = |c: f32| if c > 0.5 { 1.0 - c } else { c };
78            [q8(f(r)), q8(f(g)), q8(f(b)), q8(a)]
79        }
80        _ => [q8(r), q8(g), q8(b), q8(a)],
81    }
82}
83
84/// CPU model of the table: result of drawing a texel `texel` (straight alpha) over the destination colour `dst`
85/// with a sprite of colour `rgba` in `mode`, in `0..=255` units (not rounded). It follows the table, not the
86/// shader: stage colour `C` / alpha `A`, then `out = C * SRC + D * DEST` with the mode's factors.
87pub fn sprite_blend_reference(
88    mode: usize,
89    rgba: [f32; 4],
90    texel: [u8; 4],
91    dst: [u8; 3],
92) -> [f32; 3] {
93    let v = sprite_vertex_color(mode, rgba).map(|c| f32::from(c) / 255.0);
94    let t = texel.map(|c| f32::from(c) / 255.0);
95    let d = dst.map(|c| f32::from(c) / 255.0);
96    let sat = |x: f32| x.clamp(0.0, 1.0);
97    // stage-0 alpha: MODULATE(diffuse, texture) for 4, 7, 8, the diffuse alpha otherwise
98    let a = match mode {
99        4 | 7 | 8 => v[3] * t[3],
100        _ => v[3],
101    };
102    let mut c = [0.0f32; 3];
103    for i in 0..3 {
104        c[i] = match mode {
105            3 => t[i],
106            7 => sat(1.0 - t[i]),
107            9 => sat(t[i] + v[i] - 0.5),
108            10 => sat(2.0 * t[i] * v[i]),
109            _ => v[i] * t[i],
110        };
111    }
112    let mut out = [0.0f32; 3];
113    for i in 0..3 {
114        // (SRC factor, DEST factor)
115        let (s, dd) = match mode {
116            1 => (1.0, 0.0), // blend off
117            2 | 10 => (1.0, 1.0),
118            3 => (c[i], 1.0 - c[i]),
119            5 => (d[i], 0.0),
120            6 => (0.0, 1.0 - c[i]),
121            9 => (0.0, c[i]),
122            _ => (a, 1.0 - a),
123        };
124        out[i] = sat(c[i] * s + d[i] * dd) * 255.0;
125    }
126    out
127}
128
129/// GIF frame choice (MD3 3.37): `t = fmod(time, sum(delays))`, the first frame whose cumulative delay is
130/// strictly greater than `t`, else the last. One frame, no delays or a non-positive total always give frame 0.
131/// `delays` are in seconds and already follow the "`<= 0` means 0.1 s" rule.
132pub fn gif_frame_index(delays: &[f64], time: f64) -> usize {
133    let total: f64 = delays.iter().sum();
134    if delays.len() < 2 || total.partial_cmp(&0.0) != Some(std::cmp::Ordering::Greater) {
135        return 0;
136    }
137    let t = time % total;
138    let mut acc = 0.0;
139    for (i, d) in delays.iter().enumerate() {
140        acc += d;
141        if acc > t {
142            return i;
143        }
144    }
145    delays.len() - 1
146}
147
148/// An image registered with [`Renderer::set_sprite_image`](crate::Renderer::set_sprite_image).
149pub(crate) struct SpriteImage {
150    /// One view per animation frame (a view keeps its texture alive).
151    pub(crate) frames: Vec<wgpu::TextureView>,
152}
153
154/// GPU vertex of a sprite quad.
155#[repr(C)]
156#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
157struct GpuVertex {
158    pos: [f32; 2],
159    uv: [f32; 2],
160    color: [f32; 4],
161}
162
163const ATTRS: [wgpu::VertexAttribute; 3] =
164    wgpu::vertex_attr_array![0 => Float32x2, 1 => Float32x2, 2 => Float32x4];
165
166/// Vertex stage (sprite space has y down) and one fragment entry point per mode, each producing the stage-0
167/// colour and alpha of the table.
168const SRC: &str = r#"
169@group(0) @binding(0) var tex: texture_2d<f32>;
170@group(0) @binding(1) var samp: sampler;
171
172struct VOut {
173    @builtin(position) position: vec4<f32>,
174    @location(0) uv: vec2<f32>,
175    @location(1) color: vec4<f32>,
176};
177
178@vertex
179fn vs_main(@location(0) pos: vec2<f32>, @location(1) uv: vec2<f32>, @location(2) color: vec4<f32>) -> VOut {
180    var o: VOut;
181    o.position = vec4<f32>(pos.x, -pos.y, 0.0, 1.0);
182    o.uv = uv;
183    o.color = color;
184    return o;
185}
186
187fn texel(in: VOut) -> vec4<f32> { return textureSample(tex, samp, in.uv); }
188
189// 0 Blend: MODULATE(diffuse, texture) colour, diffuse alpha
190@fragment fn fs0(in: VOut) -> @location(0) vec4<f32> {
191    let t = texel(in);
192    return vec4<f32>(in.color.rgb * t.rgb, in.color.a);
193}
194// 1 Decal, 2 Additive: colour only, alpha 1 (decal: blending off)
195@fragment fn fs1(in: VOut) -> @location(0) vec4<f32> {
196    let t = texel(in);
197    return vec4<f32>(in.color.rgb * t.rgb, 1.0);
198}
199@fragment fn fs2(in: VOut) -> @location(0) vec4<f32> {
200    let t = texel(in);
201    return vec4<f32>(in.color.rgb * t.rgb, 1.0);
202}
203// 3 Srccolor: the texture alone
204@fragment fn fs3(in: VOut) -> @location(0) vec4<f32> {
205    let t = texel(in);
206    return vec4<f32>(t.rgb, 1.0);
207}
208// 4 Colorkey: alpha = diffuse * texture alpha
209@fragment fn fs4(in: VOut) -> @location(0) vec4<f32> {
210    let t = texel(in);
211    return vec4<f32>(in.color.rgb * t.rgb, in.color.a * t.a);
212}
213// 5 Multiplicative, 6 Subtractive: colour only
214@fragment fn fs5(in: VOut) -> @location(0) vec4<f32> {
215    let t = texel(in);
216    return vec4<f32>(in.color.rgb * t.rgb, in.color.a);
217}
218@fragment fn fs6(in: VOut) -> @location(0) vec4<f32> {
219    let t = texel(in);
220    return vec4<f32>(in.color.rgb * t.rgb, in.color.a);
221}
222// 7 Invert: SUBTRACT(TFACTOR = white, texture)
223@fragment fn fs7(in: VOut) -> @location(0) vec4<f32> {
224    let t = texel(in);
225    return vec4<f32>(clamp(vec3<f32>(1.0) - t.rgb, vec3<f32>(0.0), vec3<f32>(1.0)), in.color.a * t.a);
226}
227// 8 Cut-off: MODULATE(texture, diffuse), alpha = diffuse * texture alpha
228@fragment fn fs8(in: VOut) -> @location(0) vec4<f32> {
229    let t = texel(in);
230    return vec4<f32>(t.rgb * in.color.rgb, in.color.a * t.a);
231}
232// 9 Darken: ADDSIGNED(texture, diffuse)
233@fragment fn fs9(in: VOut) -> @location(0) vec4<f32> {
234    let t = texel(in);
235    return vec4<f32>(clamp(t.rgb + in.color.rgb - vec3<f32>(0.5), vec3<f32>(0.0), vec3<f32>(1.0)), in.color.a);
236}
237// 10 Vivid: MODULATE2X(texture, diffuse)
238@fragment fn fs10(in: VOut) -> @location(0) vec4<f32> {
239    let t = texel(in);
240    return vec4<f32>(clamp(2.0 * t.rgb * in.color.rgb, vec3<f32>(0.0), vec3<f32>(1.0)), in.color.a);
241}
242"#;
243
244/// `(SRCBLEND, DESTBLEND)` of a mode; `None` = alpha blending off (decal).
245fn factors(mode: usize) -> Option<(wgpu::BlendFactor, wgpu::BlendFactor)> {
246    use wgpu::BlendFactor as F;
247    Some(match mode {
248        1 => return None,
249        2 | 10 => (F::One, F::One),
250        3 => (F::Src, F::OneMinusSrc),
251        5 => (F::Dst, F::Zero),
252        6 => (F::Zero, F::OneMinusSrc),
253        9 => (F::Zero, F::Src),
254        _ => (F::SrcAlpha, F::OneMinusSrcAlpha),
255    })
256}
257
258/// The 11 sprite pipelines, built on first use.
259pub(crate) struct SpritePipes {
260    pipelines: Vec<wgpu::RenderPipeline>,
261}
262
263impl SpritePipes {
264    pub(crate) fn new(
265        device: &wgpu::Device,
266        bgl_tex: &wgpu::BindGroupLayout,
267        format: wgpu::TextureFormat,
268    ) -> Self {
269        let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
270            label: Some("sprite"),
271            source: wgpu::ShaderSource::Wgsl(SRC.into()),
272        });
273        let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
274            label: Some("sprite"),
275            bind_group_layouts: &[Some(bgl_tex)],
276            immediate_size: 0,
277        });
278        let pipelines = (0..SPRITE_MODES)
279            .map(|mode| {
280                let entry = format!("fs{mode}");
281                // the destination alpha is never touched: it carries no meaning in the MilkDrop 2 family
282                let keep_alpha = wgpu::BlendComponent {
283                    src_factor: wgpu::BlendFactor::Zero,
284                    dst_factor: wgpu::BlendFactor::One,
285                    operation: wgpu::BlendOperation::Add,
286                };
287                let blend = factors(mode).map(|(s, d)| wgpu::BlendState {
288                    color: wgpu::BlendComponent {
289                        src_factor: s,
290                        dst_factor: d,
291                        operation: wgpu::BlendOperation::Add,
292                    },
293                    alpha: keep_alpha,
294                });
295                device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
296                    label: Some("sprite"),
297                    layout: Some(&layout),
298                    vertex: wgpu::VertexState {
299                        module: &module,
300                        entry_point: Some("vs_main"),
301                        compilation_options: Default::default(),
302                        buffers: &[Some(wgpu::VertexBufferLayout {
303                            array_stride: std::mem::size_of::<GpuVertex>() as u64,
304                            step_mode: wgpu::VertexStepMode::Vertex,
305                            attributes: &ATTRS,
306                        })],
307                    },
308                    primitive: wgpu::PrimitiveState {
309                        topology: wgpu::PrimitiveTopology::TriangleStrip,
310                        ..Default::default()
311                    },
312                    depth_stencil: None,
313                    multisample: wgpu::MultisampleState::default(),
314                    fragment: Some(wgpu::FragmentState {
315                        module: &module,
316                        entry_point: Some(&entry),
317                        compilation_options: Default::default(),
318                        targets: &[Some(wgpu::ColorTargetState {
319                            format,
320                            blend,
321                            write_mask: wgpu::ColorWrites::ALL,
322                        })],
323                    }),
324                    multiview_mask: None,
325                    cache: None,
326                })
327            })
328            .collect();
329        Self { pipelines }
330    }
331
332    /// Draw `draws` in order onto `target` (loaded, not cleared).
333    pub(crate) fn draw(
334        &self,
335        device: &wgpu::Device,
336        encoder: &mut wgpu::CommandEncoder,
337        target: &wgpu::TextureView,
338        bgl_tex: &wgpu::BindGroupLayout,
339        sampler: &wgpu::Sampler,
340        images: &HashMap<u32, SpriteImage>,
341        draws: &[&SpriteDraw],
342    ) {
343        let mut verts: Vec<GpuVertex> = Vec::with_capacity(draws.len() * 4);
344        let mut groups: Vec<(usize, wgpu::BindGroup)> = Vec::with_capacity(draws.len());
345        for d in draws {
346            let Some(view) = images.get(&d.image).and_then(|i| i.frames.get(d.frame)) else {
347                continue;
348            };
349            let mode = sprite_mode(d.blend);
350            let color = sprite_vertex_color(mode, d.rgba).map(|c| f32::from(c) / 255.0);
351            verts.extend(d.quad.iter().map(|v| GpuVertex {
352                pos: v.pos,
353                uv: v.uv,
354                color,
355            }));
356            groups.push((
357                mode,
358                device.create_bind_group(&wgpu::BindGroupDescriptor {
359                    label: Some("sprite"),
360                    layout: bgl_tex,
361                    entries: &[
362                        wgpu::BindGroupEntry {
363                            binding: 0,
364                            resource: wgpu::BindingResource::TextureView(view),
365                        },
366                        wgpu::BindGroupEntry {
367                            binding: 1,
368                            resource: wgpu::BindingResource::Sampler(sampler),
369                        },
370                    ],
371                }),
372            ));
373        }
374        if groups.is_empty() {
375            return;
376        }
377        let buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
378            label: Some("sprite verts"),
379            contents: bytemuck::cast_slice(&verts),
380            usage: wgpu::BufferUsages::VERTEX,
381        });
382        let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
383            label: Some("sprites"),
384            color_attachments: &[Some(wgpu::RenderPassColorAttachment {
385                view: target,
386                depth_slice: None,
387                resolve_target: None,
388                ops: wgpu::Operations {
389                    load: wgpu::LoadOp::Load,
390                    store: wgpu::StoreOp::Store,
391                },
392            })],
393            ..Default::default()
394        });
395        pass.set_vertex_buffer(0, buf.slice(..));
396        for (i, (mode, bg)) in groups.iter().enumerate() {
397            pass.set_pipeline(&self.pipelines[*mode]);
398            pass.set_bind_group(0, bg, &[]);
399            let s = (i * 4) as u32;
400            pass.draw(s..s + 4, 0..1);
401        }
402    }
403}
404
405#[cfg(test)]
406mod tests {
407    use super::*;
408
409    /// `T = (204, 102, 51, 255)`, `D = 128` of the blend table.
410    const T: [u8; 4] = [204, 102, 51, 255];
411    const D: [u8; 3] = [128; 3];
412
413    fn rounded(mode: usize, rgb: [f32; 3]) -> [i32; 3] {
414        sprite_blend_reference(mode, [rgb[0], rgb[1], rgb[2], 0.4], T, D).map(|c| c.round() as i32)
415    }
416
417    fn near(a: [i32; 3], b: [i32; 3]) -> bool {
418        a.iter().zip(b).all(|(x, y)| (x - y).abs() <= 1)
419    }
420
421    /// The reference reproduces the worked example of the specification (+-1 for hardware rounding).
422    #[test]
423    fn reference_matches_the_documented_example() {
424        let white = [
425            [158, 118, 97],
426            [82, 41, 20],
427            [210, 169, 148],
428            [189, 118, 113],
429            [158, 118, 97],
430            [102, 51, 26],
431            [26, 77, 102],
432            [97, 138, 158],
433            [77, 77, 77],
434            [128, 115, 90],
435            [255, 255, 230],
436        ];
437        let tint = [
438            [158, 101, 81],
439            [82, 24, 4],
440            [210, 152, 132],
441            [189, 118, 113],
442            [158, 101, 81],
443            [102, 31, 5],
444            [26, 97, 123],
445            [97, 138, 158],
446            [77, 93, 81],
447            [128, 64, 0],
448            [255, 250, 148],
449        ];
450        for mode in 0..SPRITE_MODES {
451            let got = rounded(mode, [1.0, 1.0, 1.0]);
452            assert!(near(got, white[mode]), "mode {mode} white: {got:?}");
453            let got = rounded(mode, [1.0, 0.6, 0.2]);
454            assert!(near(got, tint[mode]), "mode {mode} tint: {got:?}");
455        }
456    }
457
458    #[test]
459    fn keyed_texels_leave_the_destination_for_alpha_textured_modes() {
460        let keyed = [204, 102, 51, 0];
461        for mode in [4, 7, 8] {
462            let out = sprite_blend_reference(mode, [1.0, 1.0, 1.0, 0.4], keyed, D);
463            assert_eq!(out.map(|c| c.round() as i32), [128; 3], "mode {mode}");
464        }
465        // the others ignore the texel alpha
466        for mode in [0, 1, 2, 3, 5, 6, 9, 10] {
467            let a = sprite_blend_reference(mode, [1.0, 0.6, 0.2, 0.4], keyed, D);
468            let b = sprite_blend_reference(mode, [1.0, 0.6, 0.2, 0.4], T, D);
469            assert_eq!(a, b, "mode {mode}");
470        }
471    }
472
473    #[test]
474    fn vertex_colours_follow_the_table() {
475        let rgba = [1.0, 0.6, 0.2, 0.4];
476        assert_eq!(sprite_vertex_color(0, rgba), [255, 153, 51, 102]);
477        assert_eq!(sprite_vertex_color(1, rgba), [102, 61, 20, 255]);
478        assert_eq!(sprite_vertex_color(3, rgba), [255; 4]);
479        assert_eq!(sprite_vertex_color(7, rgba), [255, 255, 255, 102]);
480        // mode 8 folds the colour: 0.6 -> 0.4
481        let v8 = sprite_vertex_color(8, rgba);
482        assert_eq!((v8[0], v8[2], v8[3]), (0, 51, 102));
483        assert!((101..=102).contains(&v8[1]), "{v8:?}");
484        // the alpha byte wraps like `& 0xFF`
485        assert_eq!(sprite_vertex_color(0, [0.0, 0.0, 0.0, 2.0])[3], 254);
486    }
487
488    #[test]
489    fn out_of_range_blend_is_mode_zero() {
490        assert_eq!(sprite_mode(-1), 0);
491        assert_eq!(sprite_mode(11), 0);
492        assert_eq!(sprite_mode(10), 10);
493    }
494
495    #[test]
496    fn gif_frame_selection_follows_the_delay_rule() {
497        // delays [10, 20, 5] hundredths
498        let d = [0.1, 0.2, 0.05];
499        assert_eq!(gif_frame_index(&d, 0.0), 0);
500        assert_eq!(gif_frame_index(&d, 0.12), 1);
501        // cumulative 0.1, 0.3, 0.35: "0.3 > t" is false at exactly 0.3 and t = 0.31 is frame 2
502        assert_eq!(gif_frame_index(&d, 0.31), 2);
503        assert_eq!(gif_frame_index(&d, 0.36), 0, "0.36 mod 0.35 = 0.01");
504        assert_eq!(gif_frame_index(&d, 0.35 * 7.0 + 0.12), 1);
505        // single frames and degenerate delays stay on frame 0
506        assert_eq!(gif_frame_index(&[0.5], 3.0), 0);
507        assert_eq!(gif_frame_index(&[], 3.0), 0);
508        assert_eq!(gif_frame_index(&[0.0, 0.0], 3.0), 0);
509    }
510}