1use wgpu::util::DeviceExt;
23
24#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
26pub enum TransitionKind {
27 Circle = 0,
29 Plasma = 1,
31 SimpleBlend = 2,
33 Sweep = 3,
35 Warp = 4,
37 ZoomBlur = 5,
39}
40
41impl TransitionKind {
42 pub const ALL: [TransitionKind; 6] = [
44 TransitionKind::Circle,
45 TransitionKind::Plasma,
46 TransitionKind::SimpleBlend,
47 TransitionKind::Sweep,
48 TransitionKind::Warp,
49 TransitionKind::ZoomBlur,
50 ];
51
52 pub fn index(self) -> usize {
54 self as usize
55 }
56
57 pub fn from_index(i: u32) -> Self {
59 Self::ALL[i as usize % Self::ALL.len()]
60 }
61
62 pub fn name(self) -> &'static str {
64 match self {
65 TransitionKind::Circle => "circle",
66 TransitionKind::Plasma => "plasma",
67 TransitionKind::SimpleBlend => "simple_blend",
68 TransitionKind::Sweep => "sweep",
69 TransitionKind::Warp => "warp",
70 TransitionKind::ZoomBlur => "zoom_blur",
71 }
72 }
73}
74
75#[derive(Clone, Copy, Debug, PartialEq)]
77pub struct TransitionParams {
78 pub kind: TransitionKind,
80 pub linear: f64,
82 pub cosine: f64,
84 pub bicubic: f64,
86 pub duration: f64,
88 pub time: f64,
90 pub time_delta: f64,
92 pub rand_static: [i32; 4],
94}
95
96impl TransitionParams {
97 pub fn new(
100 kind: TransitionKind,
101 rand_static: [i32; 4],
102 duration: f64,
103 seconds_since_start: f64,
104 time_delta: f64,
105 ) -> Self {
106 let (linear, cosine, bicubic) = if duration > 0.0 {
107 let l = seconds_since_start / duration;
108 let c = (-(l * std::f64::consts::PI).cos() + 1.0) * 0.5;
109 let b = if l < 0.5 {
110 4.0 * l * l * l
111 } else {
112 1.0 - (-2.0 * l + 2.0).powf(3.0) / 2.0
113 };
114 (l, c, b)
115 } else {
116 (1.0, 1.0, 1.0)
117 };
118 Self {
119 kind,
120 linear,
121 cosine,
122 bicubic,
123 duration,
124 time: seconds_since_start,
125 time_delta,
126 rand_static,
127 }
128 }
129}
130
131#[repr(C)]
132#[derive(Clone, Copy, Debug, Default, bytemuck::Pod, bytemuck::Zeroable)]
133struct TransitionUniforms {
134 resolution: [f32; 4],
136 duration_params: [f32; 4],
138 time_params: [f32; 4],
140 rand_static: [i32; 4],
142}
143
144const HEADER: &str = r#"
145struct TP {
146 resolution: vec4<f32>,
147 duration_params: vec4<f32>,
148 time_params: vec4<f32>,
149 rand_static: vec4<i32>,
150};
151@group(0) @binding(0) var<uniform> tp: TP;
152@group(0) @binding(1) var tex_old: texture_2d<f32>;
153@group(0) @binding(2) var tex_new: texture_2d<f32>;
154@group(0) @binding(3) var samp: sampler;
155
156@vertex
157fn vs_main(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4<f32> {
158 var p = array<vec2<f32>, 3>(vec2<f32>(-1.0, -1.0), vec2<f32>(3.0, -1.0), vec2<f32>(-1.0, 3.0));
159 // z = 0.5: gl_FragCoord.z of projectM's z = 0 quad under the default [-1, 1] -> [0, 1] depth range
160 return vec4<f32>(p[vi], 0.5, 1.0);
161}
162
163fn glsl_mod(x: f32, y: f32) -> f32 {
164 return x - y * floor(x / y);
165}
166
167fn glsl_smoothstep(e0: f32, e1: f32, x: f32) -> f32 {
168 let t = clamp((x - e0) / (e1 - e0), 0.0, 1.0);
169 return t * t * (3.0 - 2.0 * t);
170}
171
172fn srgb_to_linear(c: vec3<f32>) -> vec3<f32> {
173 let lo = c / 12.92;
174 let hi = pow((c + vec3<f32>(0.055)) / 1.055, vec3<f32>(2.4));
175 return select(hi, lo, c <= vec3<f32>(0.04045));
176}
177
178// texture(iChannel0, p) / texture(iChannel1, p): GLSL v runs bottom-up, our images top-down.
179fn old_at(p: vec2<f32>) -> vec3<f32> {
180 return textureSampleLevel(tex_old, samp, vec2<f32>(p.x, 1.0 - p.y), 0.0).xyz;
181}
182fn new_at(p: vec2<f32>) -> vec3<f32> {
183 return textureSampleLevel(tex_new, samp, vec2<f32>(p.x, 1.0 - p.y), 0.0).xyz;
184}
185
186fn i_progress_linear() -> f32 { return tp.duration_params.x; }
187fn i_progress_cosine() -> f32 { return tp.duration_params.y; }
188fn i_progress_bicubic() -> f32 { return tp.duration_params.z; }
189
190@fragment
191fn fs_main(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
192 // gl_FragCoord: y up
193 let frag = vec4<f32>(pos.x, tp.resolution.y - pos.y, pos.z, 1.0);
194 var rgb = main_image(frag, frag.xy).xyz;
195 if (tp.resolution.w > 0.5) {
196 rgb = srgb_to_linear(rgb);
197 }
198 return vec4<f32>(rgb, 1.0);
199}
200"#;
201
202const CIRCLE: &str = r#"
203fn main_image(frag: vec4<f32>, frag_coord: vec2<f32>) -> vec4<f32> {
204 let uv = frag_coord / tp.resolution.xy;
205 let aspect = tp.resolution.y / tp.resolution.x;
206
207 let in_or_out = glsl_mod(f32(tp.rand_static.x) * 0.01, 2.0);
208
209 var progress: f32;
210 var img_inner: vec3<f32>;
211 var img_outer: vec3<f32>;
212 if (in_or_out < 1.0) {
213 img_inner = old_at(uv);
214 img_outer = new_at(uv);
215 progress = i_progress_cosine();
216 } else {
217 img_outer = old_at(uv);
218 img_inner = new_at(uv);
219 progress = 1.0 - i_progress_cosine();
220 }
221 let blend_width = glsl_mod(f32(tp.rand_static.y) * 0.001, 0.1) + 0.05;
222 progress = progress * (1.0 + blend_width) - blend_width;
223
224 let center = vec2<f32>(0.5);
225 let rad = sqrt(center.x / aspect * center.x / aspect + center.y * center.y) * progress;
226 let rad2 = rad + blend_width;
227 let r1 = sqrt((uv.x - center.x) / aspect * (uv.x - center.x) / aspect + (uv.y - center.y) * (uv.y - center.y));
228
229 var col: vec3<f32>;
230 if (r1 > rad2) {
231 col = img_inner;
232 } else if (r1 > rad) {
233 let v1 = (r1 - rad) / (rad2 - rad);
234 let v2 = 1.0 - v1;
235 col = v1 * img_inner + v2 * img_outer;
236 } else {
237 col = img_outer;
238 }
239 return vec4<f32>(col, 1.0);
240}
241"#;
242
243const PLASMA: &str = r#"
244fn sin_noise(uv: vec2<f32>) -> f32 {
245 return fract(abs(sin(uv.x * 0.018 + uv.y * 0.3077) * (f32(tp.rand_static.x) * 0.001)));
246}
247
248fn value_noise(uv: vec2<f32>, scale: f32) -> f32 {
249 let luv = fract(uv * scale);
250 let luvs = vec2<f32>(glsl_smoothstep(0.0, 1.0, fract(uv * scale).x), glsl_smoothstep(0.0, 1.0, fract(uv * scale).y));
251 let id = floor(uv * scale);
252 let tl = sin_noise(id + vec2<f32>(0.0, 1.0));
253 let tr = sin_noise(id + vec2<f32>(1.0, 1.0));
254 let t = mix(tl, tr, luvs.x);
255
256 let bl = sin_noise(id + vec2<f32>(0.0, 0.0));
257 let br = sin_noise(id + vec2<f32>(1.0, 0.0));
258 let b = mix(bl, br, luvs.x);
259
260 return mix(b, t, luvs.y) * 2.0 - 1.0;
261}
262
263fn main_image(frag: vec4<f32>, frag_coord: vec2<f32>) -> vec4<f32> {
264 var uv = frag_coord / tp.resolution.xy;
265
266 let img_old = old_at(uv);
267 let img_new = new_at(uv);
268
269 uv.y = uv.y / (tp.resolution.x / tp.resolution.y);
270
271 let scale = glsl_mod(f32(tp.rand_static.y) * 0.01, 7.0) * 4.0 + 4.0;
272
273 var fract_value = 0.0;
274 var amp = 1.0;
275 for (var i = 0; i < 16; i = i + 1) {
276 fract_value = fract_value + value_noise(uv, f32(i + 1) * scale) * amp;
277 amp = amp * 0.5;
278 }
279
280 fract_value = fract_value * 0.25;
281 fract_value = fract_value + 0.5;
282
283 let cutoff = glsl_smoothstep(i_progress_cosine() + 0.1, i_progress_cosine() - 0.1, fract_value);
284 let col = mix(img_old, img_new, cutoff);
285 return vec4<f32>(col, 1.0);
286}
287"#;
288
289const SIMPLE_BLEND: &str = r#"
290fn main_image(frag: vec4<f32>, frag_coord: vec2<f32>) -> vec4<f32> {
291 let uv = frag_coord / tp.resolution.xy;
292 return vec4<f32>(mix(old_at(uv), new_at(uv), i_progress_cosine()), 1.0);
293}
294"#;
295
296const SWEEP: &str = r#"
297fn atan_y_over_x(y: f32, x: f32) -> f32 {
298 if (x > 0.0) {
299 return atan(y / x);
300 } else if (x < 0.0 && y >= 0.0) {
301 return atan(y / x) + 3.14159265;
302 } else if (x < 0.0 && y < 0.0) {
303 return atan(y / x) - 3.14159265;
304 }
305 return 1.57079632 * sign(y);
306}
307
308fn main_image(frag: vec4<f32>, frag_coord: vec2<f32>) -> vec4<f32> {
309 var uv = frag_coord / tp.resolution.xy;
310 let img_old = old_at(uv);
311 let img_new = new_at(uv);
312
313 let current_angle = glsl_mod(f32(tp.rand_static.x), 360.0);
314 let blend_width = glsl_mod(f32(tp.rand_static.y) * 0.001, 0.3) + 0.1;
315
316 uv = uv - 0.5;
317 let angle = 90.0 * 0.017453292 - current_angle * 0.017453292 + atan_y_over_x(uv.y, uv.x);
318
319 let len = length(uv) / sqrt(2.0);
320 uv = vec2<f32>(cos(angle) * len, sin(angle) * len) + 0.5;
321
322 let col = mix(img_new, img_old, glsl_smoothstep(i_progress_cosine(), i_progress_cosine() + blend_width, (uv.x / (1.0 + 2.0 * blend_width)) + blend_width));
323 return vec4<f32>(col, 1.0);
324}
325"#;
326
327const WARP: &str = r#"
328fn main_image(frag: vec4<f32>, frag_coord: vec2<f32>) -> vec4<f32> {
329 let uv = frag_coord / tp.resolution.xy;
330
331 let direction = glsl_mod(f32(tp.rand_static.x) * 0.01, 4.0);
332 var coord: f32;
333 if (direction < 1.0) {
334 coord = uv.x;
335 } else if (direction < 2.0) {
336 coord = 1.0 - uv.x;
337 } else if (direction < 3.0) {
338 coord = uv.y;
339 } else {
340 coord = 1.0 - uv.y;
341 }
342
343 let x = glsl_smoothstep(0.0, 1.0, (i_progress_cosine() * 2.0 + coord - 1.0));
344 let a = old_at((uv - 0.5) * (1.0 - x) + 0.5);
345 let b = new_at((uv - 0.5) * x + 0.5);
346 return vec4<f32>(mix(a, b, x), 1.0);
347}
348"#;
349
350const ZOOM_BLUR: &str = r#"
351const STRENGTH: f32 = 0.3;
352const PI: f32 = 3.141592653589793;
353
354fn linear_ease(begin: f32, change: f32, duration: f32, time: f32) -> f32 {
355 return change * time / duration + begin;
356}
357
358fn exponential_ease_in_out(begin: f32, change: f32, duration: f32, time_in: f32) -> f32 {
359 var time = time_in;
360 if (time == 0.0) {
361 return begin;
362 } else if (time == duration) {
363 return begin + change;
364 }
365 time = time / (duration / 2.0);
366 if (time < 1.0) {
367 return change / 2.0 * pow(2.0, 10.0 * (time - 1.0)) + begin;
368 }
369 return change / 2.0 * (-pow(2.0, -10.0 * (time - 1.0)) + 2.0) + begin;
370}
371
372fn sinusoidal_ease_in_out(begin: f32, change: f32, duration: f32, time: f32) -> f32 {
373 return -change / 2.0 * (cos(PI * time / duration) - 1.0) + begin;
374}
375
376fn random3(scale: vec3<f32>, seed: f32, frag: vec3<f32>) -> f32 {
377 return fract(sin(dot(frag + seed, scale)) * 43758.5453 + seed);
378}
379
380fn cross_fade(uv: vec2<f32>, dissolve: f32) -> vec3<f32> {
381 return mix(old_at(uv), new_at(uv), dissolve);
382}
383
384fn main_image(frag: vec4<f32>, frag_coord: vec2<f32>) -> vec4<f32> {
385 let tex_coord = frag_coord / tp.resolution.xy;
386 let progress = i_progress_cosine();
387 let center = vec2<f32>(linear_ease(0.5, 0.0, 1.0, progress), 0.5);
388 let dissolve = exponential_ease_in_out(0.0, 1.0, 1.0, progress);
389
390 let strength = sinusoidal_ease_in_out(0.0, STRENGTH, 0.5, progress);
391
392 var color = vec3<f32>(0.0);
393 var total = 0.0;
394 let to_center = center - tex_coord;
395
396 let offset = random3(vec3<f32>(12.9898, 78.233, 151.7182), 0.0, frag.xyz) * 0.5;
397
398 for (var t = 0.0; t <= 20.0; t = t + 1.0) {
399 let percent = (t + offset) / 20.0;
400 let weight = 1.0 * (percent - percent * percent);
401 color = color + cross_fade(tex_coord + to_center * percent * strength, dissolve) * weight;
402 total = total + weight;
403 }
404
405 return vec4<f32>(color / total, 1.0);
406}
407"#;
408
409fn body(kind: TransitionKind) -> &'static str {
410 match kind {
411 TransitionKind::Circle => CIRCLE,
412 TransitionKind::Plasma => PLASMA,
413 TransitionKind::SimpleBlend => SIMPLE_BLEND,
414 TransitionKind::Sweep => SWEEP,
415 TransitionKind::Warp => WARP,
416 TransitionKind::ZoomBlur => ZOOM_BLUR,
417 }
418}
419
420pub struct TransitionBlender {
422 device: wgpu::Device,
423 bgl: wgpu::BindGroupLayout,
424 sampler: wgpu::Sampler,
425 pipelines: Vec<wgpu::RenderPipeline>,
426 srgb_target: bool,
427}
428
429impl TransitionBlender {
430 pub fn new(device: &wgpu::Device, output_format: wgpu::TextureFormat) -> Self {
432 let tex_entry = |binding| wgpu::BindGroupLayoutEntry {
433 binding,
434 visibility: wgpu::ShaderStages::FRAGMENT,
435 ty: wgpu::BindingType::Texture {
436 sample_type: wgpu::TextureSampleType::Float { filterable: true },
437 view_dimension: wgpu::TextureViewDimension::D2,
438 multisampled: false,
439 },
440 count: None,
441 };
442 let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
443 label: Some("transition"),
444 entries: &[
445 wgpu::BindGroupLayoutEntry {
446 binding: 0,
447 visibility: wgpu::ShaderStages::FRAGMENT,
448 ty: wgpu::BindingType::Buffer {
449 ty: wgpu::BufferBindingType::Uniform,
450 has_dynamic_offset: false,
451 min_binding_size: None,
452 },
453 count: None,
454 },
455 tex_entry(1),
456 tex_entry(2),
457 wgpu::BindGroupLayoutEntry {
458 binding: 3,
459 visibility: wgpu::ShaderStages::FRAGMENT,
460 ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
461 count: None,
462 },
463 ],
464 });
465 let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
466 label: Some("transition"),
467 bind_group_layouts: &[Some(&bgl)],
468 immediate_size: 0,
469 });
470 let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
471 label: Some("transition"),
472 address_mode_u: wgpu::AddressMode::ClampToEdge,
473 address_mode_v: wgpu::AddressMode::ClampToEdge,
474 address_mode_w: wgpu::AddressMode::ClampToEdge,
475 mag_filter: wgpu::FilterMode::Linear,
476 min_filter: wgpu::FilterMode::Linear,
477 mipmap_filter: wgpu::MipmapFilterMode::Nearest,
478 ..Default::default()
479 });
480 let pipelines = TransitionKind::ALL
481 .iter()
482 .map(|&kind| {
483 let src = format!("{HEADER}\n{}", body(kind));
484 let sm = device.create_shader_module(wgpu::ShaderModuleDescriptor {
485 label: Some(kind.name()),
486 source: wgpu::ShaderSource::Wgsl(src.into()),
487 });
488 device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
489 label: Some(kind.name()),
490 layout: Some(&layout),
491 vertex: wgpu::VertexState {
492 module: &sm,
493 entry_point: Some("vs_main"),
494 compilation_options: Default::default(),
495 buffers: &[],
496 },
497 fragment: Some(wgpu::FragmentState {
498 module: &sm,
499 entry_point: Some("fs_main"),
500 compilation_options: Default::default(),
501 targets: &[Some(wgpu::ColorTargetState {
502 format: output_format,
503 blend: None,
504 write_mask: wgpu::ColorWrites::ALL,
505 })],
506 }),
507 primitive: wgpu::PrimitiveState::default(),
508 depth_stencil: None,
509 multisample: wgpu::MultisampleState::default(),
510 multiview_mask: None,
511 cache: None,
512 })
513 })
514 .collect();
515 Self {
516 device: device.clone(),
517 bgl,
518 sampler,
519 pipelines,
520 srgb_target: output_format.is_srgb(),
521 }
522 }
523
524 pub fn draw(
527 &self,
528 encoder: &mut wgpu::CommandEncoder,
529 old: &wgpu::TextureView,
530 new: &wgpu::TextureView,
531 target: &wgpu::TextureView,
532 size: (u32, u32),
533 p: &TransitionParams,
534 ) {
535 let u = TransitionUniforms {
536 resolution: [
537 size.0 as f32,
538 size.1 as f32,
539 0.0,
540 if self.srgb_target { 1.0 } else { 0.0 },
541 ],
542 duration_params: [
543 p.linear as f32,
544 p.cosine as f32,
545 p.bicubic as f32,
546 p.duration as f32,
547 ],
548 time_params: [p.time as f32, p.time_delta as f32, 0.0, 0.0],
549 rand_static: p.rand_static,
550 };
551 let buf = self
552 .device
553 .create_buffer_init(&wgpu::util::BufferInitDescriptor {
554 label: Some("transition uniforms"),
555 contents: bytemuck::bytes_of(&u),
556 usage: wgpu::BufferUsages::UNIFORM,
557 });
558 let bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
559 label: Some("transition"),
560 layout: &self.bgl,
561 entries: &[
562 wgpu::BindGroupEntry {
563 binding: 0,
564 resource: buf.as_entire_binding(),
565 },
566 wgpu::BindGroupEntry {
567 binding: 1,
568 resource: wgpu::BindingResource::TextureView(old),
569 },
570 wgpu::BindGroupEntry {
571 binding: 2,
572 resource: wgpu::BindingResource::TextureView(new),
573 },
574 wgpu::BindGroupEntry {
575 binding: 3,
576 resource: wgpu::BindingResource::Sampler(&self.sampler),
577 },
578 ],
579 });
580 let mut rp = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
581 label: Some("transition"),
582 color_attachments: &[Some(wgpu::RenderPassColorAttachment {
583 view: target,
584 depth_slice: None,
585 resolve_target: None,
586 ops: wgpu::Operations {
587 load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
588 store: wgpu::StoreOp::Store,
589 },
590 })],
591 ..Default::default()
592 });
593 rp.set_pipeline(&self.pipelines[p.kind.index()]);
594 rp.set_bind_group(0, &bg, &[]);
595 rp.draw(0..3, 0..1);
596 }
597}
598
599#[cfg(test)]
600mod tests {
601 use super::*;
602
603 #[test]
604 fn progress_curves_follow_projectm() {
605 let p = TransitionParams::new(TransitionKind::SimpleBlend, [0; 4], 3.0, 0.0, 0.0);
606 assert_eq!((p.linear, p.cosine, p.bicubic), (0.0, 0.0, 0.0));
607 let p = TransitionParams::new(TransitionKind::SimpleBlend, [0; 4], 3.0, 1.5, 0.0);
608 assert!((p.cosine - 0.5).abs() < 1e-15);
609 assert!((p.bicubic - 0.5).abs() < 1e-15);
610 let p = TransitionParams::new(TransitionKind::SimpleBlend, [0; 4], 3.0, 3.0, 0.0);
611 assert_eq!(p.linear, 1.0);
612 assert!((p.cosine - 1.0).abs() < 1e-15 && (p.bicubic - 1.0).abs() < 1e-15);
613 let p = TransitionParams::new(TransitionKind::SimpleBlend, [0; 4], 4.0, 1.0, 0.0);
615 assert!((p.bicubic - 4.0 * 0.25f64.powi(3)).abs() < 1e-15);
616 let p = TransitionParams::new(TransitionKind::SimpleBlend, [0; 4], 0.0, 0.0, 0.0);
618 assert_eq!((p.linear, p.cosine, p.bicubic), (1.0, 1.0, 1.0));
619 }
620
621 #[test]
622 fn kind_order_matches_projectm() {
623 let names: Vec<_> = TransitionKind::ALL.iter().map(|k| k.name()).collect();
624 assert_eq!(
625 names,
626 [
627 "circle",
628 "plasma",
629 "simple_blend",
630 "sweep",
631 "warp",
632 "zoom_blur"
633 ]
634 );
635 assert_eq!(TransitionKind::from_index(8), TransitionKind::SimpleBlend);
636 }
637}