-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathprojected_shadow_mapping.c
More file actions
1409 lines (1203 loc) · 44.4 KB
/
Copy pathprojected_shadow_mapping.c
File metadata and controls
1409 lines (1203 loc) · 44.4 KB
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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "webgpu/imgui_overlay.h"
#include "webgpu/wgpu_common.h"
#include "core/camera.h"
#include "core/gltf_model.h"
#include <cglm/cglm.h>
#ifdef __WAJIC__
#define WAJIC_SFETCH_IMPL
#include <wajic_sfetch.h>
#define WAJIC_TIME_IMPL
#include <wajic_time.h>
/* WAjic WebGPU handles are uint32_t, not pointers; redefine NULL to plain 0
* so WGPU handle assignments compile without pointer-to-integer errors. */
#ifdef NULL
#undef NULL
#define NULL 0
#endif
#else
#define SOKOL_FETCH_IMPL
#include <sokol_fetch.h>
#define SOKOL_TIME_IMPL
#include <sokol_time.h>
#endif
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpedantic"
#define CIMGUI_DEFINE_ENUMS_AND_STRUCTS
#endif
#include <cimgui.h>
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif
#include <stdbool.h>
#include <string.h>
/* -------------------------------------------------------------------------- *
* WebGPU Example - Projected Shadow Mapping
*
* Shadow mapping for directional light sources. The shadow map is generated in
* a first pass from the light's point of view. The scene is then rendered with
* shadow coord lookup in the shadow map. Includes PCF (Percentage Closer
* Filtering) for soft shadow edges, plus a debug mode to visualize the shadow
* map.
*
* Ported from the Vulkan example:
* src/examples/Vulkan/examples/shadowmapping/shadowmapping.cpp
*
* Ref:
* https://github.com/SaschaWillems/Vulkan/tree/master/examples/shadowmapping
* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- *
* WGSL Shaders
* -------------------------------------------------------------------------- */
static const char* offscreen_shader_wgsl;
static const char* scene_shader_wgsl;
static const char* debug_quad_shader_wgsl;
/* -------------------------------------------------------------------------- *
* Constants
* -------------------------------------------------------------------------- */
#define SHADOW_MAP_DIM 2048u
#define NUM_SCENES 2
/* Scene model file paths */
static const char* scene_paths[NUM_SCENES] = {
"assets/models/vulkanscene_shadow.gltf",
"assets/models/samplescene.gltf",
};
static const char* scene_names[NUM_SCENES] = {
"Vulkan scene",
"Teapots and pillars",
};
/* -------------------------------------------------------------------------- *
* Uniform data
* -------------------------------------------------------------------------- */
/* Offscreen pass: light projection MVP (depth only) */
typedef struct {
mat4 depth_mvp;
} uniform_data_offscreen_t;
/* Scene pass: camera matrices + shadow coord + lighting */
typedef struct {
mat4 projection;
mat4 view;
mat4 model;
mat4 light_space;
vec4 light_pos;
float z_near;
float z_far;
float _pad[2]; /* 16-byte alignment */
} uniform_data_scene_t;
/* -------------------------------------------------------------------------- *
* Global state struct
* -------------------------------------------------------------------------- */
static struct {
/* Camera */
camera_t camera;
/* Animation timer */
float timer;
float animation_speed;
uint64_t last_frame_time;
/* Models */
gltf_model_t scenes[NUM_SCENES];
bool scenes_loaded[NUM_SCENES];
int scenes_load_count;
bool model_buffers_created;
/* GPU vertex/index buffers per scene */
struct {
WGPUBuffer vertex_buffer;
WGPUBuffer index_buffer;
} scene_buffers[NUM_SCENES];
/* Shadow map */
struct {
WGPUTexture depth_texture;
WGPUTextureView depth_view;
} shadow_map;
/* Depth texture for main render pass */
struct {
WGPUTexture texture;
WGPUTextureView view;
} depth;
/* Uniform buffers */
struct {
WGPUBuffer offscreen;
WGPUBuffer scene;
} uniform_buffers;
/* Uniform data */
uniform_data_offscreen_t ubo_offscreen;
uniform_data_scene_t ubo_scene;
/* Bind group layouts */
struct {
WGPUBindGroupLayout offscreen;
WGPUBindGroupLayout scene;
} bind_group_layouts;
/* Pipeline layouts */
struct {
WGPUPipelineLayout offscreen;
WGPUPipelineLayout scene; /* also used for debug quad */
} pipeline_layouts;
/* Bind groups */
struct {
WGPUBindGroup offscreen;
WGPUBindGroup scene;
WGPUBindGroup debug;
} bind_groups;
/* Render pipelines */
struct {
WGPURenderPipeline offscreen; /* Shadow pass: depth only */
WGPURenderPipeline scene_shadow; /* Scene with basic shadow */
WGPURenderPipeline scene_shadow_pcf; /* Scene with PCF shadow */
WGPURenderPipeline debug; /* Shadow map visualization */
} pipelines;
/* Shadow pass render descriptors */
struct {
WGPURenderPassDepthStencilAttachment depth_att;
WGPURenderPassDescriptor descriptor;
} shadow_pass;
/* Main pass render descriptors */
WGPURenderPassColorAttachment color_attachment;
WGPURenderPassDepthStencilAttachment depth_stencil_attachment;
WGPURenderPassDescriptor render_pass_descriptor;
/* Settings (GUI) */
struct {
int32_t scene_index;
bool display_shadow_map;
bool filter_pcf;
} settings;
/* Light parameters */
float z_near;
float z_far;
float light_fov;
vec3 light_pos;
WGPUBool initialized;
} state = {
/* Default render pass */
.color_attachment = {
.loadOp = WGPULoadOp_Clear,
.storeOp = WGPUStoreOp_Store,
.clearValue = {0.0f, 0.0f, 0.0f, 1.0f},
.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED,
},
.depth_stencil_attachment = {
.depthLoadOp = WGPULoadOp_Clear,
.depthStoreOp = WGPUStoreOp_Store,
.depthClearValue = 1.0f,
.stencilLoadOp = WGPULoadOp_Clear,
.stencilStoreOp = WGPUStoreOp_Store,
.stencilClearValue = 0,
},
.render_pass_descriptor = {
.colorAttachmentCount = 1,
.colorAttachments = &state.color_attachment,
.depthStencilAttachment = &state.depth_stencil_attachment,
},
/* Shadow pass (depth only) */
.shadow_pass = {
.depth_att = {
.depthLoadOp = WGPULoadOp_Clear,
.depthStoreOp = WGPUStoreOp_Store,
.depthClearValue = 1.0f,
.stencilLoadOp = WGPULoadOp_Undefined,
.stencilStoreOp = WGPUStoreOp_Undefined,
},
.descriptor = {
.colorAttachmentCount = 0,
.colorAttachments = NULL,
.depthStencilAttachment = &state.shadow_pass.depth_att,
},
},
/* Settings defaults */
.settings = {
.scene_index = 0,
.display_shadow_map = false,
.filter_pcf = true,
},
/* Light defaults */
.z_near = 1.0f,
.z_far = 96.0f,
.light_fov = 45.0f,
.animation_speed = 0.125f, /* Vulkan base timerSpeed (0.25) * 0.5 */
};
/* -------------------------------------------------------------------------- *
* Model loading
* -------------------------------------------------------------------------- */
#ifdef __WAJIC__
static void model_fetch_callback(const sfetch_response_t* response)
{
if (!response->fetched) {
printf("projected_shadow_mapping: model fetch failed, error: %d\n",
response->error_code);
return;
}
int scene_idx = *(const int*)response->user_data;
bool ok
= gltf_model_load_from_memory(&state.scenes[scene_idx], response->data.ptr,
response->data.size, NULL, 1.0f);
if (ok) {
/* Apply the same transforms as the native gltf_model_load_from_file_ext */
static const gltf_model_desc_t desc = {
.loading_flags = GltfLoadingFlag_PreTransformVertices
| GltfLoadingFlag_PreMultiplyVertexColors,
};
if (state.scenes[scene_idx].vertex_count > 0) {
gltf_model_bake_node_transforms(&state.scenes[scene_idx],
state.scenes[scene_idx].vertices, &desc);
}
state.scenes_loaded[scene_idx] = true;
state.scenes_load_count++;
}
else {
printf("projected_shadow_mapping: failed to parse %s\n",
scene_paths[scene_idx]);
}
}
#endif /* __WAJIC__ */
static void load_models(void)
{
const gltf_model_desc_t desc = {
.loading_flags = GltfLoadingFlag_PreTransformVertices
| GltfLoadingFlag_PreMultiplyVertexColors,
/* No FlipY for WebGPU */
};
#ifdef __WAJIC__
/* WAjic: async sfetch; scenes_loaded flags set in callbacks */
static const int scene_idx[NUM_SCENES] = {0, 1};
for (int i = 0; i < NUM_SCENES; i++) {
sfetch_send(&(sfetch_request_t){
.path = scene_paths[i],
.callback = model_fetch_callback,
.user_data = {.ptr = &scene_idx[i], .size = sizeof(scene_idx[i])},
.channel = 0,
});
}
#else
for (int i = 0; i < NUM_SCENES; i++) {
state.scenes_loaded[i] = gltf_model_load_from_file_ext(
&state.scenes[i], scene_paths[i], 1.0f, &desc);
if (!state.scenes_loaded[i]) {
printf("Failed to load scene: %s\n", scene_paths[i]);
}
}
#endif /* __WAJIC__ */
}
static void create_model_buffers(struct wgpu_context_t* wgpu_context)
{
WGPUDevice device = wgpu_context->device;
for (int i = 0; i < NUM_SCENES; i++) {
/* Skip scenes that are not yet loaded or whose buffers were already created
*/
if (!state.scenes_loaded[i] || state.scene_buffers[i].vertex_buffer) {
continue;
}
gltf_model_t* m = &state.scenes[i];
size_t vb_size = m->vertex_count * sizeof(gltf_vertex_t);
size_t ib_size = m->index_count * sizeof(uint32_t);
/* Vertex buffer */
state.scene_buffers[i].vertex_buffer = wgpuDeviceCreateBuffer(
device, &(WGPUBufferDescriptor){
.label = STRVIEW("Scene - Vertex Buffer"),
.usage = WGPUBufferUsage_Vertex | WGPUBufferUsage_CopyDst,
.size = vb_size,
.mappedAtCreation = true,
});
void* vdata = wgpuBufferGetMappedRange(state.scene_buffers[i].vertex_buffer,
0, vb_size);
memcpy(vdata, m->vertices, vb_size);
wgpuBufferUnmap(state.scene_buffers[i].vertex_buffer);
/* Index buffer */
if (m->index_count > 0) {
state.scene_buffers[i].index_buffer = wgpuDeviceCreateBuffer(
device, &(WGPUBufferDescriptor){
.label = STRVIEW("Scene - Index Buffer"),
.usage = WGPUBufferUsage_Index | WGPUBufferUsage_CopyDst,
.size = ib_size,
.mappedAtCreation = true,
});
void* idata = wgpuBufferGetMappedRange(
state.scene_buffers[i].index_buffer, 0, ib_size);
memcpy(idata, m->indices, ib_size);
wgpuBufferUnmap(state.scene_buffers[i].index_buffer);
}
}
}
/* -------------------------------------------------------------------------- *
* Draw model helper
* -------------------------------------------------------------------------- */
static void draw_model(WGPURenderPassEncoder pass, int scene_index)
{
WGPUBuffer vb = state.scene_buffers[scene_index].vertex_buffer;
/* Guard: scene must be loaded and its GPU buffers must be ready */
if (!state.scenes_loaded[scene_index] || !vb) {
return;
}
gltf_model_t* model = &state.scenes[scene_index];
WGPUBuffer ib = state.scene_buffers[scene_index].index_buffer;
wgpuRenderPassEncoderSetVertexBuffer(pass, 0, vb, 0, WGPU_WHOLE_SIZE);
if (ib) {
wgpuRenderPassEncoderSetIndexBuffer(pass, ib, WGPUIndexFormat_Uint32, 0,
WGPU_WHOLE_SIZE);
}
for (uint32_t n = 0; n < model->linear_node_count; n++) {
gltf_node_t* node = model->linear_nodes[n];
if (!node->mesh) {
continue;
}
gltf_mesh_t* mesh = node->mesh;
for (uint32_t p = 0; p < mesh->primitive_count; p++) {
gltf_primitive_t* prim = &mesh->primitives[p];
if (prim->has_indices && prim->index_count > 0) {
wgpuRenderPassEncoderDrawIndexed(pass, prim->index_count, 1,
prim->first_index, 0, 0);
}
else if (prim->vertex_count > 0) {
wgpuRenderPassEncoderDraw(pass, prim->vertex_count, 1, 0, 0);
}
}
}
}
/* -------------------------------------------------------------------------- *
* Shadow map texture + sampler
* -------------------------------------------------------------------------- */
static void init_shadow_map(struct wgpu_context_t* wgpu_context)
{
WGPUDevice device = wgpu_context->device;
/* Depth texture for shadow map */
state.shadow_map.depth_texture = wgpuDeviceCreateTexture(
device, &(WGPUTextureDescriptor){
.label = STRVIEW("Shadow Map Depth"),
.usage = WGPUTextureUsage_RenderAttachment
| WGPUTextureUsage_TextureBinding,
.dimension = WGPUTextureDimension_2D,
.size = {SHADOW_MAP_DIM, SHADOW_MAP_DIM, 1},
.format = WGPUTextureFormat_Depth32Float,
.mipLevelCount = 1,
.sampleCount = 1,
});
/* Single 2D view for shadow pass render target */
state.shadow_map.depth_view = wgpuTextureCreateView(
state.shadow_map.depth_texture, &(WGPUTextureViewDescriptor){
.label = STRVIEW("Shadow Map Depth View"),
.format = WGPUTextureFormat_Depth32Float,
.dimension = WGPUTextureViewDimension_2D,
.baseMipLevel = 0,
.mipLevelCount = 1,
.baseArrayLayer = 0,
.arrayLayerCount = 1,
.aspect = WGPUTextureAspect_DepthOnly,
});
/* Set the shadow pass depth view */
state.shadow_pass.depth_att.view = state.shadow_map.depth_view;
}
/* -------------------------------------------------------------------------- *
* Main pass depth texture
* -------------------------------------------------------------------------- */
static void init_depth_texture(struct wgpu_context_t* wgpu_context)
{
/* Release old */
WGPU_RELEASE_RESOURCE(TextureView, state.depth.view);
WGPU_RELEASE_RESOURCE(Texture, state.depth.texture);
WGPUDevice device = wgpu_context->device;
uint32_t w = (uint32_t)wgpu_context->width;
uint32_t h = (uint32_t)wgpu_context->height;
state.depth.texture = wgpuDeviceCreateTexture(
device, &(WGPUTextureDescriptor){
.label = STRVIEW("Main Depth"),
.usage = WGPUTextureUsage_RenderAttachment,
.dimension = WGPUTextureDimension_2D,
.size = {w, h, 1},
.format = WGPUTextureFormat_Depth24PlusStencil8,
.mipLevelCount = 1,
.sampleCount = 1,
});
state.depth.view = wgpuTextureCreateView(
state.depth.texture, &(WGPUTextureViewDescriptor){
.format = WGPUTextureFormat_Depth24PlusStencil8,
.dimension = WGPUTextureViewDimension_2D,
.baseMipLevel = 0,
.mipLevelCount = 1,
.baseArrayLayer = 0,
.arrayLayerCount = 1,
});
}
/* -------------------------------------------------------------------------- *
* Uniform buffers
* -------------------------------------------------------------------------- */
static void init_uniform_buffers(struct wgpu_context_t* wgpu_context)
{
WGPUDevice device = wgpu_context->device;
state.uniform_buffers.offscreen = wgpuDeviceCreateBuffer(
device, &(WGPUBufferDescriptor){
.label = STRVIEW("Offscreen UBO"),
.usage = WGPUBufferUsage_Uniform | WGPUBufferUsage_CopyDst,
.size = sizeof(uniform_data_offscreen_t),
});
state.uniform_buffers.scene = wgpuDeviceCreateBuffer(
device, &(WGPUBufferDescriptor){
.label = STRVIEW("Scene UBO"),
.usage = WGPUBufferUsage_Uniform | WGPUBufferUsage_CopyDst,
.size = sizeof(uniform_data_scene_t),
});
}
/* -------------------------------------------------------------------------- *
* Light animation
* -------------------------------------------------------------------------- */
static void update_light(void)
{
float angle = state.timer * 360.0f;
float rad = glm_rad(angle);
/* Vulkan Y is down, WebGPU Y is up: negate Y */
state.light_pos[0] = cosf(rad) * 40.0f;
state.light_pos[1] = -(-50.0f + sinf(rad) * 20.0f); /* negated for WebGPU */
state.light_pos[2] = 25.0f + sinf(rad) * 5.0f;
}
/* -------------------------------------------------------------------------- *
* Update uniform buffers
* -------------------------------------------------------------------------- */
static void update_uniform_buffers(struct wgpu_context_t* wgpu_context)
{
WGPUQueue queue = wgpu_context->queue;
/* === Light's point of view (shadow map generation) === */
{
mat4 depth_projection, depth_view, depth_mvp;
glm_perspective(glm_rad(state.light_fov), 1.0f, state.z_near, state.z_far,
depth_projection);
/* lookAt from light position to scene center */
vec3 center = {0.0f, 0.0f, 0.0f};
vec3 up = {0.0f, 1.0f, 0.0f};
glm_lookat(state.light_pos, center, up, depth_view);
glm_mat4_mul(depth_projection, depth_view, depth_mvp);
glm_mat4_copy(depth_mvp, state.ubo_offscreen.depth_mvp);
wgpuQueueWriteBuffer(queue, state.uniform_buffers.offscreen, 0,
&state.ubo_offscreen, sizeof(state.ubo_offscreen));
}
/* === Camera point of view (scene rendering) === */
{
glm_mat4_copy(state.camera.matrices.perspective,
state.ubo_scene.projection);
glm_mat4_copy(state.camera.matrices.view, state.ubo_scene.view);
glm_mat4_identity(state.ubo_scene.model);
/* depthBiasMVP = depthMVP (same as offscreen) */
glm_mat4_copy(state.ubo_offscreen.depth_mvp, state.ubo_scene.light_space);
glm_vec4_copy(
(vec4){state.light_pos[0], state.light_pos[1], state.light_pos[2], 1.0f},
state.ubo_scene.light_pos);
state.ubo_scene.z_near = state.z_near;
state.ubo_scene.z_far = state.z_far;
wgpuQueueWriteBuffer(queue, state.uniform_buffers.scene, 0,
&state.ubo_scene, sizeof(state.ubo_scene));
}
}
/* -------------------------------------------------------------------------- *
* Bind group layouts
* -------------------------------------------------------------------------- */
static void init_bind_group_layouts(struct wgpu_context_t* wgpu_context)
{
WGPUDevice device = wgpu_context->device;
/* Offscreen: binding 0 = UBO (vertex only) */
{
WGPUBindGroupLayoutEntry entry = {
.binding = 0,
.visibility = WGPUShaderStage_Vertex,
.buffer = {
.type = WGPUBufferBindingType_Uniform,
.minBindingSize = sizeof(uniform_data_offscreen_t),
},
};
state.bind_group_layouts.offscreen = wgpuDeviceCreateBindGroupLayout(
device, &(WGPUBindGroupLayoutDescriptor){
.label = STRVIEW("Offscreen BGL"),
.entryCount = 1,
.entries = &entry,
});
}
/* Scene/Debug: binding 0 = UBO, binding 1 = shadow map depth texture */
{
WGPUBindGroupLayoutEntry entries[2] = {
{
.binding = 0,
.visibility = WGPUShaderStage_Vertex | WGPUShaderStage_Fragment,
.buffer = {
.type = WGPUBufferBindingType_Uniform,
.minBindingSize = sizeof(uniform_data_scene_t),
},
},
{
.binding = 1,
.visibility = WGPUShaderStage_Fragment,
.texture = {
.sampleType = WGPUTextureSampleType_UnfilterableFloat,
.viewDimension = WGPUTextureViewDimension_2D,
.multisampled = false,
},
},
};
state.bind_group_layouts.scene = wgpuDeviceCreateBindGroupLayout(
device, &(WGPUBindGroupLayoutDescriptor){
.label = STRVIEW("Scene BGL"),
.entryCount = 2,
.entries = entries,
});
}
}
/* -------------------------------------------------------------------------- *
* Pipeline layouts
* -------------------------------------------------------------------------- */
static void init_pipeline_layouts(struct wgpu_context_t* wgpu_context)
{
WGPUDevice device = wgpu_context->device;
state.pipeline_layouts.offscreen = wgpuDeviceCreatePipelineLayout(
device, &(WGPUPipelineLayoutDescriptor){
.label = STRVIEW("Offscreen Pipeline Layout"),
.bindGroupLayoutCount = 1,
.bindGroupLayouts = &state.bind_group_layouts.offscreen,
});
state.pipeline_layouts.scene = wgpuDeviceCreatePipelineLayout(
device, &(WGPUPipelineLayoutDescriptor){
.label = STRVIEW("Scene Pipeline Layout"),
.bindGroupLayoutCount = 1,
.bindGroupLayouts = &state.bind_group_layouts.scene,
});
}
/* -------------------------------------------------------------------------- *
* Bind groups
* -------------------------------------------------------------------------- */
static void init_bind_groups(struct wgpu_context_t* wgpu_context)
{
WGPUDevice device = wgpu_context->device;
/* Offscreen */
{
WGPUBindGroupEntry entry = {
.binding = 0,
.buffer = state.uniform_buffers.offscreen,
.offset = 0,
.size = sizeof(uniform_data_offscreen_t),
};
state.bind_groups.offscreen = wgpuDeviceCreateBindGroup(
device, &(WGPUBindGroupDescriptor){
.label = STRVIEW("Offscreen Bind Group"),
.layout = state.bind_group_layouts.offscreen,
.entryCount = 1,
.entries = &entry,
});
}
/* Scene + Debug (share same layout and resources) */
{
WGPUBindGroupEntry entries[2] = {
{
.binding = 0,
.buffer = state.uniform_buffers.scene,
.offset = 0,
.size = sizeof(uniform_data_scene_t),
},
{
.binding = 1,
.textureView = state.shadow_map.depth_view,
},
};
state.bind_groups.scene = wgpuDeviceCreateBindGroup(
device, &(WGPUBindGroupDescriptor){
.label = STRVIEW("Scene Bind Group"),
.layout = state.bind_group_layouts.scene,
.entryCount = 2,
.entries = entries,
});
/* Debug uses same resources */
state.bind_groups.debug = wgpuDeviceCreateBindGroup(
device, &(WGPUBindGroupDescriptor){
.label = STRVIEW("Debug Bind Group"),
.layout = state.bind_group_layouts.scene,
.entryCount = 2,
.entries = entries,
});
}
}
/* -------------------------------------------------------------------------- *
* Render pipelines
* -------------------------------------------------------------------------- */
static void init_pipelines(struct wgpu_context_t* wgpu_context)
{
WGPUDevice device = wgpu_context->device;
/* ===== Offscreen pipeline (shadow map, depth-only) ===== */
{
/* Only position attribute needed */
WGPUVertexAttribute shadow_attr = {
.shaderLocation = 0,
.format = WGPUVertexFormat_Float32x3,
.offset = offsetof(gltf_vertex_t, position),
};
WGPUVertexBufferLayout shadow_vb_layout = {
.arrayStride = sizeof(gltf_vertex_t),
.stepMode = WGPUVertexStepMode_Vertex,
.attributeCount = 1,
.attributes = &shadow_attr,
};
WGPUShaderModule shader
= wgpu_create_shader_module(device, offscreen_shader_wgsl);
WGPUDepthStencilState shadow_depth_stencil = {
.format = WGPUTextureFormat_Depth32Float,
.depthWriteEnabled = WGPUOptionalBool_True,
.depthCompare = WGPUCompareFunction_LessEqual,
.depthBias = 2,
.depthBiasSlopeScale = 1.75f,
.depthBiasClamp = 0.0f,
};
state.pipelines.offscreen = wgpuDeviceCreateRenderPipeline(
device, &(WGPURenderPipelineDescriptor){
.label = STRVIEW("Offscreen Pipeline"),
.layout = state.pipeline_layouts.offscreen,
.vertex = (WGPUVertexState){
.module = shader,
.entryPoint = STRVIEW("vs_main"),
.bufferCount = 1,
.buffers = &shadow_vb_layout,
},
.primitive = (WGPUPrimitiveState){
.topology = WGPUPrimitiveTopology_TriangleList,
.frontFace = WGPUFrontFace_CCW,
.cullMode = WGPUCullMode_None,
},
.depthStencil = &shadow_depth_stencil,
.multisample = (WGPUMultisampleState){
.count = 1,
.mask = 0xFFFFFFFF,
},
.fragment = NULL, /* Depth-only pass */
});
WGPU_RELEASE_RESOURCE(ShaderModule, shader);
}
/* ===== Scene pipeline (shadow, no PCF) ===== */
{
WGPUVertexAttribute scene_attrs[] = {
{.shaderLocation = 0,
.format = WGPUVertexFormat_Float32x3,
.offset = offsetof(gltf_vertex_t, position)},
{.shaderLocation = 1,
.format = WGPUVertexFormat_Float32x2,
.offset = offsetof(gltf_vertex_t, uv0)},
{.shaderLocation = 2,
.format = WGPUVertexFormat_Float32x4,
.offset = offsetof(gltf_vertex_t, color)},
{.shaderLocation = 3,
.format = WGPUVertexFormat_Float32x3,
.offset = offsetof(gltf_vertex_t, normal)},
};
WGPUVertexBufferLayout scene_vb_layout = {
.arrayStride = sizeof(gltf_vertex_t),
.stepMode = WGPUVertexStepMode_Vertex,
.attributeCount = ARRAY_SIZE(scene_attrs),
.attributes = scene_attrs,
};
WGPUShaderModule shader
= wgpu_create_shader_module(device, scene_shader_wgsl);
WGPUBlendState blend_state = wgpu_create_blend_state(false);
WGPUColorTargetState color_target = {
.format = wgpu_context->render_format,
.blend = &blend_state,
.writeMask = WGPUColorWriteMask_All,
};
WGPUDepthStencilState depth_stencil = {
.format = WGPUTextureFormat_Depth24PlusStencil8,
.depthWriteEnabled = WGPUOptionalBool_True,
.depthCompare = WGPUCompareFunction_LessEqual,
.stencilFront = {.compare = WGPUCompareFunction_Always},
.stencilBack = {.compare = WGPUCompareFunction_Always},
};
/* No PCF variant */
WGPUConstantEntry no_pcf_const = {
.key = STRVIEW("enablePCF"),
.value = 0.0,
};
state.pipelines.scene_shadow = wgpuDeviceCreateRenderPipeline(
device, &(WGPURenderPipelineDescriptor){
.label = STRVIEW("Scene Shadow Pipeline"),
.layout = state.pipeline_layouts.scene,
.vertex = (WGPUVertexState){
.module = shader,
.entryPoint = STRVIEW("vs_main"),
.bufferCount = 1,
.buffers = &scene_vb_layout,
},
.primitive = (WGPUPrimitiveState){
.topology = WGPUPrimitiveTopology_TriangleList,
.frontFace = WGPUFrontFace_CCW,
.cullMode = WGPUCullMode_Back,
},
.depthStencil = &depth_stencil,
.multisample = (WGPUMultisampleState){
.count = 1,
.mask = 0xFFFFFFFF,
},
.fragment = &(WGPUFragmentState){
.module = shader,
.entryPoint = STRVIEW("fs_main"),
.targetCount = 1,
.targets = &color_target,
.constantCount = 1,
.constants = &no_pcf_const,
},
});
/* PCF variant */
WGPUConstantEntry pcf_const = {
.key = STRVIEW("enablePCF"),
.value = 1.0,
};
state.pipelines.scene_shadow_pcf = wgpuDeviceCreateRenderPipeline(
device, &(WGPURenderPipelineDescriptor){
.label = STRVIEW("Scene Shadow PCF Pipeline"),
.layout = state.pipeline_layouts.scene,
.vertex = (WGPUVertexState){
.module = shader,
.entryPoint = STRVIEW("vs_main"),
.bufferCount = 1,
.buffers = &scene_vb_layout,
},
.primitive = (WGPUPrimitiveState){
.topology = WGPUPrimitiveTopology_TriangleList,
.frontFace = WGPUFrontFace_CCW,
.cullMode = WGPUCullMode_Back,
},
.depthStencil = &depth_stencil,
.multisample = (WGPUMultisampleState){
.count = 1,
.mask = 0xFFFFFFFF,
},
.fragment = &(WGPUFragmentState){
.module = shader,
.entryPoint = STRVIEW("fs_main"),
.targetCount = 1,
.targets = &color_target,
.constantCount = 1,
.constants = &pcf_const,
},
});
WGPU_RELEASE_RESOURCE(ShaderModule, shader);
}
/* ===== Debug pipeline (shadow map visualization) ===== */
{
WGPUShaderModule shader
= wgpu_create_shader_module(device, debug_quad_shader_wgsl);
WGPUBlendState blend_state = wgpu_create_blend_state(false);
WGPUColorTargetState color_target = {
.format = wgpu_context->render_format,
.blend = &blend_state,
.writeMask = WGPUColorWriteMask_All,
};
WGPUDepthStencilState depth_stencil = {
.format = WGPUTextureFormat_Depth24PlusStencil8,
.depthWriteEnabled = WGPUOptionalBool_True,
.depthCompare = WGPUCompareFunction_LessEqual,
.stencilFront = {.compare = WGPUCompareFunction_Always},
.stencilBack = {.compare = WGPUCompareFunction_Always},
};
state.pipelines.debug = wgpuDeviceCreateRenderPipeline(
device, &(WGPURenderPipelineDescriptor){
.label = STRVIEW("Debug Quad Pipeline"),
.layout = state.pipeline_layouts.scene,
.vertex = (WGPUVertexState){
.module = shader,
.entryPoint = STRVIEW("vs_main"),
.bufferCount = 0, /* Procedural quad */
.buffers = NULL,
},
.primitive = (WGPUPrimitiveState){
.topology = WGPUPrimitiveTopology_TriangleList,
.frontFace = WGPUFrontFace_CCW,
.cullMode = WGPUCullMode_None,
},
.depthStencil = &depth_stencil,
.multisample = (WGPUMultisampleState){
.count = 1,
.mask = 0xFFFFFFFF,
},
.fragment = &(WGPUFragmentState){
.module = shader,
.entryPoint = STRVIEW("fs_main"),
.targetCount = 1,
.targets = &color_target,
},
});
WGPU_RELEASE_RESOURCE(ShaderModule, shader);
}
}
/* -------------------------------------------------------------------------- *
* GUI
* -------------------------------------------------------------------------- */
static void render_gui(struct wgpu_context_t* wgpu_context)
{
UNUSED_VAR(wgpu_context);
igSetNextWindowPos((ImVec2){10.0f, 10.0f}, ImGuiCond_FirstUseEver,
(ImVec2){0.0f, 0.0f});
igSetNextWindowSize((ImVec2){260.0f, 0.0f}, ImGuiCond_FirstUseEver);
igBegin("Settings", NULL, ImGuiWindowFlags_AlwaysAutoResize);
if (igCollapsingHeader_BoolPtr("Settings", NULL,
ImGuiTreeNodeFlags_DefaultOpen)) {
imgui_overlay_combo_box("Scenes", &state.settings.scene_index, scene_names,
NUM_SCENES);
igCheckbox("Display shadow render target",
&state.settings.display_shadow_map);
igCheckbox("PCF filtering", &state.settings.filter_pcf);
}
igEnd();
}
/* -------------------------------------------------------------------------- *
* Input handling
* -------------------------------------------------------------------------- */
static void input_event_cb(struct wgpu_context_t* wgpu_context,
const input_event_t* input_event)
{
imgui_overlay_handle_input(wgpu_context, input_event);
/* Skip camera input when ImGui captures the mouse */
if (!imgui_overlay_want_capture_mouse()) {
camera_on_input_event(&state.camera, input_event);
}
if (input_event->type == INPUT_EVENT_TYPE_RESIZED) {
init_depth_texture(wgpu_context);
}
}
/* -------------------------------------------------------------------------- *
* Init / Frame / Shutdown
* -------------------------------------------------------------------------- */
static int init(struct wgpu_context_t* wgpu_context)
{
if (!wgpu_context) {
return EXIT_FAILURE;
}
stm_setup();
#ifdef __WAJIC__
sfetch_setup(&(sfetch_desc_t){
.max_requests = NUM_SCENES,
.num_channels = 1,
.num_lanes = NUM_SCENES,
});
#endif
/* Camera setup */