summaryrefslogtreecommitdiff
path: root/src/gpu/effects/flash_effect.cc
blob: de7be622686018940182f96384bed91816dc5862 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// This file is part of the 64k demo project.
// It implements the FlashEffect - brief white flash on beat hits.

#include "gpu/effects/flash_effect.h"
#include "gpu/effects/post_process_helper.h"
#include <cmath>

FlashEffect::FlashEffect(WGPUDevice device, WGPUQueue queue,
                         WGPUTextureFormat format)
    : PostProcessEffect(device, queue) {
  const char* shader_code = R"(
    struct VertexOutput {
      @builtin(position) position: vec4<f32>,
      @location(0) uv: vec2<f32>,
    };

    struct Uniforms {
      flash_intensity: f32,
      _pad0: f32,
      _pad1: f32,
      _pad2: f32,
    };

    @group(0) @binding(0) var inputSampler: sampler;
    @group(0) @binding(1) var inputTexture: texture_2d<f32>;
    @group(0) @binding(2) var<uniform> uniforms: Uniforms;

    @vertex
    fn vs_main(@builtin(vertex_index) vertexIndex: u32) -> VertexOutput {
      var output: VertexOutput;
      var pos = array<vec2<f32>, 3>(
        vec2<f32>(-1.0, -1.0),
        vec2<f32>(3.0, -1.0),
        vec2<f32>(-1.0, 3.0)
      );
      output.position = vec4<f32>(pos[vertexIndex], 0.0, 1.0);
      output.uv = pos[vertexIndex] * 0.5 + 0.5;
      return output;
    }

    @fragment
    fn fs_main(input: VertexOutput) -> @location(0) vec4<f32> {
      let color = textureSample(inputTexture, inputSampler, input.uv);
      // Add white flash: blend towards white based on flash intensity
      let white = vec3<f32>(1.0, 1.0, 1.0);
      let flashed = mix(color.rgb, white, uniforms.flash_intensity);
      return vec4<f32>(flashed, color.a);
    }
  )";

  pipeline_ = create_post_process_pipeline(device, format, shader_code);
  uniforms_ = gpu_create_buffer(device, 16, WGPUBufferUsage_Uniform | WGPUBufferUsage_CopyDst);
}

void FlashEffect::update_bind_group(WGPUTextureView input_view) {
  pp_update_bind_group(device_, pipeline_, &bind_group_, input_view, uniforms_);
}

void FlashEffect::render(WGPURenderPassEncoder pass, float time,
                         float beat, float intensity, float aspect_ratio) {
  (void)time;
  (void)beat;
  (void)aspect_ratio;

  // Trigger flash on strong beat hits
  if (intensity > 0.7f && flash_intensity_ < 0.2f) {
    flash_intensity_ = 0.8f;  // Trigger flash
  }

  // Exponential decay
  flash_intensity_ *= 0.85f;

  float uniforms[4] = {flash_intensity_, 0.0f, 0.0f, 0.0f};
  wgpuQueueWriteBuffer(queue_, uniforms_.buffer, 0, uniforms, sizeof(uniforms));

  wgpuRenderPassEncoderSetPipeline(pass, pipeline_);
  wgpuRenderPassEncoderSetBindGroup(pass, 0, bind_group_, 0, nullptr);
  wgpuRenderPassEncoderDraw(pass, 3, 1, 0, 0);
}