summaryrefslogtreecommitdiff
path: root/src/gpu/effects/particles_effect.cc
blob: 545fdfbd25eed65e57e18150da560cfbdfa2c3ae (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
// This file is part of the 64k demo project.
// It implements the ParticlesEffect.

#include "gpu/demo_effects.h"
#include "gpu/gpu.h"
#include <vector>

// --- ParticlesEffect ---
ParticlesEffect::ParticlesEffect(WGPUDevice device, WGPUQueue queue,
                                 WGPUTextureFormat format)
    : queue_(queue) {
  uniforms_ =
      gpu_create_buffer(device, sizeof(float) * 4,
                        WGPUBufferUsage_Uniform | WGPUBufferUsage_CopyDst);
  std::vector<Particle> init_p(NUM_PARTICLES);
  particles_buffer_ = gpu_create_buffer(
      device, sizeof(Particle) * NUM_PARTICLES,
      WGPUBufferUsage_Storage | WGPUBufferUsage_Vertex, init_p.data());
  ResourceBinding cb[] = {{particles_buffer_, WGPUBufferBindingType_Storage},
                          {uniforms_, WGPUBufferBindingType_Uniform}};
  compute_pass_ = gpu_create_compute_pass(device, particle_compute_wgsl, cb, 2);
  compute_pass_.workgroup_size_x = (NUM_PARTICLES + 63) / 64;
  ResourceBinding rb[] = {
      {particles_buffer_, WGPUBufferBindingType_ReadOnlyStorage},
      {uniforms_, WGPUBufferBindingType_Uniform}};
  render_pass_ =
      gpu_create_render_pass(device, format, particle_render_wgsl, rb, 2);
  render_pass_.vertex_count = 6;
  render_pass_.instance_count = NUM_PARTICLES;
}
void ParticlesEffect::compute(WGPUCommandEncoder e, float t, float b, float i,
                              float a) {
  struct {
    float p, a, t, d;
  } u = {i, a, t, 0.0f};
  wgpuQueueWriteBuffer(queue_, uniforms_.buffer, 0, &u, sizeof(u));
  WGPUComputePassEncoder pass = wgpuCommandEncoderBeginComputePass(e, nullptr);
  wgpuComputePassEncoderSetPipeline(pass, compute_pass_.pipeline);
  wgpuComputePassEncoderSetBindGroup(pass, 0, compute_pass_.bind_group, 0,
                                     nullptr);
  wgpuComputePassEncoderDispatchWorkgroups(pass, compute_pass_.workgroup_size_x,
                                           1, 1);
  wgpuComputePassEncoderEnd(pass);
}
void ParticlesEffect::render(WGPURenderPassEncoder pass, float t, float b,
                             float i, float a) {
  wgpuRenderPassEncoderSetPipeline(pass, render_pass_.pipeline);
  wgpuRenderPassEncoderSetBindGroup(pass, 0, render_pass_.bind_group, 0,
                                    nullptr);
  wgpuRenderPassEncoderDraw(pass, render_pass_.vertex_count,
                            render_pass_.instance_count, 0, 0);
}