summaryrefslogtreecommitdiff
path: root/src/gpu/effects/rotating_cube_effect.cc
blob: 8d1f05a71c6f8c7fdffb4bfd8c0e24332da30eff (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
// This file is part of the 64k demo project.
// It implements RotatingCubeEffect for bump-mapped rotating cube rendering.
// Uses auxiliary texture masking to render only inside a circular region.

#include "gpu/effects/rotating_cube_effect.h"
#include "generated/assets.h"
#include "gpu/effects/shader_composer.h"
#include "util/asset_manager_utils.h"

RotatingCubeEffect::RotatingCubeEffect(const GpuContext& ctx) : Effect(ctx) {
}

RotatingCubeEffect::~RotatingCubeEffect() {
  if (mask_sampler_)
    wgpuSamplerRelease(mask_sampler_);
  if (noise_sampler_)
    wgpuSamplerRelease(noise_sampler_);
  if (noise_view_)
    wgpuTextureViewRelease(noise_view_);
  if (noise_texture_)
    wgpuTextureRelease(noise_texture_);
  if (bind_group_1_)
    wgpuBindGroupRelease(bind_group_1_);
  if (bind_group_0_)
    wgpuBindGroupRelease(bind_group_0_);
  if (pipeline_)
    wgpuRenderPipelineRelease(pipeline_);
}

void RotatingCubeEffect::init(MainSequence* demo) {
  demo_ = demo;

  uniform_buffer_ =
      gpu_create_buffer(ctx_.device, sizeof(Uniforms),
                        WGPUBufferUsage_Uniform | WGPUBufferUsage_CopyDst);
  object_buffer_ =
      gpu_create_buffer(ctx_.device, sizeof(ObjectData),
                        WGPUBufferUsage_Storage | WGPUBufferUsage_CopyDst);

  const WGPUTextureDescriptor tex_desc = {
      .usage =
          WGPUTextureUsage_TextureBinding | WGPUTextureUsage_RenderAttachment,
      .dimension = WGPUTextureDimension_2D,
      .size = {1, 1, 1},
      .format = WGPUTextureFormat_RGBA8Unorm,
      .mipLevelCount = 1,
      .sampleCount = 1,
  };
  noise_texture_ = wgpuDeviceCreateTexture(ctx_.device, &tex_desc);
  noise_view_ = wgpuTextureCreateView(noise_texture_, nullptr);

  WGPUSamplerDescriptor sampler_desc = {};
  sampler_desc.addressModeU = WGPUAddressMode_Repeat;
  sampler_desc.addressModeV = WGPUAddressMode_Repeat;
  sampler_desc.magFilter = WGPUFilterMode_Linear;
  sampler_desc.minFilter = WGPUFilterMode_Linear;
  sampler_desc.maxAnisotropy = 1;
  noise_sampler_ = wgpuDeviceCreateSampler(ctx_.device, &sampler_desc);

  WGPUSamplerDescriptor mask_sampler_desc = {};
  mask_sampler_desc.addressModeU = WGPUAddressMode_ClampToEdge;
  mask_sampler_desc.addressModeV = WGPUAddressMode_ClampToEdge;
  mask_sampler_desc.magFilter = WGPUFilterMode_Linear;
  mask_sampler_desc.minFilter = WGPUFilterMode_Linear;
  mask_sampler_desc.maxAnisotropy = 1;
  mask_sampler_ = wgpuDeviceCreateSampler(ctx_.device, &mask_sampler_desc);

  size_t shader_size;
  const char* shader_code =
      (const char*)GetAsset(AssetId::ASSET_MASKED_CUBE_SHADER, &shader_size);

  ShaderComposer::CompositionMap composition_map;
  composition_map["render/scene_query_mode"] = "render/scene_query_linear";
  composed_shader_ = ShaderComposer::Get().Compose(
      {}, std::string(shader_code, shader_size), composition_map);

  WGPUShaderSourceWGSL wgsl_src = {};
  wgsl_src.chain.sType = WGPUSType_ShaderSourceWGSL;
  wgsl_src.code = str_view(composed_shader_.c_str());

  WGPUShaderModuleDescriptor shader_desc = {};
  shader_desc.nextInChain = &wgsl_src.chain;
  WGPUShaderModule shader_module =
      wgpuDeviceCreateShaderModule(ctx_.device, &shader_desc);

  const WGPUBindGroupLayoutEntry bgl_entries_0[] = {
      {.binding = 0,
       .visibility = WGPUShaderStage_Vertex | WGPUShaderStage_Fragment,
       .buffer = {.type = WGPUBufferBindingType_Uniform,
                  .minBindingSize = sizeof(Uniforms)}},
      {.binding = 1,
       .visibility = WGPUShaderStage_Vertex | WGPUShaderStage_Fragment,
       .buffer = {.type = WGPUBufferBindingType_ReadOnlyStorage,
                  .minBindingSize = sizeof(ObjectData)}},
      {.binding = 3,
       .visibility = WGPUShaderStage_Fragment,
       .texture = {.sampleType = WGPUTextureSampleType_Float,
                   .viewDimension = WGPUTextureViewDimension_2D}},
      {.binding = 4,
       .visibility = WGPUShaderStage_Fragment,
       .sampler = {.type = WGPUSamplerBindingType_Filtering}},
  };
  const WGPUBindGroupLayoutDescriptor bgl_desc_0 = {
      .entryCount = 4,
      .entries = bgl_entries_0,
  };
  WGPUBindGroupLayout bgl_0 =
      wgpuDeviceCreateBindGroupLayout(ctx_.device, &bgl_desc_0);

  const WGPUBindGroupLayoutEntry bgl_entries_1[] = {
      {.binding = 0,
       .visibility = WGPUShaderStage_Fragment,
       .texture = {.sampleType = WGPUTextureSampleType_Float,
                   .viewDimension = WGPUTextureViewDimension_2D}},
      {.binding = 1,
       .visibility = WGPUShaderStage_Fragment,
       .sampler = {.type = WGPUSamplerBindingType_Filtering}},
  };
  const WGPUBindGroupLayoutDescriptor bgl_desc_1 = {
      .entryCount = 2,
      .entries = bgl_entries_1,
  };
  WGPUBindGroupLayout bgl_1 =
      wgpuDeviceCreateBindGroupLayout(ctx_.device, &bgl_desc_1);

  const WGPUBindGroupLayout bgls[] = {bgl_0, bgl_1};
  const WGPUPipelineLayoutDescriptor pl_desc = {
      .bindGroupLayoutCount = 2,
      .bindGroupLayouts = bgls,
  };
  WGPUPipelineLayout pipeline_layout =
      wgpuDeviceCreatePipelineLayout(ctx_.device, &pl_desc);

  const WGPUColorTargetState color_target = {
      .format = ctx_.format,
      .writeMask = WGPUColorWriteMask_All,
  };

  const WGPUDepthStencilState depth_stencil = {
      .format = WGPUTextureFormat_Depth24Plus,
      .depthWriteEnabled = WGPUOptionalBool_True,
      .depthCompare = WGPUCompareFunction_Less,
  };

  WGPUFragmentState fragment = {};
  fragment.module = shader_module;
  fragment.entryPoint = str_view("fs_main");
  fragment.targetCount = 1;
  fragment.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.primitive.cullMode = WGPUCullMode_None;
  pipeline_desc.depthStencil = &depth_stencil;
  pipeline_desc.multisample.count = 1;
  pipeline_desc.multisample.mask = 0xFFFFFFFF;
  pipeline_desc.fragment = &fragment;

  pipeline_ = wgpuDeviceCreateRenderPipeline(ctx_.device, &pipeline_desc);
  wgpuShaderModuleRelease(shader_module);
  wgpuPipelineLayoutRelease(pipeline_layout);

  const WGPUBindGroupEntry entries_0[] = {
      {.binding = 0,
       .buffer = uniform_buffer_.buffer,
       .size = sizeof(Uniforms)},
      {.binding = 1,
       .buffer = object_buffer_.buffer,
       .size = sizeof(ObjectData)},
      {.binding = 3, .textureView = noise_view_},
      {.binding = 4, .sampler = noise_sampler_},
  };

  const WGPUBindGroupDescriptor bg_desc_0 = {
      .layout = bgl_0,
      .entryCount = 4,
      .entries = entries_0,
  };
  bind_group_0_ = wgpuDeviceCreateBindGroup(ctx_.device, &bg_desc_0);
  wgpuBindGroupLayoutRelease(bgl_0);

  WGPUTextureView mask_view = demo_->get_auxiliary_view("circle_mask");
  const WGPUBindGroupEntry entries_1[] = {
      {.binding = 0, .textureView = mask_view},
      {.binding = 1, .sampler = mask_sampler_},
  };

  const WGPUBindGroupDescriptor bg_desc_1 = {
      .layout = bgl_1,
      .entryCount = 2,
      .entries = entries_1,
  };
  bind_group_1_ = wgpuDeviceCreateBindGroup(ctx_.device, &bg_desc_1);
  wgpuBindGroupLayoutRelease(bgl_1);
}

void RotatingCubeEffect::render(WGPURenderPassEncoder pass, float time,
                                float beat, float intensity,
                                float aspect_ratio) {
  rotation_ += 0.016f * 1.5f;

  const vec3 camera_pos = vec3(0, 0, 5);
  const vec3 target = vec3(0, 0, 0);
  const vec3 up = vec3(0, 1, 0);

  const mat4 view = mat4::look_at(camera_pos, target, up);
  const float fov = 60.0f * 3.14159f / 180.0f;
  const mat4 proj = mat4::perspective(fov, aspect_ratio, 0.1f, 100.0f);
  const mat4 view_proj = proj * view;

  const quat rot = quat::from_axis(vec3(0.3f, 1.0f, 0.2f), rotation_);
  const mat4 T = mat4::translate(vec3(0, 0, 0));
  const mat4 R = rot.to_mat();
  const mat4 S = mat4::scale(vec3(1.5f, 1.5f, 1.5f));
  const mat4 model = T * R * S;
  const mat4 inv_model = model.inverse();

  const Uniforms uniforms = {
      .view_proj = view_proj,
      .inv_view_proj = view_proj.inverse(),
      .camera_pos_time = vec4(camera_pos.x, camera_pos.y, camera_pos.z, time),
      .params = vec4(1.0f, 0.0f, 0.0f, 0.0f),
      .resolution = vec2(1280.0f, 720.0f),
  };

  const ObjectData obj_data = {
      .model = model,
      .inv_model = inv_model,
      .color = vec4(0.8f, 0.4f, 0.2f, 1.0f),
      .params = vec4(1.0f, 0.0f, 0.0f, 0.0f),
  };

  wgpuQueueWriteBuffer(ctx_.queue, uniform_buffer_.buffer, 0, &uniforms,
                       sizeof(Uniforms));
  wgpuQueueWriteBuffer(ctx_.queue, object_buffer_.buffer, 0, &obj_data,
                       sizeof(ObjectData));

  wgpuRenderPassEncoderSetPipeline(pass, pipeline_);
  wgpuRenderPassEncoderSetBindGroup(pass, 0, bind_group_0_, 0, nullptr);
  wgpuRenderPassEncoderSetBindGroup(pass, 1, bind_group_1_, 0, nullptr);
  wgpuRenderPassEncoderDraw(pass, 36, 1, 0, 0);
}