-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathoffscreen.c
More file actions
1397 lines (1203 loc) · 49.1 KB
/
offscreen.c
File metadata and controls
1397 lines (1203 loc) · 49.1 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
/* -------------------------------------------------------------------------- *
* WebGPU Example - Offscreen Rendering
*
* Renders a scene (Chinese Dragon) into an offscreen framebuffer, then uses
* that texture as a reflection map on a mirror plane in the main pass.
* An optional debug mode displays the raw offscreen texture via a fullscreen
* triangle.
*
* Render passes:
* 1. Offscreen pass (512x512):
* Draws the dragon with Y-flipped model matrix → reflection image.
* 2. Main pass (window-size):
* Debug mode → fullscreen triangle sampling the offscreen texture.
* Normal mode → mirror plane (projective sampling) + lit dragon above.
*
* Ref:
* https://github.com/SaschaWillems/Vulkan/tree/master/examples/offscreen
* -------------------------------------------------------------------------- */
#include "webgpu/imgui_overlay.h"
#include "webgpu/wgpu_common.h"
#include <cglm/cglm.h>
#define SOKOL_LOG_IMPL
#include <sokol_log.h>
#define SOKOL_TIME_IMPL
#include <sokol_time.h>
#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 "core/camera.h"
#include "core/gltf_model.h"
#include <stdlib.h>
#include <string.h>
/* -------------------------------------------------------------------------- *
* WGSL Shaders (forward declarations — defined at bottom of file)
* -------------------------------------------------------------------------- */
static const char* offscreen_phong_shader_wgsl;
static const char* offscreen_mirror_shader_wgsl;
static const char* offscreen_quad_shader_wgsl;
/* -------------------------------------------------------------------------- *
* Constants
* -------------------------------------------------------------------------- */
/* Fixed-size offscreen framebuffer — matches Vulkan reference (FB_DIM = 512) */
#define OFFSCREEN_WIDTH (512u)
#define OFFSCREEN_HEIGHT (512u)
/* Depth format shared by both offscreen and main passes */
#define DEPTH_FORMAT (WGPUTextureFormat_Depth24PlusStencil8)
/* -------------------------------------------------------------------------- *
* Uniform data (matches Vulkan UBO layout: projection + view + model + light) *
* -------------------------------------------------------------------------- */
typedef struct {
mat4 projection; /* 64 bytes */
mat4 view; /* 64 bytes */
mat4 model; /* 64 bytes */
vec4 light_pos; /* 16 bytes */
} ubo_data_t; /* 208 bytes total */
/* -------------------------------------------------------------------------- *
* State
* -------------------------------------------------------------------------- */
static struct {
/* Camera */
camera_t camera;
/* Models */
gltf_model_t dragon_model;
gltf_model_t plane_model;
bool models_loaded;
/* GPU buffers (vertices + indices) */
WGPUBuffer dragon_vb;
WGPUBuffer dragon_ib;
WGPUBuffer plane_vb;
WGPUBuffer plane_ib;
/* Offscreen framebuffer (fixed 512x512) */
struct {
WGPUTexture color_tex;
WGPUTextureView color_view;
WGPUTexture depth_tex;
WGPUTextureView depth_view;
WGPUSampler sampler;
} offscreen;
/* Main-pass depth texture (window-size, re-created on resize) */
struct {
WGPUTexture handle;
WGPUTextureView view;
} depth_tex;
/* Uniform buffers (one per role) */
WGPUBuffer ubo_model; /* main dragon */
WGPUBuffer ubo_mirror; /* mirror plane */
WGPUBuffer ubo_offscreen; /* offscreen (flipped) dragon */
/* Uniform data CPU-side */
ubo_data_t ubo_model_data;
ubo_data_t ubo_mirror_data;
ubo_data_t ubo_offscreen_data;
/* Model animation */
float model_rotation_y; /* degrees, updated each frame */
/* Bind group layouts */
WGPUBindGroupLayout shaded_bgl; /* binding 0: UBO (vertex) */
WGPUBindGroupLayout textured_bgl; /* binding 0: UBO (vertex)
binding 1: sampler (fragment)
binding 2: texture (fragment) */
/* Pipeline layouts */
WGPUPipelineLayout shaded_layout;
WGPUPipelineLayout textured_layout;
/* Bind groups */
WGPUBindGroup offscreen_bg; /* shaded BGL — for offscreen pass */
WGPUBindGroup model_bg; /* shaded BGL — for main dragon */
WGPUBindGroup mirror_bg; /* textured BGL — mirror + debug pass */
/* Render pipelines */
WGPURenderPipeline debug_pipeline; /* fullscreen quad: offscreen tex */
WGPURenderPipeline shaded_pipeline; /* Phong-lit dragon (back cull) */
WGPURenderPipeline offscreen_pipeline; /* Phong offscreen (front cull) */
WGPURenderPipeline mirror_pipeline; /* mirror plane with reflection */
/* Offscreen render pass descriptors */
WGPURenderPassColorAttachment offscreen_color_att;
WGPURenderPassDepthStencilAttachment offscreen_depth_att;
WGPURenderPassDescriptor offscreen_pass;
/* Main render pass descriptors */
WGPURenderPassColorAttachment main_color_att;
WGPURenderPassDepthStencilAttachment main_depth_att;
WGPURenderPassDescriptor main_pass;
/* GUI settings */
bool debug_display;
/* Timing */
uint64_t last_frame_time;
/* Window size (for resize detection) */
int last_width;
int last_height;
WGPUBool initialized;
} state = {
/* clang-format off */
.offscreen_color_att = {
.loadOp = WGPULoadOp_Clear,
.storeOp = WGPUStoreOp_Store,
.clearValue = {0.0f, 0.0f, 0.0f, 0.0f},
.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED,
},
.offscreen_depth_att = {
.depthLoadOp = WGPULoadOp_Clear,
.depthStoreOp = WGPUStoreOp_Discard,
.depthClearValue = 1.0f,
.stencilLoadOp = WGPULoadOp_Clear,
.stencilStoreOp = WGPUStoreOp_Discard,
.stencilClearValue = 0,
},
.offscreen_pass = {
.colorAttachmentCount = 1,
.colorAttachments = &state.offscreen_color_att,
.depthStencilAttachment = &state.offscreen_depth_att,
},
.main_color_att = {
.loadOp = WGPULoadOp_Clear,
.storeOp = WGPUStoreOp_Store,
.clearValue = {0.025f, 0.025f, 0.025f, 1.0f},
.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED,
},
.main_depth_att = {
.depthLoadOp = WGPULoadOp_Clear,
.depthStoreOp = WGPUStoreOp_Store,
.depthClearValue = 1.0f,
.stencilLoadOp = WGPULoadOp_Clear,
.stencilStoreOp = WGPUStoreOp_Store,
.stencilClearValue = 0,
},
.main_pass = {
.colorAttachmentCount = 1,
.colorAttachments = &state.main_color_att,
.depthStencilAttachment = &state.main_depth_att,
},
/* clang-format on */
};
/* -------------------------------------------------------------------------- *
* Model loading
* -------------------------------------------------------------------------- */
/* No FlipY for WebGPU — gltf uses Y-up, same as WebGPU clip space.
* No PreMultiplyVertexColors needed here (phong shader uses vertex color). */
static const gltf_model_desc_t model_load_desc = {
.loading_flags = GltfLoadingFlag_PreTransformVertices
| GltfLoadingFlag_PreMultiplyVertexColors,
};
static void load_models(void)
{
bool ok = gltf_model_load_from_file_ext(&state.dragon_model,
"assets/models/chinesedragon.gltf",
1.0f, &model_load_desc);
if (!ok) {
printf("[offscreen] Failed to load chinesedragon.gltf\n");
return;
}
ok = gltf_model_load_from_file_ext(
&state.plane_model, "assets/models/plane.gltf", 1.0f, &model_load_desc);
if (!ok) {
printf("[offscreen] Failed to load plane.gltf\n");
return;
}
state.models_loaded = true;
}
static void create_model_buffers(struct wgpu_context_t* wgpu_context)
{
if (!state.models_loaded) {
return;
}
WGPUDevice device = wgpu_context->device;
/* Helper to upload a model's vertices and indices */
#define UPLOAD_MODEL(m, vb, ib) \
do { \
size_t vb_size = (m)->vertex_count * sizeof(gltf_vertex_t); \
(vb) = wgpuDeviceCreateBuffer( \
device, &(WGPUBufferDescriptor){ \
.label = STRVIEW(#m " Vertex Buffer"), \
.usage = WGPUBufferUsage_Vertex | WGPUBufferUsage_CopyDst, \
.size = vb_size, \
.mappedAtCreation = true, \
}); \
void* vdata = wgpuBufferGetMappedRange((vb), 0, vb_size); \
memcpy(vdata, (m)->vertices, vb_size); \
wgpuBufferUnmap((vb)); \
if ((m)->index_count > 0) { \
size_t ib_size = (m)->index_count * sizeof(uint32_t); \
(ib) = wgpuDeviceCreateBuffer( \
device, &(WGPUBufferDescriptor){ \
.label = STRVIEW(#m " Index Buffer"), \
.usage = WGPUBufferUsage_Index | WGPUBufferUsage_CopyDst, \
.size = ib_size, \
.mappedAtCreation = true, \
}); \
void* idata = wgpuBufferGetMappedRange((ib), 0, ib_size); \
memcpy(idata, (m)->indices, ib_size); \
wgpuBufferUnmap((ib)); \
} \
} while (0)
UPLOAD_MODEL(&state.dragon_model, state.dragon_vb, state.dragon_ib);
UPLOAD_MODEL(&state.plane_model, state.plane_vb, state.plane_ib);
#undef UPLOAD_MODEL
}
/* -------------------------------------------------------------------------- *
* Offscreen framebuffer (fixed 512x512, created once)
* -------------------------------------------------------------------------- */
static void init_offscreen_framebuffer(struct wgpu_context_t* wgpu_context)
{
WGPUDevice device = wgpu_context->device;
/* ---- Color attachment (sampled in mirror/debug pass) ---- */
state.offscreen.color_tex = wgpuDeviceCreateTexture(
device, &(WGPUTextureDescriptor){
.label = STRVIEW("Offscreen Color Texture"),
.usage = WGPUTextureUsage_RenderAttachment
| WGPUTextureUsage_TextureBinding,
.dimension = WGPUTextureDimension_2D,
.size = {OFFSCREEN_WIDTH, OFFSCREEN_HEIGHT, 1},
.format = WGPUTextureFormat_RGBA8Unorm,
.mipLevelCount = 1,
.sampleCount = 1,
});
ASSERT(state.offscreen.color_tex != NULL);
state.offscreen.color_view = wgpuTextureCreateView(
state.offscreen.color_tex, &(WGPUTextureViewDescriptor){
.label = STRVIEW("Offscreen Color View"),
.format = WGPUTextureFormat_RGBA8Unorm,
.dimension = WGPUTextureViewDimension_2D,
.baseMipLevel = 0,
.mipLevelCount = 1,
.baseArrayLayer = 0,
.arrayLayerCount = 1,
.aspect = WGPUTextureAspect_All,
});
ASSERT(state.offscreen.color_view != NULL);
/* ---- Sampler for mirror/debug access ---- */
state.offscreen.sampler = wgpuDeviceCreateSampler(
device, &(WGPUSamplerDescriptor){
.label = STRVIEW("Offscreen Sampler"),
.addressModeU = WGPUAddressMode_ClampToEdge,
.addressModeV = WGPUAddressMode_ClampToEdge,
.addressModeW = WGPUAddressMode_ClampToEdge,
.magFilter = WGPUFilterMode_Linear,
.minFilter = WGPUFilterMode_Linear,
.mipmapFilter = WGPUMipmapFilterMode_Linear,
.lodMinClamp = 0.0f,
.lodMaxClamp = 1.0f,
.maxAnisotropy = 1,
});
ASSERT(state.offscreen.sampler != NULL);
/* ---- Depth attachment (discard at end of pass, not sampled) ---- */
state.offscreen.depth_tex = wgpuDeviceCreateTexture(
device, &(WGPUTextureDescriptor){
.label = STRVIEW("Offscreen Depth Texture"),
.usage = WGPUTextureUsage_RenderAttachment,
.dimension = WGPUTextureDimension_2D,
.size = {OFFSCREEN_WIDTH, OFFSCREEN_HEIGHT, 1},
.format = DEPTH_FORMAT,
.mipLevelCount = 1,
.sampleCount = 1,
});
ASSERT(state.offscreen.depth_tex != NULL);
state.offscreen.depth_view = wgpuTextureCreateView(
state.offscreen.depth_tex, &(WGPUTextureViewDescriptor){
.label = STRVIEW("Offscreen Depth View"),
.format = DEPTH_FORMAT,
.dimension = WGPUTextureViewDimension_2D,
.baseMipLevel = 0,
.mipLevelCount = 1,
.baseArrayLayer = 0,
.arrayLayerCount = 1,
.aspect = WGPUTextureAspect_All,
});
ASSERT(state.offscreen.depth_view != NULL);
/* Wire up pass descriptor views */
state.offscreen_color_att.view = state.offscreen.color_view;
state.offscreen_depth_att.view = state.offscreen.depth_view;
}
static void destroy_offscreen_framebuffer(void)
{
WGPU_RELEASE_RESOURCE(Sampler, state.offscreen.sampler)
WGPU_RELEASE_RESOURCE(TextureView, state.offscreen.color_view)
WGPU_RELEASE_RESOURCE(Texture, state.offscreen.color_tex)
WGPU_RELEASE_RESOURCE(TextureView, state.offscreen.depth_view)
WGPU_RELEASE_RESOURCE(Texture, state.offscreen.depth_tex)
}
/* -------------------------------------------------------------------------- *
* Main-pass depth texture (window-size, re-created on resize)
* -------------------------------------------------------------------------- */
static void init_main_depth_texture(struct wgpu_context_t* wgpu_context)
{
WGPUDevice device = wgpu_context->device;
uint32_t w = (uint32_t)wgpu_context->width;
uint32_t h = (uint32_t)wgpu_context->height;
state.depth_tex.handle = wgpuDeviceCreateTexture(
device, &(WGPUTextureDescriptor){
.label = STRVIEW("Main Depth Texture"),
.usage = WGPUTextureUsage_RenderAttachment,
.dimension = WGPUTextureDimension_2D,
.size = {w, h, 1},
.format = DEPTH_FORMAT,
.mipLevelCount = 1,
.sampleCount = 1,
});
ASSERT(state.depth_tex.handle != NULL);
state.depth_tex.view = wgpuTextureCreateView(
state.depth_tex.handle, &(WGPUTextureViewDescriptor){
.label = STRVIEW("Main Depth View"),
.format = DEPTH_FORMAT,
.dimension = WGPUTextureViewDimension_2D,
.baseMipLevel = 0,
.mipLevelCount = 1,
.baseArrayLayer = 0,
.arrayLayerCount = 1,
.aspect = WGPUTextureAspect_All,
});
ASSERT(state.depth_tex.view != NULL);
state.main_depth_att.view = state.depth_tex.view;
state.last_width = (int)w;
state.last_height = (int)h;
}
static void destroy_main_depth_texture(void)
{
WGPU_RELEASE_RESOURCE(TextureView, state.depth_tex.view)
WGPU_RELEASE_RESOURCE(Texture, state.depth_tex.handle)
}
/* -------------------------------------------------------------------------- *
* Uniform buffers
* -------------------------------------------------------------------------- */
static void init_uniform_buffers(struct wgpu_context_t* wgpu_context)
{
WGPUDevice device = wgpu_context->device;
/* Light position at world origin (acts as headlight since view * (0,0,0,1)
* = camera origin = (0,0,0) in view space) — matching Vulkan example. */
vec4 light_pos = {0.0f, 0.0f, 0.0f, 1.0f};
glm_vec4_copy(light_pos, state.ubo_model_data.light_pos);
glm_vec4_copy(light_pos, state.ubo_mirror_data.light_pos);
glm_vec4_copy(light_pos, state.ubo_offscreen_data.light_pos);
WGPUBufferDescriptor ubo_desc = {
.usage = WGPUBufferUsage_Uniform | WGPUBufferUsage_CopyDst,
.size = sizeof(ubo_data_t),
};
ubo_desc.label = STRVIEW("UBO Model");
state.ubo_model = wgpuDeviceCreateBuffer(device, &ubo_desc);
ASSERT(state.ubo_model != NULL);
ubo_desc.label = STRVIEW("UBO Mirror");
state.ubo_mirror = wgpuDeviceCreateBuffer(device, &ubo_desc);
ASSERT(state.ubo_mirror != NULL);
ubo_desc.label = STRVIEW("UBO Offscreen");
state.ubo_offscreen = wgpuDeviceCreateBuffer(device, &ubo_desc);
ASSERT(state.ubo_offscreen != NULL);
}
static void update_uniform_buffers(struct wgpu_context_t* wgpu_context,
float delta_time)
{
/* Advance rotation */
state.model_rotation_y += delta_time * 10.0f; /* °/s — matches Vulkan */
float aspect = (float)wgpu_context->width / (float)wgpu_context->height;
/* Shared projection + view */
glm_perspective(glm_rad(60.0f), aspect, 0.1f, 256.0f,
state.ubo_model_data.projection);
glm_mat4_copy(state.camera.matrices.view, state.ubo_model_data.view);
/* -- Model UBO: rotate + translate dragon.
* Vulkan: translate(0,-1,0) in Y-down convention = object sits on floor.
* WebGPU: negate Y → translate(0,+1,0) so dragon is above floor (Y=0). */
glm_mat4_identity(state.ubo_model_data.model);
glm_rotate_y(state.ubo_model_data.model, glm_rad(state.model_rotation_y),
state.ubo_model_data.model);
glm_translate(state.ubo_model_data.model, (vec3){0.0f, 1.0f, 0.0f});
wgpuQueueWriteBuffer(wgpu_context->queue, state.ubo_model, 0,
&state.ubo_model_data, sizeof(ubo_data_t));
/* -- Mirror UBO: identity model (the plane sits at Y=0) -- */
glm_mat4_copy(state.ubo_model_data.projection,
state.ubo_mirror_data.projection);
glm_mat4_copy(state.ubo_model_data.view, state.ubo_mirror_data.view);
glm_mat4_identity(state.ubo_mirror_data.model);
wgpuQueueWriteBuffer(wgpu_context->queue, state.ubo_mirror, 0,
&state.ubo_mirror_data, sizeof(ubo_data_t));
/* -- Offscreen UBO: rotate + Y-scale(-1) + translate dragon -- */
/* Projection and view are the same as the main camera */
glm_mat4_copy(state.ubo_model_data.projection,
state.ubo_offscreen_data.projection);
glm_mat4_copy(state.ubo_model_data.view, state.ubo_offscreen_data.view);
glm_mat4_identity(state.ubo_offscreen_data.model);
glm_rotate_y(state.ubo_offscreen_data.model, glm_rad(state.model_rotation_y),
state.ubo_offscreen_data.model);
/* Y-flip + same translate as main dragon (negated Vulkan -1 → +1). */
glm_scale(state.ubo_offscreen_data.model, (vec3){1.0f, -1.0f, 1.0f});
glm_translate(state.ubo_offscreen_data.model, (vec3){0.0f, 1.0f, 0.0f});
wgpuQueueWriteBuffer(wgpu_context->queue, state.ubo_offscreen, 0,
&state.ubo_offscreen_data, sizeof(ubo_data_t));
}
/* -------------------------------------------------------------------------- *
* Bind group layouts
* -------------------------------------------------------------------------- */
static void init_bind_group_layouts(struct wgpu_context_t* wgpu_context)
{
WGPUDevice device = wgpu_context->device;
/* Shaded BGL: single UBO at binding 0 (vertex stage) */
{
WGPUBindGroupLayoutEntry entry = {
.binding = 0,
.visibility = WGPUShaderStage_Vertex,
.buffer = {
.type = WGPUBufferBindingType_Uniform,
.minBindingSize = sizeof(ubo_data_t),
},
};
state.shaded_bgl = wgpuDeviceCreateBindGroupLayout(
device, &(WGPUBindGroupLayoutDescriptor){
.label = STRVIEW("Shaded BGL"),
.entryCount = 1,
.entries = &entry,
});
ASSERT(state.shaded_bgl != NULL);
}
/* Textured BGL: UBO (0), sampler (1), texture (2) */
{
WGPUBindGroupLayoutEntry entries[3] = {
[0] = {
.binding = 0,
.visibility = WGPUShaderStage_Vertex,
.buffer = {
.type = WGPUBufferBindingType_Uniform,
.minBindingSize = sizeof(ubo_data_t),
},
},
[1] = {
.binding = 1,
.visibility = WGPUShaderStage_Fragment,
.sampler = { .type = WGPUSamplerBindingType_Filtering },
},
[2] = {
.binding = 2,
.visibility = WGPUShaderStage_Fragment,
.texture = {
.sampleType = WGPUTextureSampleType_Float,
.viewDimension = WGPUTextureViewDimension_2D,
.multisampled = false,
},
},
};
state.textured_bgl = wgpuDeviceCreateBindGroupLayout(
device, &(WGPUBindGroupLayoutDescriptor){
.label = STRVIEW("Textured BGL"),
.entryCount = ARRAY_SIZE(entries),
.entries = entries,
});
ASSERT(state.textured_bgl != NULL);
}
}
/* -------------------------------------------------------------------------- *
* Pipeline layouts
* -------------------------------------------------------------------------- */
static void init_pipeline_layouts(struct wgpu_context_t* wgpu_context)
{
WGPUDevice device = wgpu_context->device;
state.shaded_layout = wgpuDeviceCreatePipelineLayout(
device, &(WGPUPipelineLayoutDescriptor){
.label = STRVIEW("Shaded Pipeline Layout"),
.bindGroupLayoutCount = 1,
.bindGroupLayouts = &state.shaded_bgl,
});
ASSERT(state.shaded_layout != NULL);
state.textured_layout = wgpuDeviceCreatePipelineLayout(
device, &(WGPUPipelineLayoutDescriptor){
.label = STRVIEW("Textured Pipeline Layout"),
.bindGroupLayoutCount = 1,
.bindGroupLayouts = &state.textured_bgl,
});
ASSERT(state.textured_layout != NULL);
}
/* -------------------------------------------------------------------------- *
* Bind groups
* -------------------------------------------------------------------------- */
static void init_bind_groups(struct wgpu_context_t* wgpu_context)
{
WGPUDevice device = wgpu_context->device;
/* offscreen_bg: shaded — draws the flipped dragon */
{
WGPUBindGroupEntry entry = {
.binding = 0,
.buffer = state.ubo_offscreen,
.offset = 0,
.size = sizeof(ubo_data_t),
};
state.offscreen_bg
= wgpuDeviceCreateBindGroup(device, &(WGPUBindGroupDescriptor){
.label = STRVIEW("Offscreen BG"),
.layout = state.shaded_bgl,
.entryCount = 1,
.entries = &entry,
});
ASSERT(state.offscreen_bg != NULL);
}
/* model_bg: shaded — draws the main lit dragon */
{
WGPUBindGroupEntry entry = {
.binding = 0,
.buffer = state.ubo_model,
.offset = 0,
.size = sizeof(ubo_data_t),
};
state.model_bg
= wgpuDeviceCreateBindGroup(device, &(WGPUBindGroupDescriptor){
.label = STRVIEW("Model BG"),
.layout = state.shaded_bgl,
.entryCount = 1,
.entries = &entry,
});
ASSERT(state.model_bg != NULL);
}
/* mirror_bg: textured — mirror plane and debug quad */
{
WGPUBindGroupEntry entries[3] = {
[0] = {
.binding = 0,
.buffer = state.ubo_mirror,
.offset = 0,
.size = sizeof(ubo_data_t),
},
[1] = {
.binding = 1,
.sampler = state.offscreen.sampler,
},
[2] = {
.binding = 2,
.textureView = state.offscreen.color_view,
},
};
state.mirror_bg
= wgpuDeviceCreateBindGroup(device, &(WGPUBindGroupDescriptor){
.label = STRVIEW("Mirror BG"),
.layout = state.textured_bgl,
.entryCount = ARRAY_SIZE(entries),
.entries = entries,
});
ASSERT(state.mirror_bg != NULL);
}
}
static void destroy_bind_groups(void)
{
WGPU_RELEASE_RESOURCE(BindGroup, state.offscreen_bg)
WGPU_RELEASE_RESOURCE(BindGroup, state.model_bg)
WGPU_RELEASE_RESOURCE(BindGroup, state.mirror_bg)
}
/* -------------------------------------------------------------------------- *
* Render pipelines
* -------------------------------------------------------------------------- */
/* gltf_vertex_t interleaved layout — locations match gltf_vertex_t offsets:
* location 0: position (vec3f) at offset 0
* location 1: normal (vec3f) at offset 12
* location 2: uv0 (vec2f) at offset 24 (consumed but unused)
* location 3: color (vec4f) at offset 56 */
static WGPUVertexBufferLayout make_gltf_vbl(void)
{
static WGPUVertexAttribute attrs[4];
attrs[0] = (WGPUVertexAttribute){
.shaderLocation = 0,
.offset = offsetof(gltf_vertex_t, position),
.format = WGPUVertexFormat_Float32x3,
};
attrs[1] = (WGPUVertexAttribute){
.shaderLocation = 1,
.offset = offsetof(gltf_vertex_t, normal),
.format = WGPUVertexFormat_Float32x3,
};
attrs[2] = (WGPUVertexAttribute){
.shaderLocation = 2,
.offset = offsetof(gltf_vertex_t, uv0),
.format = WGPUVertexFormat_Float32x2,
};
attrs[3] = (WGPUVertexAttribute){
.shaderLocation = 3,
.offset = offsetof(gltf_vertex_t, color),
.format = WGPUVertexFormat_Float32x4,
};
return (WGPUVertexBufferLayout){
.arrayStride = sizeof(gltf_vertex_t),
.stepMode = WGPUVertexStepMode_Vertex,
.attributeCount = 4,
.attributes = attrs,
};
}
static void init_pipelines(struct wgpu_context_t* wgpu_context)
{
WGPUDevice device = wgpu_context->device;
WGPUVertexBufferLayout vbl = make_gltf_vbl();
/* Depth stencil state shared by all mesh passes */
WGPUDepthStencilState depth_state = {
.format = DEPTH_FORMAT,
.depthWriteEnabled = WGPUOptionalBool_True,
.depthCompare = WGPUCompareFunction_LessEqual,
.stencilFront.compare = WGPUCompareFunction_Always,
.stencilBack.compare = WGPUCompareFunction_Always,
};
/* ---- (1) Debug pipeline: fullscreen triangle showing offscreen tex ---- */
{
WGPUShaderModule sm
= wgpu_create_shader_module(device, offscreen_quad_shader_wgsl);
WGPUColorTargetState ct = {
.format = wgpu_context->render_format,
.writeMask = WGPUColorWriteMask_All,
};
state.debug_pipeline = wgpuDeviceCreateRenderPipeline(
device,
&(WGPURenderPipelineDescriptor){
.label = STRVIEW("Debug Pipeline"),
.layout = state.textured_layout,
.vertex = {
.module = sm,
.entryPoint = STRVIEW("vs_quad"),
.bufferCount = 0,
.buffers = NULL,
},
.primitive = {
.topology = WGPUPrimitiveTopology_TriangleList,
.cullMode = WGPUCullMode_None,
.frontFace = WGPUFrontFace_CCW,
},
.depthStencil = NULL, /* no depth for fullscreen pass */
.multisample = {.count = 1, .mask = 0xFFFFFFFF},
.fragment = &(WGPUFragmentState){
.module = sm,
.entryPoint = STRVIEW("fs_quad"),
.targetCount = 1,
.targets = &ct,
},
});
ASSERT(state.debug_pipeline != NULL);
wgpuShaderModuleRelease(sm);
}
/* ---- (2) Shaded pipeline: Phong-lit dragon (main pass, back cull) ---- */
{
WGPUShaderModule sm
= wgpu_create_shader_module(device, offscreen_phong_shader_wgsl);
WGPUColorTargetState ct = {
.format = wgpu_context->render_format,
.writeMask = WGPUColorWriteMask_All,
};
state.shaded_pipeline = wgpuDeviceCreateRenderPipeline(
device,
&(WGPURenderPipelineDescriptor){
.label = STRVIEW("Shaded Pipeline"),
.layout = state.shaded_layout,
.vertex = {
.module = sm,
.entryPoint = STRVIEW("vs_phong"),
.bufferCount = 1,
.buffers = &vbl,
},
.primitive = {
.topology = WGPUPrimitiveTopology_TriangleList,
.cullMode = WGPUCullMode_Back,
.frontFace = WGPUFrontFace_CCW,
},
.depthStencil = &depth_state,
.multisample = {.count = 1, .mask = 0xFFFFFFFF},
.fragment = &(WGPUFragmentState){
.module = sm,
.entryPoint = STRVIEW("fs_phong"),
.targetCount = 1,
.targets = &ct,
},
});
ASSERT(state.shaded_pipeline != NULL);
wgpuShaderModuleRelease(sm);
}
/* ---- (3) Offscreen pipeline: Phong dragon (offscreen pass, front cull) --
* The Y-flipped dragon is rendered back-to-front from the camera's
* perspective, so we flip the cull mode to FRONT to match what Vulkan
* does (VK_CULL_MODE_FRONT_BIT for the offscreen pass). */
{
WGPUShaderModule sm
= wgpu_create_shader_module(device, offscreen_phong_shader_wgsl);
WGPUColorTargetState ct = {
.format = WGPUTextureFormat_RGBA8Unorm,
.writeMask = WGPUColorWriteMask_All,
};
WGPUDepthStencilState ds = depth_state;
state.offscreen_pipeline = wgpuDeviceCreateRenderPipeline(
device,
&(WGPURenderPipelineDescriptor){
.label = STRVIEW("Offscreen Phong Pipeline"),
.layout = state.shaded_layout,
.vertex = {
.module = sm,
.entryPoint = STRVIEW("vs_phong"),
.bufferCount = 1,
.buffers = &vbl,
},
.primitive = {
.topology = WGPUPrimitiveTopology_TriangleList,
.cullMode = WGPUCullMode_Front, /* flipped for mirror reflection */
.frontFace = WGPUFrontFace_CCW,
},
.depthStencil = &ds,
.multisample = {.count = 1, .mask = 0xFFFFFFFF},
.fragment = &(WGPUFragmentState){
.module = sm,
.entryPoint = STRVIEW("fs_phong"),
.targetCount = 1,
.targets = &ct,
},
});
ASSERT(state.offscreen_pipeline != NULL);
wgpuShaderModuleRelease(sm);
}
/* ---- (4) Mirror pipeline: plane with projective reflection texture ---- */
{
WGPUShaderModule sm
= wgpu_create_shader_module(device, offscreen_mirror_shader_wgsl);
WGPUColorTargetState ct = {
.format = wgpu_context->render_format,
.writeMask = WGPUColorWriteMask_All,
};
state.mirror_pipeline = wgpuDeviceCreateRenderPipeline(
device,
&(WGPURenderPipelineDescriptor){
.label = STRVIEW("Mirror Pipeline"),
.layout = state.textured_layout,
.vertex = {
.module = sm,
.entryPoint = STRVIEW("vs_mirror"),
.bufferCount = 1,
.buffers = &vbl,
},
.primitive = {
.topology = WGPUPrimitiveTopology_TriangleList,
.cullMode = WGPUCullMode_None, /* render both faces of the plane */
.frontFace = WGPUFrontFace_CCW,
},
.depthStencil = &depth_state,
.multisample = {.count = 1, .mask = 0xFFFFFFFF},
.fragment = &(WGPUFragmentState){
.module = sm,
.entryPoint = STRVIEW("fs_mirror"),
.targetCount = 1,
.targets = &ct,
},
});
ASSERT(state.mirror_pipeline != NULL);
wgpuShaderModuleRelease(sm);
}
}
/* -------------------------------------------------------------------------- *
* Draw helpers
* -------------------------------------------------------------------------- */
static void draw_model(WGPURenderPassEncoder pass, gltf_model_t* m,
WGPUBuffer vb, WGPUBuffer ib)
{
if (!state.models_loaded || !vb) {
return;
}
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 < m->linear_node_count; n++) {
gltf_node_t* node = m->linear_nodes[n];
if (!node->mesh) {
continue;
}
for (uint32_t p = 0; p < node->mesh->primitive_count; p++) {
gltf_primitive_t* prim = &node->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);
}
}
}
}
/* -------------------------------------------------------------------------- *
* 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){280.0f, 0.0f}, ImGuiCond_FirstUseEver);
igBegin("Offscreen Rendering", NULL, ImGuiWindowFlags_AlwaysAutoResize);
if (igCollapsingHeader_BoolPtr("Settings", NULL,
ImGuiTreeNodeFlags_DefaultOpen)) {
imgui_overlay_checkbox("Display render target", &state.debug_display);
}
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);
}
}
/* -------------------------------------------------------------------------- *
* Window resize
* -------------------------------------------------------------------------- */
static void on_resize(struct wgpu_context_t* wgpu_context)
{
destroy_main_depth_texture();
init_main_depth_texture(wgpu_context);
camera_update_aspect_ratio(&state.camera, (float)wgpu_context->width
/ (float)wgpu_context->height);
}
/* -------------------------------------------------------------------------- *
* Init / Frame / Shutdown
* -------------------------------------------------------------------------- */
static int init(struct wgpu_context_t* wgpu_context)
{
if (!wgpu_context) {
return EXIT_FAILURE;
}
stm_setup();
/* Camera — Vulkan: position (0, 1, -6), rotation (-2.5, 0, 0).
* Porting guide: negate camera Y (camera.c negates internally), negate X. */
camera_init(&state.camera);
state.camera.type = CameraType_LookAt;
state.camera.invert_dx = true;
state.camera.invert_dy = true;
camera_set_perspective(
&state.camera, 60.0f,
(float)wgpu_context->width / (float)wgpu_context->height, 0.1f, 256.0f);
camera_set_rotation(&state.camera, (vec3){2.5f, 0.0f, 0.0f});
/* WebGPU +Y = top of screen, Vulkan +Y = bottom (flipY=false).
* Pass the SAME value as the Vulkan setPosition({0,1,-6}) so that
* camera_set_position's internal Y-negation compensates for the flip:
* stored = (0, -1, -6) → view T(0,-1,-6) → camera above floor at Y=+1. */
camera_set_position(&state.camera, (vec3){0.0f, 1.0f, -6.0f});
state.camera.rotation_speed = 0.5f;