Skip to main content

lactea_render/renderer/
mod.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//! GPU side: resources, pipelines and the per-frame pass sequence.
6
7use crate::blur;
8use crate::config::{Compat, CompatRules, CompiledShader, RenderConfig, RenderError, StrokeRaster};
9use crate::flash_limit::{FALLBACK_FRAME_SECONDS, FlashLimiter};
10use crate::frame::{FrameInput, ShapeImage};
11use crate::geom::{self, WarpVertex, WfVertex};
12use crate::motion::MotionVectorState;
13use crate::noise;
14use crate::rng::Rng;
15use crate::shader_ext::ShaderExt;
16use crate::shaders;
17use crate::sprite::{SpriteDraw, SpriteImage, SpritePipes};
18use crate::stroke::{self, LineRule};
19use crate::uniforms::{self, MilkUniformInputs, RotParams};
20use crate::warp_mesh::{self, MeshGeometry, VertexVars, WarpAnim};
21use crate::wavegen;
22use crate::wavegen_md3;
23use lactea_abi::dump::Stage;
24use lactea_abi::{
25    Address, BINDING_MILK_EXT, FFT_BINS, FRAGMENT_ENTRY, Filter, MeshVertex, MilkUniforms,
26    NoiseTex, PassUniforms, ShaderInterface, TexDim, TexSource,
27};
28use std::collections::HashMap;
29use wgpu::util::DeviceExt;
30
31mod burn;
32mod fixed;
33mod orchestrate;
34mod passes;
35mod pipelines;
36mod uv_readback;
37
38use pipelines::*;
39use uv_readback::UvReadback;
40
41const INTERNAL_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;
42
43// ---------------------------------------------------------------------------------------
44// small GPU helpers
45// ---------------------------------------------------------------------------------------
46
47#[derive(Clone)]
48struct Tex {
49    texture: wgpu::Texture,
50    view: wgpu::TextureView,
51    w: u32,
52    h: u32,
53}
54
55fn create_target(device: &wgpu::Device, w: u32, h: u32, label: &str) -> Tex {
56    let texture = device.create_texture(&wgpu::TextureDescriptor {
57        label: Some(label),
58        size: wgpu::Extent3d {
59            width: w,
60            height: h,
61            depth_or_array_layers: 1,
62        },
63        mip_level_count: 1,
64        sample_count: 1,
65        dimension: wgpu::TextureDimension::D2,
66        format: INTERNAL_FORMAT,
67        usage: wgpu::TextureUsages::RENDER_ATTACHMENT
68            | wgpu::TextureUsages::TEXTURE_BINDING
69            | wgpu::TextureUsages::COPY_SRC
70            | wgpu::TextureUsages::COPY_DST,
71        view_formats: &[],
72        texture_binding_view_dimension: None,
73    });
74    let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
75    Tex {
76        texture,
77        view,
78        w,
79        h,
80    }
81}
82
83/// `texCoords` of projectM's warp shader: `RG16F`.
84const WARP_SINK_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rg16Float;
85
86fn create_sink(device: &wgpu::Device, w: u32, h: u32) -> Tex {
87    let texture = device.create_texture(&wgpu::TextureDescriptor {
88        label: Some("warp_sink"),
89        size: wgpu::Extent3d {
90            width: w,
91            height: h,
92            depth_or_array_layers: 1,
93        },
94        mip_level_count: 1,
95        sample_count: 1,
96        dimension: wgpu::TextureDimension::D2,
97        format: WARP_SINK_FORMAT,
98        usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
99        view_formats: &[],
100        texture_binding_view_dimension: None,
101    });
102    let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
103    Tex {
104        texture,
105        view,
106        w,
107        h,
108    }
109}
110
111/// An empty `R32Float` texture, as the shader FFT and BeatDrop's wave textures are: zero until the first upload.
112/// `R32Float` is not filterable without `FLOAT32_FILTERABLE`; the translated shaders `textureLoad` it and blend the
113/// neighbouring texels by hand.
114fn create_r32f_tex(
115    device: &wgpu::Device,
116    queue: &wgpu::Queue,
117    label: &str,
118    w: usize,
119    h: usize,
120) -> Tex {
121    let texture = device.create_texture(&wgpu::TextureDescriptor {
122        label: Some(label),
123        size: wgpu::Extent3d {
124            width: w as u32,
125            height: h as u32,
126            depth_or_array_layers: 1,
127        },
128        mip_level_count: 1,
129        sample_count: 1,
130        dimension: wgpu::TextureDimension::D2,
131        format: wgpu::TextureFormat::R32Float,
132        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
133        view_formats: &[],
134        texture_binding_view_dimension: None,
135    });
136    queue.write_texture(
137        wgpu::TexelCopyTextureInfo {
138            texture: &texture,
139            mip_level: 0,
140            origin: wgpu::Origin3d::ZERO,
141            aspect: wgpu::TextureAspect::All,
142        },
143        &vec![0u8; w * h * 4],
144        wgpu::TexelCopyBufferLayout {
145            offset: 0,
146            bytes_per_row: Some(w as u32 * 4),
147            rows_per_image: Some(h as u32),
148        },
149        wgpu::Extent3d {
150            width: w as u32,
151            height: h as u32,
152            depth_or_array_layers: 1,
153        },
154    );
155    let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
156    Tex {
157        texture,
158        view,
159        w: w as u32,
160        h: h as u32,
161    }
162}
163
164/// CPU box-filter mip chain (D3D `AUTOGENMIPMAP` equivalent), level 0 included.
165fn mip_chain(data: &[u8], w: u32, h: u32) -> Vec<(Vec<u8>, u32, u32)> {
166    let mut levels = vec![(data.to_vec(), w, h)];
167    while levels.last().map(|l| l.1 > 1 || l.2 > 1).unwrap_or(false) {
168        let (src, sw, sh) = levels.last().unwrap();
169        let (dw, dh) = ((*sw / 2).max(1), (*sh / 2).max(1));
170        let mut dst = vec![0u8; (dw * dh * 4) as usize];
171        for y in 0..dh {
172            for x in 0..dw {
173                let x0 = (x * 2).min(sw - 1);
174                let x1 = (x * 2 + 1).min(sw - 1);
175                let y0 = (y * 2).min(sh - 1);
176                let y1 = (y * 2 + 1).min(sh - 1);
177                for c in 0..4 {
178                    let s = |xx: u32, yy: u32| src[((yy * sw + xx) * 4 + c) as usize] as u32;
179                    dst[((y * dw + x) * 4 + c) as usize] =
180                        ((s(x0, y0) + s(x1, y0) + s(x0, y1) + s(x1, y1) + 2) / 4) as u8;
181                }
182            }
183        }
184        levels.push((dst, dw, dh));
185    }
186    levels
187}
188
189fn upload_2d(
190    device: &wgpu::Device,
191    queue: &wgpu::Queue,
192    w: u32,
193    h: u32,
194    rgba: &[u8],
195    mips: bool,
196    label: &str,
197) -> Tex {
198    let levels = if mips {
199        mip_chain(rgba, w, h)
200    } else {
201        vec![(rgba.to_vec(), w, h)]
202    };
203    let texture = device.create_texture(&wgpu::TextureDescriptor {
204        label: Some(label),
205        size: wgpu::Extent3d {
206            width: w,
207            height: h,
208            depth_or_array_layers: 1,
209        },
210        mip_level_count: levels.len() as u32,
211        sample_count: 1,
212        dimension: wgpu::TextureDimension::D2,
213        format: INTERNAL_FORMAT,
214        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
215        view_formats: &[],
216        texture_binding_view_dimension: None,
217    });
218    for (i, (data, lw, lh)) in levels.iter().enumerate() {
219        queue.write_texture(
220            wgpu::TexelCopyTextureInfo {
221                texture: &texture,
222                mip_level: i as u32,
223                origin: wgpu::Origin3d::ZERO,
224                aspect: wgpu::TextureAspect::All,
225            },
226            data,
227            wgpu::TexelCopyBufferLayout {
228                offset: 0,
229                bytes_per_row: Some(lw * 4),
230                rows_per_image: Some(*lh),
231            },
232            wgpu::Extent3d {
233                width: *lw,
234                height: *lh,
235                depth_or_array_layers: 1,
236            },
237        );
238    }
239    let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
240    Tex {
241        texture,
242        view,
243        w,
244        h,
245    }
246}
247
248fn upload_3d(device: &wgpu::Device, queue: &wgpu::Queue, n: u32, rgba: &[u8], label: &str) -> Tex {
249    let texture = device.create_texture(&wgpu::TextureDescriptor {
250        label: Some(label),
251        size: wgpu::Extent3d {
252            width: n,
253            height: n,
254            depth_or_array_layers: n,
255        },
256        mip_level_count: 1,
257        sample_count: 1,
258        dimension: wgpu::TextureDimension::D3,
259        format: INTERNAL_FORMAT,
260        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
261        view_formats: &[],
262        texture_binding_view_dimension: None,
263    });
264    queue.write_texture(
265        wgpu::TexelCopyTextureInfo {
266            texture: &texture,
267            mip_level: 0,
268            origin: wgpu::Origin3d::ZERO,
269            aspect: wgpu::TextureAspect::All,
270        },
271        rgba,
272        wgpu::TexelCopyBufferLayout {
273            offset: 0,
274            bytes_per_row: Some(n * 4),
275            rows_per_image: Some(n),
276        },
277        wgpu::Extent3d {
278            width: n,
279            height: n,
280            depth_or_array_layers: n,
281        },
282    );
283    let view = texture.create_view(&wgpu::TextureViewDescriptor {
284        dimension: Some(wgpu::TextureViewDimension::D3),
285        ..Default::default()
286    });
287    Tex {
288        texture,
289        view,
290        w: n,
291        h: n,
292    }
293}
294
295/// `frames` must be a non-empty list of `w * h * 4` byte images of a non-empty size that fits the device's
296/// largest 2D texture (`max_side`).
297fn check_frames(
298    what: &str,
299    max_side: u32,
300    w: u32,
301    h: u32,
302    frames: &[&[u8]],
303) -> Result<(), RenderError> {
304    if w > max_side || h > max_side {
305        return Err(RenderError::Invalid(format!(
306            "{what}: {w}x{h} exceeds the device texture limit of {max_side}"
307        )));
308    }
309    let need = w as usize * h as usize * 4;
310    if w == 0 || h == 0 || frames.is_empty() || frames.iter().any(|f| f.len() != need) {
311        return Err(RenderError::Invalid(format!(
312            "{what}: {} frame(s) of {w}x{h} need {need} bytes each",
313            frames.len()
314        )));
315    }
316    Ok(())
317}
318
319fn buffer_init<T: bytemuck::Pod>(
320    device: &wgpu::Device,
321    label: &str,
322    data: &[T],
323    usage: wgpu::BufferUsages,
324) -> wgpu::Buffer {
325    let bytes: &[u8] = bytemuck::cast_slice(data);
326    if bytes.is_empty() {
327        // zero-sized buffers are awkward; hand out a 16-byte dummy
328        return device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
329            label: Some(label),
330            contents: &[0u8; 16],
331            usage,
332        });
333    }
334    device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
335        label: Some(label),
336        contents: bytes,
337        usage,
338    })
339}
340
341// ---------------------------------------------------------------------------------------
342// blend modes / pipeline set
343// ---------------------------------------------------------------------------------------
344
345use crate::blend::{self, Which};
346/// A blur pass's uniform values and the bind group built from them.
347type BlurBindGroup = ([[f32; 4]; 6], wgpu::BindGroup);
348
349#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
350enum Blend {
351    /// D3DRS_ALPHABLENDENABLE = FALSE (or ONE/ZERO)
352    Replace,
353    /// ONE / ONE
354    Add,
355    /// SRCALPHA / INVSRCALPHA
356    SrcAlpha,
357    /// INVSRCALPHA / SRCALPHA (`bFlipAlpha` of MD2's preset blend)
358    InvSrcAlpha,
359    /// SRCALPHA / ONE
360    SrcAlphaAdd,
361    /// INVDESTCOLOR / ZERO
362    InvDstZero,
363    /// ZERO / DESTCOLOR
364    ZeroDst,
365    /// ZERO / INVDESTCOLOR
366    ZeroInvDst,
367    /// DESTCOLOR / ONE
368    DstOne,
369}
370
371impl Blend {
372    /// Every variant: the pipeline maps are keyed over this, so a new mode gets its pipelines
373    /// without a second list. `blend_state` is the exhaustive match that forces a new arm.
374    const ALL: [Blend; 9] = [
375        Blend::Replace,
376        Blend::Add,
377        Blend::SrcAlpha,
378        Blend::InvSrcAlpha,
379        Blend::SrcAlphaAdd,
380        Blend::InvDstZero,
381        Blend::ZeroDst,
382        Blend::ZeroInvDst,
383        Blend::DstOne,
384    ];
385}
386
387fn blend_state(b: Blend) -> Option<wgpu::BlendState> {
388    use wgpu::BlendFactor as F;
389    let (s, d) = match b {
390        Blend::Replace => return None,
391        Blend::Add => (F::One, F::One),
392        Blend::SrcAlpha => (F::SrcAlpha, F::OneMinusSrcAlpha),
393        Blend::InvSrcAlpha => (F::OneMinusSrcAlpha, F::SrcAlpha),
394        Blend::SrcAlphaAdd => (F::SrcAlpha, F::One),
395        Blend::InvDstZero => (F::OneMinusDst, F::Zero),
396        Blend::ZeroDst => (F::Zero, F::Dst),
397        Blend::ZeroInvDst => (F::Zero, F::OneMinusDst),
398        Blend::DstOne => (F::Dst, F::One),
399    };
400    let c = wgpu::BlendComponent {
401        src_factor: s,
402        dst_factor: d,
403        operation: wgpu::BlendOperation::Add,
404    };
405    Some(wgpu::BlendState { color: c, alpha: c })
406}
407
408#[derive(Clone, Copy, Debug, PartialEq, Eq)]
409enum Kind {
410    Flat,
411    Tex,
412    /// A textured draw that samples the main image with the leftover blur sampler (linear, clamp), see
413    /// `Renderer::build_overlay`.
414    TexLeak,
415    /// A textured draw that samples a shape's `image=` user texture (index into `Batch::images`).
416    TexImage(u32),
417}
418
419/// Primitive topology of a flat-colour draw.
420#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
421enum Prim {
422    /// `TriangleList`
423    Tri,
424    /// `LineList` (pairs of vertices, vertex colours interpolate along the line)
425    Line,
426    /// `PointList` (1 px)
427    Point,
428}
429
430#[derive(Default)]
431struct Batch {
432    wf: Vec<WfVertex>,
433    mesh: Vec<MeshVertex>,
434    cmds: Vec<(Kind, Blend, Prim, u32, u32)>,
435    /// Textures of [`Kind::TexImage`] commands (one entry per command).
436    images: Vec<ShapeImage>,
437    /// Command indices after the custom shapes / after the custom waves: where sprite layers 2 and 3 go.
438    marks: [usize; 2],
439    /// Commands before this index never merge with later ones (a sprite layer may be drawn in between).
440    barrier: usize,
441}
442
443impl Batch {
444    fn flat(&mut self, blend: Blend, verts: &[WfVertex]) {
445        self.flat_prim(Prim::Tri, blend, verts);
446    }
447    fn flat_prim(&mut self, prim: Prim, blend: Blend, verts: &[WfVertex]) {
448        if verts.is_empty() {
449            return;
450        }
451        let start = self.wf.len() as u32;
452        self.wf.extend_from_slice(verts);
453        if self.cmds.len() > self.barrier
454            && let Some(last) = self.cmds.last_mut()
455            && last.0 == Kind::Flat
456            && last.1 == blend
457            && last.2 == prim
458            && last.3 + last.4 == start
459        {
460            last.4 += verts.len() as u32;
461            return;
462        }
463        self.cmds
464            .push((Kind::Flat, blend, prim, start, verts.len() as u32));
465    }
466    fn tex(&mut self, blend: Blend, verts: &[MeshVertex]) {
467        if verts.is_empty() {
468            return;
469        }
470        let start = self.mesh.len() as u32;
471        self.mesh.extend_from_slice(verts);
472        if self.cmds.len() > self.barrier
473            && let Some(last) = self.cmds.last_mut()
474            && last.0 == Kind::Tex
475            && last.1 == blend
476            && last.3 + last.4 == start
477        {
478            last.4 += verts.len() as u32;
479            return;
480        }
481        self.cmds
482            .push((Kind::Tex, blend, Prim::Tri, start, verts.len() as u32));
483    }
484    fn tex_leak(&mut self, blend: Blend, verts: &[MeshVertex]) {
485        if verts.is_empty() {
486            return;
487        }
488        let start = self.mesh.len() as u32;
489        self.mesh.extend_from_slice(verts);
490        self.cmds
491            .push((Kind::TexLeak, blend, Prim::Tri, start, verts.len() as u32));
492    }
493    /// A textured fill that samples the user texture of a shape's `image=` key.
494    fn tex_image(&mut self, blend: Blend, verts: &[MeshVertex], image: &ShapeImage) {
495        if verts.is_empty() {
496            return;
497        }
498        let start = self.mesh.len() as u32;
499        self.mesh.extend_from_slice(verts);
500        let id = self.images.len() as u32;
501        self.images.push(ShapeImage {
502            name: image.name.to_ascii_lowercase(),
503            ..image.clone()
504        });
505        self.cmds.push((
506            Kind::TexImage(id),
507            blend,
508            Prim::Tri,
509            start,
510            verts.len() as u32,
511        ));
512    }
513    /// Let `fill` append vertices of `prim` to the flat-vertex buffer and record them as one command (merged with the
514    /// previous one when it is compatible), without an intermediate buffer.
515    fn flat_extend(&mut self, prim: Prim, blend: Blend, fill: impl FnOnce(&mut Vec<WfVertex>)) {
516        let start = self.wf.len() as u32;
517        fill(&mut self.wf);
518        let count = self.wf.len() as u32 - start;
519        if count == 0 {
520            return;
521        }
522        if self.cmds.len() > self.barrier
523            && let Some(last) = self.cmds.last_mut()
524            && last.0 == Kind::Flat
525            && last.1 == blend
526            && last.2 == prim
527            && last.3 + last.4 == start
528        {
529            last.4 += count;
530            return;
531        }
532        self.cmds.push((Kind::Flat, blend, prim, start, count));
533    }
534    /// 1-pixel line segments: `segs` holds pairs of vertices (clip space, per-vertex colour); `rule` picks the
535    /// GL line rule (see `stroke.rs`).
536    fn segments(
537        &mut self,
538        mode: StrokeRaster,
539        rule: LineRule,
540        blend: Blend,
541        w: f32,
542        h: f32,
543        segs: &[WfVertex],
544    ) {
545        match mode {
546            StrokeRaster::Native => self.flat_prim(Prim::Line, blend, segs),
547            StrokeRaster::Emulated => self.flat_extend(Prim::Point, blend, |out| {
548                stroke::raster_segments(segs, w as u32, h as u32, rule, out);
549            }),
550            StrokeRaster::Quads => self.flat_extend(Prim::Tri, blend, |out| {
551                for s in segs.as_chunks::<2>().0 {
552                    geom::push_line(out, s[0].pos, s[1].pos, w, h, s[0].color);
553                }
554            }),
555        }
556    }
557    /// Points of `size` pixels (`size == 1` is a 1-px GL point; larger sizes are D3D9 point sprites = quads).
558    fn points(
559        &mut self,
560        mode: StrokeRaster,
561        blend: Blend,
562        w: f32,
563        h: f32,
564        pts: &[WfVertex],
565        size: f32,
566    ) {
567        match mode {
568            StrokeRaster::Native if size <= 1.0 => self.flat_prim(Prim::Point, blend, pts),
569            StrokeRaster::Emulated if size <= 1.0 => self.flat_extend(Prim::Point, blend, |out| {
570                stroke::raster_points(pts, w as u32, h as u32, out);
571            }),
572            _ => self.flat_extend(Prim::Tri, blend, |out| {
573                for p in pts {
574                    geom::push_point(out, p.pos, size, w, h, p.color);
575                }
576            }),
577        }
578    }
579    /// Remember the current end of the command list as sprite split `which` (0 = after the custom shapes, 1 = after
580    /// the custom waves).
581    fn mark(&mut self, which: usize) {
582        self.marks[which] = self.cmds.len();
583        self.barrier = self.cmds.len();
584    }
585    fn is_empty(&self) -> bool {
586        self.cmds.is_empty()
587    }
588}
589
590struct Pipelines {
591    bgl_tex: wgpu::BindGroupLayout,
592    bgl_warp_vs: wgpu::BindGroupLayout,
593    /// projectM warp vertex stage + fixed-function fragment, keyed by `main_alpha`
594    warp_tex: HashMap<bool, wgpu::RenderPipeline>,
595    warp_uv_readback: wgpu::RenderPipeline,
596    bgl_blur: wgpu::BindGroupLayout,
597    bgl_blit: wgpu::BindGroupLayout,
598    bgl_mu: wgpu::BindGroupLayout,
599    /// keyed by (blend, alpha): `alpha` = projectM RGBA semantics (alpha written, `tex.a` modulates)
600    tex: HashMap<(Blend, bool), wgpu::RenderPipeline>,
601    flat: HashMap<(Blend, Prim, bool), wgpu::RenderPipeline>,
602    blur_h: wgpu::RenderPipeline,
603    blur_v: wgpu::RenderPipeline,
604    blit: wgpu::RenderPipeline,
605    /// Bilinear blit into the host's output format, built when the internal image is not the output's size.
606    blit_linear: std::sync::OnceLock<wgpu::RenderPipeline>,
607    /// Bilinear copy between `INTERNAL_FORMAT` images of different sizes (keeping the feedback image on a resize),
608    /// built on first use.
609    resample: std::sync::OnceLock<wgpu::RenderPipeline>,
610    output_format: wgpu::TextureFormat,
611    mesh_vs: wgpu::ShaderModule,
612    /// `[linear wrap, linear clamp, point wrap, point clamp]` with mips, then the same four limited to level 0
613    samplers: [wgpu::Sampler; 8],
614    /// MD3 sprite pipelines, built when the first sprite image is registered.
615    sprite: std::sync::OnceLock<SpritePipes>,
616    /// The `burn_texture` copy pipeline, built on first use.
617    burn: std::sync::OnceLock<burn::BurnPipe>,
618    /// Sprite pipelines for the host's output format when it is not the internal one.
619    sprite_out: std::sync::OnceLock<SpritePipes>,
620}
621
622/// Uniforms of [`shaders::warp_vs`] (projectM's warp vertex shader).
623#[repr(C)]
624#[derive(Clone, Copy, Debug, Default, bytemuck::Pod, bytemuck::Zeroable)]
625struct WarpVsUniforms {
626    /// `aspectX, aspectY, invAspectX, invAspectY`
627    aspect: [f32; 4],
628    /// `warpTime, warpScaleInverse, texelOffset.x, texelOffset.y`
629    timing: [f32; 4],
630    /// `warpFactors`
631    factors: [f32; 4],
632    /// `frag_COLOR` (`decay`, or 1)
633    diffuse: [f32; 4],
634}
635
636struct ShaderPass {
637    pipeline: wgpu::RenderPipeline,
638    /// Warp shaders only: the same fragment stage behind projectM's warp vertex shader ([`shaders::warp_vs`]).
639    warp_pipeline: Option<wgpu::RenderPipeline>,
640    pass_bgl: wgpu::BindGroupLayout,
641    interface: ShaderInterface,
642    /// Warp shaders: the fragment stage returns the interpolated UV as a second output ([`with_uv_output`]).
643    uv_sink: bool,
644    /// `CompatRules::md2_preset_blend` only: the same fragment stage with MD2's blend-pass alpha blending, keyed
645    /// `[SRCALPHA / INVSRCALPHA, INVSRCALPHA / SRCALPHA]` (`bFlipAlpha`), mesh vertices.
646    alpha_pipelines: Option<[wgpu::RenderPipeline; 2]>,
647}
648
649/// Vertex data of a user-shader pass: the generic mesh vertex, or projectM's warp mesh vertex (GPU UV
650/// evaluation) with the uniforms of its vertex stage.
651enum PassVerts<'a> {
652    Mesh(&'a [MeshVertex]),
653    Warp(&'a [WarpVertex], &'a WarpVsUniforms),
654}
655
656struct UserTex {
657    /// The texture (the first frame of an animation).
658    tex: Tex,
659    anim: Option<UserAnim>,
660}
661
662/// An animated GIF used as a shader texture (MD3): the frame shown is picked by the time of the frame.
663struct UserAnim {
664    /// Never empty.
665    frames: Vec<Tex>,
666    /// Seconds per frame, same length as `frames`.
667    delays: Vec<f64>,
668}
669
670impl UserTex {
671    fn view_at(&self, time: f64) -> &wgpu::TextureView {
672        match &self.anim {
673            Some(a) => &a.frames[crate::sprite::gif_frame_index(&a.delays, time)].view,
674            None => &self.tex.view,
675        }
676    }
677}
678
679/// The shader-side state of one preset: its warp / composite pass and the user textures their samplers read (MD2's
680/// `m_shaders`, and `m_OldShaders` during a blend).
681struct ShaderSet {
682    warp: Option<ShaderPass>,
683    comp: Option<ShaderPass>,
684    user_tex: HashMap<String, UserTex>,
685}
686
687/// A preset's installed shaders and textures, detached from the renderer ([`Renderer::take_shader_state`]).
688pub struct ShaderState(ShaderSet);
689
690/// How a user-shader pass writes its target ([`Renderer::run_shader_pass`]).
691#[derive(Clone, Copy, Debug, PartialEq, Eq)]
692enum PassBlend {
693    /// Clear the target, opaque draw.
694    Replace,
695    /// Keep the target, `SRCALPHA / INVSRCALPHA`.
696    SrcAlpha,
697    /// Keep the target, `INVSRCALPHA / SRCALPHA`.
698    InvSrcAlpha,
699}
700
701/// Row pitch of a buffer copy of `row_bytes` bytes per row (wgpu requires multiples of 256).
702fn padded_bytes_per_row(row_bytes: u32) -> u32 {
703    row_bytes.div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT) * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT
704}
705
706/// Whether a GPU buffer can be mapped and waited for inside a call. WebGPU maps buffers only once control returns
707/// to the browser's event loop, so such a wait never completes there: the web build reads nothing back and the
708/// motion vector pass uses the CPU port of the warp formula (`cpu_warp_uv`) instead of the GPU's own UVs.
709pub(crate) const SYNC_READBACK: bool = cfg!(not(target_arch = "wasm32"));
710
711/// Read an `Rgba8Unorm`-sized (4 bytes per texel) `w` x `h` texture back as tightly packed RGBA8 (row 0 = top).
712/// Submits its own copy and waits for it, so the frame's command buffers must have been submitted. Always an error
713/// on the web ([`SYNC_READBACK`]).
714pub fn readback_rgba8(
715    device: &wgpu::Device,
716    queue: &wgpu::Queue,
717    texture: &wgpu::Texture,
718    w: u32,
719    h: u32,
720) -> Result<Vec<u8>, RenderError> {
721    if !SYNC_READBACK {
722        return Err(RenderError::Readback(
723            "synchronous GPU readback is not available on the web".to_owned(),
724        ));
725    }
726    let bpr = padded_bytes_per_row(w * 4);
727    let buf = device.create_buffer(&wgpu::BufferDescriptor {
728        label: Some("readback"),
729        size: u64::from(bpr) * u64::from(h),
730        usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
731        mapped_at_creation: false,
732    });
733    let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
734        label: Some("readback"),
735    });
736    enc.copy_texture_to_buffer(
737        wgpu::TexelCopyTextureInfo {
738            texture,
739            mip_level: 0,
740            origin: wgpu::Origin3d::ZERO,
741            aspect: wgpu::TextureAspect::All,
742        },
743        wgpu::TexelCopyBufferInfo {
744            buffer: &buf,
745            layout: wgpu::TexelCopyBufferLayout {
746                offset: 0,
747                bytes_per_row: Some(bpr),
748                rows_per_image: Some(h),
749            },
750        },
751        wgpu::Extent3d {
752            width: w,
753            height: h,
754            depth_or_array_layers: 1,
755        },
756    );
757    queue.submit(Some(enc.finish()));
758    let slice = buf.slice(..);
759    let (tx, rx) = std::sync::mpsc::channel();
760    slice.map_async(wgpu::MapMode::Read, move |r| {
761        let _ = tx.send(r);
762    });
763    device
764        .poll(wgpu::PollType::wait_indefinitely())
765        .map_err(|e| RenderError::Readback(format!("{e:?}")))?;
766    rx.recv()
767        .map_err(|e| RenderError::Readback(e.to_string()))?
768        .map_err(|e| RenderError::Readback(e.to_string()))?;
769    let data = slice
770        .get_mapped_range()
771        .map_err(|e| RenderError::Readback(e.to_string()))?;
772    let row = w as usize * 4;
773    let mut out = Vec::with_capacity(row * h as usize);
774    for y in 0..h {
775        let s = y as usize * bpr as usize;
776        out.extend_from_slice(&data[s..s + row]);
777    }
778    drop(data);
779    buf.unmap();
780    Ok(out)
781}
782
783/// Index buffer of the GPU warp mesh ([`geom::warp_gpu_indices`]) and its index count; only projectM's rules draw it.
784/// Constant for a mesh size, so built when the mesh changes rather than every frame.
785fn warp_index_buffer(
786    device: &wgpu::Device,
787    geom: &MeshGeometry,
788    rules: &CompatRules,
789) -> Option<(wgpu::Buffer, u32)> {
790    if !rules.warp_uv_on_gpu {
791        return None;
792    }
793    let idx = geom::warp_gpu_indices(geom, rules.warp_diag_flipped);
794    let buf = buffer_init(device, "warp indices", &idx, wgpu::BufferUsages::INDEX);
795    Some((buf, idx.len() as u32))
796}
797
798/// Check a render size against zero and the device's 2D texture limit.
799fn check_size(device: &wgpu::Device, width: u32, height: u32) -> Result<(), RenderError> {
800    if width == 0 || height == 0 {
801        return Err(RenderError::Invalid(format!(
802            "render size must be non-zero, got {width}x{height}"
803        )));
804    }
805    let max = device.limits().max_texture_dimension_2d;
806    if width > max || height > max {
807        return Err(RenderError::Invalid(format!(
808            "render size {width}x{height} exceeds the device texture limit of {max}"
809        )));
810    }
811    Ok(())
812}
813
814/// The mesh geometry of `cfg`, after checking that its size and mesh are usable.
815fn checked_geometry(
816    device: &wgpu::Device,
817    cfg: &RenderConfig,
818) -> Result<MeshGeometry, RenderError> {
819    check_size(device, cfg.width, cfg.height)?;
820    MeshGeometry::new(cfg.mesh[0], cfg.mesh[1], cfg.width, cfg.height)
821}
822
823// ---------------------------------------------------------------------------------------
824// Renderer
825// ---------------------------------------------------------------------------------------
826
827/// The flash limit and what `render_frame` needs to apply it.
828struct FlashState {
829    /// Largest change of a colour channel per second.
830    limit: f32,
831    limiter: FlashLimiter,
832    /// Time of the last limited frame.
833    last_time: Option<f64>,
834}
835
836/// Smallest and largest [`Renderer::set_render_scale`].
837const RENDER_SCALE_RANGE: (f32, f32) = (0.25, 2.0);
838
839/// Internal image size for an output size and render scale (at least one pixel per axis).
840fn scaled_size(out: (u32, u32), scale: f32) -> (u32, u32) {
841    let f = |v: u32| ((f64::from(v) * f64::from(scale)).round() as u32).max(1);
842    if scale == 1.0 {
843        out
844    } else {
845        (f(out.0), f(out.1))
846    }
847}
848
849/// The MilkDrop 2 frame renderer. See the crate docs for the pass order.
850pub struct Renderer {
851    device: wgpu::Device,
852    queue: wgpu::Queue,
853    cfg: RenderConfig,
854    rules: CompatRules,
855    geom: MeshGeometry,
856    /// Triangles of the GPU warp mesh over the unique vertices of [`geom::build_warp_gpu_vertices`].
857    warp_indices: Option<(wgpu::Buffer, u32)>,
858    /// See [`Renderer::blit`]: per source image (`final`, then the two flash limiter images).
859    blit_bg: std::cell::RefCell<[Option<wgpu::BindGroup>; 3]>,
860    /// Size of the host target ([`Renderer::output_size`]); `cfg.width x cfg.height` is the internal image.
861    out_size: (u32, u32),
862    /// Internal image size relative to the output ([`Renderer::set_render_scale`]).
863    render_scale: f32,
864    /// [`Renderer::set_keep_feedback_on_resize`].
865    keep_feedback_on_resize: bool,
866    /// [`Renderer::set_capture_warped`].
867    capture_warped: bool,
868    /// [`Renderer::set_flash_limit`]; `None` allocates nothing and records no pass.
869    flash: Option<FlashState>,
870    /// Bind groups of blur passes 1.. keyed by their uniform values (see `Renderer::run_blur`); dropped on `resize`.
871    blur_bg: std::cell::RefCell<Vec<Option<BlurBindGroup>>>,
872    rot: RotParams,
873    pipes: std::sync::Arc<Pipelines>,
874    /// `m_lpVS[0..2]` ping-pong; `main[main_idx]` holds the latest `main` image.
875    main: [Tex; 2],
876    main_idx: usize,
877    warped: Tex,
878    final_tex: Tex,
879    blur: Vec<Tex>,
880    noise: Vec<Tex>,
881    user_tex: HashMap<String, UserTex>,
882    /// MD3 sprite images by id ([`Renderer::set_sprite_image`]).
883    sprite_images: HashMap<u32, SpriteImage>,
884    /// Time of the frame being recorded: animated textures pick their frame from it.
885    anim_time: f64,
886    dummy_2d: Tex,
887    dummy_3d: Tex,
888    /// `sampler_fft` ([`TexSource::Fft`]): the smoothed MilkDrop 3 shader FFT (512 x 1), or under
889    /// `CompatRules::md2_shader_inputs` BeatDrop's `m_lpFFTTexture` (1024 x 2: spectrum, peak hold). Owned per renderer
890    /// (a [`Renderer::sibling`] has its own) and replaced whenever a frame carries `FrameInput::ext.fft` /
891    /// `FrameInput::ext.beatdrop`.
892    fft: Tex,
893    /// BeatDrop's `m_lpWaveTexture` (480 x 2: left, right), only under `CompatRules::md2_shader_inputs`. The
894    /// translator names it by the user texture `"wave"` (the frozen ABI has no source for it): see
895    /// [`Renderer::engine_wave`].
896    wave: Option<Tex>,
897    /// Scratch attachment for the user warp shader's second output ([`with_uv_output`]); never read.
898    warp_sink: Tex,
899    warp_shader: Option<ShaderPass>,
900    comp_shader: Option<ShaderPass>,
901    /// MD2's `m_OldShaders` (+ the old preset's textures): the old preset's shaders while a preset blend runs.
902    old_shaders: Option<ShaderSet>,
903    /// Warp UV grid of the previous frame (motion vector reverse propagation).
904    prev_warp_uv: Option<Vec<[f32; 2]>>,
905    /// The previous frame's warp vertex-shader inputs, to evaluate its UVs on the GPU (motion vector lookups).
906    prev_warp_gpu: Option<crate::frame::WarpGpu>,
907    /// Persistent readback of the GPU's warp UVs ([`Renderer::gpu_warp_vertex_uv`]).
908    uv_readback: Option<UvReadback>,
909    /// projectM's motion vector mesh (stale vertices, index count).
910    mv_state: MotionVectorState,
911    frames_since_resize: u32,
912    /// projectM's persistent main-wave buffer tail (see [`wavegen::PmWaveTail`]); zero at preset load.
913    main_wave_tail: wavegen::PmWaveTail,
914    /// Working buffers of the per-frame geometry builders.
915    scratch: FrameScratch,
916    /// Highest blur level used by the last rendered frame's shaders (for tests / diagnostics).
917    last_blur_levels: u8,
918    /// Minimum blur level computed every frame ([`Renderer::set_min_blur_levels`]).
919    #[cfg(feature = "diagnostics")]
920    min_blur_levels: u8,
921    /// One-shot override of the composite `sampler_main` ([`Renderer::inject_comp_source`]).
922    #[cfg(feature = "diagnostics")]
923    comp_source_override: Option<Tex>,
924}
925
926/// Hooks for comparing against a reference render (feature `diagnostics`): replacing internal images, forcing
927/// per-frame state and reading intermediate images back.
928#[cfg(feature = "diagnostics")]
929impl Renderer {
930    /// Replace a built-in noise texture (e.g. with a reference render's noise). 2D: `size*size*4` bytes,
931    /// row 0 first; volumes: `size^3*4`, slice-major. Sizes are MD2's (see [`crate::noise::noise_spec`]).
932    pub fn inject_noise(&mut self, which: NoiseTex, data: &[u8]) -> Result<(), RenderError> {
933        let (size, _, vol) = noise::noise_spec(which);
934        let expect = if vol {
935            (size * size * size * 4) as usize
936        } else {
937            (size * size * 4) as usize
938        };
939        if data.len() != expect {
940            return Err(RenderError::Invalid(format!(
941                "{which:?}: expected {expect} bytes, got {}",
942                data.len()
943            )));
944        }
945        self.noise[which.index()] = if vol {
946            upload_3d(&self.device, &self.queue, size, data, "noise_vol")
947        } else {
948            upload_2d(&self.device, &self.queue, size, size, data, true, "noise")
949        };
950        Ok(())
951    }
952
953    /// Replace the previous-frame image (`main`, what the next warp samples).
954    pub fn inject_main(&mut self, rgba8: &[u8]) -> Result<(), RenderError> {
955        let t = &self.main[self.main_idx];
956        self.write_rgba8(t, rgba8, "inject_main")
957    }
958
959    /// Use `rgba8` as the composite source (a comp shader's `sampler_main`, or the no-shader composite's
960    /// texture) for the next rendered frame only. Does not touch the stored `main` image, so the `main` stage
961    /// read-back stays the renderer's own.
962    pub fn inject_comp_source(&mut self, rgba8: &[u8]) -> Result<(), RenderError> {
963        let (w, h) = (self.cfg.width, self.cfg.height);
964        let t = create_target(&self.device, w, h, "comp source override");
965        self.write_rgba8(&t, rgba8, "inject_comp_source")?;
966        self.comp_source_override = Some(t);
967        Ok(())
968    }
969
970    /// Make the next frame's motion-vector pass use this warp UV grid (the previous frame's UVs).
971    pub fn inject_prev_warp_uv(&mut self, uv: Option<Vec<[f32; 2]>>) {
972        self.prev_warp_uv = uv;
973    }
974
975    /// The image the last frame's warp pass sampled (previous `main` + this frame's motion vectors).
976    /// Valid until the next `render_frame`.
977    pub fn read_warp_source(&self) -> Result<(u32, u32, Vec<u8>), RenderError> {
978        self.read_texture(&self.main[1 - self.main_idx])
979    }
980
981    /// Compute at least `levels` (0..=3) blur levels every frame even if no shader samples them, so
982    /// `Stage::Blur1..3` can be read back.
983    pub fn set_min_blur_levels(&mut self, levels: u8) {
984        self.min_blur_levels = levels.min(3);
985    }
986
987    /// Per-preset random parameters (rotation matrices, hue offsets).
988    pub fn rot_params(&self) -> &RotParams {
989        &self.rot
990    }
991
992    /// Replace the per-preset random parameters (they otherwise stay as drawn from the seed).
993    pub fn set_rot_params(&mut self, p: RotParams) {
994        self.rot = p;
995    }
996
997    /// Upload a full-size RGBA8 image (row 0 = top) into `t`.
998    fn write_rgba8(&self, t: &Tex, rgba8: &[u8], what: &str) -> Result<(), RenderError> {
999        let need = t.w as usize * t.h as usize * 4;
1000        if rgba8.len() != need {
1001            return Err(RenderError::Invalid(format!(
1002                "{what}: need {need} bytes, got {}",
1003                rgba8.len()
1004            )));
1005        }
1006        self.queue.write_texture(
1007            wgpu::TexelCopyTextureInfo {
1008                texture: &t.texture,
1009                mip_level: 0,
1010                origin: wgpu::Origin3d::ZERO,
1011                aspect: wgpu::TextureAspect::All,
1012            },
1013            rgba8,
1014            wgpu::TexelCopyBufferLayout {
1015                offset: 0,
1016                bytes_per_row: Some(t.w * 4),
1017                rows_per_image: Some(t.h),
1018            },
1019            wgpu::Extent3d {
1020                width: t.w,
1021                height: t.h,
1022                depth_or_array_layers: 1,
1023            },
1024        );
1025        Ok(())
1026    }
1027}
1028
1029impl Renderer {
1030    /// Create a renderer. Textures are cleared to black; noise textures are generated from
1031    /// `cfg.seed` (MD2 algorithm). `device`/`queue` are cloned handles (cheap).
1032    ///
1033    /// # Errors
1034    ///
1035    /// [`RenderError::Invalid`] if the size is zero or the mesh is not an even grid of at least 2x2 cells.
1036    pub fn new(
1037        device: &wgpu::Device,
1038        queue: &wgpu::Queue,
1039        cfg: RenderConfig,
1040    ) -> Result<Self, RenderError> {
1041        let geom = checked_geometry(device, &cfg)?;
1042        let pipes = std::sync::Arc::new(Pipelines::new(device, cfg.output_format));
1043        let out_size = (cfg.width, cfg.height);
1044        Ok(Self::assemble(
1045            device, queue, cfg, out_size, 1.0, geom, pipes, None,
1046        ))
1047    }
1048
1049    /// A second renderer with the same configuration that shares this one's pipelines and
1050    /// (immutable) noise textures but has its own images, shaders and user textures: what the
1051    /// engine needs to run two presets at once while they transition. Cheaper than
1052    /// [`Renderer::new`] (no pipeline compilation, no noise generation), but it still allocates the render targets.
1053    pub fn sibling(&self) -> Self {
1054        self.sibling_with_compat(self.cfg.compat)
1055    }
1056
1057    /// [`Renderer::sibling`] that follows another compatibility mode: same size, mesh, stroke setting, shared
1058    /// pipelines and noise (neither depends on the mode), but its own images, shaders and textures, and the rules of
1059    /// `compat`. What the engine builds into when an automatically selected mode changes.
1060    pub fn sibling_with_compat(&self, compat: Compat) -> Self {
1061        let mut cfg = self.cfg.clone();
1062        cfg.compat = compat;
1063        let mut r = Self::assemble(
1064            &self.device,
1065            &self.queue,
1066            cfg,
1067            self.out_size,
1068            self.render_scale,
1069            self.geom.clone(),
1070            std::sync::Arc::clone(&self.pipes),
1071            Some(self.noise.clone()),
1072        );
1073        #[cfg(feature = "diagnostics")]
1074        {
1075            r.min_blur_levels = self.min_blur_levels;
1076        }
1077        r.rot = self.rot.clone();
1078        r.keep_feedback_on_resize = self.keep_feedback_on_resize;
1079        r.capture_warped = self.capture_warped;
1080        r
1081    }
1082
1083    #[allow(clippy::too_many_arguments)]
1084    fn assemble(
1085        device: &wgpu::Device,
1086        queue: &wgpu::Queue,
1087        cfg: RenderConfig,
1088        out_size: (u32, u32),
1089        render_scale: f32,
1090        geom: MeshGeometry,
1091        pipes: std::sync::Arc<Pipelines>,
1092        shared_noise: Option<Vec<Tex>>,
1093    ) -> Self {
1094        let rules = cfg.compat.rules();
1095
1096        let (w, h) = (cfg.width, cfg.height);
1097        let main = [
1098            create_target(device, w, h, "main0"),
1099            create_target(device, w, h, "main1"),
1100        ];
1101        let warped = create_target(device, w, h, "warped");
1102        let final_tex = create_target(device, w, h, "final");
1103        let blur = blur::blur_tex_sizes(w, h)
1104            .iter()
1105            .enumerate()
1106            .map(|(i, &(bw, bh))| create_target(device, bw, bh, &format!("blur{i}")))
1107            .collect();
1108
1109        let rng = Rng::new(cfg.seed);
1110        let noise_tex = match shared_noise {
1111            Some(n) => n,
1112            None => {
1113                let mut noise_rng = rng.fork(0x6E6F_6973);
1114                let mut noise_tex = Vec::new();
1115                for t in noise::ALL_NOISE {
1116                    let data = noise::generate(t, &mut noise_rng, &rules);
1117                    let (size, _, vol) = noise::noise_spec(t);
1118                    noise_tex.push(if vol {
1119                        upload_3d(device, queue, size, &data, "noise_vol")
1120                    } else {
1121                        upload_2d(device, queue, size, size, &data, true, "noise")
1122                    });
1123                }
1124                noise_tex
1125            }
1126        };
1127        let rot = RotParams::randomize(&mut rng.fork(0x7072_6573));
1128        let dummy_2d = upload_2d(device, queue, 1, 1, &[0, 0, 0, 255], false, "dummy2d");
1129        let dummy_3d = upload_3d(device, queue, 1, &[0, 0, 0, 255], "dummy3d");
1130        let (fft_w, fft_h) = if rules.md2_shader_inputs {
1131            (crate::BEATDROP_FFT_BINS, 2)
1132        } else {
1133            (FFT_BINS, 1)
1134        };
1135        let fft = create_r32f_tex(device, queue, "fft", fft_w, fft_h);
1136        let wave = rules
1137            .md2_shader_inputs
1138            .then(|| create_r32f_tex(device, queue, "wave", crate::BEATDROP_WAVE_SAMPLES, 2));
1139
1140        let warp_indices = warp_index_buffer(device, &geom, &rules);
1141        let r = Renderer {
1142            device: device.clone(),
1143            queue: queue.clone(),
1144            cfg,
1145            rules,
1146            geom,
1147            warp_indices,
1148            blit_bg: Default::default(),
1149            out_size,
1150            render_scale,
1151            keep_feedback_on_resize: false,
1152            capture_warped: cfg!(feature = "diagnostics"),
1153            flash: None,
1154            blur_bg: Default::default(),
1155            rot,
1156            pipes,
1157            main,
1158            main_idx: 0,
1159            warped,
1160            final_tex,
1161            blur,
1162            noise: noise_tex,
1163            user_tex: HashMap::new(),
1164            sprite_images: HashMap::new(),
1165            anim_time: 0.0,
1166            dummy_2d,
1167            dummy_3d,
1168            fft,
1169            wave,
1170            warp_sink: create_sink(device, w, h),
1171            warp_shader: None,
1172            comp_shader: None,
1173            old_shaders: None,
1174            prev_warp_uv: None,
1175            prev_warp_gpu: None,
1176            uv_readback: None,
1177            mv_state: MotionVectorState::default(),
1178            frames_since_resize: 0,
1179            main_wave_tail: Default::default(),
1180            scratch: FrameScratch::default(),
1181            last_blur_levels: 0,
1182            #[cfg(feature = "diagnostics")]
1183            min_blur_levels: 0,
1184            #[cfg(feature = "diagnostics")]
1185            comp_source_override: None,
1186        };
1187        r.clear_all();
1188        r
1189    }
1190
1191    // ---- configuration ----------------------------------------------------------------
1192
1193    /// The configuration in use (size and mesh follow [`Renderer::resize`] / [`Renderer::set_mesh_size`]).
1194    pub fn config(&self) -> &RenderConfig {
1195        &self.cfg
1196    }
1197
1198    /// The warp-mesh geometry (vertex positions, `rad`, `ang`) — what the engine needs to run per-pixel code.
1199    pub fn mesh_geometry(&self) -> &MeshGeometry {
1200        &self.geom
1201    }
1202
1203    /// The reference behaviour followed where MilkDrop 2 and projectM differ.
1204    pub fn compat(&self) -> Compat {
1205        self.cfg.compat
1206    }
1207
1208    /// The rasteriser actually used for lines and points: the configured one, except that
1209    /// `Compat::MilkDrop2` / `Compat::MilkDrop3` always draw D3D9-style thin quads.
1210    pub fn stroke_raster(&self) -> StrokeRaster {
1211        self.stroke_mode()
1212    }
1213
1214    fn stroke_mode(&self) -> StrokeRaster {
1215        if self.rules.gl_strokes {
1216            self.cfg.stroke
1217        } else {
1218            StrokeRaster::Quads
1219        }
1220    }
1221
1222    /// Switch the line / point rasteriser (see [`StrokeRaster`]); takes effect on the next frame.
1223    pub fn set_stroke_raster(&mut self, s: StrokeRaster) {
1224        self.cfg.stroke = s;
1225    }
1226
1227    /// Resize the output to `width x height` and the internal image to that times the render scale
1228    /// ([`Renderer::set_render_scale`]). Clears every texture and forgets the previous frame
1229    /// (`m_nFramesSinceResize = 0`), except that with [`Renderer::set_keep_feedback_on_resize`] the previous `main`
1230    /// image is resampled into the new size. Noise and user textures are kept; an active flash limit
1231    /// ([`Renderer::set_flash_limit`]) fades in from black again.
1232    pub fn resize(&mut self, width: u32, height: u32) -> Result<(), RenderError> {
1233        self.reallocate((width, height), self.render_scale)
1234    }
1235
1236    /// Render the feedback chain (`main`, warped, blur and final images) at `scale` times the output size and
1237    /// upsample the composite to the host target when blitting (bilinear). `1.0` (the default) renders at the output
1238    /// size and blits as before. `scale` is clamped to 0.25..=2.0; NaN is an error. Changing the scale reallocates
1239    /// every image like [`Renderer::resize`]; [`Renderer::config`] reports the internal size from then on
1240    /// ([`Renderer::output_size`] stays the target's).
1241    ///
1242    /// Fails with [`RenderError::Invalid`] (changing nothing) for NaN or when the internal size exceeds the device's
1243    /// texture limit.
1244    pub fn set_render_scale(&mut self, scale: f32) -> Result<(), RenderError> {
1245        if scale.is_nan() {
1246            return Err(RenderError::Invalid(
1247                "render scale must be a number".to_owned(),
1248            ));
1249        }
1250        let scale = scale.clamp(RENDER_SCALE_RANGE.0, RENDER_SCALE_RANGE.1);
1251        if scale == self.render_scale {
1252            return Ok(());
1253        }
1254        self.reallocate(self.out_size, scale)
1255    }
1256
1257    /// The render scale in effect ([`Renderer::set_render_scale`]).
1258    pub fn render_scale(&self) -> f32 {
1259        self.render_scale
1260    }
1261
1262    /// Size of the host target `render_frame` blits to. Equals `config().width x config().height` at render scale 1.
1263    pub fn output_size(&self) -> (u32, u32) {
1264        self.out_size
1265    }
1266
1267    /// Keep the feedback image across [`Renderer::resize`] / [`Renderer::set_render_scale`]: the previous `main`
1268    /// image is resampled (bilinear) into the new size instead of starting from black, so the picture does not
1269    /// restart when a window is dragged. Off by default (MilkDrop 2 and projectM clear everything).
1270    pub fn set_keep_feedback_on_resize(&mut self, keep: bool) {
1271        self.keep_feedback_on_resize = keep;
1272    }
1273
1274    /// Whether the feedback image survives a resize ([`Renderer::set_keep_feedback_on_resize`]).
1275    pub fn keep_feedback_on_resize(&self) -> bool {
1276        self.keep_feedback_on_resize
1277    }
1278
1279    /// Keep a copy of the image right after the warp pass so [`Stage::Warped`] can be read back. Off by default
1280    /// (the copy costs a full-image GPU copy every frame) and on with the `diagnostics` feature. While off,
1281    /// `read_stage(Stage::Warped)` fails with [`RenderError::Invalid`]; the other stages are unaffected. Takes effect
1282    /// on the next frame.
1283    pub fn set_capture_warped(&mut self, capture: bool) {
1284        self.capture_warped = capture;
1285    }
1286
1287    /// Whether the warped stage is captured ([`Renderer::set_capture_warped`]).
1288    pub fn capture_warped(&self) -> bool {
1289        self.capture_warped
1290    }
1291
1292    /// Limit how fast every colour channel of every pixel of the picture `render_frame` blits can change
1293    /// (photosensitivity): `Some(max_change_per_second)` in units of the full 0..1 range, `None` (the default) off.
1294    /// The rate uses `FrameInput::time` differences, so it does not depend on the frame rate: a channel flashing at
1295    /// `f` Hz swings by at most `limit / (2 f)` (0.6 keeps flashes of 3 Hz or more within 10 % of the range);
1296    /// slow changes pass unchanged. The picture fades in from black when the limit is switched on or the size changes.
1297    /// This reduces the risk of a reaction; it is no guarantee.
1298    ///
1299    /// Only `render_frame`'s blit is limited: not `render_frame_to_output` / [`Renderer::output_view`] (hosts that
1300    /// blend presets limit their blend with a [`FlashLimiter`]) and not sprites drawn onto the target afterwards.
1301    /// Off, the pass, its images and its pipeline do not exist. Changing the limit while on keeps the shown frame.
1302    ///
1303    /// Fails with [`RenderError::Invalid`] for a limit that is not a positive finite number, or when the images
1304    /// cannot be allocated.
1305    pub fn set_flash_limit(&mut self, limit: Option<f32>) -> Result<(), RenderError> {
1306        match limit {
1307            None => self.flash = None,
1308            Some(l) if !(l.is_finite() && l > 0.0) => {
1309                return Err(RenderError::Invalid(format!(
1310                    "flash limit must be a positive finite number, got {l}"
1311                )));
1312            }
1313            Some(l) => match &mut self.flash {
1314                Some(f) => f.limit = l,
1315                None => {
1316                    self.flash = Some(FlashState {
1317                        limit: l,
1318                        limiter: FlashLimiter::new(&self.device, self.cfg.width, self.cfg.height)?,
1319                        last_time: None,
1320                    });
1321                }
1322            },
1323        }
1324        *self.blit_bg.borrow_mut() = Default::default();
1325        Ok(())
1326    }
1327
1328    /// The flash limit in effect ([`Renderer::set_flash_limit`]).
1329    pub fn flash_limit(&self) -> Option<f32> {
1330        self.flash.as_ref().map(|f| f.limit)
1331    }
1332
1333    /// Reallocate every size-dependent image for an output size and render scale, keeping the feedback image if
1334    /// asked to. Nothing changes if the sizes are refused.
1335    fn reallocate(&mut self, out: (u32, u32), scale: f32) -> Result<(), RenderError> {
1336        check_size(&self.device, out.0, out.1)?;
1337        let (width, height) = scaled_size(out, scale);
1338        check_size(&self.device, width, height)?;
1339        let new_flash = match &self.flash {
1340            Some(_) => Some(FlashLimiter::new(&self.device, width, height)?),
1341            None => None,
1342        };
1343        let geom = MeshGeometry::new(self.cfg.mesh[0], self.cfg.mesh[1], width, height)?;
1344
1345        self.geom = geom;
1346        self.cfg.width = width;
1347        self.cfg.height = height;
1348        self.out_size = out;
1349        self.render_scale = scale;
1350        let d = &self.device;
1351        let old_main = std::mem::replace(
1352            &mut self.main,
1353            [
1354                create_target(d, width, height, "main0"),
1355                create_target(d, width, height, "main1"),
1356            ],
1357        );
1358        self.warped = create_target(d, width, height, "warped");
1359        self.warp_sink = create_sink(d, width, height);
1360        self.final_tex = create_target(d, width, height, "final");
1361        *self.blit_bg.borrow_mut() = Default::default();
1362        self.blur_bg.borrow_mut().clear();
1363        self.blur = blur::blur_tex_sizes(width, height)
1364            .iter()
1365            .enumerate()
1366            .map(|(i, &(bw, bh))| create_target(d, bw, bh, &format!("blur{i}")))
1367            .collect();
1368        if let (Some(f), Some(l)) = (&mut self.flash, new_flash) {
1369            f.limiter = l;
1370            f.last_time = None;
1371        }
1372        let old_idx = self.main_idx;
1373        self.main_idx = 0;
1374        self.forget_prev_warp();
1375        self.mv_state.reset();
1376        self.frames_since_resize = 0;
1377        self.clear_all();
1378        if self.keep_feedback_on_resize {
1379            self.resample_main(&old_main[old_idx]);
1380        }
1381        Ok(())
1382    }
1383
1384    /// Change the warp-mesh resolution (cells per axis; the caller applies projectM's clamping, see
1385    /// `lactea::Engine::set_mesh_size`). The previous frame's warp grid and the motion-vector state
1386    /// belong to the old mesh and are forgotten; the images are kept.
1387    pub fn set_mesh_size(&mut self, mesh: [u32; 2]) -> Result<(), RenderError> {
1388        if self.cfg.mesh == mesh {
1389            return Ok(());
1390        }
1391        self.geom = MeshGeometry::new(mesh[0], mesh[1], self.cfg.width, self.cfg.height)?;
1392        self.cfg.mesh = mesh;
1393        self.warp_indices = warp_index_buffer(&self.device, &self.geom, &self.rules);
1394        self.forget_prev_warp();
1395        self.mv_state.reset();
1396        Ok(())
1397    }
1398
1399    /// Change the sub-texel offset added to warp UVs (`projectm_set_texel_offset`); takes effect on
1400    /// the next frame.
1401    pub fn set_texel_offset(&mut self, offset: [f32; 2]) {
1402        self.cfg.texel_offset = offset;
1403    }
1404
1405    /// Start a preset from a black frame (projectM `start_clean`): clears every image and
1406    /// forgets the previous frame's warp grid; drops all user textures (the next preset
1407    /// registers its own). Noise textures are kept.
1408    pub fn reset_images(&mut self) {
1409        self.main_idx = 0;
1410        self.forget_prev_warp();
1411        self.mv_state.reset();
1412        self.main_wave_tail = Default::default();
1413        self.frames_since_resize = 0;
1414        self.user_tex.clear();
1415        self.sprite_images.clear();
1416        self.old_shaders = None;
1417        self.clear_all();
1418    }
1419
1420    fn clear_all(&self) {
1421        let mut enc = self
1422            .device
1423            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
1424                label: Some("clear"),
1425            });
1426        let mut all: Vec<&Tex> = vec![&self.main[0], &self.main[1], &self.warped, &self.final_tex];
1427        all.extend(self.blur.iter());
1428        for t in all {
1429            let _ = enc.begin_render_pass(&wgpu::RenderPassDescriptor {
1430                label: Some("clear"),
1431                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
1432                    view: &t.view,
1433                    depth_slice: None,
1434                    resolve_target: None,
1435                    ops: wgpu::Operations {
1436                        load: wgpu::LoadOp::Clear(wgpu::Color {
1437                            r: 0.0,
1438                            g: 0.0,
1439                            b: 0.0,
1440                            a: if self.rules.main_alpha { 0.0 } else { 1.0 },
1441                        }),
1442                        store: wgpu::StoreOp::Store,
1443                    },
1444                })],
1445                ..Default::default()
1446            });
1447        }
1448        self.queue.submit(Some(enc.finish()));
1449    }
1450
1451    // ---- shaders ----------------------------------------------------------------------
1452
1453    /// Install (or remove, `None` = MD2 `WarpedBlit_NoShaders`) the warp shader.
1454    pub fn set_warp_shader(&mut self, shader: Option<CompiledShader>) -> Result<(), RenderError> {
1455        self.warp_shader = match shader {
1456            Some(s) => Some(self.build_shader_pass(&s, "warp")?),
1457            None => None,
1458        };
1459        Ok(())
1460    }
1461
1462    /// Install (or remove, `None` = MD2 `ShowToUser_NoShaders`) the composite shader.
1463    pub fn set_comp_shader(&mut self, shader: Option<CompiledShader>) -> Result<(), RenderError> {
1464        self.comp_shader = match shader {
1465            Some(s) => Some(self.build_shader_pass(&s, "comp")?),
1466            None => None,
1467        };
1468        Ok(())
1469    }
1470
1471    /// Detach the installed warp / composite shaders and the user textures (MD2's `m_shaders`), leaving the renderer
1472    /// without any. The engine uses this to build the next preset's shaders next to the running ones during a preset
1473    /// blend ([`Renderer::set_old_shader_state`]) and to put the old ones back when that load fails.
1474    pub fn take_shader_state(&mut self) -> ShaderState {
1475        ShaderState(ShaderSet {
1476            warp: self.warp_shader.take(),
1477            comp: self.comp_shader.take(),
1478            user_tex: std::mem::take(&mut self.user_tex),
1479        })
1480    }
1481
1482    /// Reinstall a state taken with [`Renderer::take_shader_state`] (replacing whatever is installed).
1483    pub fn restore_shader_state(&mut self, state: ShaderState) {
1484        let ShaderSet {
1485            warp,
1486            comp,
1487            user_tex,
1488        } = state.0;
1489        self.warp_shader = warp;
1490        self.comp_shader = comp;
1491        self.user_tex = user_tex;
1492    }
1493
1494    /// MD2's `m_OldShaders`: keep `state` (the outgoing preset's shaders and textures) alive for the old half of a
1495    /// preset blend; `None` releases them (`m_OldShaders.*.Clear()` when the blend ends).
1496    pub fn set_old_shader_state(&mut self, state: Option<ShaderState>) {
1497        self.old_shaders = state.map(|s| s.0);
1498    }
1499
1500    /// Whether old shaders are being kept for a preset blend.
1501    pub fn has_old_shaders(&self) -> bool {
1502        self.old_shaders.is_some()
1503    }
1504
1505    /// `(warp, composite)`: whether the installed shaders are user / default pixel shaders (`m_nWarpPSVersion > 0`
1506    /// style flags of the *new* preset and of the old one, if one is kept).
1507    pub fn shader_flags(&self) -> ((bool, bool), (bool, bool)) {
1508        let old = self
1509            .old_shaders
1510            .as_ref()
1511            .map_or((false, false), |o| (o.warp.is_some(), o.comp.is_some()));
1512        (
1513            (self.warp_shader.is_some(), self.comp_shader.is_some()),
1514            old,
1515        )
1516    }
1517
1518    fn build_shader_pass(
1519        &self,
1520        s: &CompiledShader,
1521        label: &str,
1522    ) -> Result<ShaderPass, RenderError> {
1523        if s.interface.textures.len() > lactea_abi::MAX_PASS_TEXTURES {
1524            return Err(RenderError::Invalid(format!(
1525                "{} textures > {}",
1526                s.interface.textures.len(),
1527                lactea_abi::MAX_PASS_TEXTURES
1528            )));
1529        }
1530        let device = &self.device;
1531        // group(1) layout from the interface
1532        // the fold functions read `pu` in the vertex stage
1533        let pass_ubo_stages = if s.folds.is_empty() {
1534            wgpu::ShaderStages::FRAGMENT
1535        } else {
1536            wgpu::ShaderStages::VERTEX_FRAGMENT
1537        };
1538        let mut entries = vec![ubo_entry(
1539            lactea_abi::BINDING_PASS_UNIFORMS,
1540            pass_ubo_stages,
1541        )];
1542        for (i, t) in s.interface.textures.iter().enumerate() {
1543            let dim = match t.dim {
1544                TexDim::D2 => wgpu::TextureViewDimension::D2,
1545                TexDim::D3 => wgpu::TextureViewDimension::D3,
1546            };
1547            // R32Float is not filterable: the translated shader only `textureLoad`s the FFT and BeatDrop's wave
1548            // textures (the sampler entry stays `Filtering` and is never paired with it in a `textureSample`)
1549            let filterable =
1550                !matches!(t.source, TexSource::Fft) && self.engine_wave(&t.source).is_none();
1551            entries.push(tex_entry(
1552                lactea_abi::texture_binding(i as u32),
1553                dim,
1554                filterable,
1555            ));
1556            entries.push(samp_entry(lactea_abi::sampler_binding(i as u32)));
1557        }
1558
1559        #[cfg(not(target_arch = "wasm32"))]
1560        let scope = device.push_error_scope(wgpu::ErrorFilter::Validation);
1561        let pass_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
1562            label: Some(label),
1563            entries: &entries,
1564        });
1565        // projectM's user warp shader also writes the interpolated warp UV to a second attachment (`texCoords`,
1566        // read back by the motion-vector pass). That second use of `uv` keeps Mesa's NIR from folding constants
1567        // into the varying's plane equation (`uv - 0.5` becomes `plane(uv) - 0.5` instead of the folded
1568        // `plane(uv - 0.5)`, which rounds differently); projectM's driver compiles the shader unfolded, so ours must too.
1569        let (wgsl, uv_sink) = match (label == "warp").then(|| with_uv_output(&s.wgsl)).flatten() {
1570            Some(w) => (w, true),
1571            None => (s.wgsl.clone(), false), // not a recognisable entry: let the shader validation report it
1572        };
1573        let fs = device.create_shader_module(wgpu::ShaderModuleDescriptor {
1574            label: Some(label),
1575            source: wgpu::ShaderSource::Wgsl(wgsl.as_str().into()),
1576        });
1577        let fold_vs = (!s.folds.is_empty()).then(|| {
1578            device.create_shader_module(wgpu::ShaderModuleDescriptor {
1579                label: Some(label),
1580                source: wgpu::ShaderSource::Wgsl(shaders::mesh_vs_folds(&s.folds).into()),
1581            })
1582        });
1583        let mesh_vs = fold_vs.as_ref().unwrap_or(&self.pipes.mesh_vs);
1584        let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
1585            label: Some(label),
1586            bind_group_layouts: &[Some(&self.pipes.bgl_mu), Some(&pass_bgl)],
1587            immediate_size: 0,
1588        });
1589        let make_pipeline = |layout: &wgpu::PipelineLayout,
1590                             vs: &wgpu::ShaderModule,
1591                             buffers: &[Option<wgpu::VertexBufferLayout>],
1592                             blend: Option<wgpu::BlendState>| {
1593            let color = Some(wgpu::ColorTargetState {
1594                format: INTERNAL_FORMAT,
1595                blend,
1596                write_mask: wgpu::ColorWrites::COLOR,
1597            });
1598            let sink = Some(wgpu::ColorTargetState {
1599                format: WARP_SINK_FORMAT,
1600                blend: None,
1601                write_mask: wgpu::ColorWrites::ALL,
1602            });
1603            device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
1604                label: Some(label),
1605                layout: Some(layout),
1606                vertex: wgpu::VertexState {
1607                    module: vs,
1608                    entry_point: Some("vs_main"),
1609                    compilation_options: Default::default(),
1610                    buffers,
1611                },
1612                primitive: wgpu::PrimitiveState::default(),
1613                depth_stencil: None,
1614                multisample: wgpu::MultisampleState::default(),
1615                fragment: Some(wgpu::FragmentState {
1616                    module: &fs,
1617                    entry_point: Some(FRAGMENT_ENTRY),
1618                    compilation_options: Default::default(),
1619                    targets: &[color, sink][..if uv_sink { 2 } else { 1 }],
1620                }),
1621                multiview_mask: None,
1622                cache: None,
1623            })
1624        };
1625        let pipeline = make_pipeline(&layout, mesh_vs, &[Some(mesh_layout())], None);
1626        // MD2's preset blend draws the second pass of a shader pair alpha-blended over the first
1627        let alpha_pipelines = self.rules.md2_preset_blend.then(|| {
1628            [Blend::SrcAlpha, Blend::InvSrcAlpha]
1629                .map(|b| make_pipeline(&layout, mesh_vs, &[Some(mesh_layout())], blend_state(b)))
1630        });
1631        let warp_pipeline = if label == "warp" {
1632            let warp_vs_sm = device.create_shader_module(wgpu::ShaderModuleDescriptor {
1633                label: Some("warp_vs"),
1634                source: wgpu::ShaderSource::Wgsl(
1635                    if s.folds.is_empty() {
1636                        shaders::warp_vs(2)
1637                    } else {
1638                        shaders::warp_vs_folds(2, &s.folds)
1639                    }
1640                    .into(),
1641                ),
1642            });
1643            let warp_layout_pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
1644                label: Some("warp gpu"),
1645                bind_group_layouts: &[
1646                    Some(&self.pipes.bgl_mu),
1647                    Some(&pass_bgl),
1648                    Some(&self.pipes.bgl_warp_vs),
1649                ],
1650                immediate_size: 0,
1651            });
1652            Some(make_pipeline(
1653                &warp_layout_pl,
1654                &warp_vs_sm,
1655                &[Some(warp_layout())],
1656                None,
1657            ))
1658        } else {
1659            None
1660        };
1661        #[cfg(not(target_arch = "wasm32"))]
1662        if let Some(err) = pollster::block_on(scope.pop()) {
1663            return Err(RenderError::Shader(err.to_string()));
1664        }
1665        Ok(ShaderPass {
1666            pipeline,
1667            warp_pipeline,
1668            pass_bgl,
1669            interface: s.interface.clone(),
1670            uv_sink,
1671            alpha_pipelines,
1672        })
1673    }
1674
1675    // ---- textures ---------------------------------------------------------------------
1676
1677    /// Register a user texture (`sampler_<name>`): RGBA8, row 0 = top, with a CPU mip chain.
1678    /// `name` is matched case-insensitively against `TexSource::User`.
1679    pub fn set_user_texture(
1680        &mut self,
1681        name: &str,
1682        w: u32,
1683        h: u32,
1684        rgba8: &[u8],
1685    ) -> Result<(), RenderError> {
1686        check_frames(
1687            &format!("user texture {name}"),
1688            self.device.limits().max_texture_dimension_2d,
1689            w,
1690            h,
1691            &[rgba8],
1692        )?;
1693        let tex = upload_2d(&self.device, &self.queue, w, h, rgba8, true, name);
1694        self.user_tex
1695            .insert(name.to_ascii_lowercase(), UserTex { tex, anim: None });
1696        Ok(())
1697    }
1698
1699    /// Register an animated user texture (an animated GIF as `sampler_<name>`, `Compat::MilkDrop3`): `frames` are
1700    /// `w * h * 4` RGBA8 images (row 0 = top), `delays` their durations in seconds. Every draw shows the frame
1701    /// [`gif_frame_index`](crate::gif_frame_index) picks for the time of the frame being rendered. No mip chain.
1702    pub fn set_user_animation(
1703        &mut self,
1704        name: &str,
1705        w: u32,
1706        h: u32,
1707        frames: &[&[u8]],
1708        delays: &[f64],
1709    ) -> Result<(), RenderError> {
1710        check_frames(
1711            name,
1712            self.device.limits().max_texture_dimension_2d,
1713            w,
1714            h,
1715            frames,
1716        )?;
1717        if delays.len() != frames.len() {
1718            return Err(RenderError::Invalid(format!(
1719                "animated texture {name}: {} frames but {} delays",
1720                frames.len(),
1721                delays.len()
1722            )));
1723        }
1724        let tex: Vec<Tex> = frames
1725            .iter()
1726            .map(|f| upload_2d(&self.device, &self.queue, w, h, f, false, name))
1727            .collect();
1728        self.user_tex.insert(
1729            name.to_ascii_lowercase(),
1730            UserTex {
1731                tex: tex[0].clone(),
1732                anim: Some(UserAnim {
1733                    frames: tex,
1734                    delays: delays.to_vec(),
1735                }),
1736            },
1737        );
1738        Ok(())
1739    }
1740
1741    /// Register the image of an MD3 sprite under `id` ([`SpriteDraw::image`](crate::SpriteDraw::image)), replacing
1742    /// any image with that id. `frames` are `w * h * 4` RGBA8 images (row 0 = top, straight alpha, colour key already
1743    /// applied); a static image has one frame and `mips` (full chain, trilinear sampling), a GIF has no mips.
1744    pub fn set_sprite_image(
1745        &mut self,
1746        id: u32,
1747        w: u32,
1748        h: u32,
1749        frames: &[&[u8]],
1750        mips: bool,
1751    ) -> Result<(), RenderError> {
1752        check_frames(
1753            "sprite",
1754            self.device.limits().max_texture_dimension_2d,
1755            w,
1756            h,
1757            frames,
1758        )?;
1759        // a sprite is about to be drawn: build the pipelines now, not as a hitch in the first frame that draws one
1760        self.pipes.sprites(&self.device);
1761        let views = frames
1762            .iter()
1763            .map(|f| upload_2d(&self.device, &self.queue, w, h, f, mips, "sprite").view)
1764            .collect();
1765        self.sprite_images.insert(id, SpriteImage { frames: views });
1766        Ok(())
1767    }
1768
1769    /// Forget every sprite image.
1770    pub fn clear_sprite_images(&mut self) {
1771        self.sprite_images.clear();
1772    }
1773
1774    /// Forget every user texture (`set_user_texture` / `set_user_animation`); shaders sampling one see the
1775    /// placeholder until it is registered again.
1776    pub fn clear_user_textures(&mut self) {
1777        self.user_tex.clear();
1778    }
1779
1780    /// Whether an image is registered under `id`.
1781    pub fn has_sprite_image(&self, id: u32) -> bool {
1782        self.sprite_images.contains_key(&id)
1783    }
1784
1785    /// Forget the image registered under `id`, if any.
1786    pub fn remove_sprite_image(&mut self, id: u32) {
1787        self.sprite_images.remove(&id);
1788    }
1789    /// Draw sprites (any layer value) onto `target`, an `Rgba8Unorm` view: the sprite pass on its own, for hosts
1790    /// that composite themselves and for tests. Draws whose image or frame is not registered are skipped.
1791    pub fn draw_sprites(
1792        &self,
1793        encoder: &mut wgpu::CommandEncoder,
1794        target: &wgpu::TextureView,
1795        draws: &[SpriteDraw],
1796    ) {
1797        let refs: Vec<&SpriteDraw> = draws.iter().collect();
1798        self.sprite_pass(encoder, target, &refs);
1799    }
1800
1801    /// Draw `draws` into the image the next frame's warp reads (projectM's `burn`), the ones with `burn` set only:
1802    /// call after [`Renderer::render_frame_to_output`], when that image is the one just produced.
1803    pub fn burn_sprites(&self, encoder: &mut wgpu::CommandEncoder, draws: &[SpriteDraw]) {
1804        let burn: Vec<&SpriteDraw> = draws.iter().filter(|d| d.burn).collect();
1805        if !burn.is_empty() {
1806            self.sprite_pass(encoder, &self.main[self.main_idx].view, &burn);
1807        }
1808    }
1809
1810    /// Draw `draws` onto `target`, a view of the host's output (`RenderConfig::output_format`), loaded not cleared:
1811    /// sprites over a finished frame, e.g. over a soft cut's blend.
1812    pub fn draw_sprites_to_output(
1813        &self,
1814        encoder: &mut wgpu::CommandEncoder,
1815        target: &wgpu::TextureView,
1816        draws: &[SpriteDraw],
1817    ) {
1818        let refs: Vec<&SpriteDraw> = draws.iter().collect();
1819        self.pipes
1820            .sprites_for(&self.device, self.cfg.output_format)
1821            .draw(
1822                &self.device,
1823                encoder,
1824                target,
1825                &self.pipes.bgl_tex,
1826                self.pipes.sampler(Filter::Linear, Address::Wrap, false),
1827                &self.sprite_images,
1828                &refs,
1829            );
1830    }
1831
1832    /// Read a stage back as `(width, height, RGBA8)` (row 0 = top). The command buffers of the
1833    /// frame must have been submitted. `Stage::Main` is the image the next frame's warp samples;
1834    /// `Warped` the image right after the warp pass; `Blur1..3` the user-visible blur levels
1835    /// (blur textures 1, 3, 5); `Final` the composite output.
1836    pub fn read_stage(&self, stage: Stage) -> Result<(u32, u32, Vec<u8>), RenderError> {
1837        let t = match stage {
1838            Stage::Final => &self.final_tex,
1839            Stage::Main => &self.main[self.main_idx],
1840            Stage::Warped if !self.capture_warped => {
1841                return Err(RenderError::Invalid(
1842                    "the warped stage is not captured: call set_capture_warped(true) before the frame".to_owned(),
1843                ));
1844            }
1845            Stage::Warped => &self.warped,
1846            Stage::Blur1 => &self.blur[1],
1847            Stage::Blur2 => &self.blur[3],
1848            Stage::Blur3 => &self.blur[5],
1849        };
1850        self.read_texture(t)
1851    }
1852
1853    fn read_texture(&self, t: &Tex) -> Result<(u32, u32, Vec<u8>), RenderError> {
1854        let data = readback_rgba8(&self.device, &self.queue, &t.texture, t.w, t.h)?;
1855        Ok((t.w, t.h, data))
1856    }
1857
1858    // ---- rendering --------------------------------------------------------------------
1859
1860    /// Blur levels forced on by a diagnostic request (0 without the `diagnostics` feature).
1861    fn diagnostic_blur_levels(&self) -> u8 {
1862        #[cfg(feature = "diagnostics")]
1863        {
1864            self.min_blur_levels.min(3)
1865        }
1866        #[cfg(not(feature = "diagnostics"))]
1867        {
1868            0
1869        }
1870    }
1871
1872    /// The image a composite pass reads as its `sampler_main`: `regular`, or the injected one.
1873    fn comp_source_view<'a>(&'a self, regular: &'a wgpu::TextureView) -> &'a wgpu::TextureView {
1874        #[cfg(feature = "diagnostics")]
1875        if let Some(t) = &self.comp_source_override {
1876            return &t.view;
1877        }
1878        regular
1879    }
1880
1881    /// Highest blur level (0..=3) the installed shaders require (including the old preset's while a preset blend
1882    /// keeps them: MD2's `ApplyShaderParams` counts every pass it applies, also `m_OldShaders`).
1883    pub fn blur_levels_required(&self) -> u8 {
1884        let level = |p: &Option<ShaderPass>| p.as_ref().map_or(0, |s| s.interface.max_blur_level);
1885        let mut m = level(&self.warp_shader).max(level(&self.comp_shader));
1886        if let Some(o) = &self.old_shaders {
1887            m = m.max(level(&o.warp)).max(level(&o.comp));
1888        }
1889        m.min(3)
1890    }
1891
1892    /// Forget the previous frame's warp grid, vertex inputs and their pending UV readback.
1893    fn forget_prev_warp(&mut self) {
1894        self.prev_warp_uv = None;
1895        self.prev_warp_gpu = None;
1896        if let Some(rb) = &mut self.uv_readback {
1897            rb.pending = None;
1898        }
1899    }
1900
1901    /// Submit the UV readback of `prev_warp_gpu` (the vertex inputs of the frame just recorded), or drop the pending
1902    /// one if there are none.
1903    fn submit_uv_readback(&mut self) {
1904        let Some(wg) = self.prev_warp_gpu.as_ref() else {
1905            if let Some(rb) = &mut self.uv_readback {
1906                rb.pending = None;
1907            }
1908            return;
1909        };
1910        let (w, h) = (self.geom.gx + 1, self.geom.gy + 1);
1911        let verts = geom::build_warp_gpu_vertices(&self.geom, &wg.vars);
1912        let toff = self.texel_offset_uv();
1913        let mut vu = self.warp_vs_uniforms(wg, toff, 1.0);
1914        vu.diffuse = [w as f32, h as f32, 0.0, 0.0];
1915        if !matches!(&self.uv_readback, Some(rb) if rb.w == w && rb.h == h) {
1916            self.uv_readback = Some(UvReadback::new(&self.device, &self.pipes, w, h));
1917        }
1918        if let Some(rb) = &mut self.uv_readback {
1919            rb.submit(&self.device, &self.queue, &self.pipes, &verts, &vu, toff);
1920        }
1921    }
1922
1923    /// The GPU's own per-vertex warp UVs of `prev_warp_gpu` (`warp_vs` evaluated on the device, lactea mesh index
1924    /// order). projectM's motion vector lookup reads the interpolation of *these* (`RG16F` UV map written by the warp
1925    /// pass), so the CPU port of the formula (`warp_mesh`) differs from it by the GPU's `pow` / `sin` / `cos`
1926    /// approximations and fusion.
1927    ///
1928    /// Normally the readback was submitted at the end of the previous frame ([`Renderer::submit_uv_readback`]); it
1929    /// is only recorded here (and waited for) when that frame did not draw motion vectors or the texel offset
1930    /// changed since.
1931    fn gpu_warp_vertex_uv(&mut self) -> Result<Vec<[f32; 2]>, RenderError> {
1932        let toff = self.texel_offset_uv();
1933        let submitted = self
1934            .uv_readback
1935            .as_ref()
1936            .and_then(|rb| rb.pending.as_ref())
1937            .is_some_and(|(_, t)| *t == toff);
1938        if !submitted {
1939            self.submit_uv_readback();
1940        }
1941        let Some(rb) = self.uv_readback.as_mut() else {
1942            return Err(RenderError::Readback(
1943                "no previous warp vertex inputs".to_owned(),
1944            ));
1945        };
1946        let uv = rb.collect(&self.device, &self.geom);
1947        if uv.is_err() {
1948            self.uv_readback = None;
1949        }
1950        uv
1951    }
1952
1953    fn texel_offset_uv(&self) -> [f32; 2] {
1954        warp_mesh::texel_offset_uv(self.cfg.texel_offset, self.cfg.width, self.cfg.height)
1955    }
1956
1957    /// Default warp UVs when the engine supplies none: identity motion.
1958    fn default_warp_uv(&self, f: &FrameInput) -> Vec<[f32; 2]> {
1959        let anim = WarpAnim::new(f.time as f32, 1.0, 1.0);
1960        let v = VertexVars {
1961            warp: 0.0,
1962            ..Default::default()
1963        };
1964        warp_mesh::warp_mesh_uniform(&self.geom, &v, &anim, self.texel_offset_uv())
1965    }
1966
1967    /// The CPU warp UV grid of `wg` (`warp_mesh`, as the engine computes it for a renderer without a GPU warp stage):
1968    /// the fallback of a motion vector lookup whose GPU readback failed.
1969    fn cpu_warp_uv(&self, wg: &crate::frame::WarpGpu) -> Vec<[f32; 2]> {
1970        let toff = self.texel_offset_uv();
1971        wg.vars
1972            .iter()
1973            .enumerate()
1974            .map(|(n, vv)| warp_mesh::warp_vertex_uv(&self.geom, n, vv, &wg.anim, toff))
1975            .collect()
1976    }
1977
1978    /// Record one frame into `encoder`, ending with the composite blitted to `target`.
1979    ///
1980    /// All per-frame GPU data is baked into buffers at record time, so frames may be recorded in
1981    /// any order, but the encoder must be submitted before [`Renderer::read_stage`] is called.
1982    /// `target` must be a view of an [`Renderer::output_size`] texture of `cfg.output_format` (the internal image is
1983    /// upsampled to it when the render scale is not 1).
1984    ///
1985    /// Fails with [`RenderError::Invalid`] (recording nothing) if `input.warp_uv` does not match the mesh or
1986    /// `input.md2_blend` is set without `Compat::MilkDrop2` / `Compat::MilkDrop3` or its `vert_alpha` does not match
1987    /// the mesh.
1988    pub fn render_frame(
1989        &mut self,
1990        encoder: &mut wgpu::CommandEncoder,
1991        input: &FrameInput,
1992        target: &wgpu::TextureView,
1993    ) -> Result<(), RenderError> {
1994        self.render_frame_inner(encoder, input, Some(target))
1995    }
1996
1997    /// Like [`Renderer::render_frame`] but stops after the composite: the finished image stays in
1998    /// the renderer ([`Renderer::output_view`]) and nothing is written to a host target. Used for
1999    /// presets that are blended into the frame by a transition.
2000    pub fn render_frame_to_output(
2001        &mut self,
2002        encoder: &mut wgpu::CommandEncoder,
2003        input: &FrameInput,
2004    ) -> Result<(), RenderError> {
2005        self.render_frame_inner(encoder, input, None)
2006    }
2007
2008    /// The composited image of the last rendered frame (`Rgba8Unorm`, row 0 = top, the `final`
2009    /// stage): projectM's `Preset::OutputTexture()`.
2010    pub fn output_view(&self) -> &wgpu::TextureView {
2011        &self.final_tex.view
2012    }
2013
2014    /// Start this preset from `src`'s composited image instead of black (projectM
2015    /// `DrawInitialImage`, used when `start_clean` is off): the image the first warp samples.
2016    /// `src` must have the same size. Call after [`Renderer::reset_images`].
2017    ///
2018    /// Fails with [`RenderError::Invalid`] if the two renderers differ in size.
2019    pub fn draw_initial_image(
2020        &mut self,
2021        encoder: &mut wgpu::CommandEncoder,
2022        src: &Renderer,
2023    ) -> Result<(), RenderError> {
2024        if (self.cfg.width, self.cfg.height) != (src.cfg.width, src.cfg.height) {
2025            return Err(RenderError::Invalid(format!(
2026                "initial image size mismatch: {}x{} vs {}x{}",
2027                self.cfg.width, self.cfg.height, src.cfg.width, src.cfg.height
2028            )));
2029        }
2030        self.main_idx = 0;
2031        encoder.copy_texture_to_texture(
2032            wgpu::TexelCopyTextureInfo {
2033                texture: &src.final_tex.texture,
2034                mip_level: 0,
2035                origin: wgpu::Origin3d::ZERO,
2036                aspect: wgpu::TextureAspect::All,
2037            },
2038            wgpu::TexelCopyTextureInfo {
2039                texture: &self.main[0].texture,
2040                mip_level: 0,
2041                origin: wgpu::Origin3d::ZERO,
2042                aspect: wgpu::TextureAspect::All,
2043            },
2044            wgpu::Extent3d {
2045                width: self.cfg.width,
2046                height: self.cfg.height,
2047                depth_or_array_layers: 1,
2048            },
2049        );
2050        Ok(())
2051    }
2052
2053    /// Reject frame inputs the renderer cannot draw, before anything is recorded.
2054    fn check_input(&self, input: &FrameInput) -> Result<(), RenderError> {
2055        if let Some(u) = &input.warp_uv {
2056            let n = self.geom.vertex_count();
2057            if u.len() != n {
2058                return Err(RenderError::Invalid(format!(
2059                    "FrameInput.warp_uv has {} entries, the {}x{} mesh needs {n}",
2060                    u.len(),
2061                    self.geom.gx,
2062                    self.geom.gy
2063                )));
2064            }
2065        }
2066        if self.rules.warp_uv_on_gpu
2067            && let Some(wg) = &input.warp_gpu
2068            && wg.vars.len() != self.geom.vertex_count()
2069        {
2070            return Err(RenderError::Invalid(format!(
2071                "FrameInput.warp_gpu has {} vertices, the {}x{} mesh needs {}",
2072                wg.vars.len(),
2073                self.geom.gx,
2074                self.geom.gy,
2075                self.geom.vertex_count()
2076            )));
2077        }
2078        if input.md2_blend.is_some() && !self.rules.md2_preset_blend {
2079            return Err(RenderError::Invalid(
2080                "FrameInput.md2_blend needs Compat::MilkDrop2 or Compat::MilkDrop3".to_owned(),
2081            ));
2082        }
2083        if let Some(bl) = &input.md2_blend
2084            && bl.vert_alpha.len() != self.geom.vertex_count()
2085        {
2086            return Err(RenderError::Invalid(format!(
2087                "FrameInput.md2_blend.vert_alpha has {} entries, the {}x{} mesh needs {}",
2088                bl.vert_alpha.len(),
2089                self.geom.gx,
2090                self.geom.gy,
2091                self.geom.vertex_count()
2092            )));
2093        }
2094        Ok(())
2095    }
2096
2097    // ---- fixed-function content ---------------------------------------------------------
2098}
2099
2100const BLACK: wgpu::Color = wgpu::Color {
2101    r: 0.0,
2102    g: 0.0,
2103    b: 0.0,
2104    a: 1.0,
2105};
2106
2107/// Per-frame working buffers of the overlay / motion-vector builders, kept across frames so a frame
2108/// allocates nothing once they are warm. Contents are overwritten by every user.
2109#[derive(Default)]
2110struct FrameScratch {
2111    pm_wave: wavegen::PmWaveScratch,
2112    /// custom-wave source points / colours
2113    pts: Vec<[f32; 2]>,
2114    cols: Vec<[f32; 4]>,
2115    /// smoothed points / colours
2116    sp: Vec<[f32; 2]>,
2117    sc: Vec<[f32; 4]>,
2118    /// vertices handed to a `Batch` (dots, segments, motion vectors)
2119    verts: Vec<WfVertex>,
2120    /// one strip's segments before they are appended to `verts`
2121    seg: Vec<WfVertex>,
2122}
2123
2124/// `SmoothWave` carrying per-vertex colours (`vo[j+1].Diffuse = vi[i].Diffuse`), into reusable buffers.
2125fn smooth_with_colors_into(
2126    sp: &mut Vec<[f32; 2]>,
2127    sc: &mut Vec<[f32; 4]>,
2128    pts: &[[f32; 2]],
2129    cols: &[[f32; 4]],
2130) {
2131    wavegen::smooth_wave_into(sp, pts);
2132    let n = pts.len();
2133    sc.clear();
2134    sc.reserve(sp.len());
2135    for c in &cols[..n - 1] {
2136        sc.push(*c);
2137        sc.push(*c);
2138    }
2139    sc.push(cols[n - 1]);
2140}
2141
2142#[cfg(test)]
2143mod uv_output_tests {
2144    use super::with_uv_output;
2145
2146    /// Regression (`sin((uv.x - 0.5) * 100)` gave 15 480 wrong pixels in 13 frames): the warp shader's
2147    /// fragment entry gets projectM's second `texCoords` output so `uv` has two uses, like projectM's.
2148    #[test]
2149    fn warp_entry_gets_a_second_uv_output() {
2150        let src = "fn f() {}\n@fragment\nfn fs_main(in: VsOut) -> @location(0) vec4<f32> {\n    return in.diffuse;\n}\n";
2151        let out = with_uv_output(src).unwrap();
2152        assert!(with_uv_output("this is not wgsl").is_none());
2153        assert!(out.contains("fn fs_main_color(in: VsOut) -> vec4<f32> {"));
2154        assert!(out.contains("fn fs_main(in: VsOut) -> WarpFsOut"));
2155        assert!(out.contains("o.uv = in.uv.xy;"));
2156        assert_eq!(out.matches("@fragment").count(), 1);
2157    }
2158}