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
|
// This file is part of the 64k demo project.
// It implements the Renderer3D class.
#include "3d/renderer.h"
#include <algorithm>
#include <cassert>
#include <cstring>
#include <iostream>
#if !defined(STRIP_ALL)
bool Renderer3D::s_debug_enabled_ = false;
#endif
static const char* kShaderCode = R"(
struct GlobalUniforms {
view_proj: mat4x4<f32>,
camera_pos_time: vec4<f32>,
params: vec4<f32>,
};
struct ObjectData {
model: mat4x4<f32>,
inv_model: mat4x4<f32>,
color: vec4<f32>,
params: vec4<f32>,
};
struct ObjectsBuffer {
objects: array<ObjectData>,
};
@group(0) @binding(0) var<uniform> globals: GlobalUniforms;
@group(0) @binding(1) var<storage, read> object_data: ObjectsBuffer;
@group(0) @binding(2) var noise_tex: texture_2d<f32>;
@group(0) @binding(3) var noise_sampler: sampler;
struct VertexOutput {
@builtin(position) position: vec4<f32>,
@location(0) local_pos: vec3<f32>,
@location(1) color: vec4<f32>,
@location(2) @interpolate(flat) instance_index: u32,
@location(3) world_pos: vec3<f32>,
};
@vertex
fn vs_main(@builtin(vertex_index) vertex_index: u32,
@builtin(instance_index) instance_index: u32) -> VertexOutput {
var pos = array<vec3<f32>, 36>(
vec3(-1.0, -1.0, 1.0), vec3( 1.0, -1.0, 1.0), vec3( 1.0, 1.0, 1.0),
vec3(-1.0, -1.0, 1.0), vec3( 1.0, 1.0, 1.0), vec3(-1.0, 1.0, 1.0),
vec3(-1.0, -1.0, -1.0), vec3(-1.0, 1.0, -1.0), vec3( 1.0, 1.0, -1.0),
vec3(-1.0, -1.0, -1.0), vec3( 1.0, 1.0, -1.0), vec3( 1.0, -1.0, -1.0),
vec3(-1.0, 1.0, -1.0), vec3(-1.0, 1.0, 1.0), vec3( 1.0, 1.0, 1.0),
vec3(-1.0, 1.0, -1.0), vec3( 1.0, 1.0, 1.0), vec3( 1.0, 1.0, -1.0),
vec3(-1.0, -1.0, -1.0), vec3( 1.0, -1.0, -1.0), vec3( 1.0, -1.0, 1.0),
vec3(-1.0, -1.0, -1.0), vec3( 1.0, -1.0, 1.0), vec3(-1.0, -1.0, 1.0),
vec3( 1.0, -1.0, -1.0), vec3( 1.0, 1.0, -1.0), vec3( 1.0, 1.0, 1.0),
vec3( 1.0, -1.0, -1.0), vec3( 1.0, 1.0, 1.0), vec3( 1.0, -1.0, 1.0),
vec3(-1.0, -1.0, -1.0), vec3(-1.0, -1.0, 1.0), vec3(-1.0, 1.0, 1.0),
vec3(-1.0, -1.0, -1.0), vec3(-1.0, 1.0, 1.0), vec3(-1.0, 1.0, -1.0)
);
let p = pos[vertex_index];
let obj = object_data.objects[instance_index];
let world_pos = obj.model * vec4<f32>(p, 1.0);
let clip_pos = globals.view_proj * world_pos;
var out: VertexOutput;
out.position = clip_pos;
out.local_pos = p;
out.color = obj.color;
out.instance_index = instance_index;
out.world_pos = world_pos.xyz;
return out;
}
fn sdSphere(p: vec3<f32>, r: f32) -> f32 {
return length(p) - r;
}
fn sdBox(p: vec3<f32>, b: vec3<f32>) -> f32 {
let q = abs(p) - b;
return length(max(q, vec3<f32>(0.0))) + min(max(q.x, max(q.y, q.z)), 0.0);
}
fn sdTorus(p: vec3<f32>, t: vec2<f32>) -> f32 {
let q = vec2<f32>(length(p.xz) - t.x, p.y);
return length(q) - t.y;
}
fn sdPlane(p: vec3<f32>, n: vec3<f32>, h: f32) -> f32 {
return dot(p, n) + h;
}
fn get_dist(p: vec3<f32>, obj_type: f32) -> f32 {
if (obj_type == 1.0) { return length(p) - 1.0; } // Unit Sphere
if (obj_type == 2.0) { return sdBox(p, vec3<f32>(1.0)); } // Unit Box
if (obj_type == 3.0) { return sdTorus(p, vec2<f32>(1.0, 0.4)); } // Unit Torus
if (obj_type == 4.0) { return sdPlane(p, vec3<f32>(0.0, 1.0, 0.0), 0.0); }
return 100.0;
}
fn map_scene(p: vec3<f32>, skip_idx: u32) -> f32 {
var d = 1000.0;
let count = u32(globals.params.x);
for (var i = 0u; i < count; i = i + 1u) {
if (i == skip_idx) { continue; }
let obj = object_data.objects[i];
let obj_type = obj.params.x;
if (obj_type <= 0.0) { continue; }
let q = (obj.inv_model * vec4<f32>(p, 1.0)).xyz;
// Extraction of approx min scale for distance normalization
let scale_x = length(obj.model[0].xyz);
let scale_y = length(obj.model[1].xyz);
let scale_z = length(obj.model[2].xyz);
let s = min(scale_x, min(scale_y, scale_z));
d = min(d, get_dist(q, obj_type) * s);
}
return d;
}
fn calc_shadow(ro: vec3<f32>, rd: vec3<f32>, tmin: f32, tmax: f32, skip_idx: u32) -> f32 {
var res = 1.0;
var t = tmin;
if (t < 0.1) { t = 0.1; } // Robust bias to avoid self-shadowing
for (var i = 0; i < 32; i = i + 1) {
let h = map_scene(ro + rd * t, skip_idx);
if (h < 0.001) { return 0.0; }
res = min(res, 16.0 * h / t); // Standard k=16
t = t + clamp(h, 0.02, 0.5);
if (t > tmax) { break; }
}
return clamp(res, 0.0, 1.0);
}
fn get_normal(p: vec3<f32>, obj_type: f32) -> vec3<f32> {
if (obj_type == 1.0) { return normalize(p); }
let e = vec2<f32>(0.001, 0.0);
return normalize(vec3<f32>(
get_dist(p + e.xyy, obj_type) - get_dist(p - e.xyy, obj_type),
get_dist(p + e.yxy, obj_type) - get_dist(p - e.yxy, obj_type),
get_dist(p + e.yyx, obj_type) - get_dist(p - e.yyx, obj_type)
));
}
@fragment
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
let obj = object_data.objects[in.instance_index];
let obj_type = obj.params.x;
var p: vec3<f32>;
var normal: vec3<f32>;
var base_color = in.color.rgb;
let light_dir = normalize(vec3<f32>(1.0, 1.0, 1.0));
if (obj_type <= 0.0) { // Raster path
p = in.world_pos;
let local_normal = normalize(cross(dpdx(in.local_pos), dpdy(in.local_pos)));
// Normal transformation: multiply by transpose of inverse
let normal_matrix = mat3x3<f32>(obj.inv_model[0].xyz, obj.inv_model[1].xyz, obj.inv_model[2].xyz);
normal = normalize(transpose(normal_matrix) * local_normal);
} else { // SDF path
let ro = globals.camera_pos_time.xyz;
let rd = normalize(in.world_pos - ro);
var t = length(in.world_pos - ro) * 0.9;
for (var i = 0; i < 64; i = i + 1) {
p = ro + rd * t;
let q = (obj.inv_model * vec4<f32>(p, 1.0)).xyz;
let d_local = get_dist(q, obj_type);
let scale_x = length(obj.model[0].xyz);
let scale_y = length(obj.model[1].xyz);
let scale_z = length(obj.model[2].xyz);
let s = min(scale_x, min(scale_y, scale_z));
let d_world = d_local * s;
if (d_world < 0.001) { break; }
t = t + d_world;
if (t > length(in.world_pos - ro) * 1.5) { discard; }
}
let q_hit = (obj.inv_model * vec4<f32>(p, 1.0)).xyz;
let n_local = get_normal(q_hit, obj_type);
let normal_matrix = mat3x3<f32>(obj.inv_model[0].xyz, obj.inv_model[1].xyz, obj.inv_model[2].xyz);
normal = normalize(transpose(normal_matrix) * n_local);
}
let shadow = calc_shadow(p, light_dir, 0.05, 20.0, in.instance_index);
let diffuse = max(dot(normal, light_dir), 0.0);
let lighting = diffuse * (0.2 + 0.8 * shadow) + 0.15;
return vec4<f32>(base_color * lighting, 1.0);
}
)";
void Renderer3D::init(WGPUDevice device, WGPUQueue queue,
WGPUTextureFormat format) {
device_ = device;
queue_ = queue;
format_ = format;
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;
default_sampler_ = wgpuDeviceCreateSampler(device_, &sampler_desc);
create_default_resources();
create_pipeline();
#if !defined(STRIP_ALL)
visual_debug_.init(device_, format_);
#endif
}
void Renderer3D::shutdown() {
#if !defined(STRIP_ALL)
visual_debug_.shutdown();
#endif
if (default_sampler_)
wgpuSamplerRelease(default_sampler_);
if (pipeline_)
wgpuRenderPipelineRelease(pipeline_);
if (bind_group_)
wgpuBindGroupRelease(bind_group_);
if (global_uniform_buffer_)
wgpuBufferRelease(global_uniform_buffer_);
if (object_storage_buffer_)
wgpuBufferRelease(object_storage_buffer_);
if (depth_view_)
wgpuTextureViewRelease(depth_view_);
if (depth_texture_)
wgpuTextureRelease(depth_texture_);
}
void Renderer3D::resize(int width, int height) {
if (width == width_ && height == height_)
return;
width_ = width;
height_ = height;
if (depth_view_)
wgpuTextureViewRelease(depth_view_);
if (depth_texture_)
wgpuTextureRelease(depth_texture_);
WGPUTextureDescriptor desc = {};
desc.usage = WGPUTextureUsage_RenderAttachment;
desc.dimension = WGPUTextureDimension_2D;
desc.size = {(uint32_t)width, (uint32_t)height, 1};
desc.format = WGPUTextureFormat_Depth24Plus;
desc.mipLevelCount = 1;
desc.sampleCount = 1;
depth_texture_ = wgpuDeviceCreateTexture(device_, &desc);
WGPUTextureViewDescriptor view_desc = {};
view_desc.format = WGPUTextureFormat_Depth24Plus;
view_desc.dimension = WGPUTextureViewDimension_2D;
view_desc.aspect = WGPUTextureAspect_DepthOnly;
view_desc.arrayLayerCount = 1;
view_desc.mipLevelCount = 1;
depth_view_ = wgpuTextureCreateView(depth_texture_, &view_desc);
}
void Renderer3D::create_default_resources() {
global_uniform_buffer_ =
gpu_create_buffer(device_, sizeof(GlobalUniforms),
WGPUBufferUsage_Uniform | WGPUBufferUsage_CopyDst,
nullptr)
.buffer;
object_storage_buffer_ =
gpu_create_buffer(device_, sizeof(ObjectData) * kMaxObjects,
WGPUBufferUsage_Storage | WGPUBufferUsage_CopyDst,
nullptr)
.buffer;
}
void Renderer3D::set_noise_texture(WGPUTextureView noise_view) {
noise_texture_view_ = noise_view;
// Note: Bind group needs recreation if texture changes, but we'll do it in
// render for simplicity or just once at init if it's static. For this demo,
// let's recreate in render if changed.
}
void Renderer3D::create_pipeline() {
WGPUBindGroupLayoutEntry entries[4] = {};
entries[0].binding = 0;
entries[0].visibility = WGPUShaderStage_Vertex | WGPUShaderStage_Fragment;
entries[0].buffer.type = WGPUBufferBindingType_Uniform;
entries[0].buffer.minBindingSize = sizeof(GlobalUniforms);
entries[1].binding = 1;
entries[1].visibility = WGPUShaderStage_Vertex | WGPUShaderStage_Fragment;
entries[1].buffer.type = WGPUBufferBindingType_ReadOnlyStorage;
entries[1].buffer.minBindingSize = sizeof(ObjectData) * kMaxObjects;
entries[2].binding = 2;
entries[2].visibility = WGPUShaderStage_Fragment;
entries[2].texture.sampleType = WGPUTextureSampleType_Float;
entries[2].texture.viewDimension = WGPUTextureViewDimension_2D;
entries[3].binding = 3;
entries[3].visibility = WGPUShaderStage_Fragment;
entries[3].sampler.type = WGPUSamplerBindingType_Filtering;
WGPUBindGroupLayoutDescriptor bgl_desc = {};
bgl_desc.entryCount = 4;
bgl_desc.entries = entries;
WGPUBindGroupLayout bgl = wgpuDeviceCreateBindGroupLayout(device_, &bgl_desc);
WGPUPipelineLayoutDescriptor pl_desc = {};
pl_desc.bindGroupLayoutCount = 1;
pl_desc.bindGroupLayouts = &bgl;
WGPUPipelineLayout pipeline_layout =
wgpuDeviceCreatePipelineLayout(device_, &pl_desc);
#if defined(DEMO_CROSS_COMPILE_WIN32)
WGPUShaderModuleWGSLDescriptor wgsl_desc = {};
wgsl_desc.chain.sType = WGPUSType_ShaderModuleWGSLDescriptor;
wgsl_desc.code = kShaderCode;
WGPUShaderModuleDescriptor shader_desc = {};
shader_desc.nextInChain = (const WGPUChainedStruct*)&wgsl_desc.chain;
#else
WGPUShaderSourceWGSL wgsl_desc = {};
wgsl_desc.chain.sType = WGPUSType_ShaderSourceWGSL;
wgsl_desc.code = {kShaderCode, strlen(kShaderCode)};
WGPUShaderModuleDescriptor shader_desc = {};
shader_desc.nextInChain = (const WGPUChainedStruct*)&wgsl_desc.chain;
#endif
WGPUShaderModule shader_module =
wgpuDeviceCreateShaderModule(device_, &shader_desc);
WGPUDepthStencilState depth_stencil = {};
depth_stencil.format = WGPUTextureFormat_Depth24Plus;
depth_stencil.depthWriteEnabled = WGPUOptionalBool_True;
depth_stencil.depthCompare = WGPUCompareFunction_Less;
WGPURenderPipelineDescriptor desc = {};
desc.layout = pipeline_layout;
desc.vertex.module = shader_module;
#if defined(DEMO_CROSS_COMPILE_WIN32)
desc.vertex.entryPoint = "vs_main";
#else
desc.vertex.entryPoint = {"vs_main", 7};
#endif
WGPUColorTargetState color_target = {};
color_target.format = format_;
color_target.writeMask = WGPUColorWriteMask_All;
WGPUFragmentState fragment = {};
fragment.module = shader_module;
#if defined(DEMO_CROSS_COMPILE_WIN32)
fragment.entryPoint = "fs_main";
#else
fragment.entryPoint = {"fs_main", 7};
#endif
fragment.targetCount = 1;
fragment.targets = &color_target;
desc.fragment = &fragment;
desc.primitive.topology = WGPUPrimitiveTopology_TriangleList;
desc.primitive.cullMode = WGPUCullMode_Back;
desc.primitive.frontFace = WGPUFrontFace_CCW;
desc.depthStencil = &depth_stencil;
desc.multisample.count = 1;
desc.multisample.mask = 0xFFFFFFFF;
pipeline_ = wgpuDeviceCreateRenderPipeline(device_, &desc);
wgpuBindGroupLayoutRelease(bgl);
wgpuPipelineLayoutRelease(pipeline_layout);
wgpuShaderModuleRelease(shader_module);
}
void Renderer3D::update_uniforms(const Scene& scene, const Camera& camera,
float time) {
GlobalUniforms globals;
globals.view_proj = camera.get_projection_matrix() * camera.get_view_matrix();
globals.camera_pos_time =
vec4(camera.position.x, camera.position.y, camera.position.z, time);
globals.params =
vec4((float)std::min((size_t)kMaxObjects, scene.objects.size()), 0.0f,
0.0f, 0.0f);
wgpuQueueWriteBuffer(queue_, global_uniform_buffer_, 0, &globals,
sizeof(GlobalUniforms));
std::vector<ObjectData> obj_data;
for (const auto& obj : scene.objects) {
ObjectData data;
data.model = obj.get_model_matrix();
// Calculate Inverse for point transformation
data.inv_model = data.model.inverse();
data.color = obj.color;
float type_id = 0.0f;
if (obj.type == ObjectType::SPHERE)
type_id = 1.0f;
else if (obj.type == ObjectType::BOX)
type_id = 2.0f;
else if (obj.type == ObjectType::TORUS)
type_id = 3.0f;
else if (obj.type == ObjectType::PLANE)
type_id = 4.0f;
data.params = vec4(type_id, 0, 0, 0);
obj_data.push_back(data);
if (obj_data.size() >= kMaxObjects)
break;
}
if (!obj_data.empty()) {
wgpuQueueWriteBuffer(queue_, object_storage_buffer_, 0, obj_data.data(),
obj_data.size() * sizeof(ObjectData));
}
}
void Renderer3D::draw(WGPURenderPassEncoder pass, const Scene& scene,
const Camera& camera, float time) {
update_uniforms(scene, camera, time);
// Lazy Bind Group creation
if (bind_group_)
wgpuBindGroupRelease(bind_group_);
WGPUBindGroupEntry bg_entries[4] = {};
bg_entries[0].binding = 0;
bg_entries[0].buffer = global_uniform_buffer_;
bg_entries[0].size = sizeof(GlobalUniforms);
bg_entries[1].binding = 1;
bg_entries[1].buffer = object_storage_buffer_;
bg_entries[1].size = sizeof(ObjectData) * kMaxObjects;
bg_entries[2].binding = 2;
bg_entries[2].textureView = noise_texture_view_;
bg_entries[3].binding = 3;
bg_entries[3].sampler = default_sampler_;
WGPUBindGroupDescriptor bg_desc = {};
bg_desc.layout = wgpuRenderPipelineGetBindGroupLayout(pipeline_, 0);
bg_desc.entryCount = 4;
bg_desc.entries = bg_entries;
bind_group_ = wgpuDeviceCreateBindGroup(device_, &bg_desc);
wgpuBindGroupLayoutRelease(bg_desc.layout);
wgpuRenderPassEncoderSetPipeline(pass, pipeline_);
wgpuRenderPassEncoderSetBindGroup(pass, 0, bind_group_, 0, nullptr);
uint32_t instance_count =
(uint32_t)std::min((size_t)kMaxObjects, scene.objects.size());
if (instance_count > 0) {
wgpuRenderPassEncoderDraw(pass, 36, instance_count, 0, 0);
}
#if !defined(STRIP_ALL)
if (s_debug_enabled_) {
for (const auto& obj : scene.objects) {
// Simple AABB approximation from scale
visual_debug_.add_box(obj.position, obj.scale,
vec3(1.0f, 1.0f, 0.0f)); // Yellow boxes
}
// Calculate ViewProj matrix for the debug renderer
mat4 view_proj = camera.get_projection_matrix() * camera.get_view_matrix();
visual_debug_.render(pass, view_proj);
}
#endif
}
void Renderer3D::render(const Scene& scene, const Camera& camera, float time,
WGPUTextureView target_view,
WGPUTextureView depth_view_opt) {
WGPUTextureView depth_view = depth_view_opt ? depth_view_opt : depth_view_;
if (!depth_view)
return;
WGPURenderPassColorAttachment color_attachment = {};
gpu_init_color_attachment(color_attachment, target_view);
color_attachment.clearValue = {0.05, 0.05, 0.1, 1.0};
WGPURenderPassDepthStencilAttachment depth_attachment = {};
depth_attachment.view = depth_view;
depth_attachment.depthLoadOp = WGPULoadOp_Clear;
depth_attachment.depthStoreOp = WGPUStoreOp_Store;
depth_attachment.depthClearValue = 1.0f;
WGPURenderPassDescriptor pass_desc = {};
pass_desc.colorAttachmentCount = 1;
pass_desc.colorAttachments = &color_attachment;
pass_desc.depthStencilAttachment = &depth_attachment;
WGPUCommandEncoder encoder = wgpuDeviceCreateCommandEncoder(device_, nullptr);
WGPURenderPassEncoder pass =
wgpuCommandEncoderBeginRenderPass(encoder, &pass_desc);
wgpuRenderPassEncoderSetViewport(pass, 0.0f, 0.0f, (float)width_,
(float)height_, 0.0f, 1.0f);
draw(pass, scene, camera, time);
wgpuRenderPassEncoderEnd(pass);
WGPUCommandBuffer commands = wgpuCommandEncoderFinish(encoder, nullptr);
wgpuQueueSubmit(queue_, 1, &commands);
wgpuRenderPassEncoderRelease(pass);
wgpuCommandBufferRelease(commands);
wgpuCommandEncoderRelease(encoder);
}
|