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` (already clamped to 0..8 by the engine as MD2 does).
102    pub gamma: f32,
103    /// `var_pf_echo_zoom` (clamped to 0.001..1000).
104    pub echo_zoom: f32,
105    /// `var_pf_echo_alpha`.
106    pub echo_alpha: f32,
107    /// `(int)var_pf_echo_orient % 4`.
108    pub echo_orient: i32,
109    /// `var_pf_brighten` (non-zero == true).
110    pub brighten: bool,
111    /// `var_pf_darken`.
112    pub darken: bool,
113    /// `var_pf_solarize`.
114    pub solarize: bool,
115    /// `var_pf_invert`.
116    pub invert: bool,
117    /// `var_pf_wrap > 0.5` (`m_fSnapPoint`): address mode of the no-shader warp sampler.
118    pub wrap: bool,
119    /// Preset field `fShader` (`m_fShader.eval()`): hue-shader amount for the no-shader composite.
120    pub fshader: f32,
121}
122
123/// Blur-chain parameters (`var_pf_blur*`).
124#[derive(Clone, Debug)]
125pub struct BlurParams {
126    /// `var_pf_blur1min..blur3min`, `blur1max..blur3max` (raw; the renderer applies the "push apart" clamping).
127    pub min: [f32; 3],
128    /// `var_pf_blur1max..blur3max`.
129    pub max: [f32; 3],
130    /// `var_pf_blur1_edge_darken`.
131    pub edge_darken: f32,
132}
133
134/// Outer/inner border: `var_pf_ob_*` / `var_pf_ib_*`.
135#[derive(Clone, Debug)]
136pub struct Borders {
137    /// `var_pf_ob_size`.
138    pub ob_size: f32,
139    /// `var_pf_ob_r/g/b/a`.
140    pub ob_rgba: [f32; 4],
141    /// `var_pf_ib_size`.
142    pub ib_size: f32,
143    /// `var_pf_ib_r/g/b/a`.
144    pub ib_rgba: [f32; 4],
145    /// Skip both borders (`DrawSprites` border gate of MilkDrop 3: hidden during blends with `DisableBox`, never drawn
146    /// for a double preset).
147    pub hidden: bool,
148}
149
150/// Motion vector field: `var_pf_mv_x/y/dx/dy/l/r/g/b/a`.
151#[derive(Clone, Debug)]
152pub struct MotionVectors {
153    /// `var_pf_mv_x`: number of columns.
154    pub x: f32,
155    /// `var_pf_mv_y`: number of rows.
156    pub y: f32,
157    /// `var_pf_mv_dx`: horizontal offset.
158    pub dx: f32,
159    /// `var_pf_mv_dy`: vertical offset.
160    pub dy: f32,
161    /// `var_pf_mv_l`: length scale.
162    pub l: f32,
163    /// `var_pf_mv_r/g/b/a`.
164    pub rgba: [f32; 4],
165}
166
167/// Main waveform (`DrawWave` inputs).
168#[derive(Clone, Debug)]
169pub struct MainWave {
170    /// `var_pf_wave_mode` as the renderer should draw it: the engine applies the compat mode's wrap (`% 18` MD2,
171    /// `% 16` projectM, the C remainder `% 17` of MilkDrop 3, where a negative value draws nothing visible).
172    pub mode: i32,
173    /// `var_pf_wave_r/g/b` and `var_pf_wave_a`.
174    pub rgba: [f32; 4],
175    /// `var_pf_wave_x` (0..1).
176    pub x: f32,
177    /// `var_pf_wave_y` (0..1; y=1 is the top of the screen).
178    pub y: f32,
179    /// `var_pf_wave_mystery`.
180    pub mystery: f32,
181    /// `var_pf_wave_usedots`.
182    pub usedots: bool,
183    /// `var_pf_wave_thick`.
184    pub thick: bool,
185    /// `var_pf_wave_additive`.
186    pub additive: bool,
187    /// `var_pf_wave_brighten` (maximize colour).
188    pub brighten: bool,
189    /// `m_fWaveScale.eval()` (applied to the waveform at the top of `RenderFrame`: `scale = fWaveScale/128`).
190    pub scale: f32,
191    /// `m_fWaveSmoothing.eval()` (IIR smoothing with `mix2 = smoothing`).
192    pub smoothing: f32,
193    /// `m_bModWaveAlphaByVolume`.
194    pub mod_alpha_by_volume: bool,
195    /// `m_fModWaveAlphaStart`.
196    pub mod_alpha_start: f32,
197    /// `m_fModWaveAlphaEnd`.
198    pub mod_alpha_end: f32,
199    /// Raw `mysound.fWave[0]` / `[1]` (left, right): 576 samples, **MD2 units** (signed, full scale
200    /// about ±128; the renderer multiplies by `scale/128` and smooths exactly like `RenderFrame`).
201    /// Same layout as `lactea_audio::AudioFrame::wave` (only the first 480 are valid but the
202    /// main-wave modes peek at up to index 511 like MD2).
203    pub wave: [[f32; NUM_WAVE_INPUT]; 2],
204    /// `mysound.fSpecLeft` / `fSpecRight` (512 bins), only read by wave mode 8
205    /// (same layout as `AudioFrame::spectrum`).
206    pub spectrum: [[f32; NUM_FREQ_SAMPLES]; 2],
207}
208
209/// One evaluated custom-shape instance (`CShape` after per-frame code for that instance).
210#[derive(Clone, Debug)]
211pub struct ShapeInstance {
212    /// `var_pf_sides` (clamped to `3..=CompatRules::max_shape_sides` by the renderer).
213    pub sides: i32,
214    /// `var_pf_x`, projectM / MD2 compute the fan centre `x * 2.0 - 1.0` in double and round to `f32` once, so
215    /// `x` / `y` stay in the equation VM's `f64` (0..1, y=1 top).
216    pub x: f64,
217    /// `var_pf_y`, see `x`.
218    pub y: f64,
219    /// `var_pf_rad`.
220    pub rad: f32,
221    /// `var_pf_ang`.
222    pub ang: f32,
223    /// Inner colour `var_pf_r/g/b/a`.
224    pub rgba: [f32; 4],
225    /// Outer colour `var_pf_r2/g2/b2/a2`.
226    pub rgba2: [f32; 4],
227    /// Border colour `var_pf_border_*`.
228    pub border_rgba: [f32; 4],
229    /// `var_pf_additive`.
230    pub additive: bool,
231    /// `var_pf_thick` (thick outline).
232    pub thick: bool,
233    /// `var_pf_textured`.
234    pub textured: bool,
235    /// `var_pf_tex_zoom`.
236    pub tex_zoom: f32,
237    /// `var_pf_tex_ang`.
238    pub tex_ang: f32,
239    /// projectM's `shapecode_N_image`: a textured shape samples this user texture (see
240    /// [`Renderer::set_user_texture`](crate::Renderer::set_user_texture)) instead of the main image.
241    /// `None` (the default, and every MilkDrop 2 shape) keeps the main-image behaviour.
242    pub image: Option<ShapeImage>,
243}
244
245/// The texture of a shape's `image=` key, already split like projectM's `ExtractTextureSettings`
246/// (`fw_` / `fc_` / `pw_` / `pc_` prefixes pick filter and wrapping; no prefix = linear + repeat).
247#[derive(Clone, Debug, PartialEq, Eq)]
248pub struct ShapeImage {
249    /// Lower-case texture name without prefix and extension (the key of `set_user_texture`).
250    pub name: String,
251    /// Bilinear (`true`) or nearest (`false`) filtering.
252    pub linear: bool,
253    /// Repeat (`true`) or clamp-to-edge (`false`) addressing.
254    pub wrap: bool,
255}
256
257impl Default for ShapeInstance {
258    /// state.cpp defaults (`m_shape[i]`).
259    fn default() -> Self {
260        Self {
261            sides: 4,
262            x: 0.5,
263            y: 0.5,
264            rad: 0.1,
265            ang: 0.0,
266            rgba: [1.0, 0.0, 0.0, 1.0],
267            rgba2: [0.0, 1.0, 0.0, 0.0],
268            border_rgba: [1.0, 1.0, 1.0, 0.1],
269            additive: false,
270            thick: false,
271            textured: false,
272            tex_zoom: 1.0,
273            tex_ang: 0.0,
274            image: None,
275        }
276    }
277}
278
279/// One evaluated custom-wave point (`var_pp_x/y/r/g/b/a` after per-point code). `x` / `y` are the VM's `f64`:
280/// projectM turns them into clip space as `static_cast<float>((x * 2.0 - 1.0) * invAspectX)`, i.e. the product is also
281/// taken in double (MD2: `(float)(x * 2 - 1) * invAspectX`, see `CompatRules::wave_point_f64_aspect`).
282#[derive(Clone, Copy, Debug)]
283pub struct WavePoint {
284    /// `var_pp_x` (0..1).
285    pub x: f64,
286    /// `var_pp_y` (0..1, y=1 top).
287    pub y: f64,
288    /// `var_pp_r/g/b/a`.
289    pub rgba: [f32; 4],
290}
291
292/// One evaluated custom wave (`CWave`). `points.len()` is the `samples` actually produced
293/// (<= 512). Spectrum / `sep` / smoothing / scaling are the engine's job (see
294/// [`crate::wavegen::custom_wave_values`]).
295#[derive(Clone, Debug, Default)]
296pub struct CustomWave {
297    /// The evaluated points.
298    pub points: Vec<WavePoint>,
299    /// `bUseDots`: draw points instead of a line.
300    pub use_dots: bool,
301    /// `bDrawThick`.
302    pub thick: bool,
303    /// `bAdditive`.
304    pub additive: bool,
305}
306
307impl Default for BlurParams {
308    fn default() -> Self {
309        Self {
310            min: [0.0; 3],
311            max: [1.0; 3],
312            edge_darken: 0.25,
313        }
314    }
315}
316
317impl Default for PostParams {
318    fn default() -> Self {
319        Self {
320            decay: 0.98,
321            gamma: 2.0,
322            echo_zoom: 2.0,
323            echo_alpha: 0.0,
324            echo_orient: 0,
325            brighten: false,
326            darken: false,
327            solarize: false,
328            invert: false,
329            wrap: true,
330            fshader: 0.0,
331        }
332    }
333}
334
335impl Default for Borders {
336    fn default() -> Self {
337        // state.cpp: ob_size 0.01, ib_size 0.01, colours ob (0,0,0,0), ib (0.25,0.25,0.25,0)
338        Self {
339            ob_size: 0.01,
340            ob_rgba: [0.0; 4],
341            ib_size: 0.01,
342            ib_rgba: [0.25, 0.25, 0.25, 0.0],
343            hidden: false,
344        }
345    }
346}
347
348impl Default for MotionVectors {
349    fn default() -> Self {
350        // state.cpp defaults: mv_x 12, mv_y 9, mv_l 0.9, colour (1,1,1,1). Presets that want no
351        // field set mv_a = 0 (.milk files always carry `mv_a`).
352        Self {
353            x: 12.0,
354            y: 9.0,
355            dx: 0.0,
356            dy: 0.0,
357            l: 0.9,
358            rgba: [1.0, 1.0, 1.0, 1.0],
359        }
360    }
361}
362
363impl Default for MainWave {
364    fn default() -> Self {
365        Self {
366            mode: 0,
367            rgba: [1.0, 1.0, 1.0, 0.8],
368            x: 0.5,
369            y: 0.5,
370            mystery: 0.0,
371            usedots: false,
372            thick: false,
373            additive: false,
374            brighten: true,
375            scale: 1.0,
376            smoothing: 0.75,
377            mod_alpha_by_volume: false,
378            mod_alpha_start: 0.75,
379            mod_alpha_end: 0.95,
380            wave: [[0.0; NUM_WAVE_INPUT]; 2],
381            spectrum: [[0.0; NUM_FREQ_SAMPLES]; 2],
382        }
383    }
384}
385
386/// See [`FrameInput::warp_gpu`].
387#[derive(Clone, Debug)]
388pub struct WarpGpu {
389    /// `(gx+1)*(gy+1)` entries in the same order as `warp_uv`: the ten motion variables of each vertex
390    /// after per-pixel code.
391    pub vars: Vec<crate::warp_mesh::VertexVars>,
392    /// Per-frame warp animation terms (`WarpAnim::projectm`).
393    pub anim: crate::warp_mesh::WarpAnim,
394}
395
396/// Per-shader-pass random state. projectM gives the warp and the composite shader independent
397/// `rand_preset` / `rand_frame` / `rot_*` streams (MD2 shares one set per preset); the engine
398/// supplies them here. Any `None` falls back to the renderer's own state.
399#[derive(Clone, Debug)]
400pub struct PassRandom {
401    /// `rand_frame`: four values drawn once per frame.
402    pub rand_frame: [f32; 4],
403    /// `rand_preset`: four values drawn once per preset.
404    pub rand_preset: [f32; 4],
405    /// The 24 `rot_*` matrices exactly as uploaded (ABI layout, see [`lactea_abi::MilkUniforms::rot`]).
406    pub rot: Option<Box<[[[f32; 4]; 3]; lactea_abi::NUM_ROT]>>,
407}
408
409impl Default for FrameInput {
410    /// A default MilkDrop state at frame 0 with silent audio (decay .98, gamma 2, white wave 0).
411    fn default() -> Self {
412        Self {
413            time: 0.0,
414            fps: 60.0,
415            frame: 0,
416            progress: 0.0,
417            bass: 1.0,
418            mid: 1.0,
419            treb: 1.0,
420            bass_att: 1.0,
421            mid_att: 1.0,
422            treb_att: 1.0,
423            imm_abs: [0.0; 3],
424            q: [0.0; 32],
425            rand_frame: [0.0; 4],
426            rand_preset: [0.0; 4],
427            warp_uv: None,
428            warp_gpu: None,
429            post: PostParams::default(),
430            blur: BlurParams::default(),
431            borders: Borders::default(),
432            mv: MotionVectors::default(),
433            main_wave: MainWave::default(),
434            shapes: Vec::new(),
435            waves: Vec::new(),
436            darken_center: false,
437            warp_random: None,
438            ext: crate::ShaderExt::default(),
439            comp_random: None,
440            hue_offsets: None,
441            md2_blend: None,
442            sprites: Vec::new(),
443        }
444    }
445}