1use crate::mask::{MaskOp, StencilTest};
10use std::collections::HashMap;
11use std::hash::{BuildHasherDefault, Hasher};
12
13use ssruntime::runtime::framedata::ss::runtime::BlendType;
14
15#[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
64type KeyMap<K, V> = HashMap<K, V, BuildHasherDefault<KeyHasher>>;
66
67#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
74pub(crate) enum GeomClass {
75 Quad,
80 Mesh,
84 Shape,
87 Effect,
90}
91
92impl GeomClass {
93 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 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 GeomClass::Effect => "vs_cov_quad",
115 }
116 }
117}
118
119fn 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
145pub(crate) const COVERAGE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;
149
150pub(crate) const QUAD_FAN_VERTS: u32 = 12;
157
158pub(crate) const SHAPE_FAN_VERTS: u32 = 30;
166
167pub(crate) const MESH_PRIM_SHIFT: u32 = 24;
176
177pub(crate) const MESH_DRAW_PRIMS: u32 = 1 << (32 - MESH_PRIM_SHIFT);
180
181pub(crate) const CROWD_SHIFT: u32 = 12;
191
192pub(crate) const MESH_FIRST_PRIMS: u32 = 1 << (32 - CROWD_SHIFT);
195
196#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
198pub(crate) enum PipelineKind {
199 Content(usize, StencilTest, GeomClass),
202 Mask(MaskOp, GeomClass),
205 ContentCoverage(usize, StencilTest, GeomClass),
210 Coverage(GeomClass),
217 Shader(u32, usize),
221 Composite,
225}
226
227#[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 _info_buffer: wgpu::Buffer,
251 alpha: AlphaMode,
252}
253
254#[derive(Clone, Copy, Debug, PartialEq, Eq)]
266pub enum AlphaMode {
267 Premultiplied,
270 Straight,
273}
274
275#[repr(C)]
282#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
283struct TexInfo {
284 size: [f32; 4],
286 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
297pub struct SSRenderer {
309 pub(crate) pipelines: KeyMap<PipelineKey, wgpu::RenderPipeline>,
311 shader_module: wgpu::ShaderModule,
313 pipeline_layout: wgpu::PipelineLayout,
314 ss_shader_module: wgpu::ShaderModule,
317 ss_pipeline_layout: wgpu::PipelineLayout,
319 coverage_pipeline_layout: wgpu::PipelineLayout,
321 coverage_bind_group_layout: wgpu::BindGroupLayout,
324
325 pub(crate) scene_bind_group_layout: wgpu::BindGroupLayout,
330 texture_bind_group_layout: wgpu::BindGroupLayout,
332 pub(crate) ss_params_bind_group_layout: wgpu::BindGroupLayout,
334
335 sampler: wgpu::Sampler,
336 white_texture: wgpu::Texture,
340 white_bind_group: wgpu::BindGroup,
341 white_ready: bool,
342
343 textures: KeyMap<u32, TextureEntry>,
346 texture_sources: HashMap<u32, (Vec<u8>, u32, u32)>,
355 texture_digests: HashMap<u32, u32>,
369 texture_uploads: usize,
374 texture_changes: u64,
379}
380
381pub(crate) struct Provenance {
384 pub retention: Retention,
386 pub digest: Option<u32>,
390}
391
392#[derive(Clone, Copy, Debug, PartialEq, Eq)]
395pub enum Retention {
396 Retain,
398 Reproducible,
402}
403
404const 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
409pub(crate) fn blend_index(blend: BlendType) -> usize {
412 (blend.0 as usize).min(BLEND_ORDER.len() - 1)
413}
414
415fn 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 _ => (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
436fn 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
445const STENCIL_PLANE_COUNTER: u32 = 0x7F;
459const STENCIL_PLANE_PARITY: u32 = 0x80;
460
461fn 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
473fn 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
481fn 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
486fn 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
500const 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
921const 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
1187pub(crate) const SHADER_PARAM_STRIDE: usize = 256;
1192pub(crate) const SHADER_PARAM_STRIDE_F32: usize = SHADER_PARAM_STRIDE / 4;
1194
1195const 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
1214pub(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
1220const 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 pub fn new(device: &wgpu::Device) -> Self {
1510 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 let storage = |binding: u32, has_dynamic_offset: bool| wgpu::BindGroupLayoutEntry {
1522 binding,
1523 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 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 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 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 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 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 pub fn pipeline_count(&self) -> usize {
1661 self.pipelines.len()
1662 }
1663
1664 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 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: &'static str,
1685 entry: &'a str,
1686 blend: Option<wgpu::BlendState>,
1687 write_mask: wgpu::ColorWrites,
1688 depth_stencil: Option<wgpu::DepthStencilState>,
1689 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 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 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 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 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 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 vertex_entry: GeomClass::Quad.entry(),
1765 entry,
1766 blend: Some(blend_state(blend_of(blend_idx))),
1767 write_mask: wgpu::ColorWrites::ALL,
1768 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 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 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 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 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 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 pub fn texture_alpha_mode(&self, hash: u32) -> Option<AlphaMode> {
1873 self.textures.get(&hash).map(|t| t.alpha)
1874 }
1875
1876 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 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 self.register_premultiplied(device, queue, hash, rgba, (width, height), Provenance { retention, digest: None });
1912 }
1913
1914 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 pub fn texture_digest(&self, hash: u32) -> Option<u32> {
1936 self.texture_digests.get(&hash).copied()
1937 }
1938
1939 fn write_and_register(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, hash: u32, premul: &[u8], (width, height): (u32, u32)) -> bool {
1946 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 pub fn texture_size(&self, hash: u32) -> Option<(f32, f32)> {
2001 self.textures.get(&hash).map(|t| t.size)
2002 }
2003
2004 pub fn texture_count(&self) -> usize {
2006 self.textures.len()
2007 }
2008
2009 pub fn texture_upload_count(&self) -> usize {
2016 self.texture_uploads
2017 }
2018
2019 pub(crate) fn texture_changes(&self) -> u64 {
2021 self.texture_changes
2022 }
2023
2024 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 pub(crate) fn white_bind_group(&self) -> &wgpu::BindGroup {
2033 &self.white_bind_group
2034 }
2035
2036 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 pub fn forget_texture_sources(&mut self) {
2057 self.texture_sources.clear();
2058 }
2059
2060 pub fn restore_device(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) {
2072 let sources = std::mem::take(&mut self.texture_sources);
2075 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 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
2098pub(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
2114pub(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
2128fn 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}