1use std::collections::HashMap;
13use wgpu::util::DeviceExt;
14
15pub const SPRITE_MODES: usize = 11;
17
18#[derive(Clone, Copy, Debug, PartialEq)]
20pub struct SpriteVertex {
21 pub pos: [f32; 2],
24 pub uv: [f32; 2],
26}
27
28#[derive(Clone, Debug)]
30pub struct SpriteDraw {
31 pub layer: u8,
35 pub image: u32,
37 pub frame: usize,
39 pub blend: i32,
41 pub rgba: [f32; 4],
44 pub quad: [SpriteVertex; 4],
46 pub burn: bool,
50}
51
52pub fn sprite_mode(blend: i32) -> usize {
54 if (0..SPRITE_MODES as i32).contains(&blend) {
55 blend as usize
56 } else {
57 0
58 }
59}
60
61fn q8(x: f32) -> u8 {
63 ((x * 255.0) as i32 & 0xFF) as u8
64}
65
66pub fn sprite_vertex_color(mode: usize, rgba: [f32; 4]) -> [u8; 4] {
71 let [r, g, b, a] = rgba;
72 match mode {
73 1 | 2 => [q8(r * a), q8(g * a), q8(b * a), 255],
74 3 => [255; 4],
75 7 => [255, 255, 255, q8(a)],
76 8 => {
77 let f = |c: f32| if c > 0.5 { 1.0 - c } else { c };
78 [q8(f(r)), q8(f(g)), q8(f(b)), q8(a)]
79 }
80 _ => [q8(r), q8(g), q8(b), q8(a)],
81 }
82}
83
84pub fn sprite_blend_reference(
88 mode: usize,
89 rgba: [f32; 4],
90 texel: [u8; 4],
91 dst: [u8; 3],
92) -> [f32; 3] {
93 let v = sprite_vertex_color(mode, rgba).map(|c| f32::from(c) / 255.0);
94 let t = texel.map(|c| f32::from(c) / 255.0);
95 let d = dst.map(|c| f32::from(c) / 255.0);
96 let sat = |x: f32| x.clamp(0.0, 1.0);
97 let a = match mode {
99 4 | 7 | 8 => v[3] * t[3],
100 _ => v[3],
101 };
102 let mut c = [0.0f32; 3];
103 for i in 0..3 {
104 c[i] = match mode {
105 3 => t[i],
106 7 => sat(1.0 - t[i]),
107 9 => sat(t[i] + v[i] - 0.5),
108 10 => sat(2.0 * t[i] * v[i]),
109 _ => v[i] * t[i],
110 };
111 }
112 let mut out = [0.0f32; 3];
113 for i in 0..3 {
114 let (s, dd) = match mode {
116 1 => (1.0, 0.0), 2 | 10 => (1.0, 1.0),
118 3 => (c[i], 1.0 - c[i]),
119 5 => (d[i], 0.0),
120 6 => (0.0, 1.0 - c[i]),
121 9 => (0.0, c[i]),
122 _ => (a, 1.0 - a),
123 };
124 out[i] = sat(c[i] * s + d[i] * dd) * 255.0;
125 }
126 out
127}
128
129pub fn gif_frame_index(delays: &[f64], time: f64) -> usize {
133 let total: f64 = delays.iter().sum();
134 if delays.len() < 2 || total.partial_cmp(&0.0) != Some(std::cmp::Ordering::Greater) {
135 return 0;
136 }
137 let t = time % total;
138 let mut acc = 0.0;
139 for (i, d) in delays.iter().enumerate() {
140 acc += d;
141 if acc > t {
142 return i;
143 }
144 }
145 delays.len() - 1
146}
147
148pub(crate) struct SpriteImage {
150 pub(crate) frames: Vec<wgpu::TextureView>,
152}
153
154#[repr(C)]
156#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
157struct GpuVertex {
158 pos: [f32; 2],
159 uv: [f32; 2],
160 color: [f32; 4],
161}
162
163const ATTRS: [wgpu::VertexAttribute; 3] =
164 wgpu::vertex_attr_array![0 => Float32x2, 1 => Float32x2, 2 => Float32x4];
165
166const VERTEX_SRC: &str = r#"
168@group(0) @binding(0) var tex: texture_2d<f32>;
169@group(0) @binding(1) var samp: sampler;
170
171struct VOut {
172 @builtin(position) position: vec4<f32>,
173 @location(0) uv: vec2<f32>,
174 @location(1) color: vec4<f32>,
175};
176
177@vertex
178fn vs_main(@location(0) pos: vec2<f32>, @location(1) uv: vec2<f32>, @location(2) color: vec4<f32>) -> VOut {
179 var o: VOut;
180 o.position = vec4<f32>(pos.x, -pos.y, 0.0, 1.0);
181 o.uv = uv;
182 o.color = color;
183 return o;
184}
185"#;
186
187const FRAGMENT_RETURNS: [&str; 11] = [
190 "vec4<f32>(in.color.rgb * t.rgb, in.color.a)",
192 "vec4<f32>(in.color.rgb * t.rgb, 1.0)",
194 "vec4<f32>(in.color.rgb * t.rgb, 1.0)",
196 "vec4<f32>(t.rgb, 1.0)",
198 "vec4<f32>(in.color.rgb * t.rgb, in.color.a * t.a)",
200 "vec4<f32>(in.color.rgb * t.rgb, in.color.a)",
202 "vec4<f32>(in.color.rgb * t.rgb, in.color.a)",
204 "vec4<f32>(clamp(vec3<f32>(1.0) - t.rgb, vec3<f32>(0.0), vec3<f32>(1.0)), in.color.a * t.a)",
206 "vec4<f32>(t.rgb * in.color.rgb, in.color.a * t.a)",
208 "vec4<f32>(clamp(t.rgb + in.color.rgb - vec3<f32>(0.5), vec3<f32>(0.0), vec3<f32>(1.0)), in.color.a)",
210 "vec4<f32>(clamp(2.0 * t.rgb * in.color.rgb, vec3<f32>(0.0), vec3<f32>(1.0)), in.color.a)",
212];
213
214fn shader_source() -> String {
216 let mut s = String::from(VERTEX_SRC);
217 for (mode, ret) in FRAGMENT_RETURNS.iter().enumerate() {
218 s.push_str(&format!(
219 "@fragment fn fs{mode}(in: VOut) -> @location(0) vec4<f32> {{\n let t = textureSample(tex, samp, in.uv);\n return {ret};\n}}\n"
220 ));
221 }
222 s
223}
224
225fn factors(mode: usize) -> Option<(wgpu::BlendFactor, wgpu::BlendFactor)> {
227 use wgpu::BlendFactor as F;
228 Some(match mode {
229 1 => return None,
230 2 | 10 => (F::One, F::One),
231 3 => (F::Src, F::OneMinusSrc),
232 5 => (F::Dst, F::Zero),
233 6 => (F::Zero, F::OneMinusSrc),
234 9 => (F::Zero, F::Src),
235 _ => (F::SrcAlpha, F::OneMinusSrcAlpha),
236 })
237}
238
239pub(crate) struct SpritePipes {
241 pipelines: Vec<wgpu::RenderPipeline>,
242}
243
244impl SpritePipes {
245 pub(crate) fn new(
246 device: &wgpu::Device,
247 bgl_tex: &wgpu::BindGroupLayout,
248 format: wgpu::TextureFormat,
249 ) -> Self {
250 let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
251 label: Some("sprite"),
252 source: wgpu::ShaderSource::Wgsl(shader_source().into()),
253 });
254 let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
255 label: Some("sprite"),
256 bind_group_layouts: &[Some(bgl_tex)],
257 immediate_size: 0,
258 });
259 let pipelines = (0..SPRITE_MODES)
260 .map(|mode| {
261 let entry = format!("fs{mode}");
262 let keep_alpha = wgpu::BlendComponent {
264 src_factor: wgpu::BlendFactor::Zero,
265 dst_factor: wgpu::BlendFactor::One,
266 operation: wgpu::BlendOperation::Add,
267 };
268 let blend = factors(mode).map(|(s, d)| wgpu::BlendState {
269 color: wgpu::BlendComponent {
270 src_factor: s,
271 dst_factor: d,
272 operation: wgpu::BlendOperation::Add,
273 },
274 alpha: keep_alpha,
275 });
276 device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
277 label: Some("sprite"),
278 layout: Some(&layout),
279 vertex: wgpu::VertexState {
280 module: &module,
281 entry_point: Some("vs_main"),
282 compilation_options: Default::default(),
283 buffers: &[Some(wgpu::VertexBufferLayout {
284 array_stride: std::mem::size_of::<GpuVertex>() as u64,
285 step_mode: wgpu::VertexStepMode::Vertex,
286 attributes: &ATTRS,
287 })],
288 },
289 primitive: wgpu::PrimitiveState {
290 topology: wgpu::PrimitiveTopology::TriangleStrip,
291 ..Default::default()
292 },
293 depth_stencil: None,
294 multisample: wgpu::MultisampleState::default(),
295 fragment: Some(wgpu::FragmentState {
296 module: &module,
297 entry_point: Some(&entry),
298 compilation_options: Default::default(),
299 targets: &[Some(wgpu::ColorTargetState {
300 format,
301 blend,
302 write_mask: wgpu::ColorWrites::ALL,
303 })],
304 }),
305 multiview_mask: None,
306 cache: None,
307 })
308 })
309 .collect();
310 Self { pipelines }
311 }
312
313 pub(crate) fn draw(
315 &self,
316 device: &wgpu::Device,
317 encoder: &mut wgpu::CommandEncoder,
318 target: &wgpu::TextureView,
319 bgl_tex: &wgpu::BindGroupLayout,
320 sampler: &wgpu::Sampler,
321 images: &HashMap<u32, SpriteImage>,
322 draws: &[&SpriteDraw],
323 ) {
324 let mut verts: Vec<GpuVertex> = Vec::with_capacity(draws.len() * 4);
325 let mut groups: Vec<(usize, wgpu::BindGroup)> = Vec::with_capacity(draws.len());
326 for d in draws {
327 let Some(view) = images.get(&d.image).and_then(|i| i.frames.get(d.frame)) else {
328 continue;
329 };
330 let mode = sprite_mode(d.blend);
331 let color = sprite_vertex_color(mode, d.rgba).map(|c| f32::from(c) / 255.0);
332 verts.extend(d.quad.iter().map(|v| GpuVertex {
333 pos: v.pos,
334 uv: v.uv,
335 color,
336 }));
337 groups.push((
338 mode,
339 device.create_bind_group(&wgpu::BindGroupDescriptor {
340 label: Some("sprite"),
341 layout: bgl_tex,
342 entries: &[
343 wgpu::BindGroupEntry {
344 binding: 0,
345 resource: wgpu::BindingResource::TextureView(view),
346 },
347 wgpu::BindGroupEntry {
348 binding: 1,
349 resource: wgpu::BindingResource::Sampler(sampler),
350 },
351 ],
352 }),
353 ));
354 }
355 if groups.is_empty() {
356 return;
357 }
358 let buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
359 label: Some("sprite verts"),
360 contents: bytemuck::cast_slice(&verts),
361 usage: wgpu::BufferUsages::VERTEX,
362 });
363 let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
364 label: Some("sprites"),
365 color_attachments: &[Some(wgpu::RenderPassColorAttachment {
366 view: target,
367 depth_slice: None,
368 resolve_target: None,
369 ops: wgpu::Operations {
370 load: wgpu::LoadOp::Load,
371 store: wgpu::StoreOp::Store,
372 },
373 })],
374 ..Default::default()
375 });
376 pass.set_vertex_buffer(0, buf.slice(..));
377 for (i, (mode, bg)) in groups.iter().enumerate() {
378 pass.set_pipeline(&self.pipelines[*mode]);
379 pass.set_bind_group(0, bg, &[]);
380 let s = (i * 4) as u32;
381 pass.draw(s..s + 4, 0..1);
382 }
383 }
384}
385
386#[cfg(test)]
387mod tests {
388 use super::*;
389
390 const T: [u8; 4] = [204, 102, 51, 255];
392 const D: [u8; 3] = [128; 3];
393
394 fn rounded(mode: usize, rgb: [f32; 3]) -> [i32; 3] {
395 sprite_blend_reference(mode, [rgb[0], rgb[1], rgb[2], 0.4], T, D).map(|c| c.round() as i32)
396 }
397
398 fn near(a: [i32; 3], b: [i32; 3]) -> bool {
399 a.iter().zip(b).all(|(x, y)| (x - y).abs() <= 1)
400 }
401
402 #[test]
404 fn reference_matches_the_documented_example() {
405 let white = [
406 [158, 118, 97],
407 [82, 41, 20],
408 [210, 169, 148],
409 [189, 118, 113],
410 [158, 118, 97],
411 [102, 51, 26],
412 [26, 77, 102],
413 [97, 138, 158],
414 [77, 77, 77],
415 [128, 115, 90],
416 [255, 255, 230],
417 ];
418 let tint = [
419 [158, 101, 81],
420 [82, 24, 4],
421 [210, 152, 132],
422 [189, 118, 113],
423 [158, 101, 81],
424 [102, 31, 5],
425 [26, 97, 123],
426 [97, 138, 158],
427 [77, 93, 81],
428 [128, 64, 0],
429 [255, 250, 148],
430 ];
431 for mode in 0..SPRITE_MODES {
432 let got = rounded(mode, [1.0, 1.0, 1.0]);
433 assert!(near(got, white[mode]), "mode {mode} white: {got:?}");
434 let got = rounded(mode, [1.0, 0.6, 0.2]);
435 assert!(near(got, tint[mode]), "mode {mode} tint: {got:?}");
436 }
437 }
438
439 #[test]
440 fn keyed_texels_leave_the_destination_for_alpha_textured_modes() {
441 let keyed = [204, 102, 51, 0];
442 for mode in [4, 7, 8] {
443 let out = sprite_blend_reference(mode, [1.0, 1.0, 1.0, 0.4], keyed, D);
444 assert_eq!(out.map(|c| c.round() as i32), [128; 3], "mode {mode}");
445 }
446 for mode in [0, 1, 2, 3, 5, 6, 9, 10] {
448 let a = sprite_blend_reference(mode, [1.0, 0.6, 0.2, 0.4], keyed, D);
449 let b = sprite_blend_reference(mode, [1.0, 0.6, 0.2, 0.4], T, D);
450 assert_eq!(a, b, "mode {mode}");
451 }
452 }
453
454 #[test]
455 fn vertex_colours_follow_the_table() {
456 let rgba = [1.0, 0.6, 0.2, 0.4];
457 assert_eq!(sprite_vertex_color(0, rgba), [255, 153, 51, 102]);
458 assert_eq!(sprite_vertex_color(1, rgba), [102, 61, 20, 255]);
459 assert_eq!(sprite_vertex_color(3, rgba), [255; 4]);
460 assert_eq!(sprite_vertex_color(7, rgba), [255, 255, 255, 102]);
461 let v8 = sprite_vertex_color(8, rgba);
463 assert_eq!((v8[0], v8[2], v8[3]), (0, 51, 102));
464 assert!((101..=102).contains(&v8[1]), "{v8:?}");
465 assert_eq!(sprite_vertex_color(0, [0.0, 0.0, 0.0, 2.0])[3], 254);
467 }
468
469 #[test]
470 fn out_of_range_blend_is_mode_zero() {
471 assert_eq!(sprite_mode(-1), 0);
472 assert_eq!(sprite_mode(11), 0);
473 assert_eq!(sprite_mode(10), 10);
474 }
475
476 #[test]
477 fn gif_frame_selection_follows_the_delay_rule() {
478 let d = [0.1, 0.2, 0.05];
480 assert_eq!(gif_frame_index(&d, 0.0), 0);
481 assert_eq!(gif_frame_index(&d, 0.12), 1);
482 assert_eq!(gif_frame_index(&d, 0.31), 2);
484 assert_eq!(gif_frame_index(&d, 0.36), 0, "0.36 mod 0.35 = 0.01");
485 assert_eq!(gif_frame_index(&d, 0.35 * 7.0 + 0.12), 1);
486 assert_eq!(gif_frame_index(&[0.5], 3.0), 0);
488 assert_eq!(gif_frame_index(&[], 3.0), 0);
489 assert_eq!(gif_frame_index(&[0.0, 0.0], 3.0), 0);
490 }
491}