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