Skip to main content

lactea_render/
frame.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//! Everything the engine hands to [`crate::Renderer::render_frame`]: per-frame values *after*
6//! per-frame equations, per-vertex results, evaluated custom waves / shapes, and the main
7//! waveform. Field docs name the MD2 variable they correspond to (state.cpp `var_pf_*`,
8//! `mysound.*`, `CShape`, `CWave`).
9
10use crate::wavegen::{NUM_FREQ_SAMPLES, NUM_WAVE_INPUT};
11
12/// Per-frame values after per-frame equations.
13#[derive(Clone, Debug)]
14pub struct FrameInput {
15    // ---- timing -------------------------------------------------------------------------
16    /// `GetTime()` (== `time` var, `_c2.x`). Frame n is exactly `n / fps`.
17    pub time: f64,
18    /// `GetFps()` (`fps`, `_c2.y`).
19    pub fps: f32,
20    /// `GetFrame()` (`frame`, `_c2.z`).
21    pub frame: u32,
22    /// `progress` (`_c2.w`): `(time - preset_start) / (next_preset_time - preset_start)`.
23    pub progress: f32,
24
25    // ---- audio levels -------------------------------------------------------------------
26    /// `mysound.imm_rel[0..3]` = `bass, mid, treb` (`_c3.xyz`).
27    pub bass: f32,
28    /// `mysound.imm_rel[1]` = `mid`.
29    pub mid: f32,
30    /// `mysound.imm_rel[2]` = `treb`.
31    pub treb: f32,
32    /// `mysound.avg_rel[0..3]` = `bass_att, mid_att, treb_att` (`_c4.xyz`).
33    pub bass_att: f32,
34    /// `mysound.avg_rel[1]` = `mid_att`.
35    pub mid_att: f32,
36    /// `mysound.avg_rel[2]` = `treb_att`.
37    pub treb_att: f32,
38    /// `mysound.imm[0..3]` (absolute, un-normalised). Only used by main-wave mode 3
39    /// (`alpha *= pow(treble_rel, 2)` where MD2 reads `mysound.imm[2]`).
40    pub imm_abs: [f32; 3],
41
42    // ---- per-frame equation outputs -------------------------------------------------------
43    /// `q1..q32` after per-frame code (`_qa.._qh`).
44    pub q: [f32; 32],
45    /// `m_rand_frame` (`rand_frame`): four `FRAND`s drawn once per frame.
46    pub rand_frame: [f32; 4],
47    /// `m_pState->m_rand_preset` (`rand_preset`): four `FRAND`s drawn once per preset.
48    pub rand_preset: [f32; 4],
49
50    /// Final UV of every warp-mesh vertex, `(gx+1)*(gy+1)` entries, row 0 first (clip y = -1); a different length
51    /// is rejected by [`Renderer::render_frame`](crate::Renderer::render_frame). Build with [`crate::warp_mesh`].
52    /// `None` = no motion (zoom 1, no warp), except with `warp_gpu` under projectM's compat rules, where the GPU
53    /// computes the UVs and the renderer derives this grid from `warp_gpu` only if a motion vector lookup needs
54    /// it. The UVs are also what the next frame's motion vectors read, and what the MilkDrop 2 compat paths draw.
55    pub warp_uv: Option<Vec<[f32; 2]>>,
56    /// Per-vertex inputs of projectM's warp *vertex shader*: with `Compat::ProjectM` the renderer lets the
57    /// GPU evaluate the warp UV formula (`pow`/`sin`/`cos` are GPU approximations, not libm, so the
58    /// result is only reproducible on the GPU) from these instead of using `warp_uv`; `vars` must then have one
59    /// entry per mesh vertex. `None` = use `warp_uv`.
60    pub warp_gpu: Option<WarpGpu>,
61
62    /// Decay and composite-pass controls.
63    pub post: PostParams,
64    /// Blur-chain parameters.
65    pub blur: BlurParams,
66    /// Outer / inner borders.
67    pub borders: Borders,
68    /// Motion-vector field.
69    pub mv: MotionVectors,
70    /// Main waveform.
71    pub main_wave: MainWave,
72    /// Custom shapes in draw order (`m_shape[0..16]`, each instance already evaluated).
73    pub shapes: Vec<ShapeInstance>,
74    /// Custom waves in draw order (`m_wave[0..16]`, per-point equations already evaluated).
75    pub waves: Vec<CustomWave>,
76    /// `var_pf_darken_center`.
77    pub darken_center: bool,
78    /// Random state of the warp / composite shader pass (override of `rand_frame` / `rand_preset`
79    /// above and of the renderer's rotation matrices); `None` = use the fields above.
80    pub warp_random: Option<PassRandom>,
81    /// Random state of the composite shader pass, see `warp_random`.
82    pub comp_random: Option<PassRandom>,
83    /// Phases of the four hue-shader corner colours (`m_fRandStart` / projectM `hueRandomOffsets`);
84    /// `None` = the renderer's per-preset values.
85    pub hue_offsets: Option<[f32; 4]>,
86    /// MilkDrop 2's preset blend (`m_bBlending`) in progress (`CompatRules::md2_preset_blend`): the fields above are
87    /// then the new state's blended values and this carries the rest, see [`Md2Blend`](crate::Md2Blend). `None` = no blend.
88    pub md2_blend: Option<crate::blend::Md2Blend>,
89    /// MilkDrop 3 shader inputs (`_c14`, `_qi.._qp`, shader time, FFT); neutral outside MilkDrop 3.
90    pub ext: crate::ShaderExt,
91    /// MilkDrop 3 preset sprites to draw this frame (see [`crate::sprite::SpriteDraw::layer`] for where each goes); empty for
92    /// everything but `Compat::MilkDrop3` presets that carry a sprite.
93    pub sprites: Vec<crate::sprite::SpriteDraw>,
94}
95
96/// Decay, composite-pass controls.
97#[derive(Clone, Debug)]
98pub struct PostParams {
99    /// `var_pf_decay` (no-shader warp: multiplies the sampled image; quantised to 8 bit as MD2 does).
100    pub decay: f32,
101    /// `var_pf_gamma`. MD2 mode has the engine clamp it to 0..8; projectM mode passes the preset value through, so the
102    /// renderer bounds the number of gamma passes itself.
103    pub gamma: f32,
104    /// `var_pf_echo_zoom` (clamped to 0.001..1000).
105    pub echo_zoom: f32,
106    /// `var_pf_echo_alpha`.
107    pub echo_alpha: f32,
108    /// `(int)var_pf_echo_orient % 4`.
109    pub echo_orient: i32,
110    /// `var_pf_brighten` (non-zero == true).
111    pub brighten: bool,
112    /// `var_pf_darken`.
113    pub darken: bool,
114    /// `var_pf_solarize`.
115    pub solarize: bool,
116    /// `var_pf_invert`.
117    pub invert: bool,
118    /// `var_pf_wrap > 0.5` (`m_fSnapPoint`): address mode of the no-shader warp sampler.
119    pub wrap: bool,
120    /// Preset field `fShader` (`m_fShader.eval()`): hue-shader amount for the no-shader composite.
121    pub fshader: f32,
122}
123
124/// Blur-chain parameters (`var_pf_blur*`).
125#[derive(Clone, Debug)]
126pub struct BlurParams {
127    /// `var_pf_blur1min..blur3min`, `blur1max..blur3max` (raw; the renderer applies the "push apart" clamping).
128    pub min: [f32; 3],
129    /// `var_pf_blur1max..blur3max`.
130    pub max: [f32; 3],
131    /// `var_pf_blur1_edge_darken`.
132    pub edge_darken: f32,
133}
134
135/// Outer/inner border: `var_pf_ob_*` / `var_pf_ib_*`.
136#[derive(Clone, Debug)]
137pub struct Borders {
138    /// `var_pf_ob_size`.
139    pub ob_size: f32,
140    /// `var_pf_ob_r/g/b/a`.
141    pub ob_rgba: [f32; 4],
142    /// `var_pf_ib_size`.
143    pub ib_size: f32,
144    /// `var_pf_ib_r/g/b/a`.
145    pub ib_rgba: [f32; 4],
146    /// Skip both borders (`DrawSprites` border gate of MilkDrop 3: hidden during blends with `DisableBox`, never drawn
147    /// for a double preset).
148    pub hidden: bool,
149}
150
151/// Motion vector field: `var_pf_mv_x/y/dx/dy/l/r/g/b/a`.
152#[derive(Clone, Debug)]
153pub struct MotionVectors {
154    /// `var_pf_mv_x`: number of columns.
155    pub x: f32,
156    /// `var_pf_mv_y`: number of rows.
157    pub y: f32,
158    /// `var_pf_mv_dx`: horizontal offset.
159    pub dx: f32,
160    /// `var_pf_mv_dy`: vertical offset.
161    pub dy: f32,
162    /// `var_pf_mv_l`: length scale.
163    pub l: f32,
164    /// `var_pf_mv_r/g/b/a`.
165    pub rgba: [f32; 4],
166}
167
168/// Main waveform (`DrawWave` inputs).
169#[derive(Clone, Debug)]
170pub struct MainWave {
171    /// `var_pf_wave_mode` as the renderer should draw it: the engine applies the compat mode's wrap (`% 18` MD2,
172    /// `% 16` projectM, the C remainder `% 17` of MilkDrop 3, where a negative value draws nothing visible).
173    pub mode: i32,
174    /// `var_pf_wave_r/g/b` and `var_pf_wave_a`.
175    pub rgba: [f32; 4],
176    /// `var_pf_wave_x` (0..1).
177    pub x: f32,
178    /// `var_pf_wave_y` (0..1; y=1 is the top of the screen).
179    pub y: f32,
180    /// `var_pf_wave_mystery`.
181    pub mystery: f32,
182    /// `var_pf_wave_usedots`.
183    pub usedots: bool,
184    /// `var_pf_wave_thick`.
185    pub thick: bool,
186    /// `var_pf_wave_additive`.
187    pub additive: bool,
188    /// `var_pf_wave_brighten` (maximize colour).
189    pub brighten: bool,
190    /// `m_fWaveScale.eval()` (applied to the waveform at the top of `RenderFrame`: `scale = fWaveScale/128`).
191    pub scale: f32,
192    /// `m_fWaveSmoothing.eval()` (IIR smoothing with `mix2 = smoothing`).
193    pub smoothing: f32,
194    /// `m_bModWaveAlphaByVolume`.
195    pub mod_alpha_by_volume: bool,
196    /// `m_fModWaveAlphaStart`.
197    pub mod_alpha_start: f32,
198    /// `m_fModWaveAlphaEnd`.
199    pub mod_alpha_end: f32,
200    /// Raw `mysound.fWave[0]` / `[1]` (left, right): 576 samples, **MD2 units** (signed, full scale
201    /// about ±128; the renderer multiplies by `scale/128` and smooths exactly like `RenderFrame`).
202    /// Same layout as `lactea_audio::AudioFrame::wave` (only the first 480 are valid but the
203    /// main-wave modes peek at up to index 511 like MD2).
204    pub wave: [[f32; NUM_WAVE_INPUT]; 2],
205    /// `mysound.fSpecLeft` / `fSpecRight` (512 bins), only read by wave mode 8
206    /// (same layout as `AudioFrame::spectrum`).
207    pub spectrum: [[f32; NUM_FREQ_SAMPLES]; 2],
208}
209
210/// One evaluated custom-shape instance (`CShape` after per-frame code for that instance).
211#[derive(Clone, Debug)]
212pub struct ShapeInstance {
213    /// `var_pf_sides` (clamped to `3..=CompatRules::max_shape_sides` by the renderer).
214    pub sides: i32,
215    /// `var_pf_x`, projectM / MD2 compute the fan centre `x * 2.0 - 1.0` in double and round to `f32` once, so
216    /// `x` / `y` stay in the equation VM's `f64` (0..1, y=1 top).
217    pub x: f64,
218    /// `var_pf_y`, see `x`.
219    pub y: f64,
220    /// `var_pf_rad`.
221    pub rad: f32,
222    /// `var_pf_ang`.
223    pub ang: f32,
224    /// Inner colour `var_pf_r/g/b/a`.
225    pub rgba: [f32; 4],
226    /// Outer colour `var_pf_r2/g2/b2/a2`.
227    pub rgba2: [f32; 4],
228    /// Border colour `var_pf_border_*`.
229    pub border_rgba: [f32; 4],
230    /// `var_pf_additive`.
231    pub additive: bool,
232    /// `var_pf_thick` (thick outline).
233    pub thick: bool,
234    /// `var_pf_textured`.
235    pub textured: bool,
236    /// `var_pf_tex_zoom`.
237    pub tex_zoom: f32,
238    /// `var_pf_tex_ang`.
239    pub tex_ang: f32,
240    /// projectM's `shapecode_N_image`: a textured shape samples this user texture (see
241    /// [`Renderer::set_user_texture`](crate::Renderer::set_user_texture)) instead of the main image.
242    /// `None` (the default, and every MilkDrop 2 shape) keeps the main-image behaviour.
243    pub image: Option<ShapeImage>,
244}
245
246/// The texture of a shape's `image=` key, already split like projectM's `ExtractTextureSettings`
247/// (`fw_` / `fc_` / `pw_` / `pc_` prefixes pick filter and wrapping; no prefix = linear + repeat).
248#[derive(Clone, Debug, PartialEq, Eq)]
249pub struct ShapeImage {
250    /// Lower-case texture name without prefix and extension (the key of `set_user_texture`).
251    pub name: String,
252    /// Bilinear (`true`) or nearest (`false`) filtering.
253    pub linear: bool,
254    /// Repeat (`true`) or clamp-to-edge (`false`) addressing.
255    pub wrap: bool,
256}
257
258impl Default for ShapeInstance {
259    /// state.cpp defaults (`m_shape[i]`).
260    fn default() -> Self {
261        Self {
262            sides: 4,
263            x: 0.5,
264            y: 0.5,
265            rad: 0.1,
266            ang: 0.0,
267            rgba: [1.0, 0.0, 0.0, 1.0],
268            rgba2: [0.0, 1.0, 0.0, 0.0],
269            border_rgba: [1.0, 1.0, 1.0, 0.1],
270            additive: false,
271            thick: false,
272            textured: false,
273            tex_zoom: 1.0,
274            tex_ang: 0.0,
275            image: None,
276        }
277    }
278}
279
280/// One evaluated custom-wave point (`var_pp_x/y/r/g/b/a` after per-point code). `x` / `y` are the VM's `f64`:
281/// projectM turns them into clip space as `static_cast<float>((x * 2.0 - 1.0) * invAspectX)`, i.e. the product is also
282/// taken in double (MD2: `(float)(x * 2 - 1) * invAspectX`, see `CompatRules::wave_point_f64_aspect`).
283#[derive(Clone, Copy, Debug)]
284pub struct WavePoint {
285    /// `var_pp_x` (0..1).
286    pub x: f64,
287    /// `var_pp_y` (0..1, y=1 top).
288    pub y: f64,
289    /// `var_pp_r/g/b/a`.
290    pub rgba: [f32; 4],
291}
292
293/// One evaluated custom wave (`CWave`). `points.len()` is the `samples` actually produced
294/// (<= 512). Spectrum / `sep` / smoothing / scaling are the engine's job (see
295/// [`crate::wavegen::custom_wave_values_into`]).
296#[derive(Clone, Debug, Default)]
297pub struct CustomWave {
298    /// The evaluated points.
299    pub points: Vec<WavePoint>,
300    /// `bUseDots`: draw points instead of a line.
301    pub use_dots: bool,
302    /// `bDrawThick`.
303    pub thick: bool,
304    /// `bAdditive`.
305    pub additive: bool,
306}
307
308impl Default for BlurParams {
309    fn default() -> Self {
310        Self {
311            min: [0.0; 3],
312            max: [1.0; 3],
313            edge_darken: 0.25,
314        }
315    }
316}
317
318impl Default for PostParams {
319    fn default() -> Self {
320        Self {
321            decay: 0.98,
322            gamma: 2.0,
323            echo_zoom: 2.0,
324            echo_alpha: 0.0,
325            echo_orient: 0,
326            brighten: false,
327            darken: false,
328            solarize: false,
329            invert: false,
330            wrap: true,
331            fshader: 0.0,
332        }
333    }
334}
335
336impl Default for Borders {
337    fn default() -> Self {
338        // state.cpp: ob_size 0.01, ib_size 0.01, colours ob (0,0,0,0), ib (0.25,0.25,0.25,0)
339        Self {
340            ob_size: 0.01,
341            ob_rgba: [0.0; 4],
342            ib_size: 0.01,
343            ib_rgba: [0.25, 0.25, 0.25, 0.0],
344            hidden: false,
345        }
346    }
347}
348
349impl Default for MotionVectors {
350    fn default() -> Self {
351        // state.cpp defaults: mv_x 12, mv_y 9, mv_l 0.9, colour (1,1,1,1). Presets that want no
352        // field set mv_a = 0 (.milk files always carry `mv_a`).
353        Self {
354            x: 12.0,
355            y: 9.0,
356            dx: 0.0,
357            dy: 0.0,
358            l: 0.9,
359            rgba: [1.0, 1.0, 1.0, 1.0],
360        }
361    }
362}
363
364impl Default for MainWave {
365    fn default() -> Self {
366        Self {
367            mode: 0,
368            rgba: [1.0, 1.0, 1.0, 0.8],
369            x: 0.5,
370            y: 0.5,
371            mystery: 0.0,
372            usedots: false,
373            thick: false,
374            additive: false,
375            brighten: true,
376            scale: 1.0,
377            smoothing: 0.75,
378            mod_alpha_by_volume: false,
379            mod_alpha_start: 0.75,
380            mod_alpha_end: 0.95,
381            wave: [[0.0; NUM_WAVE_INPUT]; 2],
382            spectrum: [[0.0; NUM_FREQ_SAMPLES]; 2],
383        }
384    }
385}
386
387/// See [`FrameInput::warp_gpu`].
388#[derive(Clone, Debug)]
389pub struct WarpGpu {
390    /// `(gx+1)*(gy+1)` entries in the same order as `warp_uv`: the ten motion variables of each vertex
391    /// after per-pixel code.
392    pub vars: Vec<crate::warp_mesh::VertexVars>,
393    /// Per-frame warp animation terms (`WarpAnim::projectm`).
394    pub anim: crate::warp_mesh::WarpAnim,
395}
396
397/// Per-shader-pass random state. projectM gives the warp and the composite shader independent
398/// `rand_preset` / `rand_frame` / `rot_*` streams (MD2 shares one set per preset); the engine
399/// supplies them here. Any `None` falls back to the renderer's own state.
400#[derive(Clone, Debug)]
401pub struct PassRandom {
402    /// `rand_frame`: four values drawn once per frame.
403    pub rand_frame: [f32; 4],
404    /// `rand_preset`: four values drawn once per preset.
405    pub rand_preset: [f32; 4],
406    /// The 24 `rot_*` matrices exactly as uploaded (ABI layout, see [`lactea_abi::MilkUniforms::rot`]).
407    pub rot: Option<Box<[[[f32; 4]; 3]; lactea_abi::NUM_ROT]>>,
408}
409
410impl Default for FrameInput {
411    /// A default MilkDrop state at frame 0 with silent audio (decay .98, gamma 2, white wave 0).
412    fn default() -> Self {
413        Self {
414            time: 0.0,
415            fps: 60.0,
416            frame: 0,
417            progress: 0.0,
418            bass: 1.0,
419            mid: 1.0,
420            treb: 1.0,
421            bass_att: 1.0,
422            mid_att: 1.0,
423            treb_att: 1.0,
424            imm_abs: [0.0; 3],
425            q: [0.0; 32],
426            rand_frame: [0.0; 4],
427            rand_preset: [0.0; 4],
428            warp_uv: None,
429            warp_gpu: None,
430            post: PostParams::default(),
431            blur: BlurParams::default(),
432            borders: Borders::default(),
433            mv: MotionVectors::default(),
434            main_wave: MainWave::default(),
435            shapes: Vec::new(),
436            waves: Vec::new(),
437            darken_center: false,
438            warp_random: None,
439            ext: crate::ShaderExt::default(),
440            comp_random: None,
441            hue_offsets: None,
442            md2_blend: None,
443            sprites: Vec::new(),
444        }
445    }
446}