Skip to main content

lactea_render/
blend.rs

1// SPDX-FileCopyrightText: 2026 Gianluca Boiano
2// SPDX-FileCopyrightText: 2005-2013 Nullsoft, Inc.
3// SPDX-License-Identifier: (MIT OR Apache-2.0) AND BSD-3-Clause
4
5//! MilkDrop 2's preset blend (`CState::m_bBlending`), renderer side.
6//!
7//! MD2 has no image-space cross-fade. While a blend runs the old preset's `CState` (`m_pOldState`) lives
8//! next to the new one (`m_pState`) inside **one** frame pipeline: the engine evaluates both states' equations,
9//! blends the per-frame variables and the per-vertex warp UVs, and the renderer draws
10//!
11//! * the warp pass twice (`WarpedBlit_Shaders` / `WarpedBlit_NoShaders` pass 0 = old shader, pass 1 = new shader) on
12//!   the *blended* mesh, culling mesh tiles by the per-vertex alpha `(DWORD)(mix2*255)` and alpha-blending pass 1,
13//! * custom shapes / waves of both states with `alpha_mult` (`progress` for the new state, `1 - progress` for the old),
14//! * the main waveform twice when the wave mode changed (`its = 2`) and blends the two polylines,
15//! * the composite twice with the old and the new composite shader (`ShowToUser_Shaders` / `ShowToUser_NoShaders`).
16//!
17//! This module holds the data the engine hands over ([`Md2Blend`]) and the pure logic of those passes (tile culling,
18//! the pass tables of `RenderFrame`, the composite alpha lookup, the two-wave blend). Everything is unit tested; the
19//! GPU drawing lives in `renderer.rs`.
20
21use crate::frame::{BlurParams, PassRandom};
22use crate::geom::{FCGSX, FCGSY};
23
24/// `CosineInterp` (vis_milk2 `utility.h`, not part of `third_party/md2`): `0.5 - 0.5 cos(pi x)`. Used for the blend of
25/// the per-frame variables, the wave blend and the video-echo flip.
26pub fn cosine_interp(x: f32) -> f32 {
27    0.5 - 0.5 * (x * std::f32::consts::PI).cos()
28}
29
30/// What the old state contributes to the shader passes of a blend frame (its `ApplyShaderParams(.., m_pOldState)`
31/// inputs that differ from the new state's: `q1..q32`, blur range, `rand_preset` / `rot_*`).
32#[derive(Clone, Debug)]
33pub struct Md2OldPass {
34    /// `m_pOldState->var_pf_q[0..32]` after its per-frame code.
35    pub q: [f32; 32],
36    /// The old state's own (unblended) `var_pf_blur*` (`GetSafeBlurMinMax(m_pOldState)`).
37    pub blur: BlurParams,
38    /// MilkDrop 3: the old state's `_c14` / `_qi.._qp` / shader time (`ShaderExt::fft` is ignored here).
39    pub ext: crate::ShaderExt,
40    /// Random state of the old warp / composite pass (`m_pOldState->m_rand_preset`, `m_rot_*`; `rand_frame` is the
41    /// frame's one `m_rand_frame`).
42    pub warp_random: Option<PassRandom>,
43    /// Random state of the old composite pass.
44    pub comp_random: Option<PassRandom>,
45}
46
47/// Everything the renderer needs to draw a blend frame, on top of the new state's [`crate::FrameInput`] (whose
48/// per-frame values are already the blended `m_pState->var_pf_*`).
49#[derive(Clone, Debug)]
50pub struct Md2Blend {
51    /// `m_pState->m_fBlendProgress`: linear, `0..=1` (a blend ends once it exceeds 1).
52    pub progress: f32,
53    /// `m_verts[n].Diffuse >> 24` for every warp-mesh vertex (lactea mesh order): `(DWORD)(mix2 * 255)`, `mix2` being
54    /// the clamped per-vertex blend factor (255 = new preset only).
55    pub vert_alpha: Vec<u8>,
56    /// The old state's shader-pass inputs.
57    pub old: Md2OldPass,
58    /// `Some(m_nOldWaveMode)` when the main wave is drawn twice (`its == 2`: blending and the wave mode changed).
59    pub old_wave_mode: Option<i32>,
60    /// `alpha_mult` of every entry of `FrameInput::shapes` / `FrameInput::waves` (`progress` for the new state's,
61    /// `1 - progress` for the old one's). Missing entries mean 1.
62    pub shape_alpha_mult: Vec<f32>,
63    /// Same for `FrameInput::waves`.
64    pub wave_alpha_mult: Vec<f32>,
65}
66
67/// `bIsNeeded` of the tile culling in `WarpedBlit_*` / `ShowToUser_Shaders`: with `flip_culling == false` a
68/// triangle is drawn when any vertex alpha is > 0, with `true` when any is < 255 (`nAlphaTestValue`).
69pub fn tile_needed(d: [u8; 3], flip_culling: bool) -> bool {
70    if flip_culling {
71        (d[0] & d[1] & d[2]) < 255
72    } else {
73        (d[0] | d[1] | d[2]) > 0
74    }
75}
76
77/// Which state's shader / state parameters a pass uses (`nPass`: 0 = old, 1 = new).
78#[derive(Clone, Copy, Debug, PartialEq, Eq)]
79pub enum Which {
80    Old,
81    New,
82}
83
84/// One call of `WarpedBlit_*(nPass, bAlphaBlend, bFlipAlpha, bCullTiles, bFlipCulling)` /
85/// `ShowToUser_*`.
86#[derive(Clone, Copy, Debug, PartialEq, Eq)]
87pub struct DrawPass {
88    pub which: Which,
89    /// `*_Shaders` (user / default pixel shader) rather than `*_NoShaders` (fixed function).
90    pub shaders: bool,
91    pub alpha_blend: bool,
92    pub flip_alpha: bool,
93    pub cull_tiles: bool,
94    pub flip_culling: bool,
95}
96
97const fn pass(which: Which, shaders: bool, a: bool, fa: bool, c: bool, fc: bool) -> DrawPass {
98    DrawPass {
99        which,
100        shaders,
101        alpha_blend: a,
102        flip_alpha: fa,
103        cull_tiles: c,
104        flip_culling: fc,
105    }
106}
107
108/// The warp passes of `RenderFrame` while blending (`bOldPresetUsesWarpShader`, `bNewPresetUsesWarpShader`).
109pub fn warp_passes(old_shader: bool, new_shader: bool) -> &'static [DrawPass] {
110    use Which::{New, Old};
111    const BOTH: [DrawPass; 2] = [
112        pass(Old, true, false, false, true, true),
113        pass(New, true, true, false, true, false),
114    ];
115    const NEW_ONLY: [DrawPass; 2] = [
116        pass(Old, false, false, false, true, true),
117        pass(New, true, true, false, true, false),
118    ];
119    const OLD_ONLY: [DrawPass; 2] = [
120        pass(Old, true, false, false, true, true),
121        pass(New, false, true, false, true, false),
122    ];
123    // "all the blending just happens in the vertex UV's, so just pretend there's no blend"
124    const NONE: [DrawPass; 1] = [pass(New, false, false, false, false, false)];
125    match (old_shader, new_shader) {
126        (true, true) => &BOTH,
127        (false, true) => &NEW_ONLY,
128        (true, false) => &OLD_ONLY,
129        (false, false) => &NONE,
130    }
131}
132
133/// The composite passes of `RenderFrame` while blending (`bOldPresetUsesCompShader`, `bNewPresetUsesCompShader`);
134/// `ShowToUser_NoShaders()` always draws the whole quad and comes first.
135pub fn comp_passes(old_shader: bool, new_shader: bool) -> &'static [DrawPass] {
136    use Which::{New, Old};
137    const BOTH: [DrawPass; 2] = [
138        pass(Old, true, false, false, true, true),
139        pass(New, true, true, false, true, false),
140    ];
141    const NEW_ONLY: [DrawPass; 2] = [
142        pass(New, false, false, false, false, false),
143        pass(New, true, true, false, true, false),
144    ];
145    // "THA FUNKY REVERSAL"
146    const OLD_ONLY: [DrawPass; 2] = [
147        pass(New, false, false, false, false, false),
148        pass(Old, true, true, true, true, true),
149    ];
150    const NONE: [DrawPass; 1] = [pass(New, false, false, false, false, false)];
151    match (old_shader, new_shader) {
152        (true, true) => &BOTH,
153        (false, true) => &NEW_ONLY,
154        (true, false) => &OLD_ONLY,
155        (false, false) => &NONE,
156    }
157}
158
159/// Texture coordinates of composite-mesh vertex `(i, j)` before the half-texel shift (`SquishToCenter` of the 32x24
160/// grid, `plugin.cpp` ~2420), and the `x, y` (0..1, y up) `ShowToUser_Shaders` derives from `m_comp_verts[].x/y`
161/// (`(u - 0.5/W)*2-1`, `-((v - 0.5/H)*2-1)`, then `*0.5+0.5`).
162pub fn comp_vertex_xy01(i: usize, j: usize, w: u32, h: u32) -> (f32, f32) {
163    let div_x = 1.0 / (FCGSX - 2) as f32;
164    let div_y = 1.0 / (FCGSY - 2) as f32;
165    let j2 = j - j / (FCGSY / 2);
166    let i2 = i - i / (FCGSX / 2);
167    let v = squish_to_center(j2 as f32 * div_y, 3.0);
168    let u = squish_to_center(i2 as f32 * div_x, 3.0);
169    let half_w = 0.5 / w as f32;
170    let half_h = 0.5 / h as f32;
171    let sy = -((v - half_h) * 2.0 - 1.0);
172    let sx = (u - half_w) * 2.0 - 1.0;
173    (sx * 0.5 + 0.5, sy * 0.5 + 0.5)
174}
175
176fn squish_to_center(x: f32, exp: f32) -> f32 {
177    if x > 0.5 {
178        return (x * 2.0 - 1.0).powf(exp) * 0.5 + 0.5;
179    }
180    (1.0 - (1.0 - x * 2.0).powf(exp)) * 0.5
181}
182
183/// The alpha byte of a composite vertex while blending (`ShowToUser_Shaders`): bilinear lookup of the warp mesh's
184/// vertex alphas at `(x, y)` (0..1 over the mesh, the lookup point clamped to cells `0..grid-1`), then
185/// `D3DCOLOR_RGBA_01`'s `(int)(alpha * 255)` of the double result.
186pub fn comp_vertex_alpha(vert_alpha: &[u8], grid: [u32; 2], x01: f32, y01: f32) -> u8 {
187    let (gx, gy) = (grid[0] as i32, grid[1] as i32);
188    let mut x = x01 * (gx + 1) as f32;
189    let mut y = y01 * (gy + 1) as f32;
190    x = x.min((gx - 1) as f32).max(0.0);
191    y = y.min((gy - 1) as f32).max(0.0);
192    let nx = x as i32;
193    let ny = y as i32;
194    let dx = f64::from(x - nx as f32);
195    let dy = f64::from(y - ny as f32);
196    let at = |yy: i32, xx: i32| f64::from(vert_alpha[(yy * (gx + 1) + xx) as usize]);
197    let mut alpha = at(ny, nx) * (1.0 - dx) * (1.0 - dy)
198        + at(ny, nx + 1) * dx * (1.0 - dy)
199        + at(ny + 1, nx) * (1.0 - dx) * dy
200        + at(ny + 1, nx + 1) * dx * dy;
201    alpha /= f64::from(255.0f32);
202    ((alpha * 255.0) as i32 & 0xFF) as u8
203}
204
205/// A polyline of `DrawWave`: vertices before `SmoothWave`, and `nBreak` (`None` = -1).
206#[derive(Clone, Debug, PartialEq)]
207pub struct WaveLine {
208    pub verts: Vec<[f32; 2]>,
209    pub brk: Option<usize>,
210}
211
212/// The "blend 2 waveforms" block at the end of `DrawWave`: `new` is `v1[]` (the current wave), `old` is `v2[]`
213/// (`m_nOldWaveMode`'s wave). Returns the blended line with `nVerts1 = new.verts.len()` vertices and the (possibly
214/// moved) break. `mix` is `CosineInterp(progress)` (1 = new only).
215pub fn blend_waves(new: &WaveLine, old: &WaveLine, mix: f32) -> WaveLine {
216    let mix2 = 1.0 - mix;
217    let n1 = new.verts.len();
218    let n2 = old.verts.len();
219    let mut out = new.clone();
220    // "this won't yet handle the case where (nBreak1 > 0 && nBreak2 > 0)"
221    let m = (n2 as f32 - 1.0) / n1 as f32;
222    let nbreak2 = old.brk.map_or(-1, |b| b as i64);
223    for i in 0..n1 {
224        let f_idx = i as f32 * m;
225        let n_idx = f_idx as usize;
226        let t = f_idx - n_idx as f32;
227        let (x, y);
228        if n_idx as i64 == nbreak2 - 1 {
229            x = old.verts[n_idx][0];
230            y = old.verts[n_idx][1];
231            out.brk = Some(i + 1);
232        } else {
233            // MD2 reads one vertex past the end for the very last index; its `v2` array is zero-filled there
234            let b = old.verts.get(n_idx + 1).copied().unwrap_or([0.0, 0.0]);
235            x = old.verts[n_idx][0] * (1.0 - t) + b[0] * t;
236            y = old.verts[n_idx][1] * (1.0 - t) + b[1] * t;
237        }
238        out.verts[i][0] = new.verts[i][0] * mix + x * mix2;
239        out.verts[i][1] = new.verts[i][1] * mix + y * mix2;
240    }
241    out
242}
243
244/// `alpha1 = alpha1*mix + alpha2*(1-mix)` of `DrawWave`.
245pub fn blend_wave_alpha(alpha_new: f32, alpha_old: f32, mix: f32) -> f32 {
246    alpha_new * mix + alpha_old * (1.0 - mix)
247}
248
249#[cfg(test)]
250mod tests {
251    use super::*;
252
253    #[test]
254    fn cosine_interp_endpoints_and_midpoint() {
255        assert_eq!(cosine_interp(0.0), 0.0);
256        assert!((cosine_interp(1.0) - 1.0).abs() < 1e-7);
257        assert!((cosine_interp(0.5) - 0.5).abs() < 1e-7);
258        // 0.5 - 0.5 cos(pi/4)
259        assert!(
260            (cosine_interp(0.25) - (0.5 - 0.5 * (std::f32::consts::FRAC_PI_4).cos())).abs() < 1e-6
261        );
262    }
263
264    #[test]
265    fn tile_culling_rules() {
266        // normal culling: needed when any alpha > 0
267        assert!(!tile_needed([0, 0, 0], false));
268        assert!(tile_needed([0, 0, 1], false));
269        assert!(tile_needed([255, 255, 255], false));
270        // flipped culling: needed unless every alpha is 255
271        assert!(!tile_needed([255, 255, 255], true));
272        assert!(tile_needed([255, 255, 254], true));
273        assert!(tile_needed([0, 0, 0], true));
274        // `d1 & d2 & d3 < 255` (bitwise AND): 254 & 255 & 255 = 254
275        assert!(tile_needed([254, 255, 255], true));
276    }
277
278    #[test]
279    fn warp_pass_table() {
280        use Which::{New, Old};
281        let p = warp_passes(true, true);
282        assert_eq!(p.len(), 2);
283        assert_eq!(p[0], pass(Old, true, false, false, true, true));
284        assert_eq!(p[1], pass(New, true, true, false, true, false));
285        let p = warp_passes(false, true);
286        assert_eq!(
287            (
288                p[0].shaders,
289                p[0].flip_culling,
290                p[1].shaders,
291                p[1].alpha_blend
292            ),
293            (false, true, true, true)
294        );
295        let p = warp_passes(true, false);
296        assert_eq!(
297            (
298                p[0].shaders,
299                p[1].shaders,
300                p[1].alpha_blend,
301                p[1].cull_tiles
302            ),
303            (true, false, true, true)
304        );
305        // neither: a single un-culled, un-blended fixed-function pass
306        assert_eq!(
307            warp_passes(false, false),
308            vec![pass(New, false, false, false, false, false)]
309        );
310    }
311
312    #[test]
313    fn comp_pass_table_incl_funky_reversal() {
314        use Which::{New, Old};
315        assert_eq!(
316            comp_passes(false, false),
317            vec![pass(New, false, false, false, false, false)]
318        );
319        let p = comp_passes(false, true);
320        assert_eq!(p[0], pass(New, false, false, false, false, false));
321        assert_eq!(p[1], pass(New, true, true, false, true, false));
322        // the old preset had a comp shader, the new one has not: fixed function first, then the OLD shader with flipped
323        // alpha blending (src * (1 - a) + dst * a) and flipped culling
324        let p = comp_passes(true, false);
325        assert_eq!(p[0], pass(New, false, false, false, false, false));
326        assert_eq!(p[1], pass(Old, true, true, true, true, true));
327        let p = comp_passes(true, true);
328        assert_eq!(p[0], pass(Old, true, false, false, true, true));
329        assert_eq!(p[1], pass(New, true, true, false, true, false));
330    }
331
332    #[test]
333    fn comp_vertices_cover_the_unit_square() {
334        let (x, y) = comp_vertex_xy01(0, 0, 640, 360);
335        // corner (0, 0): u = v = 0, so x01 = -0.5/W (the `-fHalfTexelW` shift of `m_comp_verts`), y01 = 1 + 0.5/H
336        assert!(
337            (x + 0.5 / 640.0).abs() < 1e-6 && (y - (1.0 + 0.5 / 360.0)).abs() < 1e-6,
338            "top-left {x} {y}"
339        );
340        let (x, y) = comp_vertex_xy01(FCGSX - 1, FCGSY - 1, 640, 360);
341        assert!(
342            (x - (1.0 - 0.5 / 640.0)).abs() < 1e-6 && (y - 0.5 / 360.0).abs() < 1e-6,
343            "bottom-right {x} {y}"
344        );
345        // symmetric about the centre (the two middle columns/rows are the duplicated centre seam)
346        let (xa, ya) = comp_vertex_xy01(FCGSX / 2 - 1, FCGSY / 2 - 1, 640, 360);
347        let (xb, yb) = comp_vertex_xy01(FCGSX / 2, FCGSY / 2, 640, 360);
348        assert!((xa - 0.5).abs() < 2e-3 && (xb - 0.5).abs() < 2e-3);
349        assert!((ya - 0.5).abs() < 2e-3 && (yb - 0.5).abs() < 2e-3);
350    }
351
352    #[test]
353    fn comp_alpha_lookup_is_a_clamped_bilinear_fetch() {
354        let grid = [4u32, 4];
355        let n = ((grid[0] + 1) * (grid[1] + 1)) as usize;
356        // constant alpha
357        let a = vec![128u8; n];
358        let v = comp_vertex_alpha(&a, grid, 0.37, 0.61);
359        assert!(v == 127 || v == 128, "{v}");
360        let full = vec![255u8; n];
361        assert!(comp_vertex_alpha(&full, grid, 0.9, 0.1) >= 254);
362        // alpha rises with the column index: reading further right gives a larger value
363        let mut ramp = vec![0u8; n];
364        for y in 0..5 {
365            for x in 0..5 {
366                ramp[y * 5 + x] = (x * 60) as u8;
367            }
368        }
369        let l = comp_vertex_alpha(&ramp, grid, 0.05, 0.5);
370        let r = comp_vertex_alpha(&ramp, grid, 0.6, 0.5);
371        assert!(l < r, "{l} {r}");
372        // hand check: (x01 = 0.4) * 5 = 2.0 -> cell 2 exactly: alpha00 = 120 (dx = 0) -> (int)(120/255*255) <= 120
373        let h = comp_vertex_alpha(&ramp, grid, 0.4, 0.5);
374        assert!(h == 119 || h == 120, "{h}");
375        // the lookup point is clamped to the cells (x01 = 1 -> cell grid-1, dx = 0 -> alpha at column 3)
376        let c = comp_vertex_alpha(&ramp, grid, 1.0, 0.5);
377        assert!(c == 179 || c == 180, "{c}");
378    }
379
380    #[test]
381    fn blend_waves_resamples_the_old_line_and_mixes() {
382        let new = WaveLine {
383            verts: vec![[0.0, 0.0]; 4],
384            brk: None,
385        };
386        let old = WaveLine {
387            verts: vec![[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]],
388            brk: None,
389        };
390        // mix = 1: the new wave untouched; mix = 0: the old wave resampled onto 4 vertices
391        assert_eq!(blend_waves(&new, &old, 1.0).verts, new.verts);
392        let b = blend_waves(&new, &old, 0.0);
393        // m = (3-1)/4 = 0.5: indices 0, .5, 1, 1.5
394        let want = [[1.0, 2.0], [2.0, 3.0], [3.0, 4.0], [4.0, 5.0]];
395        for (g, w) in b.verts.iter().zip(want) {
396            assert!(
397                (g[0] - w[0]).abs() < 1e-6 && (g[1] - w[1]).abs() < 1e-6,
398                "{g:?} {w:?}"
399            );
400        }
401        // halfway
402        let b = blend_waves(&new, &old, 0.5);
403        assert!((b.verts[2][0] - 1.5).abs() < 1e-6 && (b.verts[2][1] - 2.0).abs() < 1e-6);
404    }
405
406    #[test]
407    fn blend_waves_moves_the_break_to_the_old_break() {
408        let new = WaveLine {
409            verts: vec![[0.0; 2]; 8],
410            brk: Some(4),
411        };
412        let old = WaveLine {
413            verts: vec![[0.0; 2]; 6],
414            brk: Some(3),
415        };
416        let b = blend_waves(&new, &old, 0.5);
417        // m = 5/8: nIdx == nBreak2 - 1 = 2 for fIdx in [2,3): i = 4 (2.5) -> break after vertex i + 1 = 5
418        assert_eq!(b.brk, Some(5));
419        // old wave without break keeps the new break
420        let old2 = WaveLine {
421            verts: vec![[0.0; 2]; 6],
422            brk: None,
423        };
424        assert_eq!(blend_waves(&new, &old2, 0.5).brk, Some(4));
425    }
426
427    #[test]
428    fn wave_alpha_blend_is_linear_in_the_cosine_mix() {
429        assert_eq!(blend_wave_alpha(1.0, 0.0, 1.0), 1.0);
430        assert_eq!(blend_wave_alpha(1.0, 0.0, 0.0), 0.0);
431        assert!((blend_wave_alpha(0.8, 0.2, 0.25) - (0.8 * 0.25 + 0.2 * 0.75)).abs() < 1e-7);
432    }
433}