summaryrefslogtreecommitdiff
path: root/src/gpu/gpu.cc
blob: 92c661b59ecc8e85f7fc2a535111c057001519a0 (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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
// This file is part of the 64k demo project.
// It implements the WebGPU rendering pipeline and shader management.
// Driven by audio peaks for synchronized visual effects.

#include "gpu.h"
#include "platform.h"

#include <GLFW/glfw3.h>
#include <webgpu.h>
#include <wgpu.h>

#include <algorithm>
#include <cassert>
#include <cstdint>
#include <cstring>
#include <math.h>
#include <vector>

#ifndef STRIP_ALL
#include <iostream>
#endif

static WGPUInstance g_instance = nullptr;
static WGPUAdapter g_adapter = nullptr;
static WGPUDevice g_device = nullptr;
static WGPUQueue g_queue = nullptr;
static WGPUSurface g_surface = nullptr;
static WGPUSurfaceConfiguration g_config = {};

// We keep the main render pass as a global for now
static RenderPass g_main_pass;
static GpuBuffer g_uniform_buffer_struct;

// Particle System Globals
static ComputePass g_particle_compute_pass;
static RenderPass g_particle_render_pass;
static GpuBuffer g_particle_buffer;
static const int NUM_PARTICLES = 10000;

struct Particle {
  float pos[4];   // x, y, z, life
  float vel[4];   // vx, vy, vz, padding
  float rot[4];   // angle, speed, padding, padding
  float color[4]; // r, g, b, a
};

static WGPUStringView label_view(const char *str) {
#ifndef STRIP_ALL
  if (!str)
    return {nullptr, 0};
  return {str, strlen(str)};
#else
  (void)str;
  return {nullptr, 0};
#endif
}

static WGPUStringView str_view(const char *str) {
  if (!str)
    return {nullptr, 0};
  return {str, strlen(str)};
}

// --- Helper Functions ---

GpuBuffer gpu_create_buffer(size_t size, WGPUBufferUsage usage,
                            const void *data) {
  WGPUBufferDescriptor desc = {};
  desc.label = label_view("GpuBuffer");
  desc.usage = usage;
  desc.size = size;
  desc.mappedAtCreation = (data != nullptr); // Map if we have initial data

  WGPUBuffer buffer = wgpuDeviceCreateBuffer(g_device, &desc);

  if (data) {
    void *ptr = wgpuBufferGetMappedRange(buffer, 0, size);
    memcpy(ptr, data, size);
    wgpuBufferUnmap(buffer);
  }

  return {buffer, size};
}

RenderPass gpu_create_render_pass(const char *shader_code,
                                  ResourceBinding *bindings, int num_bindings) {
  RenderPass pass = {};

  // Create Shader Module
  WGPUShaderSourceWGSL wgsl_src = {};
  wgsl_src.chain.sType = WGPUSType_ShaderSourceWGSL;
  wgsl_src.code = str_view(shader_code);
  WGPUShaderModuleDescriptor shader_desc = {};
  shader_desc.nextInChain = &wgsl_src.chain;
  WGPUShaderModule shader_module =
      wgpuDeviceCreateShaderModule(g_device, &shader_desc);

  // Create Bind Group Layout & Bind Group
  std::vector<WGPUBindGroupLayoutEntry> bgl_entries;
  std::vector<WGPUBindGroupEntry> bg_entries;

  for (int i = 0; i < num_bindings; ++i) {
    WGPUBindGroupLayoutEntry bgl_entry = {};
    bgl_entry.binding = i;
    bgl_entry.visibility = WGPUShaderStage_Vertex | WGPUShaderStage_Fragment;
    bgl_entry.buffer.type = bindings[i].type;
    bgl_entry.buffer.minBindingSize = bindings[i].buffer.size;
    bgl_entries.push_back(bgl_entry);

    WGPUBindGroupEntry bg_entry = {};
    bg_entry.binding = i;
    bg_entry.buffer = bindings[i].buffer.buffer;
    bg_entry.size = bindings[i].buffer.size;
    bg_entries.push_back(bg_entry);
  }

  WGPUBindGroupLayoutDescriptor bgl_desc = {};
  bgl_desc.entryCount = (uint32_t)bgl_entries.size();
  bgl_desc.entries = bgl_entries.data();
  WGPUBindGroupLayout bind_group_layout =
      wgpuDeviceCreateBindGroupLayout(g_device, &bgl_desc);

  WGPUBindGroupDescriptor bg_desc = {};
  bg_desc.layout = bind_group_layout;
  bg_desc.entryCount = (uint32_t)bg_entries.size();
  bg_desc.entries = bg_entries.data();
  pass.bind_group = wgpuDeviceCreateBindGroup(g_device, &bg_desc);

  // Pipeline Layout
  WGPUPipelineLayoutDescriptor pl_desc = {};
  pl_desc.bindGroupLayoutCount = 1;
  pl_desc.bindGroupLayouts = &bind_group_layout;
  WGPUPipelineLayout pipeline_layout =
      wgpuDeviceCreatePipelineLayout(g_device, &pl_desc);

  // Render Pipeline
  WGPUColorTargetState color_target = {};
  color_target.format = g_config.format; // Use global swapchain format
  color_target.writeMask = WGPUColorWriteMask_All;
  color_target.blend = nullptr;

  // Add additive blending for particles if it's the particle pass (hacky check
  // based on vertex count or similar? No, let's just enable additive blending
  // for everything for now as it looks cool for the demo, or make it
  // configurable later. For now, simple replacement)
  WGPUBlendState blend = {};
  blend.color.srcFactor = WGPUBlendFactor_SrcAlpha;
  blend.color.dstFactor = WGPUBlendFactor_One;
  blend.color.operation = WGPUBlendOperation_Add;
  blend.alpha.srcFactor = WGPUBlendFactor_SrcAlpha;
  blend.alpha.dstFactor = WGPUBlendFactor_One;
  blend.alpha.operation = WGPUBlendOperation_Add;
  color_target.blend = &blend;

  WGPUFragmentState fragment_state = {};
  fragment_state.module = shader_module;
  fragment_state.entryPoint = str_view("fs_main");
  fragment_state.targetCount = 1;
  fragment_state.targets = &color_target;

  WGPURenderPipelineDescriptor pipeline_desc = {};
  pipeline_desc.layout = pipeline_layout;
  pipeline_desc.vertex.module = shader_module;
  pipeline_desc.vertex.entryPoint = str_view("vs_main");
  pipeline_desc.primitive.topology = WGPUPrimitiveTopology_TriangleList;
  pipeline_desc.multisample.count = 1;
  pipeline_desc.multisample.mask = 0xFFFFFFFF;
  pipeline_desc.fragment = &fragment_state;

  pass.pipeline = wgpuDeviceCreateRenderPipeline(g_device, &pipeline_desc);

  return pass;
}

ComputePass gpu_create_compute_pass(const char *shader_code,
                                    ResourceBinding *bindings,
                                    int num_bindings) {
  ComputePass pass = {};

  WGPUShaderSourceWGSL wgsl_src = {};
  wgsl_src.chain.sType = WGPUSType_ShaderSourceWGSL;
  wgsl_src.code = str_view(shader_code);
  WGPUShaderModuleDescriptor shader_desc = {};
  shader_desc.nextInChain = &wgsl_src.chain;
  WGPUShaderModule shader_module =
      wgpuDeviceCreateShaderModule(g_device, &shader_desc);

  std::vector<WGPUBindGroupLayoutEntry> bgl_entries;
  std::vector<WGPUBindGroupEntry> bg_entries;

  for (int i = 0; i < num_bindings; ++i) {
    WGPUBindGroupLayoutEntry bgl_entry = {};
    bgl_entry.binding = i;
    bgl_entry.visibility = WGPUShaderStage_Compute;
    bgl_entry.buffer.type = bindings[i].type;
    bgl_entry.buffer.minBindingSize = bindings[i].buffer.size;
    bgl_entries.push_back(bgl_entry);

    WGPUBindGroupEntry bg_entry = {};
    bg_entry.binding = i;
    bg_entry.buffer = bindings[i].buffer.buffer;
    bg_entry.size = bindings[i].buffer.size;
    bg_entries.push_back(bg_entry);
  }

  WGPUBindGroupLayoutDescriptor bgl_desc = {};
  bgl_desc.entryCount = (uint32_t)bgl_entries.size();
  bgl_desc.entries = bgl_entries.data();
  WGPUBindGroupLayout bind_group_layout =
      wgpuDeviceCreateBindGroupLayout(g_device, &bgl_desc);

  WGPUBindGroupDescriptor bg_desc = {};
  bg_desc.layout = bind_group_layout;
  bg_desc.entryCount = (uint32_t)bg_entries.size();
  bg_desc.entries = bg_entries.data();
  pass.bind_group = wgpuDeviceCreateBindGroup(g_device, &bg_desc);

  WGPUPipelineLayoutDescriptor pl_desc = {};
  pl_desc.bindGroupLayoutCount = 1;
  pl_desc.bindGroupLayouts = &bind_group_layout;
  WGPUPipelineLayout pipeline_layout =
      wgpuDeviceCreatePipelineLayout(g_device, &pl_desc);

  WGPUComputePipelineDescriptor pipeline_desc = {};
  pipeline_desc.layout = pipeline_layout;
  pipeline_desc.compute.module = shader_module;
  pipeline_desc.compute.entryPoint = str_view("main");

  pass.pipeline = wgpuDeviceCreateComputePipeline(g_device, &pipeline_desc);
  return pass;
}

// --- Main Init/Draw ---

#ifndef STRIP_ALL
static void handle_request_adapter(WGPURequestAdapterStatus status,
                                   WGPUAdapter adapter, WGPUStringView message,
                                   void *userdata1, void *userdata2) {
  if (status == WGPURequestAdapterStatus_Success) {
    *((WGPUAdapter *)userdata1) = adapter;
  } else {
    printf("Request adapter failed: %.*s\n", (int)message.length, message.data);
  }
}
static void handle_request_device(WGPURequestDeviceStatus status,
                                  WGPUDevice device, WGPUStringView message,
                                  void *userdata1, void *userdata2) {
  if (status == WGPURequestDeviceStatus_Success) {
    *((WGPUDevice *)userdata1) = device;
  } else {
    printf("Request device failed: %.*s\n", (int)message.length, message.data);
  }
}
static void handle_device_error(WGPUDevice const *device, WGPUErrorType type,
                                WGPUStringView message, void *userdata1,
                                void *userdata2) {
  printf("WebGPU Error: %.*s\n", (int)message.length, message.data);
}
#else
static void handle_request_adapter(WGPURequestAdapterStatus status,
                                   WGPUAdapter adapter, WGPUStringView message,
                                   void *userdata1, void *userdata2) {
  if (status == WGPURequestAdapterStatus_Success) {
    *((WGPUAdapter *)userdata1) = adapter;
  }
}
static void handle_request_device(WGPURequestDeviceStatus status,
                                  WGPUDevice device, WGPUStringView message,
                                  void *userdata1, void *userdata2) {
  if (status == WGPURequestDeviceStatus_Success) {
    *((WGPUDevice *)userdata1) = device;
  }
}
#endif

const char *main_shader_wgsl = R"(
struct Uniforms {
    audio_peak : f32,
    aspect_ratio: f32,
    time: f32,
};

@group(0) @binding(0) var<uniform> uniforms : Uniforms;

@vertex
fn vs_main(@builtin(vertex_index) vertex_index: u32) -> @builtin(position) vec4<f32> {
    let PI = 3.14159265;
    let num_sides = 7.0;

    // Pulse scale based on audio peak
    let base_scale = 0.5;
    let pulse_scale = 0.3 * uniforms.audio_peak;
    let scale = base_scale + pulse_scale;

    let tri_idx = f32(vertex_index / 3u);
    let sub_idx = vertex_index % 3u;

    if (sub_idx == 0u) {
        return vec4<f32>(0.0, 0.0, 0.0, 1.0);
    }

    // Apply rotation based on time
    let rotation = uniforms.time * 0.5;
    let i = tri_idx + f32(sub_idx - 1u);
    let angle = i * 2.0 * PI / num_sides + rotation;
    let x = scale * cos(angle) / uniforms.aspect_ratio;
    let y = scale * sin(angle);

    return vec4<f32>(x, y, 0.0, 1.0);
}

@fragment
fn fs_main() -> @location(0) vec4<f32> {
    // Dynamic color shifting based on time and responsiveness to peak
    let h = uniforms.time * 2.0 + uniforms.audio_peak * 3.0;
    let r = sin(h + 0.0) * 0.5 + 0.5;
    let g = sin(h + 2.0) * 0.9 + 0.3;
    let b = sin(h + 4.0) * 0.5 + 0.5;

    let boost = uniforms.audio_peak * 0.5;
    return vec4<f32>(r + boost, g + boost, b + boost, 0.5); // Alpha 0.5 for blending
}
)";

const char *particle_compute_wgsl = R"(
struct Particle {
    pos : vec4<f32>,
    vel : vec4<f32>,
    rot : vec4<f32>,
    color : vec4<f32>,
};

struct Uniforms {
    audio_peak : f32,
    aspect_ratio: f32,
    time: f32,
};

@group(0) @binding(0) var<storage, read_write> particles : array<Particle>;
@group(0) @binding(1) var<uniform> uniforms : Uniforms;

@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) GlobalInvocationID : vec3<u32>) {
    let index = GlobalInvocationID.x;
    if (index >= arrayLength(&particles)) {
        return;
    }

    var p = particles[index];

    // Update Position
    p.pos.x = p.pos.x + p.vel.x * 0.016;
    p.pos.y = p.pos.y + p.vel.y * 0.016;
    p.pos.z = p.pos.z + p.vel.z * 0.016;

    // Gravity / Audio attraction
    p.vel.y = p.vel.y - 0.01 * (1.0 + uniforms.audio_peak * 5.0);

    // Rotate
    p.rot.x = p.rot.x + p.rot.y * 0.016;

    // Reset if out of bounds
    if (p.pos.y < -1.5) {
        p.pos.y = 1.5;
        p.pos.x = (f32(index % 100u) / 50.0) - 1.0 + (uniforms.audio_peak * 0.5);
        p.vel.y = 0.0;
        p.vel.x = (f32(index % 10u) - 5.0) * 0.1;
    }

    particles[index] = p;
}
)";

const char *particle_render_wgsl = R"(
struct Particle {
    pos : vec4<f32>,
    vel : vec4<f32>,
    rot : vec4<f32>,
    color : vec4<f32>,
};

struct Uniforms {
    audio_peak : f32,
    aspect_ratio: f32,
    time: f32,
};

@group(0) @binding(0) var<storage, read> particles : array<Particle>;
@group(0) @binding(1) var<uniform> uniforms : Uniforms;

struct VertexOutput {
    @builtin(position) Position : vec4<f32>,
    @location(0) Color : vec4<f32>,
};

@vertex
fn vs_main(@builtin(vertex_index) vertex_index : u32, @builtin(instance_index) instance_index : u32) -> VertexOutput {
    let p = particles[instance_index];

    // Simple quad expansion
    let size = 0.02 + p.pos.z * 0.01 + uniforms.audio_peak * 0.02;

    // Vertex ID 0..5 for 2 triangles (Quad)
    // 0 1 2, 2 1 3 (Strip-like order manually mapped)
    var offsets = array<vec2<f32>, 6>(
        vec2<f32>(-1.0, -1.0),
        vec2<f32>( 1.0, -1.0),
        vec2<f32>(-1.0,  1.0),
        vec2<f32>(-1.0,  1.0),
        vec2<f32>( 1.0, -1.0),
        vec2<f32>( 1.0,  1.0)
    );

    let offset = offsets[vertex_index];

    // Rotate
    let c = cos(p.rot.x);
    let s = sin(p.rot.x);
    let rot_x = offset.x * c - offset.y * s;
    let rot_y = offset.x * s + offset.y * c;

    let x = p.pos.x + rot_x * size / uniforms.aspect_ratio;
    let y = p.pos.y + rot_y * size;

    var output : VertexOutput;
    output.Position = vec4<f32>(x, y, 0.0, 1.0);
    output.Color = p.color * (0.5 + 0.5 * uniforms.audio_peak);
    return output;
}

@fragment
fn fs_main(@location(0) Color : vec4<f32>) -> @location(0) vec4<f32> {
    return Color;
}
)";

void gpu_init(GLFWwindow *window) {
  g_instance = wgpuCreateInstance(nullptr);
  g_surface = platform_create_wgpu_surface(g_instance);

  WGPURequestAdapterOptions adapter_opts = {};
  adapter_opts.compatibleSurface = g_surface;
  adapter_opts.powerPreference = WGPUPowerPreference_HighPerformance;

  wgpuInstanceRequestAdapter(g_instance, &adapter_opts,
                             {nullptr, WGPUCallbackMode_WaitAnyOnly,
                              handle_request_adapter, &g_adapter, nullptr});
  while (!g_adapter)
    wgpuInstanceWaitAny(g_instance, 0, nullptr, 0);

  WGPUDeviceDescriptor device_desc = {};
#ifndef STRIP_ALL
  device_desc.uncapturedErrorCallbackInfo.callback = handle_device_error;
#endif

  wgpuAdapterRequestDevice(g_adapter, &device_desc,
                           {nullptr, WGPUCallbackMode_WaitAnyOnly,
                            handle_request_device, &g_device, nullptr});
  while (!g_device)
    wgpuInstanceWaitAny(g_instance, 0, nullptr, 0);

  g_queue = wgpuDeviceGetQueue(g_device);

  WGPUSurfaceCapabilities caps = {};
  wgpuSurfaceGetCapabilities(g_surface, g_adapter, &caps);
  WGPUTextureFormat swap_chain_format = caps.formats[0];

  int width, height;
  glfwGetFramebufferSize(window, &width, &height);
  g_config.device = g_device;
  g_config.format = swap_chain_format;
  g_config.usage = WGPUTextureUsage_RenderAttachment;
  g_config.width = width;
  g_config.height = height;
  g_config.presentMode = WGPUPresentMode_Fifo;
  g_config.alphaMode = WGPUCompositeAlphaMode_Opaque;
  wgpuSurfaceConfigure(g_surface, &g_config);

  // Initialize Uniforms
  g_uniform_buffer_struct = gpu_create_buffer(
      sizeof(float) * 4, WGPUBufferUsage_Uniform | WGPUBufferUsage_CopyDst,
      nullptr);

  // Initialize Main Pass
  ResourceBinding main_bindings[] = {
      {g_uniform_buffer_struct, WGPUBufferBindingType_Uniform}};
  g_main_pass = gpu_create_render_pass(main_shader_wgsl, main_bindings, 1);
  g_main_pass.vertex_count = 21;

  // Initialize Particles
  std::vector<Particle> initial_particles(NUM_PARTICLES);
  for (int i = 0; i < NUM_PARTICLES; ++i) {
    initial_particles[i].pos[0] = ((float)(rand() % 100) / 50.0f) - 1.0f;
    initial_particles[i].pos[1] = ((float)(rand() % 100) / 50.0f) - 1.0f;
    initial_particles[i].pos[2] = 0.0f;
    initial_particles[i].pos[3] = 1.0f;

    initial_particles[i].vel[0] = 0.0f;
    initial_particles[i].vel[1] = 0.0f;

    initial_particles[i].rot[0] = 0.0f;
    initial_particles[i].rot[1] = ((float)(rand() % 10) / 100.0f);

    initial_particles[i].color[0] = (float)(rand() % 10) / 10.0f;
    initial_particles[i].color[1] = (float)(rand() % 10) / 10.0f;
    initial_particles[i].color[2] = 1.0f;
    initial_particles[i].color[3] = 1.0f;
  }

  g_particle_buffer =
      gpu_create_buffer(sizeof(Particle) * NUM_PARTICLES,
                        WGPUBufferUsage_Storage | WGPUBufferUsage_CopyDst |
                            WGPUBufferUsage_Vertex,
                        initial_particles.data());

  // Initialize Particle Compute Pass
  ResourceBinding compute_bindings[] = {
      {g_particle_buffer, WGPUBufferBindingType_Storage},
      {g_uniform_buffer_struct, WGPUBufferBindingType_Uniform}};
  g_particle_compute_pass =
      gpu_create_compute_pass(particle_compute_wgsl, compute_bindings, 2);
  g_particle_compute_pass.workgroup_size_x = (NUM_PARTICLES + 63) / 64;
  g_particle_compute_pass.workgroup_size_y = 1;
  g_particle_compute_pass.workgroup_size_z = 1;

  // Initialize Particle Render Pass
  ResourceBinding render_bindings[] = {
      {g_particle_buffer, WGPUBufferBindingType_ReadOnlyStorage},
      {g_uniform_buffer_struct, WGPUBufferBindingType_Uniform}};
  g_particle_render_pass =
      gpu_create_render_pass(particle_render_wgsl, render_bindings, 2);
  g_particle_render_pass.vertex_count = 6;
  g_particle_render_pass.instance_count = NUM_PARTICLES;
}

void gpu_draw(float audio_peak, float aspect_ratio, float time) {
  WGPUSurfaceTexture surface_texture;
  wgpuSurfaceGetCurrentTexture(g_surface, &surface_texture);
  if (surface_texture.status !=
          WGPUSurfaceGetCurrentTextureStatus_SuccessOptimal &&
      surface_texture.status !=
          WGPUSurfaceGetCurrentTextureStatus_SuccessSuboptimal)
    return;

  WGPUTextureView view =
      wgpuTextureCreateView(surface_texture.texture, nullptr);

  struct {
    float audio_peak;
    float aspect_ratio;
    float time;
    float padding;
  } uniforms = {audio_peak, aspect_ratio, time, 0.0f};
  wgpuQueueWriteBuffer(g_queue, g_uniform_buffer_struct.buffer, 0, &uniforms,
                       sizeof(uniforms));

  WGPUCommandEncoderDescriptor encoder_desc = {};
  WGPUCommandEncoder encoder =
      wgpuDeviceCreateCommandEncoder(g_device, &encoder_desc);

  // --- Compute Pass ---
  {
    WGPUComputePassDescriptor compute_desc = {};
    compute_desc.label = label_view("Particle Compute");
    WGPUComputePassEncoder compute_pass =
        wgpuCommandEncoderBeginComputePass(encoder, &compute_desc);
    wgpuComputePassEncoderSetPipeline(compute_pass,
                                      g_particle_compute_pass.pipeline);
    wgpuComputePassEncoderSetBindGroup(
        compute_pass, 0, g_particle_compute_pass.bind_group, 0, nullptr);
    wgpuComputePassEncoderDispatchWorkgroups(
        compute_pass, g_particle_compute_pass.workgroup_size_x, 1, 1);
    wgpuComputePassEncoderEnd(compute_pass);
  }

  // --- Render Pass ---
  {
    WGPURenderPassColorAttachment color_attachment = {};
    color_attachment.view = view;
    color_attachment.loadOp = WGPULoadOp_Clear;
    color_attachment.storeOp = WGPUStoreOp_Store;
    float flash = audio_peak * 0.2f;
    color_attachment.clearValue = {0.05 + flash, 0.1 + flash, 0.2 + flash, 1.0};
    color_attachment.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED;

    WGPURenderPassDescriptor render_pass_desc = {};
    render_pass_desc.colorAttachmentCount = 1;
    render_pass_desc.colorAttachments = &color_attachment;

    WGPURenderPassEncoder pass =
        wgpuCommandEncoderBeginRenderPass(encoder, &render_pass_desc);

    // Draw Main Object
    wgpuRenderPassEncoderSetPipeline(pass, g_main_pass.pipeline);
    wgpuRenderPassEncoderSetBindGroup(pass, 0, g_main_pass.bind_group, 0,
                                      nullptr);
    wgpuRenderPassEncoderDraw(pass, g_main_pass.vertex_count, 1, 0, 0);

    // Draw Particles
    wgpuRenderPassEncoderSetPipeline(pass, g_particle_render_pass.pipeline);
    wgpuRenderPassEncoderSetBindGroup(
        pass, 0, g_particle_render_pass.bind_group, 0, nullptr);
    wgpuRenderPassEncoderDraw(pass, g_particle_render_pass.vertex_count,
                              g_particle_render_pass.instance_count, 0, 0);

    wgpuRenderPassEncoderEnd(pass);
  }

  WGPUCommandBufferDescriptor cmd_desc = {};
  WGPUCommandBuffer commands = wgpuCommandEncoderFinish(encoder, &cmd_desc);
  wgpuQueueSubmit(g_queue, 1, &commands);
  wgpuSurfacePresent(g_surface);

  wgpuTextureViewRelease(view);
  wgpuTextureRelease(surface_texture.texture);
}

void gpu_shutdown() {
}