Skip to main content

ssplayer_wgpu/
renderer.rs

1//! The device-scoped half of rendering.
2//!
3//! Pipelines, bind group layouts, the sampler, the white fallback, the shader
4//! modules and the atlas textures are valid for any render target on the device
5//! that made them, so the host owns one [`SSRenderer`] and lends it.
6//!
7//! The per-target, per-frame half is [`crate::SSScene`].
8
9use crate::mask::{MaskOp, StencilTest};
10use std::collections::HashMap;
11use std::hash::{BuildHasherDefault, Hasher};
12
13use ssruntime::runtime::framedata::ss::runtime::BlendType;
14
15/// The hasher behind the renderer's per-draw lookups.
16///
17/// Every draw looks up a pipeline and a texture, under keys this crate makes
18/// itself — a [`PipelineKey`], a texture key — so SipHash's defence against
19/// chosen keys buys nothing here. A multiply-rotate per word, as `rustc` hashes
20/// its own tables.
21#[derive(Default)]
22pub(crate) struct KeyHasher(u64);
23
24impl KeyHasher {
25    fn add(&mut self, word: u64) {
26        self.0 = (self.0.rotate_left(5) ^ word).wrapping_mul(0x517c_c1b7_2722_0a95);
27    }
28}
29
30impl Hasher for KeyHasher {
31    fn finish(&self) -> u64 {
32        self.0
33    }
34
35    fn write(&mut self, bytes: &[u8]) {
36        for chunk in bytes.chunks(8) {
37            let mut word = [0; 8];
38            word[..chunk.len()].copy_from_slice(chunk);
39            self.add(u64::from_le_bytes(word));
40        }
41    }
42
43    fn write_u8(&mut self, n: u8) {
44        self.add(n.into());
45    }
46
47    fn write_u16(&mut self, n: u16) {
48        self.add(n.into());
49    }
50
51    fn write_u32(&mut self, n: u32) {
52        self.add(n.into());
53    }
54
55    fn write_u64(&mut self, n: u64) {
56        self.add(n);
57    }
58
59    fn write_usize(&mut self, n: usize) {
60        self.add(n as u64);
61    }
62}
63
64/// A map hashed with [`KeyHasher`].
65type KeyMap<K, V> = HashMap<K, V, BuildHasherDefault<KeyHasher>>;
66
67/// Which vertex stage expands a draw's primitives.
68///
69/// There is no vertex buffer: the runtime's SoA arrays are copied into the
70/// scene's arena verbatim and the vertex stage reads them, with one entry point
71/// per geometry kind. They differ only in how `@builtin(vertex_index)` maps to a primitive and where
72/// that primitive's position / UV / colour come from.
73#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
74pub(crate) enum GeomClass {
75    /// Sprite quad: [`QUAD_FAN_VERTS`] vertices per primitive, indexless — a fan
76    /// of four triangles around the part's centre vertex. `vertex_index /
77    /// QUAD_FAN_VERTS` is the primitive, the remainder picks a corner or the
78    /// centre through the fixed fan pattern.
79    Quad,
80    /// Skinned mesh: irregular, so a per-vertex stream drives it — the one class
81    /// that cannot be addressed by arithmetic alone. Each entry names its
82    /// primitive relative to the draw's first, which arrives as `instance_index`.
83    Mesh,
84    /// Shape fan: a fixed [`SHAPE_FAN_VERTS`] vertices per primitive, with the
85    /// unused triangles collapsed to zero area.
86    Shape,
87    /// Effect particle: 6 vertices per primitive, one primitive per particle
88    /// quad. Its UVs arrive already normalised and its colour is per particle.
89    Effect,
90}
91
92impl GeomClass {
93    /// The WGSL vertex entry point that expands this class.
94    fn entry(self) -> &'static str {
95        match self {
96            GeomClass::Quad => "vs_quad",
97            GeomClass::Mesh => "vs_mesh",
98            GeomClass::Shape => "vs_shape",
99            GeomClass::Effect => "vs_effect",
100        }
101    }
102
103    /// The vertex entry that expands this class **into coverage space**: the same
104    /// geometry, projected by the node's bbox affine instead of the target's
105    /// projection, and stopping short of the player's placement — the bitmap is
106    /// pinned to player-local coordinates so it does not move when the player does.
107    fn coverage_entry(self) -> &'static str {
108        match self {
109            GeomClass::Quad => "vs_cov_quad",
110            GeomClass::Mesh => "vs_cov_mesh",
111            GeomClass::Shape => "vs_cov_shape",
112            // Effects never write coverage: the planner only ever hands back
113            // Quad / Mesh / Shape writers.
114            GeomClass::Effect => "vs_cov_quad",
115        }
116    }
117}
118
119/// The `const` prelude both shader modules are assembled on top of.
120///
121/// Layout facts the WGSL has to agree with the Rust on live here rather than as
122/// literals in the shader text, so a change to one cannot silently leave the
123/// other behind.
124fn wgsl_consts() -> String {
125    format!(
126        "const QUAD_FAN_VERTS: u32 = {QUAD_FAN_VERTS}u;\n\
127         const SHAPE_FAN_VERTS: u32 = {SHAPE_FAN_VERTS}u;\n\
128         const MESH_PRIM_SHIFT: u32 = {MESH_PRIM_SHIFT}u;\n\
129         const CROWD_SHIFT: u32 = {CROWD_SHIFT}u;\n\
130         const NODE_STRIDE: u32 = {}u;\n\
131         const NO_TINT: u32 = {}u;\n\
132         const COVERAGE_HEADER: u32 = {}u;\n\
133         const COVERAGE_STRIDE: u32 = {}u;\n\
134         const MAX_MASK_WRITERS: u32 = {}u;\n\
135         const COVERAGE_LAYER_BITS: u32 = {}u;\n",
136        crate::scene::NODE_STRIDE_F32,
137        crate::scene::NO_TINT,
138        crate::scene::COVERAGE_HEADER_F32,
139        crate::scene::COVERAGE_WRITER_F32,
140        crate::mask::MAX_MASK_WRITERS,
141        crate::mask::COVERAGE_LAYER_BITS,
142    )
143}
144
145/// The coverage bitmap's format. RGBA8 with one writer per bit gives 24
146/// writers, and matches what the reference implementation
147/// rasterises, so the two players encode coverage identically.
148pub(crate) const COVERAGE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;
149
150/// Vertices a sprite-quad primitive occupies: four triangles fanned around the
151/// part's centre vertex.
152///
153/// Two triangles would cut the part along one diagonal, so a deformed part would
154/// fold along it and a four-corner PartsColor would shade along it — neither is
155/// how the Editor draws.
156pub(crate) const QUAD_FAN_VERTS: u32 = 12;
157
158/// Vertices a Shape primitive always occupies, whatever its live vertex count.
159///
160/// The runtime's shape buffer holds at most 12 vertices per part, so a fan is at
161/// most 10 triangles. Reserving all 30 vertices keeps `vertex_index / 30` a valid
162/// primitive lookup — the alternative is a prefix sum and a search per vertex.
163/// Triangles past the live count collapse to a single vertex and rasterise
164/// nothing, and shapes are rare enough that the wasted invocations do not matter.
165pub(crate) const SHAPE_FAN_VERTS: u32 = 30;
166
167/// Where a mesh-stream entry's primitive starts: the bits above this name which
168/// primitive of its draw the vertex belongs to, the bits below which of that
169/// part's own vertices it is.
170///
171/// One entry per vertex, so an entry is a mesh part's own index with its tag
172/// ORed in — one copy of the runtime's triangle list, not a pair built per
173/// index. A draw names at most [`MESH_DRAW_PRIMS`] primitives, and a part may
174/// have up to 2^24 vertices.
175pub(crate) const MESH_PRIM_SHIFT: u32 = 24;
176
177/// The most primitives one mesh draw can name: the batch starts a new draw past
178/// this.
179pub(crate) const MESH_DRAW_PRIMS: u32 = 1 << (32 - MESH_PRIM_SHIFT);
180
181/// Where a draw's `instance_index` splits: the bits below say which member of a
182/// crowd is being drawn, and for a mesh the bits above name the draw's first
183/// primitive, which its stream entries count from.
184///
185/// Every other class has no primitive to carry there, so its `instance_index` is
186/// the member and nothing else. A crowd is drawn by issuing each draw once per
187/// member, which is what makes it cost one player's worth of draws however
188/// many it shows. Twelve bits give [`crate::MAX_CROWD_MEMBERS`] members, and
189/// leave a mesh draw [`MESH_FIRST_PRIMS`] primitives to start from.
190pub(crate) const CROWD_SHIFT: u32 = 12;
191
192/// The first primitive past the last a mesh draw can start at: a frame's meshes
193/// draw only from its first 2^20 primitives. Past that the draw is dropped.
194pub(crate) const MESH_FIRST_PRIMS: u32 = 1 << (32 - CROWD_SHIFT);
195
196/// What a pipeline does, before the render target is taken into account.
197#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
198pub(crate) enum PipelineKind {
199    /// Ordinary content: blend index (into [`BLEND_ORDER`]) x stencil test x the
200    /// geometry class whose vertex stage expands it.
201    Content(usize, StencilTest, GeomClass),
202    /// Mask-write geometry: the stencil op it applies, and the class. Colour
203    /// output is masked off, so blend does not vary.
204    Mask(MaskOp, GeomClass),
205    /// Content clipped by a coverage bitmap rather than by the stencil: the same
206    /// blend and class, plus the polarity the replay compares against. It needs
207    /// its own kind because it draws from a different pipeline layout — the one
208    /// with the coverage array bound at group(2).
209    ContentCoverage(usize, StencilTest, GeomClass),
210    /// Coverage-write geometry: the same shapes as
211    /// [`PipelineKind::Mask`], rasterised into the coverage bitmap instead of the
212    /// stencil. One pipeline per class — the writer's bit travels on the `Prim`,
213    /// not in the pipeline, so 24 writers still compile three pipelines between
214    /// them. Always targets [`COVERAGE_FORMAT`] and never has a depth-stencil,
215    /// so the target's own formats drop out of the key's meaning here.
216    Coverage(GeomClass),
217    /// Integration shader (`ss-*`): shader id x blend index. Never
218    /// stencil-tested — shader parts are not masked — and always
219    /// [`GeomClass::Quad`], because only Normal parts carry a SHDR attribute.
220    Shader(u32, usize),
221    /// One faded player's offscreen layer, folded back into the target at the
222    /// player's alpha. Drawn from the coverage pipeline layout, whose group(2)
223    /// is the array the layers live in.
224    Composite,
225}
226
227/// What distinguishes one render pipeline from another.
228///
229/// wgpu bakes blend, depth/stencil state **and the target's formats** into the
230/// pipeline, so every combination a frame uses needs its own object. They are
231/// built on first use and cached under this key rather than compiled up front:
232/// an animation touching one blend mode pays for one pipeline instead of the
233/// whole 12 x 3 content matrix.
234///
235/// The formats are part of the key rather than fixed at construction, which is
236/// what lets a single device-scoped [`SSRenderer`] serve render targets that do
237/// not agree on them.
238#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
239pub(crate) struct PipelineKey {
240    pub(crate) kind: PipelineKind,
241    pub(crate) color_format: wgpu::TextureFormat,
242    pub(crate) stencil_format: Option<wgpu::TextureFormat>,
243}
244
245struct TextureEntry {
246    bind_group: wgpu::BindGroup,
247    size: (f32, f32),
248    /// Kept alive alongside the bind group it feeds; also what
249    /// [`SSRenderer::texture_alpha_mode`] reports back.
250    _info_buffer: wgpu::Buffer,
251    alpha: AlphaMode,
252}
253
254/// How a texture's colour channels relate to its alpha.
255///
256/// The whole pipeline composites premultiplied, so the fragment stage has
257/// to know which form it is sampling: a premultiplied texel is divided back to
258/// straight RGB before the PartsColor maths, a straight one is used as is. The
259/// flag rides in the texture's own bind group, so it costs no extra pipeline.
260///
261/// [`SSRenderer::upload_texture`] premultiplies on the CPU and is always
262/// [`AlphaMode::Premultiplied`]; [`SSRenderer::set_texture`] takes whatever the
263/// supplier has, which for an engine's asset system is usually
264/// [`AlphaMode::Straight`].
265#[derive(Clone, Copy, Debug, PartialEq, Eq)]
266pub enum AlphaMode {
267    /// `rgb` is already multiplied by `a`. Correct under linear filtering, and
268    /// what SpriteStudio's own atlas path produces.
269    Premultiplied,
270    /// `rgb` is independent of `a` (the usual form of a decoded PNG, and what an
271    /// engine hands over unless it was told otherwise).
272    Straight,
273}
274
275/// The per-texture uniform bound at group(1) binding(2).
276///
277/// Small on purpose: it exists so [`AlphaMode`] does not become a pipeline
278/// dimension. It also carries the texel size, which is the unit the runtime's UVs
279/// arrive in — that is what lets the vertex stage normalise them
280/// instead of the CPU.
281#[repr(C)]
282#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
283struct TexInfo {
284    /// `(width, height, 1/width, 1/height)` in texels.
285    size: [f32; 4],
286    /// `x`: 1.0 when premultiplied, 0.0 when straight. `y..w` reserved.
287    flags: [f32; 4],
288}
289
290impl TexInfo {
291    fn new((width, height): (f32, f32), alpha: AlphaMode) -> Self {
292        let inv = |v: f32| if v > 0.0 { 1.0 / v } else { 0.0 };
293        Self { size: [width, height, inv(width), inv(height)], flags: [if alpha == AlphaMode::Premultiplied { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0] }
294    }
295}
296
297/// Everything whose useful lifetime is the **device**, not one player and not
298/// one render target.
299///
300/// Pipelines, bind group layouts, the sampler, the white fallback and the atlas
301/// textures are all valid for any target on the device that created them, so
302/// exactly one of these serves every [`crate::SSScene`] and every
303/// [`crate::SSPlayer`] drawing on that device. The host owns it and lends it,
304/// the same way it lends `Device` and `Queue`.
305///
306/// Nothing here is format-specific: the pipeline key carries the target formats,
307/// so targets that disagree share one renderer.
308pub struct SSRenderer {
309    /// Every pipeline used so far, built on first use.
310    pub(crate) pipelines: KeyMap<PipelineKey, wgpu::RenderPipeline>,
311    /// Inputs the lazy builder needs: the sprite/mask WGSL module and its layout.
312    shader_module: wgpu::ShaderModule,
313    pipeline_layout: wgpu::PipelineLayout,
314    /// Compiled module holding all 13 `fs_ss_*` fragment entries + the shared
315    /// vertex stage; shader pipelines are derived from it lazily.
316    ss_shader_module: wgpu::ShaderModule,
317    /// Pipeline layout for shader pipelines: [scene, texture, ss-params].
318    ss_pipeline_layout: wgpu::PipelineLayout,
319    /// Pipeline layout for coverage-masked content: [scene, texture, coverage].
320    coverage_pipeline_layout: wgpu::PipelineLayout,
321    /// Layout of the coverage group, kept so a scene can build a bind group for
322    /// whatever array it allocated this frame.
323    coverage_bind_group_layout: wgpu::BindGroupLayout,
324
325    /// group(0): the render target's projection **and its frame geometry** — the
326    /// SoA arena, the primitive table and the mesh stream the vertex stages read
327    /// in place of a vertex buffer. The layout is shared; every buffer
328    /// behind it belongs to the target ([`crate::SSScene`]).
329    pub(crate) scene_bind_group_layout: wgpu::BindGroupLayout,
330    /// group(1): atlas texture + sampler + its [`TexInfo`].
331    texture_bind_group_layout: wgpu::BindGroupLayout,
332    /// group(2): one dynamic-offset uniform (the per-part `SsParams`).
333    pub(crate) ss_params_bind_group_layout: wgpu::BindGroupLayout,
334
335    sampler: wgpu::Sampler,
336    /// 1x1 white texture, bound when a draw's texture hash is missing
337    /// — used by Shape content and textureless mask writers. Filled with white on
338    /// the first frame (the constructor has no queue to upload with).
339    white_texture: wgpu::Texture,
340    white_bind_group: wgpu::BindGroup,
341    white_ready: bool,
342
343    /// Atlas textures by fnv1a hash. Shared, so N players showing the same
344    /// character upload it once.
345    textures: KeyMap<u32, TextureEntry>,
346    /// Retained pixels for [`Retention::Retain`] uploads, so a device loss can be
347    /// recovered without the host re-supplying them.
348    ///
349    /// **Premultiplied**, not straight: these are the very buffer that was written
350    /// to the texture, kept instead of copied, and nothing ever needs the straight
351    /// form back — [`SSRenderer::restore_device`] writes them out again as they
352    /// are. Keeping straight pixels would cost a second full-size copy per atlas
353    /// (16 MB at 2048²) to buy a form no caller asks for.
354    texture_sources: HashMap<u32, (Vec<u8>, u32, u32)>,
355    /// A digest of the bytes behind each **player-loaded** atlas, for the one
356    /// question a key alone cannot answer: is what is registered still what the
357    /// loader means by it?
358    ///
359    /// The key says *which atlas*, so two players of one pack rightly find each
360    /// other's upload under it and neither re-uploads. But an authoring loop
361    /// re-exports the same file — same path, same key, new pixels — and
362    /// "already held" is how the viewer's convert / drop / look / convert again
363    /// round keeps showing the old atlas. Comparing digests separates the two.
364    ///
365    /// Absent for anything a **host** registered: it owns that entry, and a load
366    /// walk passing over the same key leaves it alone rather than claiming to
367    /// know better.
368    texture_digests: HashMap<u32, u32>,
369    /// How many times [`SSRenderer::upload_texture`] has actually created a
370    /// texture. A diagnostic: the point of a device-scoped texture map
371    /// is that N players of one pack upload its atlas once between them, and only
372    /// a counter — not the map's length — can tell that from N overwrites.
373    texture_uploads: usize,
374    /// Bumped by every change to `textures`. A frame is built against the sizes
375    /// registered here, so a scene that keeps its last frame keeps it only while
376    /// this reads what it read when that frame was built. Carried across a
377    /// device restore, which changes every entry.
378    texture_changes: u64,
379}
380
381/// How a registration is remembered — the two things that outlive the upload
382/// itself, bundled because they are asked and answered together.
383pub(crate) struct Provenance {
384    /// Whether the renderer keeps the pixels for a device-loss rebuild.
385    pub retention: Retention,
386    /// What the bytes behind them hashed to, or `None` for an upload a **host**
387    /// made: that entry is the host's, and a load walk meeting the same key
388    /// leaves it alone. See `texture_digests`.
389    pub digest: Option<u32>,
390}
391
392/// Whether [`SSRenderer::upload_texture`] keeps a copy of the pixels for device
393/// loss recovery.
394#[derive(Clone, Copy, Debug, PartialEq, Eq)]
395pub enum Retention {
396    /// Keep them. For textures the host supplied and may no longer hold.
397    Retain,
398    /// Do not: the supplier can produce them again. Embedded atlases use this —
399    /// the player re-decodes from the `.ssab` it already owns, so a second
400    /// full-size copy of every atlas would be pure waste.
401    Reproducible,
402}
403
404/// The 12 `BlendType`s in schema discriminant order. Pipelines are
405/// built in this order; [`blend_index`] maps a `BlendType` to its slot.
406const BLEND_ORDER: [BlendType; 12] =
407    [BlendType::Mix, BlendType::Mul, BlendType::Add, BlendType::Sub, BlendType::Mulalpha, BlendType::Screen, BlendType::Exclusion, BlendType::Invert, BlendType::Mul2, BlendType::Div2, BlendType::Screen2, BlendType::Overlay2];
408
409/// Blend mode -> index into the per-blend pipeline groups (schema discriminant,
410/// clamped into 0..12).
411pub(crate) fn blend_index(blend: BlendType) -> usize {
412    (blend.0 as usize).min(BLEND_ORDER.len() - 1)
413}
414
415/// Premultiplied blend state for a `BlendType` (matching the WebGL
416/// `applyBlend` table). RGB factors/op per mode; alpha is `One, OneMinusSrcAlpha`
417/// (premultiplied coverage) for every mode. Unverified modes mirror ssplayer-pixi:
418/// Mulalpha/Mul2 -> Mul, Screen2 -> Screen, Div2/Overlay2 -> Mix.
419fn blend_state(blend: BlendType) -> wgpu::BlendState {
420    use wgpu::BlendFactor::{Dst, One, OneMinusDst, OneMinusSrc, OneMinusSrcAlpha, Zero};
421    use wgpu::BlendOperation::{Add, ReverseSubtract};
422    let (src, dst, op) = match blend {
423        BlendType::Mix => (One, OneMinusSrcAlpha, Add),
424        BlendType::Add => (One, One, Add),
425        BlendType::Mul | BlendType::Mulalpha | BlendType::Mul2 => (Dst, OneMinusSrcAlpha, Add),
426        BlendType::Sub => (One, One, ReverseSubtract),
427        BlendType::Screen | BlendType::Screen2 => (OneMinusDst, One, Add),
428        BlendType::Invert => (OneMinusDst, Zero, Add),
429        BlendType::Exclusion => (OneMinusDst, OneMinusSrc, Add),
430        // Div2 / Overlay2: no GPU-native equivalent -> Mix fallback.
431        _ => (One, OneMinusSrcAlpha, Add),
432    };
433    wgpu::BlendState { color: wgpu::BlendComponent { src_factor: src, dst_factor: dst, operation: op }, alpha: wgpu::BlendComponent { src_factor: One, dst_factor: OneMinusSrcAlpha, operation: Add } }
434}
435
436/// Stencil comparison a content pipeline uses for a given test.
437fn stencil_compare(stencil: StencilTest) -> wgpu::CompareFunction {
438    match stencil {
439        StencilTest::None => wgpu::CompareFunction::Always,
440        StencilTest::Inside => wgpu::CompareFunction::NotEqual,
441        StencilTest::Outside => wgpu::CompareFunction::Equal,
442    }
443}
444
445/// Stencil bit planes, one per OP family. `Invert` and the
446/// increment/decrement pair do not commute, so they must never share bits:
447/// mixed they make coverage depend on writer order and leave the cancellation
448/// short of zero. A stencil write is `new = (op(old) & write_mask) | (old &
449/// ~write_mask)`, so restricting the written bits per OP throws the carry/borrow
450/// away and keeps each plane closed. The Test side is unaffected — it reads both
451/// planes (`read_mask` 0xFF, `value != 0`), which is exactly the union that
452/// masks of differing `mask_influence` compose to.
453///
454/// The counter must be contiguous from bit 0 (increment/decrement are ordinary
455/// arithmetic); parity takes one dedicated high bit. This player owns the whole
456/// 8-bit stencil, so the counter gets seven bits (overlap depth up to 127) and
457/// parity the eighth.
458const STENCIL_PLANE_COUNTER: u32 = 0x7F;
459const STENCIL_PLANE_PARITY: u32 = 0x80;
460
461/// The stencil write a mask writer performs. Increment/decrement wrap *within the
462/// counter plane* (`write_mask` discards the carry past bit 6), so a full
463/// increment/decrement cycle returns the plane to zero exactly like the coverage
464/// backend's counter accumulator.
465fn stencil_write_op(op: MaskOp) -> wgpu::StencilOperation {
466    match op {
467        MaskOp::Incr => wgpu::StencilOperation::IncrementWrap,
468        MaskOp::Decr => wgpu::StencilOperation::DecrementWrap,
469        MaskOp::Invert => wgpu::StencilOperation::Invert,
470    }
471}
472
473/// The bit plane a writer's OP writes into.
474fn stencil_write_plane(op: MaskOp) -> u32 {
475    match op {
476        MaskOp::Incr | MaskOp::Decr => STENCIL_PLANE_COUNTER,
477        MaskOp::Invert => STENCIL_PLANE_PARITY,
478    }
479}
480
481/// Baked stencil face for a compare + pass op (front == back; ref is always 0).
482fn stencil_face(compare: wgpu::CompareFunction, pass_op: wgpu::StencilOperation) -> wgpu::StencilFaceState {
483    wgpu::StencilFaceState { compare, fail_op: wgpu::StencilOperation::Keep, depth_fail_op: wgpu::StencilOperation::Keep, pass_op }
484}
485
486/// Depth/stencil state for a pipeline that only *tests* coverage (content), or
487/// only *writes* it (mask writers, `write_mask` = the OP's own plane).
488/// `read_mask` is always 0xFF so a test reads both planes as a union.
489/// The depth aspect is inert throughout: never written, always passing.
490fn depth_stencil_state(format: Option<wgpu::TextureFormat>, compare: wgpu::CompareFunction, pass_op: wgpu::StencilOperation, write_mask: u32) -> Option<wgpu::DepthStencilState> {
491    format.map(|format| wgpu::DepthStencilState {
492        format,
493        depth_write_enabled: Some(false),
494        depth_compare: Some(wgpu::CompareFunction::Always),
495        stencil: wgpu::StencilState { front: stencil_face(compare, pass_op), back: stencil_face(compare, pass_op), read_mask: 0xFF, write_mask },
496        bias: wgpu::DepthBiasState::default(),
497    })
498}
499
500/// Everything both WGSL modules share: the scene's SoA arena and
501/// primitive table, the texture bindings, and the four vertex stages that expand
502/// primitives into vertices. Prefixed onto [`WGSL_SHADER`] and [`SS_SHADER_WGSL`],
503/// which add only their fragment stages.
504///
505/// **There is no vertex buffer.** Each drawn part's slice of the runtime's
506/// `world_matrices` / `local_vertices` / `local_uvs` / mesh / shape arrays is
507/// copied into `f_arena` verbatim as its primitive is recorded, and the vertex
508/// stage reads them at the offsets the part's `Prim` record points at. WebGL2
509/// cannot do this — no storage buffers — and it is the single largest reason
510/// this player exists.
511///
512/// The position maths is written out scalar by scalar rather than as matrix
513/// products: a matrix product invites FMA contraction, which moves pixels and
514/// breaks the bit-exact golden comparison.
515const COMMON_WGSL: &str = r#"
516struct VertexOutput {
517    @builtin(position) clip_position: vec4<f32>,
518    @location(0) uv: vec2<f32>,
519    @location(1) color: vec4<f32>,
520    @location(2) varg: vec4<f32>,
521    // Where this fragment lands in the owning node's coverage bitmap. Written by
522    // every stage but read only by the coverage replay; the stencil path leaves
523    // it at the zero a `var` starts from.
524    @location(3) cov_uv: vec2<f32>,
525    // The primitive's coverage word and block, carried flat because the fragment
526    // stage has no primitive index of its own to look them up with.
527    @location(4) @interpolate(flat) mask_info: u32,
528    @location(5) @interpolate(flat) cov_base: u32,
529    // The owning player's tint, flat for the same reason.
530    @location(6) @interpolate(flat) tint: u32,
531}
532
533struct Globals {
534    proj: mat4x4<f32>,
535}
536
537// One drawn primitive. Which fields mean what depends on the vertex stage
538// reading it — the bases are element offsets into `f_arena`:
539//
540// | aux_base | pos_base | uv_base | count
541// ---------+---------------+-----------------+------------------+-------
542// vs_quad | world matrix | local vertices | local UVs (px) | -
543// vs_mesh | part's Y | part's X | part's UVs (px)| -
544// vs_shape | world matrix | shape vertices | shape box coords | vertices
545// vs_effect| - | particle XY | particle UVs | -
546//
547// `node_base` is the owning node's placement record for the first member of its
548// crowd — one member, the player itself, when it is no crowd — and `node_of`
549// steps to the member being drawn.
550//
551// `colors` is packed RGBA8 but only RGB is read: alpha is kept in `alphas` at
552// full precision, because a part without PartColor takes its alpha straight from
553// the runtime as an f32. `rates` is the per-corner PartsColor rate — also f32,
554// and for a mask writer it carries the cutout threshold instead.
555struct Prim {
556    aux_base: u32,
557    pos_base: u32,
558    uv_base: u32,
559    node_base: u32,
560    count: u32,
561    mode: u32,
562    alpha: f32,
563    z: f32,
564    colors: array<u32, 4>,
565    alphas: array<f32, 4>,
566    rates: array<f32, 4>,
567    // Coverage masking. `cov_base` is the arena offset of the
568    // owning node's coverage block; `mask_info` says whether this primitive is a
569    // writer baking a bit or a target replaying them, and is zero — meaning "not
570    // coverage-masked" — for every primitive under the stencil backend.
571    cov_base: u32,
572    mask_info: u32,
573    // The owning player's tint, packed like `colors`. White (`0x00FFFFFF`) is the
574    // identity — zero is black, so this field is never left to a default.
575    tint: u32,
576}
577
578// `mask_info` bits. Kept in step with the Rust constants of the same names.
579const MASK_INFO_ACTIVE: u32 = 1u;
580const MASK_INFO_WRITER: u32 = 2u;
581const MASK_INFO_INSIDE: u32 = 4u;
582
583@group(0) @binding(0) var<uniform> globals: Globals;
584// The frame's SoA arena: runtime buffers and node transforms, copied verbatim.
585@group(0) @binding(1) var<storage, read> f_arena: array<f32>;
586@group(0) @binding(2) var<storage, read> prims: array<Prim>;
587// One entry per mesh vertex drawn, indexed directly by vertex_index: which
588// primitive of its draw it belongs to from `MESH_PRIM_SHIFT` up, and which of
589// that part's own vertices below. The draw's first primitive arrives as its
590// `instance_index`.
591@group(0) @binding(3) var<storage, read> mesh_stream: array<u32>;
592
593@group(1) @binding(0) var t_diffuse: texture_2d<f32>;
594@group(1) @binding(1) var s_diffuse: sampler;
595
596// Per-texture facts that must not become pipeline dimensions:
597// `size` = (w, h, 1/w, 1/h) in texels, `flags.x` = 1 when premultiplied.
598struct TexInfo {
599    size: vec4<f32>,
600    flags: vec4<f32>,
601}
602@group(1) @binding(2) var<uniform> tex_info: TexInfo;
603
604// Straight (un-premultiplied) RGB of a sampled texel. Our own uploads are
605// premultiplied and need the divide; a texture borrowed from an engine's asset
606// system usually is not, and dividing it would blow out the edges.
607fn ss_straight_rgb(tex: vec4<f32>) -> vec3<f32> {
608    return select(tex.rgb, tex.rgb / max(tex.a, 0.0001), tex_info.flags.x > 0.5);
609}
610
611// The part's texel at `uv`, filtered in premultiplied space. The sampler blends a
612// straight texture's transparent texels' colour into its edges — dark or white
613// fringes wherever the art is scaled — so a straight texture is filtered here
614// from its four nearest texels instead, and handed back straight. `sampled` is
615// the hardware sample, taken while control flow is still uniform.
616fn ss_texel(sampled: vec4<f32>, uv: vec2<f32>) -> vec4<f32> {
617    if (tex_info.flags.x > 0.5) {
618        return sampled;
619    }
620    let dims = vec2<i32>(textureDimensions(t_diffuse, 0));
621    let p = uv * vec2<f32>(dims) - 0.5;
622    let base = vec2<i32>(floor(p));
623    let f = p - floor(p);
624    let hi = dims - vec2<i32>(1);
625    let c00 = ss_premul(textureLoad(t_diffuse, clamp(base, vec2<i32>(0), hi), 0));
626    let c10 = ss_premul(textureLoad(t_diffuse, clamp(base + vec2<i32>(1, 0), vec2<i32>(0), hi), 0));
627    let c01 = ss_premul(textureLoad(t_diffuse, clamp(base + vec2<i32>(0, 1), vec2<i32>(0), hi), 0));
628    let c11 = ss_premul(textureLoad(t_diffuse, clamp(base + vec2<i32>(1, 1), vec2<i32>(0), hi), 0));
629    let c = mix(mix(c00, c10, f.x), mix(c01, c11, f.x), f.y);
630    return vec4<f32>(c.rgb / max(c.a, 0.0001), c.a);
631}
632
633fn ss_premul(texel: vec4<f32>) -> vec4<f32> {
634    return vec4<f32>(texel.rgb * texel.a, texel.a);
635}
636
637// group(2) under the coverage layout: the coverage bitmaps for the masked
638// content that replays them, the group-alpha layers for the composite.
639@group(2) @binding(0) var t_layers: texture_2d_array<f32>;
640
641// --- coverage masking ---------------------------------------------------
642
643// A part-local point in the space the coverage bitmap is pinned to: through the
644// part's own world matrix, but *not* through the player's placement, so the
645// bitmap does not slide when the player moves.
646//
647// Deliberately a copy of the first two lines of `world_point` rather than a
648// shared helper it calls: the clip path's arithmetic is compared pixel for pixel
649// against a golden run, and factoring it out invites the compiler to contract
650// the multiply-adds differently there.
651fn local_xy(mat_base: u32, lx: f32, ly: f32) -> vec2<f32> {
652    return vec2<f32>(
653        f_arena[mat_base] * lx + f_arena[mat_base + 4u] * ly + f_arena[mat_base + 12u],
654        f_arena[mat_base + 1u] * lx + f_arena[mat_base + 5u] * ly + f_arena[mat_base + 13u],
655    );
656}
657
658// Player-local -> coverage UV, through the node's bbox affine. Zero for a
659// primitive that is not coverage-masked, which never reads the result.
660fn cov_uv_of(pi: u32, p: vec2<f32>) -> vec2<f32> {
661    if ((prims[pi].mask_info & MASK_INFO_ACTIVE) == 0u) {
662        return vec2<f32>(0.0, 0.0);
663    }
664    let b = prims[pi].cov_base;
665    return vec2<f32>(
666        f_arena[b] * p.x + f_arena[b + 2u] * p.y + f_arena[b + 4u],
667        f_arena[b + 1u] * p.x + f_arena[b + 3u] * p.y + f_arena[b + 5u],
668    );
669}
670
671// Coverage UV -> clip space, for the bake stages. The bitmap's V runs top-down
672// like a texture, so it flips against clip Y.
673fn cov_clip(uv: vec2<f32>) -> vec4<f32> {
674    return vec4<f32>(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, 0.5, 1.0);
675}
676
677// The colour one writer contributes: its own bit, in its own channel, and
678// nothing else. Alpha is 1 because the bake blends additively and a zero alpha
679// would scale the bit away on backends that premultiply first.
680fn bit_color(info: u32) -> vec4<f32> {
681    // The layer was picked by the draw call; this is the bit within it.
682    let bit = ((info >> 8u) & 0xFFu) % COVERAGE_LAYER_BITS;
683    let value = f32(1u << (bit % 8u)) / 255.0;
684    let channel = bit / 8u;
685    var c = vec4<f32>(0.0, 0.0, 0.0, 1.0);
686    if (channel == 0u) { c.r = value; }
687    else if (channel == 1u) { c.g = value; }
688    else { c.b = value; }
689    return c;
690}
691
692// --- vertex stages --------------------------------------------------------
693
694// Corner order of the two triangles making an effect particle's quad, the index
695// pattern the runtime emits for them.
696fn quad_corner(j: u32) -> u32 {
697    var order = array<u32, 6>(0u, 1u, 2u, 2u, 1u, 3u);
698    return order[j];
699}
700
701// Which of a sprite's five vertices — lt, rt, lb, rb, then the centre (4) —
702// each fan vertex is: `{c,lt,rt, c,rt,rb, c,rb,lb, c,lb,lt}`.
703fn quad_fan_vertex(j: u32) -> u32 {
704    var order = array<u32, 12>(4u, 0u, 1u, 4u, 1u, 3u, 4u, 3u, 2u, 4u, 2u, 0u);
705    return order[j];
706}
707
708// The record of the owning node's placement for one member of a crowd: its
709// matrix, then that member's alpha and tint.
710fn node_of(pi: u32, member: u32) -> u32 {
711    return prims[pi].node_base + member * NODE_STRIDE;
712}
713
714// The player's tint with the member's folded onto it. A member left white hands
715// the player's back as it was, bit for bit; the tint travels as a number,
716// exact below 2^24, so the arena stays all floats.
717fn member_tint(pi: u32, node: u32) -> u32 {
718    let tint = prims[pi].tint;
719    let member = u32(f_arena[node + 17u]);
720    if (member == NO_TINT) {
721        return tint;
722    }
723    return pack4x8unorm(vec4<f32>(unpack4x8unorm(tint).rgb * unpack4x8unorm(member).rgb, 0.0));
724}
725
726// A node's placement applied to a world-space point, summed scalar by scalar
727// like the rest of the position maths.
728fn apply_node(base: u32, x: f32, y: f32, z: f32) -> vec3<f32> {
729    return vec3<f32>(
730        f_arena[base] * x + f_arena[base + 4u] * y + f_arena[base + 8u] * z + f_arena[base + 12u],
731        f_arena[base + 1u] * x + f_arena[base + 5u] * y + f_arena[base + 9u] * z + f_arena[base + 13u],
732        f_arena[base + 2u] * x + f_arena[base + 6u] * y + f_arena[base + 10u] * z + f_arena[base + 14u],
733    );
734}
735
736// A part-local point through the part's world matrix and then its node's
737// placement. Local Z is zero, so the matrix's third column drops out.
738fn world_point(mat_base: u32, node_base: u32, lx: f32, ly: f32) -> vec3<f32> {
739    let wx = f_arena[mat_base] * lx + f_arena[mat_base + 4u] * ly + f_arena[mat_base + 12u];
740    let wy = f_arena[mat_base + 1u] * lx + f_arena[mat_base + 5u] * ly + f_arena[mat_base + 13u];
741    let wz = f_arena[mat_base + 2u] * lx + f_arena[mat_base + 6u] * ly + f_arena[mat_base + 14u];
742    return apply_node(node_base, wx, wy, wz);
743}
744
745// Clip position. Z is written as a constant: the projection's third column is
746// identity, so the depth the transform produced never reaches x/y.
747fn to_clip(p: vec3<f32>) -> vec4<f32> {
748    let pos = globals.proj * vec4<f32>(p, 1.0);
749    return vec4<f32>(pos.x, pos.y, 0.5, 1.0);
750}
751
752// The runtime's UVs are in texture pixels. A missing texture binds
753// the 1x1 white fallback, whose size of 1 makes this a no-op.
754fn normalize_uv(base: u32, k: u32) -> vec2<f32> {
755    return vec2<f32>(f_arena[base + k * 2u], f_arena[base + k * 2u + 1u]) / tex_info.size.xy;
756}
757
758// The player's tint, unpacked. It multiplies the finished composite rather than
759// the colour the PartsColor formula blends towards, which is why it reaches the
760// fragment stage instead of folding into `corner_rgba`.
761fn player_tint(packed: u32) -> vec3<f32> {
762    return unpack4x8unorm(packed).rgb;
763}
764
765// The member's alpha comes last, so a member at 1 changes nothing.
766fn corner_rgba(pi: u32, k: u32, node: u32) -> vec4<f32> {
767    return vec4<f32>(unpack4x8unorm(prims[pi].colors[k]).rgb, prims[pi].alphas[k] * prims[pi].alpha * f_arena[node + 16u]);
768}
769
770// A sprite vertex's colour: a corner's own, or for the centre (4) the mean of
771// the four. Summed in pairs so that four equal corners give that value back
772// exactly — a part without PartsColor must not shade its centre.
773fn quad_rgba(pi: u32, k: u32, node: u32) -> vec4<f32> {
774    if (k < 4u) {
775        return corner_rgba(pi, k, node);
776    }
777    return ((corner_rgba(pi, 0u, node) + corner_rgba(pi, 1u, node)) + (corner_rgba(pi, 2u, node) + corner_rgba(pi, 3u, node))) * 0.25;
778}
779
780// A sprite vertex's rate, averaged at the centre like `quad_rgba`. For a mask
781// writer this is the cutout threshold, which the pairwise sum keeps exact.
782fn quad_rate(pi: u32, k: u32) -> f32 {
783    let r = &prims[pi].rates;
784    if (k < 4u) {
785        return (*r)[k];
786    }
787    return (((*r)[0] + (*r)[1]) + ((*r)[2] + (*r)[3])) * 0.25;
788}
789
790// `varg` = [rate, isMix, isMul, isAddSub]. Only four PartsColor
791// formulas exist, so the mode is two bits on the primitive rather than three
792// floats on every vertex.
793fn varg_of(mode: u32, rate: f32) -> vec4<f32> {
794    switch mode {
795        case 1u: { return vec4<f32>(rate, 0.0, 1.0, 0.0); }
796        case 2u: { return vec4<f32>(rate, 0.0, 0.0, 1.0); }
797        case 3u: { return vec4<f32>(rate, 0.0, 0.0, -1.0); }
798        default: { return vec4<f32>(rate, 1.0, 0.0, 0.0); }
799    }
800}
801
802// A sprite as a fan around its centre: the runtime's fifth local vertex and UV,
803// with the mean of the corners' colour and rate.
804//
805// `member` is the crowd member being drawn, which is all a non-mesh draw's
806// `instance_index` carries.
807@vertex
808fn vs_quad(@builtin(vertex_index) vi: u32, @builtin(instance_index) member: u32) -> VertexOutput {
809    let pi = vi / QUAD_FAN_VERTS;
810    let k = quad_fan_vertex(vi % QUAD_FAN_VERTS);
811    let p = &prims[pi];
812    let node = node_of(pi, member);
813    let lx = f_arena[(*p).pos_base + k * 2u];
814    let ly = f_arena[(*p).pos_base + k * 2u + 1u];
815
816    var out: VertexOutput;
817    out.clip_position = to_clip(world_point((*p).aux_base, node, lx, ly));
818    out.uv = normalize_uv((*p).uv_base, k);
819    out.color = quad_rgba(pi, k, node);
820    out.varg = varg_of((*p).mode, quad_rate(pi, k));
821    out.cov_uv = cov_uv_of(pi, local_xy((*p).aux_base, lx, ly));
822    out.mask_info = prims[pi].mask_info;
823    out.cov_base = prims[pi].cov_base;
824    out.tint = member_tint(pi, node);
825    return out;
826}
827
828const MESH_VERTEX_MASK: u32 = (1u << MESH_PRIM_SHIFT) - 1u;
829const CROWD_MEMBER_MASK: u32 = (1u << CROWD_SHIFT) - 1u;
830
831@vertex
832fn vs_mesh(@builtin(vertex_index) vi: u32, @builtin(instance_index) instance: u32) -> VertexOutput {
833    let entry = mesh_stream[vi];
834    let pi = (instance >> CROWD_SHIFT) + (entry >> MESH_PRIM_SHIFT);
835    let k = entry & MESH_VERTEX_MASK;
836    let p = &prims[pi];
837    let node = node_of(pi, instance & CROWD_MEMBER_MASK);
838    // Mesh vertices arrive already in world space (the runtime skins them), so
839    // only the node's placement is left to apply.
840    let mx = f_arena[(*p).pos_base + k];
841    let my = f_arena[(*p).aux_base + k];
842
843    var out: VertexOutput;
844    out.clip_position = to_clip(apply_node(node, mx, my, (*p).z));
845    out.uv = normalize_uv((*p).uv_base, k);
846    out.color = corner_rgba(pi, 0u, node);
847    out.varg = varg_of((*p).mode, (*p).rates[0]);
848    out.cov_uv = cov_uv_of(pi, vec2<f32>(mx, my));
849    out.mask_info = prims[pi].mask_info;
850    out.cov_base = prims[pi].cov_base;
851    out.tint = member_tint(pi, node);
852    return out;
853}
854
855@vertex
856fn vs_shape(@builtin(vertex_index) vi: u32, @builtin(instance_index) member: u32) -> VertexOutput {
857    let pi = vi / SHAPE_FAN_VERTS;
858    let r = vi % SHAPE_FAN_VERTS;
859    let tri = r / 3u;
860    let p = &prims[pi];
861
862    // Fan from vertex 0. Triangles past the live vertex count collapse onto
863    // vertex 0, so they have no area and rasterise nothing.
864    var v = 0u;
865    if (tri + 2u < (*p).count) {
866        let c = r % 3u;
867        if (c == 1u) { v = tri + 1u; }
868        if (c == 2u) { v = tri + 2u; }
869    }
870    let lx = f_arena[(*p).pos_base + v * 2u];
871    let ly = f_arena[(*p).pos_base + v * 2u + 1u];
872
873    // Bilinear fill over the part's box coordinates.
874    let node = node_of(pi, member);
875    let fx = f_arena[(*p).uv_base + v * 2u];
876    let fy = f_arena[(*p).uv_base + v * 2u + 1u];
877    let top = corner_rgba(pi, 0u, node) * (1.0 - fx) + corner_rgba(pi, 1u, node) * fx;
878    let bot = corner_rgba(pi, 2u, node) * (1.0 - fx) + corner_rgba(pi, 3u, node) * fx;
879
880    var out: VertexOutput;
881    out.clip_position = to_clip(world_point((*p).aux_base, node, lx, ly));
882    // Shapes are textureless (white fallback), so any constant UV samples white.
883    out.uv = vec2<f32>(0.5, 0.5);
884    out.color = top * (1.0 - fy) + bot * fy;
885    out.varg = varg_of((*p).mode, (*p).rates[0]);
886    out.cov_uv = cov_uv_of(pi, local_xy((*p).aux_base, lx, ly));
887    out.mask_info = prims[pi].mask_info;
888    out.cov_base = prims[pi].cov_base;
889    out.tint = member_tint(pi, node);
890    return out;
891}
892
893@vertex
894fn vs_effect(@builtin(vertex_index) vi: u32, @builtin(instance_index) member: u32) -> VertexOutput {
895    let pi = vi / 6u;
896    let k = quad_corner(vi % 6u);
897    let p = &prims[pi];
898    let node = node_of(pi, member);
899    // Particle quads are emitted in the effect part's own space with
900    // vert_stride 2, so Z is zero.
901    let px = f_arena[(*p).pos_base + k * 2u];
902    let py = f_arena[(*p).pos_base + k * 2u + 1u];
903
904    var out: VertexOutput;
905    out.clip_position = to_clip(apply_node(node, px, py, 0.0));
906    // Effect UVs are already normalised, unlike the sprite/mesh pixel UVs.
907    out.uv = vec2<f32>(f_arena[(*p).uv_base + k * 2u], f_arena[(*p).uv_base + k * 2u + 1u]);
908    // One colour per particle, and no PartsColor overlay: plain modulate.
909    out.color = corner_rgba(pi, 0u, node);
910    out.varg = varg_of((*p).mode, (*p).rates[0]);
911    // The particle's own local point: the effect's coverage block already maps
912    // the effect part's space onto the player's bitmap.
913    out.cov_uv = cov_uv_of(pi, vec2<f32>(px, py));
914    out.mask_info = prims[pi].mask_info;
915    out.cov_base = prims[pi].cov_base;
916    out.tint = member_tint(pi, node);
917    return out;
918}
919"#;
920
921/// The coverage half of the sprite module: the three bake vertex stages, the
922/// bit-writing fragment, and the replay every masked part runs.
923///
924/// Split out only for reading; it is concatenated onto [`COMMON_WGSL`] with
925/// [`WGSL_SHADER`] and naga sees one module.
926const COVERAGE_WGSL: &str = r#"
927// --- bake: rasterise one writer's shape into its bit ----------------------
928
929// The same fan as `vs_quad`, so a writer's bit covers exactly what its part draws.
930@vertex
931fn vs_cov_quad(@builtin(vertex_index) vi: u32) -> VertexOutput {
932    let pi = vi / QUAD_FAN_VERTS;
933    let k = quad_fan_vertex(vi % QUAD_FAN_VERTS);
934    let p = &prims[pi];
935    let lx = f_arena[(*p).pos_base + k * 2u];
936    let ly = f_arena[(*p).pos_base + k * 2u + 1u];
937
938    var out: VertexOutput;
939    out.cov_uv = cov_uv_of(pi, local_xy((*p).aux_base, lx, ly));
940    out.mask_info = prims[pi].mask_info;
941    out.cov_base = prims[pi].cov_base;
942    out.tint = prims[pi].tint;
943    out.clip_position = cov_clip(out.cov_uv);
944    out.uv = normalize_uv((*p).uv_base, k);
945    out.color = bit_color((*p).mask_info);
946    out.varg = vec4<f32>(quad_rate(pi, k), 0.0, 0.0, 0.0);
947    return out;
948}
949
950// A bake never reads a placement — the bitmap is the player's, shared by every
951// member of a crowd — so only the mesh's first primitive is taken from its
952// `instance_index`.
953@vertex
954fn vs_cov_mesh(@builtin(vertex_index) vi: u32, @builtin(instance_index) instance: u32) -> VertexOutput {
955    let entry = mesh_stream[vi];
956    let pi = (instance >> CROWD_SHIFT) + (entry >> MESH_PRIM_SHIFT);
957    let k = entry & MESH_VERTEX_MASK;
958    let p = &prims[pi];
959    let mx = f_arena[(*p).pos_base + k];
960    let my = f_arena[(*p).aux_base + k];
961
962    var out: VertexOutput;
963    out.cov_uv = cov_uv_of(pi, vec2<f32>(mx, my));
964    out.mask_info = prims[pi].mask_info;
965    out.cov_base = prims[pi].cov_base;
966    out.tint = prims[pi].tint;
967    out.clip_position = cov_clip(out.cov_uv);
968    out.uv = normalize_uv((*p).uv_base, k);
969    out.color = bit_color((*p).mask_info);
970    out.varg = vec4<f32>((*p).rates[0], 0.0, 0.0, 0.0);
971    return out;
972}
973
974@vertex
975fn vs_cov_shape(@builtin(vertex_index) vi: u32) -> VertexOutput {
976    let pi = vi / SHAPE_FAN_VERTS;
977    let r = vi % SHAPE_FAN_VERTS;
978    let tri = r / 3u;
979    let p = &prims[pi];
980
981    var v = 0u;
982    if (tri + 2u < (*p).count) {
983        let c = r % 3u;
984        if (c == 1u) { v = tri + 1u; }
985        if (c == 2u) { v = tri + 2u; }
986    }
987    let lx = f_arena[(*p).pos_base + v * 2u];
988    let ly = f_arena[(*p).pos_base + v * 2u + 1u];
989
990    var out: VertexOutput;
991    out.cov_uv = cov_uv_of(pi, local_xy((*p).aux_base, lx, ly));
992    out.mask_info = prims[pi].mask_info;
993    out.cov_base = prims[pi].cov_base;
994    out.tint = prims[pi].tint;
995    out.clip_position = cov_clip(out.cov_uv);
996    // Shapes are textureless, so any constant UV samples the white fallback.
997    out.uv = vec2<f32>(0.5, 0.5);
998    out.color = bit_color((*p).mask_info);
999    out.varg = vec4<f32>((*p).rates[0], 0.0, 0.0, 0.0);
1000    return out;
1001}
1002
1003// Writes the writer's bit wherever its cutout says it covers.
1004// `varg.x` carries the threshold; below zero means "no cutout", which is what a
1005// textureless pure mask uses to cover its whole shape.
1006@fragment
1007fn fs_coverage(in: VertexOutput) -> @location(0) vec4<f32> {
1008    let a = textureSample(t_diffuse, s_diffuse, in.uv).a;
1009    let threshold = in.varg.x;
1010    if (threshold >= 0.0 && a <= threshold) {
1011        discard;
1012    }
1013    return in.color;
1014}
1015
1016// --- replay: reconstruct the mask state for one masked fragment -----------
1017
1018// Re-runs the writers that are in scope for this part and says whether the
1019// fragment survives. This is the stencil's job done per fragment: the bitmap
1020// holds every writer of the player's instance tree at once, and the scope test
1021// picks which of them were "applied" by the time this part drew.
1022fn mask_passes(in: VertexOutput, info: u32, cov_base: u32) -> bool {
1023    let layer = i32(f_arena[cov_base + 6u]);
1024    let count = u32(f_arena[cov_base + 7u]);
1025    let inside = (info & MASK_INFO_INSIDE) != 0u;
1026    // No writer covers anything: a part drawn only inside a mask draws nowhere.
1027    if (count == 0u) {
1028        return !inside;
1029    }
1030
1031    // Outside the bbox there is no writer to be inside of. Answering from the
1032    // polarity alone keeps the sampler's edge clamp from reading the border
1033    // texel and masking content that is nowhere near the mask.
1034    let uv = in.cov_uv;
1035    if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) {
1036        return !inside;
1037    }
1038
1039    let dims = vec2<f32>(textureDimensions(t_layers).xy);
1040    // `textureLoad`, not a sampler: a filtered read would blend one writer's bit
1041    // into the next and decode as coverage nobody wrote.
1042    let texel = vec2<i32>(clamp(uv * dims, vec2<f32>(0.0), dims - 1.0));
1043    // A tree with more writers than one layer holds spills into the layers after
1044    // it, `COVERAGE_LAYER_BITS` at a time. Records are in bit order, so each
1045    // layer is loaded once.
1046    var loaded = 0u;
1047    var cov = textureLoad(t_layers, texel, layer, 0);
1048
1049    // This part's place on the tree sequence — the whole instance tree numbered
1050    // in drawing order, so a sub-animation's parts sit between its instance part
1051    // and whatever its caller draws next.
1052    let this_seq = f32(info >> 8u);
1053    // Two accumulators, never one: increment and invert are each self-inverse but
1054    // do not commute, so mixing them makes coverage depend on the order the
1055    // writers happened to be drawn in.
1056    var parity = 0u;
1057    var counter = 0u;
1058    for (var i = 0u; i < count; i = i + 1u) {
1059        let rec = cov_base + COVERAGE_HEADER + i * COVERAGE_STRIDE;
1060        // Scope, open at both ends: a clipping writer holds from itself to the
1061        // end of the tree, a pure mask from the start of its own animation up to
1062        // itself. The player worked both out; here it is one comparison.
1063        if (!(f_arena[rec] < this_seq && this_seq < f_arena[rec + 1u])) {
1064            continue;
1065        }
1066        let tree_bit = u32(f_arena[rec + 2u]);
1067        let spill = tree_bit / COVERAGE_LAYER_BITS;
1068        if (spill != loaded) {
1069            cov = textureLoad(t_layers, texel, layer + i32(spill), 0);
1070            loaded = spill;
1071        }
1072        let bit = tree_bit % COVERAGE_LAYER_BITS;
1073        let byte = u32(cov[bit / 8u] * 255.0 + 0.5);
1074        if (((byte >> (bit % 8u)) & 1u) == 0u) {
1075            continue;
1076        }
1077        if (f_arena[rec + 3u] > 0.5) {
1078            parity = parity ^ 1u;
1079        } else {
1080            counter = counter + 1u;
1081        }
1082    }
1083
1084    let masked = (parity != 0u) || (counter != 0u);
1085    return masked == inside;
1086}
1087"#;
1088
1089const WGSL_SHADER: &str = r#"
1090// PartsColor blend (direct port of WebGL PartsColorProgram).
1091// Recover straight RGB, apply the mix/mul/add-sub blend selected by `varg`, then
1092// re-premultiply. Blend factors are premul too (see the pipeline blend table),
1093// keeping the whole path premultiplied.
1094@fragment
1095fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
1096    let tex = ss_texel(textureSample(t_diffuse, s_diffuse, in.uv), in.uv);
1097    if (tex.a == 0.0) {
1098        return vec4<f32>(0.0);
1099    }
1100    let rate = in.varg.x;
1101    let straight = ss_straight_rgb(tex);
1102    let mixC = mix(straight, in.color.rgb, rate);
1103    let mulC = straight * mix(vec3<f32>(1.0), in.color.rgb, rate);
1104    let addC = straight + in.color.rgb * rate * sign(in.varg.w);
1105    let rgb = mixC * in.varg.y + mulC * in.varg.z + addC * abs(in.varg.w);
1106    let a = tex.a * in.color.a;
1107    return vec4<f32>(rgb * player_tint(in.tint) * a, a);
1108}
1109
1110// The same composite as `fs_main`, clipped by the coverage bitmap.
1111//
1112// The texture is sampled *before* the clip decides: `textureSample` needs
1113// implicit derivatives, and WGSL forbids those once control flow has stopped
1114// being uniform — which a `discard` above it would make it.
1115@fragment
1116fn fs_main_coverage(in: VertexOutput) -> @location(0) vec4<f32> {
1117    let tex = ss_texel(textureSample(t_diffuse, s_diffuse, in.uv), in.uv);
1118    let info = in.mask_info;
1119    if ((info & MASK_INFO_ACTIVE) != 0u && !mask_passes(in, info, in.cov_base)) {
1120        discard;
1121    }
1122    if (tex.a == 0.0) {
1123        return vec4<f32>(0.0);
1124    }
1125    let rate = in.varg.x;
1126    let straight = ss_straight_rgb(tex);
1127    let mixC = mix(straight, in.color.rgb, rate);
1128    let mulC = straight * mix(vec3<f32>(1.0), in.color.rgb, rate);
1129    let addC = straight + in.color.rgb * rate * sign(in.varg.w);
1130    let rgb = mixC * in.varg.y + mulC * in.varg.z + addC * abs(in.varg.w);
1131    let a = tex.a * in.color.a;
1132    return vec4<f32>(rgb * player_tint(in.tint) * a, a);
1133}
1134
1135// Mask-write fragment: color output is discarded (ColorWrites::empty()); only
1136// the cutout matters. `varg.x` carries the threshold (< 0 = no cutout) — the
1137// rate slot rather than a colour channel, because it has to survive at full f32
1138// precision and the colours are packed to bytes.
1139@fragment
1140fn fs_mask(in: VertexOutput) -> @location(0) vec4<f32> {
1141    let a = textureSample(t_diffuse, s_diffuse, in.uv).a;
1142    let threshold = in.varg.x;
1143    if (threshold >= 0.0 && a <= threshold) {
1144        discard;
1145    }
1146    return vec4<f32>(1.0, 1.0, 1.0, 1.0);
1147}
1148
1149// --- group alpha: one faded player's layer, folded back into the target ---
1150
1151struct CompositeOutput {
1152    @builtin(position) clip_position: vec4<f32>,
1153    // Where the fragment falls on the layer, 0..1 across and down. A coordinate
1154    // rather than the fragment's own pixel, so a host whose pass draws into a
1155    // viewport of the target still lands each texel where it was drawn.
1156    @location(0) uv: vec2<f32>,
1157    @location(1) @interpolate(flat) layer: u32,
1158    @location(2) @interpolate(flat) alpha: f32,
1159}
1160
1161// One triangle over the whole target, three vertices to a primitive. The
1162// primitive carries the player's alpha, and in `count` the layer it drew into.
1163@vertex
1164fn vs_composite(@builtin(vertex_index) vi: u32) -> CompositeOutput {
1165    let pi = vi / 3u;
1166    let k = vi % 3u;
1167    // (-1, -1), (3, -1), (-1, 3).
1168    let xy = vec2<f32>(f32((k << 1u) & 2u), f32(k & 2u)) * 2.0 - 1.0;
1169    var out: CompositeOutput;
1170    out.clip_position = vec4<f32>(xy, 0.5, 1.0);
1171    out.uv = vec2<f32>(xy.x * 0.5 + 0.5, 0.5 - xy.y * 0.5);
1172    out.layer = prims[pi].count;
1173    out.alpha = prims[pi].alpha;
1174    return out;
1175}
1176
1177// The layer was drawn premultiplied, like everything else, so fading it is one
1178// multiply and the blend is the plain premultiplied over.
1179@fragment
1180fn fs_composite(in: CompositeOutput) -> @location(0) vec4<f32> {
1181    let dims = vec2<f32>(textureDimensions(t_layers).xy);
1182    let texel = vec2<i32>(clamp(in.uv * dims, vec2<f32>(0.0), dims - 1.0));
1183    return textureLoad(t_layers, texel, i32(in.layer), 0) * in.alpha;
1184}
1185"#;
1186
1187/// Bytes per shader-param slot in the dynamic-offset uniform buffer. Dynamic
1188/// uniform offsets must be a multiple of `min_uniform_buffer_offset_alignment`
1189/// (256 on all backends we target), so each part's params occupy one 256-byte
1190/// slot even though only the first 64 bytes are used.
1191pub(crate) const SHADER_PARAM_STRIDE: usize = 256;
1192/// f32 count of one slot (`SHADER_PARAM_STRIDE / 4`).
1193pub(crate) const SHADER_PARAM_STRIDE_F32: usize = SHADER_PARAM_STRIDE / 4;
1194
1195/// id_hash (SDK `PartAttributeShader.id_hash()`, `fnv1a_hash_str("ss-*")`) ->
1196/// WGSL fragment entry point. The 13 SpriteStudio integration shaders,
1197/// ports of the WebGL `SSShaderLib.ts`. Hashes are the SDK's precomputed values.
1198const SS_SHADER_ENTRIES: [(u32, &str); 13] = [
1199    (0x36629dfc, "fs_ss_sepia"),
1200    (0x8a5c3037, "fs_ss_hsb"),
1201    (0x1b721788, "fs_ss_step"),
1202    (0xc488a527, "fs_ss_pix"),
1203    (0x80d6d514, "fs_ss_noise"),
1204    (0x64e07450, "fs_ss_bmask"),
1205    (0x8f8307d4, "fs_ss_outline"),
1206    (0xb59c8d1b, "fs_ss_blur"),
1207    (0xe1df9a2b, "fs_ss_wave"),
1208    (0xe1c1ee07, "fs_ss_move"),
1209    (0x45e35578, "fs_ss_scatter"),
1210    (0x9b90e282, "fs_ss_circle"),
1211    (0x7140896a, "fs_ss_spot"),
1212];
1213
1214/// WGSL entry point for an integration-shader `id_hash`, or `None` when it is not
1215/// a built-in `ss-*` (the caller then draws the part with the plain shader).
1216pub(crate) fn ss_shader_entry(id_hash: u32) -> Option<&'static str> {
1217    SS_SHADER_ENTRIES.iter().find(|(h, _)| *h == id_hash).map(|(_, e)| *e)
1218}
1219
1220/// The 13 SpriteStudio integration shaders, ported from the WebGL
1221/// `SSShaderLib.ts` (itself the SS6-SDK GLSL). Each entry computes a straight-
1222/// alpha `Pixel`, then `ss_finish` applies the same PartsColor composite as
1223/// `fs_main` (varg mix/mul/add-sub) and re-premultiplies — except `ss-blur`,
1224/// which multiplies by the part colour directly (mirrors the SS6 reference).
1225///
1226/// `ssTex` un-premultiplies (textures are premultiplied) and samples at LOD
1227/// 0 via `textureSampleLevel` so sampling is legal inside loops / after `discard`
1228/// (WGSL forbids implicit-derivative `textureSample` in non-uniform control flow).
1229/// Per-part uniforms live in group(2): `param_a`=param0..3, `param_b`=param4..7,
1230/// `cell_rect`=(minU,minV,maxU,maxV) over the quad's corners, `pixel_size`=1/texel.
1231const SS_SHADER_WGSL: &str = r#"
1232struct SsParams {
1233    param_a: vec4<f32>, // param0..3
1234    param_b: vec4<f32>, // param4..7
1235    cell_rect: vec4<f32>, // minU, minV, maxU, maxV
1236    pixel_size: vec4<f32>, // 1/texW, 1/texH, 0, 0
1237}
1238@group(2) @binding(0) var<uniform> ss: SsParams;
1239
1240const PI: f32 = 3.141592653589793;
1241
1242fn ssTex(uv: vec2<f32>) -> vec4<f32> {
1243    let c = textureSampleLevel(t_diffuse, s_diffuse, uv, 0.0);
1244    // Straight-alpha sample; only premultiplied sources need the divide.
1245    let rgb = select(c.rgb, c.rgb / max(c.a, 0.0001), tex_info.flags.x > 0.5);
1246    return vec4<f32>(rgb, c.a);
1247}
1248
1249// PartColor composite (straight space) + re-premultiply — same math as fs_main,
1250// player tint included.
1251fn ss_finish(pixel: vec4<f32>, color: vec4<f32>, varg: vec4<f32>, tint: u32) -> vec4<f32> {
1252    let rate = varg.x;
1253    let p = pixel.rgb;
1254    let mix_c = mix(p, color.rgb, rate);
1255    let mul_c = p * mix(vec3<f32>(1.0), color.rgb, rate);
1256    let add_c = p + color.rgb * rate * sign(varg.w);
1257    let rgb = mix_c * varg.y + mul_c * varg.z + add_c * abs(varg.w);
1258    let a = pixel.a * color.a;
1259    return vec4<f32>(rgb * player_tint(tint) * a, a);
1260}
1261
1262fn ss_rand(p: vec2<f32>) -> f32 {
1263    return fract(sin(dot(p, vec2<f32>(12.9898, 78.233))) * 43758.5453);
1264}
1265
1266fn ss_rgb_to_hsb(color: vec4<f32>) -> vec4<f32> {
1267    let k = vec4<f32>(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);
1268    let p = mix(vec4<f32>(color.bg, k.wz), vec4<f32>(color.gb, k.xy), step(color.b, color.g));
1269    let q = mix(vec4<f32>(p.xyw, color.r), vec4<f32>(color.r, p.yzx), step(p.x, color.r));
1270    let d = q.x - min(q.w, q.y);
1271    let e = 1.0e-10;
1272    return vec4<f32>(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x, color.a);
1273}
1274fn ss_hsb_to_rgb(hsb: vec4<f32>) -> vec4<f32> {
1275    let k = vec4<f32>(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);
1276    let p = abs(fract(hsb.xxx + k.xyz) * 6.0 - k.www);
1277    return vec4<f32>(hsb.z * mix(k.xxx, clamp(p - k.xxx, vec3<f32>(0.0), vec3<f32>(1.0)), hsb.y), hsb.w);
1278}
1279
1280@fragment
1281fn fs_ss_sepia(in: VertexOutput) -> @location(0) vec4<f32> {
1282    let f_power = ss.param_a.x;
1283    let pixel = ssTex(in.uv);
1284    let gray = dot(pixel.rgb, vec3<f32>(0.298912, 0.586611, 0.114478));
1285    let gray_rgb = vec3<f32>(gray);
1286    let sepia_rgb = gray_rgb * vec3<f32>(1.07, 0.74, 0.43);
1287    let toned = mix(sepia_rgb, gray_rgb, step(f_power, 0.0));
1288    let mixed_rgb = mix(pixel.rgb, toned, abs(f_power));
1289    return ss_finish(vec4<f32>(mixed_rgb, pixel.a), in.color, in.varg, in.tint);
1290}
1291
1292@fragment
1293fn fs_ss_hsb(in: VertexOutput) -> @location(0) vec4<f32> {
1294    let f_hue = ss.param_a.x;
1295    let f_sat = ss.param_a.y;
1296    let f_bri = ss.param_a.z;
1297    let pixel = ssTex(in.uv);
1298    var hsb = ss_rgb_to_hsb(pixel);
1299    hsb.x = hsb.x + f_hue;
1300    hsb.y = clamp(hsb.y + f_sat, 0.0, 1.0);
1301    hsb.z = clamp(hsb.z + f_bri, 0.0, 1.0);
1302    if (hsb.x < 0.0) { hsb.x = hsb.x + 1.0; }
1303    if (hsb.x > 1.0) { hsb.x = hsb.x - 1.0; }
1304    let shifted = ss_hsb_to_rgb(hsb);
1305    return ss_finish(vec4<f32>(shifted.rgb, shifted.a), in.color, in.varg, in.tint);
1306}
1307
1308@fragment
1309fn fs_ss_step(in: VertexOutput) -> @location(0) vec4<f32> {
1310    let f_threshold = ss.param_a.x;
1311    let f_stage = ss.param_a.y;
1312    let f_color = ss.param_a.z;
1313    let pixel = ssTex(in.uv);
1314    let d = 1.0 + 255.0 * abs(f_stage);
1315    let e = 1.0e-10;
1316    let t = abs(f_threshold);
1317    let b = abs(step(f_threshold, 0.0) - max(pixel.r, max(pixel.g, pixel.b)));
1318    let r = clamp(floor((b - t) / (t + e) * 256.0 / d) * d / 256.0, 0.0, 1.0);
1319    let c = step(t, b) * r;
1320    let v = mix(vec3<f32>(c), pixel.rgb * c, f_color);
1321    return ss_finish(vec4<f32>(v, pixel.a), in.color, in.varg, in.tint);
1322}
1323
1324@fragment
1325fn fs_ss_pix(in: VertexOutput) -> @location(0) vec4<f32> {
1326    let f_power = ss.param_a.x;
1327    let px = ss.pixel_size.xy;
1328    let v = 1.0 + 96.0 * f_power;
1329    let step_uv = vec2<f32>(v * px.x, v * px.y);
1330    let coord = floor(in.uv / step_uv) * step_uv;
1331    return ss_finish(ssTex(coord), in.color, in.varg, in.tint);
1332}
1333
1334@fragment
1335fn fs_ss_noise(in: VertexOutput) -> @location(0) vec4<f32> {
1336    let f_power = ss.param_a.x;
1337    let f_color = ss.param_a.y;
1338    let f_phase = ss.param_a.z;
1339    let px = ss.pixel_size.xy;
1340    let u = floor(in.uv / px) * px;
1341    let pixel = ssTex(in.uv);
1342    let t = u + vec2<f32>(f_phase);
1343    var c = vec3<f32>(0.0);
1344    c.r = ss_rand(t);
1345    c.g = mix(c.r, ss_rand(t * c.r), f_color);
1346    c.b = mix(c.g, ss_rand(t * c.g), f_color);
1347    let rgb = clamp(mix(pixel.rgb, c, f_power), vec3<f32>(0.0), vec3<f32>(1.0));
1348    return ss_finish(vec4<f32>(rgb, pixel.a), in.color, in.varg, in.tint);
1349}
1350
1351@fragment
1352fn fs_ss_bmask(in: VertexOutput) -> @location(0) vec4<f32> {
1353    let f_brightness = ss.param_a.x;
1354    let pixel = ssTex(in.uv);
1355    let b = abs(step(f_brightness, 0.0) - max(pixel.r, max(pixel.g, pixel.b)));
1356    if (b <= abs(f_brightness)) { discard; }
1357    return ss_finish(pixel, in.color, in.varg, in.tint);
1358}
1359
1360@fragment
1361fn fs_ss_outline(in: VertexOutput) -> @location(0) vec4<f32> {
1362    let f_ratio = abs(ss.param_a.x);
1363    let e = 1.0e-5;
1364    let px = ss.pixel_size.xy;
1365    var lo = 0.0;
1366    lo = lo + step(ssTex(in.uv + vec2<f32>(-px.x, 0.0)).a, f_ratio);
1367    lo = lo + step(ssTex(in.uv + vec2<f32>(px.x, 0.0)).a, f_ratio);
1368    lo = lo + step(ssTex(in.uv + vec2<f32>(0.0, -px.y)).a, f_ratio);
1369    lo = lo + step(ssTex(in.uv + vec2<f32>(0.0, px.y)).a, f_ratio);
1370    let center = ssTex(in.uv);
1371    let hi = step(f_ratio + e, center.a);
1372    let v = min(hi * lo, 1.0);
1373    if (v <= 0.0) { discard; }
1374    return ss_finish(vec4<f32>(vec3<f32>(v), v), in.color, in.varg, in.tint);
1375}
1376
1377@fragment
1378fn fs_ss_blur(in: VertexOutput) -> @location(0) vec4<f32> {
1379    let f_focus = ss.param_a.x;
1380    let px = ss.pixel_size.xy;
1381    let d = vec2<f32>(f_focus * px.x * 16.0, f_focus * px.y * 16.0);
1382    let tc = in.uv;
1383    var sum = ssTex(tc);
1384    sum = sum + ssTex(vec2<f32>(tc.x + d.x, tc.y + d.y));
1385    sum = sum + ssTex(vec2<f32>(tc.x + d.x, tc.y));
1386    sum = sum + ssTex(vec2<f32>(tc.x, tc.y + d.y));
1387    sum = sum + ssTex(vec2<f32>(tc.x - d.x, tc.y - d.y));
1388    sum = sum + ssTex(vec2<f32>(tc.x + d.x, tc.y - d.y));
1389    sum = sum + ssTex(vec2<f32>(tc.x - d.x, tc.y + d.y));
1390    sum = sum + ssTex(vec2<f32>(tc.x - d.x, tc.y));
1391    sum = sum + ssTex(vec2<f32>(tc.x, tc.y - d.y));
1392    let pixel = sum / 9.0;
1393    // ss-blur skips the PartColor composite: straight multiply by part colour.
1394    let c = pixel * in.color;
1395    return vec4<f32>(c.rgb * player_tint(in.tint) * c.a, c.a);
1396}
1397
1398@fragment
1399fn fs_ss_wave(in: VertexOutput) -> @location(0) vec4<f32> {
1400    let f_width = ss.param_a.x;
1401    let f_height = ss.param_a.y;
1402    let f_phase = ss.param_a.z;
1403    let coord = in.uv;
1404    let px = ss.pixel_size.xy;
1405    let l = 384.0 * f_height * 0.5;
1406    let s = l * sin(coord.y * 384.0 * f_width * 0.5 + PI * 2.0 * f_phase) * px.x;
1407    return ss_finish(ssTex(vec2<f32>(coord.x + s, coord.y)), in.color, in.varg, in.tint);
1408}
1409
1410@fragment
1411fn fs_ss_move(in: VertexOutput) -> @location(0) vec4<f32> {
1412    let f_distance = ss.param_a.x;
1413    let f_direction = ss.param_a.y;
1414    let f_power = ss.param_a.z;
1415    var coord = in.uv;
1416    let px = ss.pixel_size.xy;
1417    var i_count = i32(floor(abs(f_distance) * 96.0));
1418    if (i_count > 128) { i_count = 128; }
1419    let vel = vec2<f32>(sin(f_direction * PI) * px.x, cos(f_direction * PI) * px.y) * sign(f_distance);
1420    coord = coord + vel * f32(i_count);
1421    coord = coord - vel;
1422    var pixel = ssTex(coord);
1423    for (var i: i32 = 1; i < 128; i = i + 1) {
1424        if (i >= i_count) { break; }
1425        coord = coord - vel;
1426        pixel = mix(ssTex(coord), pixel, 0.96 * abs(f_power));
1427    }
1428    return ss_finish(pixel, in.color, in.varg, in.tint);
1429}
1430
1431@fragment
1432fn fs_ss_scatter(in: VertexOutput) -> @location(0) vec4<f32> {
1433    let f_power = ss.param_a.x;
1434    let f_ratio = ss.param_a.y;
1435    let f_phase = ss.param_a.z;
1436    let coord = in.uv;
1437    let px = ss.pixel_size.xy;
1438    let u = floor(coord / px) * px;
1439    let t = u + vec2<f32>(f_phase);
1440    let r = ss_rand(t) * PI * 2.0 - PI;
1441    let r2 = step(ss_rand(t * r), f_ratio);
1442    let v = vec2<f32>(sin(r), cos(r)) * px * 96.0 * f_power * r2;
1443    return ss_finish(ssTex(coord + v), in.color, in.varg, in.tint);
1444}
1445
1446@fragment
1447fn fs_ss_circle(in: VertexOutput) -> @location(0) vec4<f32> {
1448    let f_phase = ss.param_a.x;
1449    let f_direction = ss.param_a.y;
1450    let e = 1.0e-10;
1451    let px = ss.pixel_size.xy;
1452    let uv1 = vec2<f32>(px.x + e, px.y + e);
1453    let lt_uv = ss.cell_rect.xy;
1454    let rb_uv = ss.cell_rect.zw;
1455    let center_uv = (lt_uv + rb_uv) * 0.5;
1456    let tx = in.uv / uv1;
1457    let c = center_uv / uv1;
1458    let lt = lt_uv / uv1;
1459    let rb = rb_uv / uv1;
1460    let dd = rb - lt;
1461    let v = tx - c;
1462    let r = min(abs(rb.x - c.x), abs(rb.y - c.y)) + e;
1463    let dis = length(v);
1464    if (dis > r) { discard; }
1465    let nv = select(vec2<f32>(1.0, 0.0), v / dis, dis > e);
1466    let uu = 1.0 - dis / r;
1467    var vv = (atan2(nv.y, nv.x) / PI + 1.0) * 0.5 + f_phase;
1468    if (vv < 0.0) { vv = vv + 1.0; }
1469    if (vv > 1.0) { vv = vv - 1.0; }
1470    if (f_direction <= 0.0) { vv = 1.0 - vv; }
1471    let st = dd * vec2<f32>(uu, vv) * uv1;
1472    return ss_finish(ssTex(lt_uv + st), in.color, in.varg, in.tint);
1473}
1474
1475@fragment
1476fn fs_ss_spot(in: VertexOutput) -> @location(0) vec4<f32> {
1477    let f_power = ss.param_a.x;
1478    let f_decay = ss.param_a.y;
1479    let f_color = ss.param_a.z;
1480    let e = 1.0e-10;
1481    let p = abs(f_power);
1482    let d_abs = abs(f_decay);
1483    let px = ss.pixel_size.xy;
1484    let uv1 = vec2<f32>(px.x + e, px.y + e);
1485    let lt_uv = ss.cell_rect.xy;
1486    let rb_uv = ss.cell_rect.zw;
1487    let center_uv = (lt_uv + rb_uv) * 0.5;
1488    let c = center_uv / uv1;
1489    let rb = rb_uv / uv1;
1490    let l = min(abs(rb.x - c.x), abs(rb.y - c.y)) + e;
1491    let t = in.uv / uv1;
1492    let v = c - t;
1493    var f_r = max(p / (length(v / l) + e) - p, 0.0);
1494    let f_l = max(p - length(v / l), 0.0);
1495    f_r = clamp(mix(f_r, f_l, d_abs), 0.0, 1.0);
1496    let sampled = ssTex(in.uv).rgb;
1497    let pixel = vec4<f32>(mix(vec3<f32>(1.0), sampled, f_color), f_r);
1498    return ss_finish(pixel, in.color, in.varg, in.tint);
1499}
1500"#;
1501
1502impl SSRenderer {
1503    /// Build the device-scoped resources. Cheap: no pipeline is compiled until a
1504    /// frame asks for one, so this is the shader modules, the bind group layouts,
1505    /// a sampler and a 1x1 texture.
1506    ///
1507    /// Takes no target formats — those ride in the pipeline key, which is what
1508    /// lets one renderer serve every target on the device.
1509    pub fn new(device: &wgpu::Device) -> Self {
1510        // WGSL source for a module is the shared vertex half plus its own
1511        // fragment half; naga sees one string either way.
1512        let sprite_wgsl = format!("{}{COMMON_WGSL}{COVERAGE_WGSL}{WGSL_SHADER}", wgsl_consts());
1513        let shader_module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("SpriteStudio Shader"), source: wgpu::ShaderSource::Wgsl(sprite_wgsl.into()) });
1514
1515        // group(0) is the scene: the projection, plus the frame's SoA
1516        // arena, primitive table and mesh stream — everything the vertex stages
1517        // read instead of a vertex buffer. Only the layout is shared; the
1518        // buffer behind it belongs to the render target. The three share one
1519        // buffer, the arena first, and the other two start wherever the frame's
1520        // arena ended: hence their dynamic offsets.
1521        let storage = |binding: u32, has_dynamic_offset: bool| wgpu::BindGroupLayoutEntry {
1522            binding,
1523            // The fragment stage reads the arena too: the coverage replay walks
1524            // the node's writer records there, per fragment.
1525            visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
1526            ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Storage { read_only: true }, has_dynamic_offset, min_binding_size: None },
1527            count: None,
1528        };
1529        let scene_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
1530            label: Some("SpriteStudio Scene Layout"),
1531            entries: &[
1532                wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStages::VERTEX, ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None }, count: None },
1533                storage(1, false),
1534                storage(2, true),
1535                storage(3, true),
1536            ],
1537        });
1538
1539        // group(1): atlas texture + sampler + the per-texture facts.
1540        // The uniform is visible to the vertex stage too, so UV normalisation can
1541        // move there without reshaping the layout.
1542        let texture_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
1543            label: Some("SpriteStudio Texture Bind Group Layout"),
1544            entries: &[
1545                wgpu::BindGroupLayoutEntry {
1546                    binding: 0,
1547                    visibility: wgpu::ShaderStages::FRAGMENT,
1548                    ty: wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Float { filterable: true }, view_dimension: wgpu::TextureViewDimension::D2, multisampled: false },
1549                    count: None,
1550                },
1551                wgpu::BindGroupLayoutEntry { binding: 1, visibility: wgpu::ShaderStages::FRAGMENT, ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), count: None },
1552                wgpu::BindGroupLayoutEntry {
1553                    binding: 2,
1554                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
1555                    ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: wgpu::BufferSize::new(std::mem::size_of::<TexInfo>() as u64) },
1556                    count: None,
1557                },
1558            ],
1559        });
1560
1561        let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
1562            address_mode_u: wgpu::AddressMode::ClampToEdge,
1563            address_mode_v: wgpu::AddressMode::ClampToEdge,
1564            mag_filter: wgpu::FilterMode::Linear,
1565            min_filter: wgpu::FilterMode::Linear,
1566            ..Default::default()
1567        });
1568
1569        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("SpriteStudio Pipeline Layout"), bind_group_layouts: &[Some(&scene_bind_group_layout), Some(&texture_bind_group_layout)], immediate_size: 0 });
1570
1571        // Coverage masking adds a third group holding the frame's bitmap array.
1572        // No sampler: the replay reads exact texels with `textureLoad`, because a
1573        // filtered read would blend neighbouring writers' bits into each other and
1574        // decode as coverage that nobody wrote.
1575        let coverage_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
1576            label: Some("SpriteStudio Coverage Layout"),
1577            entries: &[wgpu::BindGroupLayoutEntry {
1578                binding: 0,
1579                visibility: wgpu::ShaderStages::FRAGMENT,
1580                ty: wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Float { filterable: false }, view_dimension: wgpu::TextureViewDimension::D2Array, multisampled: false },
1581                count: None,
1582            }],
1583        });
1584        let coverage_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
1585            label: Some("SpriteStudio Coverage Pipeline Layout"),
1586            bind_group_layouts: &[Some(&scene_bind_group_layout), Some(&texture_bind_group_layout), Some(&coverage_bind_group_layout)],
1587            immediate_size: 0,
1588        });
1589
1590        // Integration-shader (`ss-*`) resources. The module is compiled
1591        // now; the pipelines are built lazily per key on first use.
1592        let ss_wgsl = format!("{}{COMMON_WGSL}{SS_SHADER_WGSL}", wgsl_consts());
1593        let ss_shader_module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("SpriteStudio SS Shaders"), source: wgpu::ShaderSource::Wgsl(ss_wgsl.into()) });
1594        let ss_params_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
1595            label: Some("SpriteStudio SS Params Layout"),
1596            entries: &[wgpu::BindGroupLayoutEntry {
1597                binding: 0,
1598                visibility: wgpu::ShaderStages::FRAGMENT,
1599                ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: true, min_binding_size: wgpu::BufferSize::new(64) },
1600                count: None,
1601            }],
1602        });
1603        let ss_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
1604            label: Some("SpriteStudio SS Pipeline Layout"),
1605            bind_group_layouts: &[Some(&scene_bind_group_layout), Some(&texture_bind_group_layout), Some(&ss_params_bind_group_layout)],
1606            immediate_size: 0,
1607        });
1608
1609        // 1x1 white fallback texture: used when a draw's texture hash
1610        // is missing and by textureless mask writers.
1611        let white_texture = device.create_texture(&wgpu::TextureDescriptor {
1612            label: Some("SpriteStudio White 1x1"),
1613            size: wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 },
1614            mip_level_count: 1,
1615            sample_count: 1,
1616            dimension: wgpu::TextureDimension::D2,
1617            format: wgpu::TextureFormat::Rgba8Unorm,
1618            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
1619            view_formats: &[],
1620        });
1621        let white_view = white_texture.create_view(&wgpu::TextureViewDescriptor::default());
1622        // Opaque white reads the same either way, so the mode is arbitrary; the
1623        // 1x1 size matters only to keep the reciprocals finite.
1624        let white_info = tex_info_buffer(device, TexInfo::new((1.0, 1.0), AlphaMode::Premultiplied));
1625        let white_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
1626            label: Some("SpriteStudio White Bind Group"),
1627            layout: &texture_bind_group_layout,
1628            entries: &[
1629                wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&white_view) },
1630                wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(&sampler) },
1631                wgpu::BindGroupEntry { binding: 2, resource: white_info.as_entire_binding() },
1632            ],
1633        });
1634
1635        Self {
1636            pipelines: KeyMap::default(),
1637            shader_module,
1638            pipeline_layout,
1639            ss_shader_module,
1640            ss_pipeline_layout,
1641            coverage_pipeline_layout,
1642            coverage_bind_group_layout,
1643            scene_bind_group_layout,
1644            texture_bind_group_layout,
1645            ss_params_bind_group_layout,
1646            sampler,
1647            white_texture,
1648            white_bind_group,
1649            white_ready: false,
1650            textures: KeyMap::default(),
1651            texture_sources: HashMap::new(),
1652            texture_digests: HashMap::new(),
1653            texture_uploads: 0,
1654            texture_changes: 0,
1655        }
1656    }
1657
1658    /// How many pipelines have been compiled so far — that is, how many distinct
1659    /// combinations the animation has actually asked for.
1660    pub fn pipeline_count(&self) -> usize {
1661        self.pipelines.len()
1662    }
1663
1664    /// Compile `key`'s pipeline if this is the first frame that needs it. A
1665    /// [`PipelineKind::Shader`] whose id is not a built-in `ss-*` shader stays
1666    /// absent; [`Self::draw`] skips draws whose pipeline is missing.
1667    pub(crate) fn ensure_pipeline(&mut self, device: &wgpu::Device, key: PipelineKey) {
1668        if self.pipelines.contains_key(&key) {
1669            return;
1670        }
1671        if let Some(pipeline) = self.build_pipeline(device, key) {
1672            self.pipelines.insert(key, pipeline);
1673        }
1674    }
1675    /// Build one pipeline. Everything that varies between them — module, fragment
1676    /// entry, blend, colour write mask, depth/stencil state — is chosen here; the
1677    /// vertex layout and primitive state are shared by all of them.
1678    fn build_pipeline(&self, device: &wgpu::Device, key: PipelineKey) -> Option<wgpu::RenderPipeline> {
1679        struct Recipe<'a> {
1680            label: String,
1681            module: &'a wgpu::ShaderModule,
1682            layout: &'a wgpu::PipelineLayout,
1683            /// Vertex entry: which geometry class expands this draw.
1684            vertex_entry: &'static str,
1685            entry: &'a str,
1686            blend: Option<wgpu::BlendState>,
1687            write_mask: wgpu::ColorWrites,
1688            depth_stencil: Option<wgpu::DepthStencilState>,
1689            /// Usually the target's own format; the coverage bitmap is its own
1690            /// target and so brings its own.
1691            color_format: wgpu::TextureFormat,
1692        }
1693        let blend_of = |idx: usize| BLEND_ORDER[idx.min(BLEND_ORDER.len() - 1)];
1694
1695        let recipe = match key.kind {
1696            PipelineKind::Content(blend_idx, stencil, class) => {
1697                let blend = blend_of(blend_idx);
1698                Recipe {
1699                    label: format!("Content {} {stencil:?} {class:?}", blend.variant_name().unwrap_or("Blend")),
1700                    module: &self.shader_module,
1701                    layout: &self.pipeline_layout,
1702                    vertex_entry: class.entry(),
1703                    entry: "fs_main",
1704                    blend: Some(blend_state(blend)),
1705                    write_mask: wgpu::ColorWrites::ALL,
1706                    // Content tests coverage; it never writes it.
1707                    depth_stencil: depth_stencil_state(key.stencil_format, stencil_compare(stencil), wgpu::StencilOperation::Keep, 0x00),
1708                    color_format: key.color_format,
1709                }
1710            }
1711            PipelineKind::Mask(op, class) => Recipe {
1712                label: format!("Mask Write {op:?} {class:?}"),
1713                module: &self.shader_module,
1714                layout: &self.pipeline_layout,
1715                vertex_entry: class.entry(),
1716                entry: "fs_mask",
1717                blend: None,
1718                // Coverage only — the fragment's colour is thrown away.
1719                write_mask: wgpu::ColorWrites::empty(),
1720                depth_stencil: depth_stencil_state(key.stencil_format, wgpu::CompareFunction::Always, stencil_write_op(op), stencil_write_plane(op)),
1721                color_format: key.color_format,
1722            },
1723            PipelineKind::ContentCoverage(blend_idx, stencil, class) => {
1724                let blend = blend_of(blend_idx);
1725                Recipe {
1726                    label: format!("Content Coverage {} {stencil:?} {class:?}", blend.variant_name().unwrap_or("Blend")),
1727                    module: &self.shader_module,
1728                    layout: &self.coverage_pipeline_layout,
1729                    vertex_entry: class.entry(),
1730                    entry: "fs_main_coverage",
1731                    blend: Some(blend_state(blend)),
1732                    write_mask: wgpu::ColorWrites::ALL,
1733                    // The clip happens in the fragment stage, so the stencil is
1734                    // inert even where the host happens to have attached one.
1735                    depth_stencil: depth_stencil_state(key.stencil_format, wgpu::CompareFunction::Always, wgpu::StencilOperation::Keep, 0x00),
1736                    color_format: key.color_format,
1737                }
1738            }
1739            PipelineKind::Coverage(class) => Recipe {
1740                label: format!("Coverage Write {class:?}"),
1741                module: &self.shader_module,
1742                layout: &self.pipeline_layout,
1743                vertex_entry: class.coverage_entry(),
1744                entry: "fs_coverage",
1745                // Additive, so writers whose bits are disjoint OR together into
1746                // one bitmap however they overlap.
1747                blend: Some(wgpu::BlendState {
1748                    color: wgpu::BlendComponent { src_factor: wgpu::BlendFactor::One, dst_factor: wgpu::BlendFactor::One, operation: wgpu::BlendOperation::Add },
1749                    alpha: wgpu::BlendComponent { src_factor: wgpu::BlendFactor::One, dst_factor: wgpu::BlendFactor::One, operation: wgpu::BlendOperation::Add },
1750                }),
1751                write_mask: wgpu::ColorWrites::ALL,
1752                // The bitmap has no depth-stencil of its own; the whole point of
1753                // this backend is not needing one.
1754                depth_stencil: None,
1755                color_format: COVERAGE_FORMAT,
1756            },
1757            PipelineKind::Shader(id_hash, blend_idx) => {
1758                let entry = ss_shader_entry(id_hash)?;
1759                Recipe {
1760                    label: format!("SS Shader {entry}"),
1761                    module: &self.ss_shader_module,
1762                    layout: &self.ss_pipeline_layout,
1763                    // SHDR is a Normal-part attribute, so shader draws are quads.
1764                    vertex_entry: GeomClass::Quad.entry(),
1765                    entry,
1766                    blend: Some(blend_state(blend_of(blend_idx))),
1767                    write_mask: wgpu::ColorWrites::ALL,
1768                    // Shader parts are never masked, so the stencil is inert.
1769                    depth_stencil: depth_stencil_state(key.stencil_format, wgpu::CompareFunction::Always, wgpu::StencilOperation::Keep, 0x00),
1770                    color_format: key.color_format,
1771                }
1772            }
1773            PipelineKind::Composite => Recipe {
1774                label: "Group Alpha Composite".into(),
1775                module: &self.shader_module,
1776                layout: &self.coverage_pipeline_layout,
1777                vertex_entry: "vs_composite",
1778                entry: "fs_composite",
1779                blend: Some(blend_state(BlendType::Mix)),
1780                write_mask: wgpu::ColorWrites::ALL,
1781                // The layer was clipped when it was drawn; here the stencil is
1782                // inert, matched to whatever the host attached.
1783                depth_stencil: depth_stencil_state(key.stencil_format, wgpu::CompareFunction::Always, wgpu::StencilOperation::Keep, 0x00),
1784                color_format: key.color_format,
1785            },
1786        };
1787
1788        Some(device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
1789            label: Some(&recipe.label),
1790            layout: Some(recipe.layout),
1791            // No vertex buffers: every attribute is read from the scene's storage
1792            // buffers by `vertex_index` arithmetic.
1793            vertex: wgpu::VertexState { module: recipe.module, entry_point: Some(recipe.vertex_entry), buffers: &[], compilation_options: Default::default() },
1794            fragment: Some(wgpu::FragmentState {
1795                module: recipe.module,
1796                entry_point: Some(recipe.entry),
1797                targets: &[Some(wgpu::ColorTargetState { format: recipe.color_format, blend: recipe.blend, write_mask: recipe.write_mask })],
1798                compilation_options: Default::default(),
1799            }),
1800            primitive: wgpu::PrimitiveState {
1801                topology: wgpu::PrimitiveTopology::TriangleList,
1802                strip_index_format: None,
1803                front_face: wgpu::FrontFace::Ccw,
1804                cull_mode: None,
1805                polygon_mode: wgpu::PolygonMode::Fill,
1806                unclipped_depth: false,
1807                conservative: false,
1808            },
1809            depth_stencil: recipe.depth_stencil,
1810            multisample: wgpu::MultisampleState::default(),
1811            multiview_mask: None,
1812            cache: None,
1813        }))
1814    }
1815    /// A bind group over one frame's coverage array.
1816    ///
1817    /// The layout is the renderer's (device-scoped, like every other layout); the
1818    /// array itself belongs to the scene that allocated it, which is why this
1819    /// builds a group rather than storing one.
1820    pub(crate) fn coverage_bind_group(&self, device: &wgpu::Device, array_view: &wgpu::TextureView) -> wgpu::BindGroup {
1821        device.create_bind_group(&wgpu::BindGroupDescriptor {
1822            label: Some("SpriteStudio Coverage Bind Group"),
1823            layout: &self.coverage_bind_group_layout,
1824            entries: &[wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(array_view) }],
1825        })
1826    }
1827
1828    /// Register a texture the **supplier** owns: the renderer builds a
1829    /// bind group around `view` and nothing else.
1830    ///
1831    /// This is the channel an engine integration uses. Bevy hands over the
1832    /// `GpuImage`'s view for its `Handle<Image>`, keeps the lifecycle it already
1833    /// has (hot reload, unload, format and mip policy), and no atlas is uploaded
1834    /// twice. `alpha` says which form the pixels are in — engine textures are
1835    /// normally [`AlphaMode::Straight`], ours are premultiplied — and costs no
1836    /// pipeline, because it rides in the texture's own bind group.
1837    ///
1838    /// wgpu's handles are refcounted internally, so the clone kept here cannot
1839    /// dangle; it does hold the texture alive, so a supplier that has finished
1840    /// with a hash calls [`SSRenderer::forget_texture`].
1841    ///
1842    /// Device loss is the supplier's to repair on this path: the
1843    /// renderer keeps no pixels it could rebuild from, so after
1844    /// [`SSRenderer::restore_device`] the supplier re-creates its texture and
1845    /// calls this again. Taking over a hash that was previously uploaded drops the
1846    /// retained copy, so the two paths cannot both claim to own one entry.
1847    pub fn set_texture(&mut self, device: &wgpu::Device, hash: u32, view: &wgpu::TextureView, (width, height): (u32, u32), alpha: AlphaMode) {
1848        self.texture_sources.remove(&hash);
1849        let size = (width as f32, height as f32);
1850        let info = tex_info_buffer(device, TexInfo::new(size, alpha));
1851        let bind_group = self.create_texture_bind_group(device, view, &info);
1852        self.texture_digests.remove(&hash);
1853        self.textures.insert(hash, TextureEntry { bind_group, size, _info_buffer: info, alpha });
1854        self.texture_changes += 1;
1855    }
1856
1857    /// Drop a texture registration (and any retained pixels for it).
1858    ///
1859    /// The counterpart of [`SSRenderer::set_texture`]: until this is called the
1860    /// renderer's clone of the view keeps the supplier's texture alive, which for
1861    /// an engine means an unload that does not actually free anything. Draws that
1862    /// still reference `hash` fall back to the 1x1 white texture.
1863    pub fn forget_texture(&mut self, hash: u32) {
1864        self.texture_changes += 1;
1865        self.textures.remove(&hash);
1866        self.texture_sources.remove(&hash);
1867        self.texture_digests.remove(&hash);
1868    }
1869
1870    /// Which form [`SSRenderer::set_texture`] / [`SSRenderer::upload_texture`]
1871    /// registered `hash` in, or `None` if it is not registered.
1872    pub fn texture_alpha_mode(&self, hash: u32) -> Option<AlphaMode> {
1873        self.textures.get(&hash).map(|t| t.alpha)
1874    }
1875
1876    /// Provide a texture the **renderer** creates. `hash` is the key the player
1877    /// draws the image under: [`crate::SSPlayer::texture_key`]'s answer for a
1878    /// pack's atlas, or the key an override returned. This is the convenience path used by the
1879    /// viewer, the web host and the C API; an engine integration wants
1880    /// [`SSRenderer::set_texture`] instead.
1881    ///
1882    /// `rgba` is straight-alpha (as decoded from PNG); it is premultiplied here so
1883    /// the whole pipeline stays premultiplied (matching WebGL's
1884    /// `UNPACK_PREMULTIPLY_ALPHA_WEBGL`). The premul shader recovers straight RGB
1885    /// before applying PartsColor.
1886    ///
1887    /// This copies `rgba` so it can premultiply without touching the caller's
1888    /// buffer. A caller that can give the buffer up — anything that just decoded it
1889    /// — wants [`SSRenderer::upload_texture_owned`] instead, which premultiplies in
1890    /// place and copies nothing.
1891    ///
1892    /// A texture the device cannot hold — empty, wider or taller than its
1893    /// `max_texture_dimension_2d`, or with `rgba` not `width * height * 4` bytes —
1894    /// is not uploaded, and whatever `hash` held before stays: it is reported on
1895    /// stderr instead of becoming a wgpu validation error, whose default handler
1896    /// panics.
1897    pub fn upload_texture(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, hash: u32, rgba: &[u8], (width, height): (u32, u32), retention: Retention) {
1898        self.upload_texture_owned(device, queue, hash, rgba.to_vec(), (width, height), retention);
1899    }
1900
1901    /// [`SSRenderer::upload_texture`], taking the pixels rather than borrowing them.
1902    ///
1903    /// The whole point is that no full-size copy happens: `rgba` is premultiplied in
1904    /// place, written to the texture, and — for [`Retention::Retain`] — retained as
1905    /// itself. A 4096² atlas is 64 MB, so the copy the borrowing form makes is
1906    /// worth a second entry point.
1907    pub fn upload_texture_owned(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, hash: u32, mut rgba: Vec<u8>, (width, height): (u32, u32), retention: Retention) {
1908        premultiply(&mut rgba);
1909        // No digest: a host owns what it uploads, and a load walk that meets
1910        // this key leaves it alone rather than claiming to know better.
1911        self.register_premultiplied(device, queue, hash, rgba, (width, height), Provenance { retention, digest: None });
1912    }
1913
1914    /// [`SSRenderer::upload_texture_owned`] for pixels that are premultiplied
1915    /// already — what the loading path hands over, having premultiplied off the
1916    /// host's thread while it was decoding.
1917    pub(crate) fn register_premultiplied(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, hash: u32, premul: Vec<u8>, (width, height): (u32, u32), how: Provenance) {
1918        if !self.write_and_register(device, queue, hash, &premul, (width, height)) {
1919            return;
1920        }
1921        match how.digest {
1922            Some(digest) => self.texture_digests.insert(hash, digest),
1923            None => self.texture_digests.remove(&hash),
1924        };
1925        if how.retention == Retention::Retain {
1926            self.texture_sources.insert(hash, (premul, width, height));
1927        }
1928    }
1929
1930    /// What the bytes behind a player-loaded atlas hashed to, or `None` when this
1931    /// key holds nothing or holds something a host registered.
1932    ///
1933    /// The load walk asks so it can tell "somebody already uploaded exactly this"
1934    /// from "this key holds a different picture now" — see `texture_digests`.
1935    pub fn texture_digest(&self, hash: u32) -> Option<u32> {
1936        self.texture_digests.get(&hash).copied()
1937    }
1938
1939    /// Create the texture, write `premul` into it and register the bind group.
1940    /// Returns whether it did.
1941    ///
1942    /// Everything that varies between the upload paths (premultiplying, retaining)
1943    /// has happened by the time this runs, so this is the only part that needs the
1944    /// device and the queue — and the only part a device-loss restore has to repeat.
1945    fn write_and_register(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, hash: u32, premul: &[u8], (width, height): (u32, u32)) -> bool {
1946        // Every texture this renderer creates comes through here, so this is where
1947        // one the device cannot hold stops. wgpu would report it as a validation
1948        // error, whose default handler panics — and the C and JavaScript faces own
1949        // their device, so it would take the host process, or every player on the
1950        // page, down with it. The faces refuse such a texture where the host hands it
1951        // over; what reaches this point came out of a pack, or a device restored
1952        // with smaller limits than the one it replaced.
1953        let why = texture_extent_error(device, (width, height)).or_else(|| (premul.len() != (width as usize) * (height as usize) * 4).then(|| format!("{} bytes do not fill a {width}x{height} RGBA8 texture", premul.len())));
1954        if let Some(why) = why {
1955            eprintln!("[ssplayer-wgpu] the texture for {hash:#010x} is not uploaded: {why}");
1956            return false;
1957        }
1958        self.texture_uploads += 1;
1959        let size = wgpu::Extent3d { width, height, depth_or_array_layers: 1 };
1960
1961        let texture = device.create_texture(&wgpu::TextureDescriptor {
1962            label: Some("SpriteStudio Texture"),
1963            size,
1964            mip_level_count: 1,
1965            sample_count: 1,
1966            dimension: wgpu::TextureDimension::D2,
1967            format: wgpu::TextureFormat::Rgba8Unorm,
1968            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
1969            view_formats: &[],
1970        });
1971
1972        queue.write_texture(
1973            wgpu::TexelCopyTextureInfo { texture: &texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
1974            premul,
1975            wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(4 * width), rows_per_image: Some(height) },
1976            size,
1977        );
1978
1979        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
1980        let size = (width as f32, height as f32);
1981        let info = tex_info_buffer(device, TexInfo::new(size, AlphaMode::Premultiplied));
1982        let bind_group = self.create_texture_bind_group(device, &view, &info);
1983        self.textures.insert(hash, TextureEntry { bind_group, size, _info_buffer: info, alpha: AlphaMode::Premultiplied });
1984        self.texture_changes += 1;
1985        true
1986    }
1987    fn create_texture_bind_group(&self, device: &wgpu::Device, view: &wgpu::TextureView, info: &wgpu::Buffer) -> wgpu::BindGroup {
1988        device.create_bind_group(&wgpu::BindGroupDescriptor {
1989            label: Some("SpriteStudio Texture Bind Group"),
1990            layout: &self.texture_bind_group_layout,
1991            entries: &[
1992                wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(view) },
1993                wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(&self.sampler) },
1994                wgpu::BindGroupEntry { binding: 2, resource: info.as_entire_binding() },
1995            ],
1996        })
1997    }
1998    /// Pixel size of a registered atlas, for normalising the runtime's UVs (which
1999    /// arrive in texture pixel space).
2000    pub fn texture_size(&self, hash: u32) -> Option<(f32, f32)> {
2001        self.textures.get(&hash).map(|t| t.size)
2002    }
2003
2004    /// How many distinct texture hashes are registered.
2005    pub fn texture_count(&self) -> usize {
2006        self.textures.len()
2007    }
2008
2009    /// How many textures [`SSRenderer::upload_texture`] has created since this
2010    /// renderer was built (device restores included).
2011    ///
2012    /// A diagnostic, and the only way to tell "N players of one pack uploaded the
2013    /// atlas once between them" from "they each uploaded it over the last one" —
2014    /// [`SSRenderer::texture_count`] reads the same either way.
2015    pub fn texture_upload_count(&self) -> usize {
2016        self.texture_uploads
2017    }
2018
2019    /// See `texture_changes`.
2020    pub(crate) fn texture_changes(&self) -> u64 {
2021        self.texture_changes
2022    }
2023
2024    /// The bind group for `hash`, or the 1x1 white fallback when it is missing
2025    /// — Shape content and textureless mask writers rely on this.
2026    pub(crate) fn texture_bind_group(&self, hash: u32) -> &wgpu::BindGroup {
2027        self.textures.get(&hash).map(|e| &e.bind_group).unwrap_or(&self.white_bind_group)
2028    }
2029
2030    /// The 1x1 white fallback's bind group, for a draw that samples no atlas but
2031    /// whose layout still has a texture group to fill.
2032    pub(crate) fn white_bind_group(&self) -> &wgpu::BindGroup {
2033        &self.white_bind_group
2034    }
2035
2036    /// Fill the white fallback. Deferred to the first frame because the
2037    /// constructor has no `Queue`; a `create_texture` alone leaves it
2038    /// transparent black, which would collapse `tex * colour` to zero.
2039    pub(crate) fn ensure_white(&mut self, queue: &wgpu::Queue) {
2040        if self.white_ready {
2041            return;
2042        }
2043        queue.write_texture(
2044            wgpu::TexelCopyTextureInfo { texture: &self.white_texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
2045            &[255u8, 255, 255, 255],
2046            wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(4), rows_per_image: Some(1) },
2047            wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 },
2048        );
2049        self.white_ready = true;
2050    }
2051
2052    /// Drop the retained copies of [`Retention::Retain`] uploads.
2053    /// Saves the duplicated pixels when the host keeps its own and would rather
2054    /// re-supply them itself; after this, [`SSRenderer::restore_device`] restores
2055    /// nothing and every texture must be uploaded again before drawing.
2056    pub fn forget_texture_sources(&mut self) {
2057        self.texture_sources.clear();
2058    }
2059
2060    /// Rebuild every GPU resource against a freshly created `device` after the
2061    /// previous one was lost.
2062    ///
2063    /// Because this is device-scoped, **one call covers every scene and player on
2064    /// the device**.
2065    ///
2066    /// Textures uploaded with [`Retention::Retain`] come back from their retained
2067    /// pixels. [`Retention::Reproducible`] ones do not: their supplier re-registers
2068    /// them (for embedded packs that is `SSPlayer::restore_textures`, which
2069    /// re-decodes from the `.ssab` it already owns). Anything holding a
2070    /// target-scoped resource — the projection buffer — restores itself.
2071    pub fn restore_device(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) {
2072        // Lift the sources out *before* replacing self — everything else in here
2073        // belonged to the dead device, but these are plain CPU pixels.
2074        let sources = std::mem::take(&mut self.texture_sources);
2075        // Kept with the retained pixels they describe, so a load after the loss
2076        // still tells a re-exported atlas from the one already on the GPU. A
2077        // reproducible texture gets its digest back when the player re-offers it.
2078        let digests = std::mem::take(&mut self.texture_digests);
2079        let (uploads, changes) = (self.texture_uploads, self.texture_changes);
2080        *self = Self::new(device);
2081        self.texture_uploads = uploads;
2082        self.texture_changes = changes + 1;
2083        for (hash, (premul, w, h)) in &sources {
2084            // Straight back out to the new device: these were retained *after*
2085            // premultiplying, so putting them through it again would darken every
2086            // partially transparent texel a second time.
2087            // One the new device cannot hold is left out, and drawn as missing.
2088            if self.write_and_register(device, queue, *hash, premul, (*w, *h))
2089                && let Some(&digest) = digests.get(hash)
2090            {
2091                self.texture_digests.insert(*hash, digest);
2092            }
2093        }
2094        self.texture_sources = sources;
2095    }
2096}
2097
2098/// Why `device` cannot hold a `width` x `height` texture, or `None` when it can.
2099///
2100/// The one check behind every face: the renderer runs it on each texture it
2101/// creates, and the C and JavaScript faces run it on what a host hands over, so
2102/// they can refuse it with an error the host sees rather than one on stderr.
2103pub(crate) fn texture_extent_error(device: &wgpu::Device, (width, height): (u32, u32)) -> Option<String> {
2104    let max = device.limits().max_texture_dimension_2d;
2105    if width == 0 || height == 0 {
2106        Some(format!("a {width}x{height} texture is empty"))
2107    } else if width > max || height > max {
2108        Some(format!("a {width}x{height} texture is past this device's {max}-pixel limit"))
2109    } else {
2110        None
2111    }
2112}
2113
2114/// Premultiply straight-alpha RGBA in place (rgb *= a/255, rounded).
2115///
2116/// The rounding is `(c * a + 127) / 255` and not something cheaper: it is what the
2117/// WebGL player's `UNPACK_PREMULTIPLY_ALPHA_WEBGL` produces, and the fixtures that
2118/// compare an uploaded atlas against a host-premultiplied one are byte-for-byte.
2119pub(crate) fn premultiply(rgba: &mut [u8]) {
2120    for px in rgba.as_chunks_mut::<4>().0 {
2121        let a = px[3] as u32;
2122        px[0] = ((px[0] as u32 * a + 127) / 255) as u8;
2123        px[1] = ((px[1] as u32 * a + 127) / 255) as u8;
2124        px[2] = ((px[2] as u32 * a + 127) / 255) as u8;
2125    }
2126}
2127
2128/// A write-once uniform holding one texture's [`TexInfo`].
2129///
2130/// Mapped at creation rather than written through a `Queue`, because
2131/// [`SSRenderer::new`] builds the white fallback's copy and the borrow model does
2132/// not lend it a queue that early.
2133fn tex_info_buffer(device: &wgpu::Device, info: TexInfo) -> wgpu::Buffer {
2134    let buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some("SpriteStudio Texture Info"), size: std::mem::size_of::<TexInfo>() as u64, usage: wgpu::BufferUsages::UNIFORM, mapped_at_creation: true });
2135    buffer.slice(..).get_mapped_range_mut().expect("a buffer created mapped, viewed once").copy_from_slice(bytemuck::bytes_of(&info));
2136    buffer.unmap();
2137    buffer
2138}