-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathinput_attachments.c
More file actions
1137 lines (980 loc) · 36.4 KB
/
Copy pathinput_attachments.c
File metadata and controls
1137 lines (980 loc) · 36.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
/* -------------------------------------------------------------------------- *
* WebGPU Example - Input Attachments
*
* Demonstrates the WebGPU equivalent of Vulkan input attachments: reading
* attachment contents from a previous render pass at the same pixel position.
* Since WebGPU does not have native subpasses / input attachments, this is
* implemented as a two-pass approach using offscreen textures:
*
* Pass 1 (Attachment Write): Render a glTF model with toon shading to
* offscreen color and depth textures.
* Pass 2 (Attachment Read): Fullscreen triangle reads those textures and
* applies either brightness/contrast (color) or depth range visualization.
*
* GUI controls let the user select which attachment to visualize and adjust
* the post-processing parameters.
*
* Ref:
* https://github.com/SaschaWillems/Vulkan/blob/master/examples/inputattachments
* -------------------------------------------------------------------------- */
#include "webgpu/imgui_overlay.h"
#include "webgpu/wgpu_common.h"
#include <cglm/cglm.h>
#ifdef __WAJIC__
#define WAJIC_SFETCH_IMPL
#include <wajic_sfetch.h>
#define WAJIC_TIME_IMPL
#include <wajic_time.h>
#else
#define SOKOL_LOG_IMPL
#include <sokol_log.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 "core/camera.h"
#include "core/gltf_model.h"
#include <stdlib.h>
#include <string.h>
#ifdef __WAJIC__
/* 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
#endif
/* -------------------------------------------------------------------------- *
* WGSL Shaders (forward declarations - defined at bottom of file)
* -------------------------------------------------------------------------- */
static const char* attachment_write_shader_wgsl;
static const char* attachment_read_shader_wgsl;
/* -------------------------------------------------------------------------- *
* State
* -------------------------------------------------------------------------- */
static struct {
/* Camera */
camera_t camera;
/* Model */
gltf_model_t scene_model;
bool model_loaded;
bool model_buffers_created; /* WAjic: true after GPU buffers uploaded */
/* GPU vertex/index buffers */
WGPUBuffer vertex_buffer;
WGPUBuffer index_buffer;
/* Offscreen attachments (color + depth written in pass 1, read in pass 2) */
struct {
WGPUTexture color_texture;
WGPUTextureView color_view;
WGPUTexture depth_texture;
WGPUTextureView depth_view;
WGPUSampler sampler;
uint32_t width;
uint32_t height;
} attachments;
/* Uniform buffers */
WGPUBuffer matrices_ubo; /* MVP for pass 1 */
WGPUBuffer params_ubo; /* Post-process params for pass 2 */
/* Uniform data */
struct {
mat4 projection;
mat4 model;
mat4 view;
} ubo_matrices;
struct {
float brightness;
float contrast;
float range_min;
float range_max;
int32_t attachment_index;
float _padding[3];
} ubo_params;
/* Bind group layouts */
WGPUBindGroupLayout write_bgl;
WGPUBindGroupLayout read_bgl;
/* Pipeline layouts */
WGPUPipelineLayout write_pipeline_layout;
WGPUPipelineLayout read_pipeline_layout;
/* Render pipelines */
WGPURenderPipeline write_pipeline;
WGPURenderPipeline read_pipeline;
/* Bind groups */
WGPUBindGroup write_bind_group;
WGPUBindGroup read_bind_group;
/* Render pass descriptors */
WGPURenderPassColorAttachment offscreen_color_att;
WGPURenderPassDepthStencilAttachment offscreen_depth_att;
WGPURenderPassDescriptor offscreen_render_pass_desc;
WGPURenderPassColorAttachment main_color_att;
WGPURenderPassDepthStencilAttachment main_depth_att;
WGPURenderPassDescriptor main_render_pass_desc;
/* Timing */
uint64_t last_frame_time;
WGPUBool initialized;
} state = {
.ubo_params = {
.brightness = 0.5f,
.contrast = 1.8f,
.range_min = 0.6f,
.range_max = 1.0f,
.attachment_index = 0,
},
.offscreen_color_att = {
.loadOp = WGPULoadOp_Clear,
.storeOp = WGPUStoreOp_Store,
.clearValue = {0.0f, 0.0f, 0.2f, 0.0f},
.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED,
},
.offscreen_depth_att = {
.depthLoadOp = WGPULoadOp_Clear,
.depthStoreOp = WGPUStoreOp_Store,
.depthClearValue = 1.0f,
.stencilLoadOp = WGPULoadOp_Undefined,
.stencilStoreOp = WGPUStoreOp_Undefined,
.stencilClearValue = 0,
},
.offscreen_render_pass_desc = {
.colorAttachmentCount = 1,
.colorAttachments = &state.offscreen_color_att,
.depthStencilAttachment = &state.offscreen_depth_att,
},
.main_color_att = {
.loadOp = WGPULoadOp_Clear,
.storeOp = WGPUStoreOp_Store,
.clearValue = {0.0f, 0.0f, 0.2f, 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_render_pass_desc = {
.colorAttachmentCount = 1,
.colorAttachments = &state.main_color_att,
.depthStencilAttachment = &state.main_depth_att,
},
};
/* -------------------------------------------------------------------------- *
* Offscreen attachment setup
* -------------------------------------------------------------------------- */
static void destroy_offscreen_attachments(void)
{
WGPU_RELEASE_RESOURCE(TextureView, state.attachments.color_view)
WGPU_RELEASE_RESOURCE(Texture, state.attachments.color_texture)
WGPU_RELEASE_RESOURCE(TextureView, state.attachments.depth_view)
WGPU_RELEASE_RESOURCE(Texture, state.attachments.depth_texture)
}
static void init_offscreen_attachments(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;
/* Skip if size hasn't changed */
if (state.attachments.width == w && state.attachments.height == h) {
return;
}
/* Destroy previous if resized */
destroy_offscreen_attachments();
state.attachments.width = w;
state.attachments.height = h;
/* Color attachment (RGBA8Unorm, used as render target + sampled texture) */
state.attachments.color_texture = wgpuDeviceCreateTexture(
device, &(WGPUTextureDescriptor){
.label = STRVIEW("Attachment Color"),
.usage = WGPUTextureUsage_RenderAttachment
| WGPUTextureUsage_TextureBinding,
.dimension = WGPUTextureDimension_2D,
.size = {w, h, 1},
.format = WGPUTextureFormat_RGBA8Unorm,
.mipLevelCount = 1,
.sampleCount = 1,
});
state.attachments.color_view = wgpuTextureCreateView(
state.attachments.color_texture, &(WGPUTextureViewDescriptor){
.format = WGPUTextureFormat_RGBA8Unorm,
.dimension = WGPUTextureViewDimension_2D,
.baseMipLevel = 0,
.mipLevelCount = 1,
.baseArrayLayer = 0,
.arrayLayerCount = 1,
.aspect = WGPUTextureAspect_All,
});
/* Depth attachment (Depth24PlusStencil8, used as render target + sampled) */
state.attachments.depth_texture = wgpuDeviceCreateTexture(
device, &(WGPUTextureDescriptor){
.label = STRVIEW("Attachment Depth"),
.usage = WGPUTextureUsage_RenderAttachment
| WGPUTextureUsage_TextureBinding,
.dimension = WGPUTextureDimension_2D,
.size = {w, h, 1},
.format = WGPUTextureFormat_Depth32Float,
.mipLevelCount = 1,
.sampleCount = 1,
});
state.attachments.depth_view = wgpuTextureCreateView(
state.attachments.depth_texture, &(WGPUTextureViewDescriptor){
.format = WGPUTextureFormat_Depth32Float,
.dimension = WGPUTextureViewDimension_2D,
.baseMipLevel = 0,
.mipLevelCount = 1,
.baseArrayLayer = 0,
.arrayLayerCount = 1,
.aspect = WGPUTextureAspect_DepthOnly,
});
/* Sampler (only created once) */
if (!state.attachments.sampler) {
state.attachments.sampler = wgpuDeviceCreateSampler(
device, &(WGPUSamplerDescriptor){
.label = STRVIEW("Attachment Sampler"),
.addressModeU = WGPUAddressMode_ClampToEdge,
.addressModeV = WGPUAddressMode_ClampToEdge,
.addressModeW = WGPUAddressMode_ClampToEdge,
.magFilter = WGPUFilterMode_Nearest,
.minFilter = WGPUFilterMode_Nearest,
.mipmapFilter = WGPUMipmapFilterMode_Nearest,
.maxAnisotropy = 1,
});
}
}
/* -------------------------------------------------------------------------- *
* Model loading
* -------------------------------------------------------------------------- */
#ifdef __WAJIC__
/* Async model fetch callback (WAjic only).
* Uses dynamic allocation (buffer.ptr = NULL): JS allocates the exact amount
* of WASM memory needed and passes a valid pointer here. */
static void model_fetch_callback(const sfetch_response_t* response)
{
if (!response->fetched) {
printf("Input Attachments: model fetch failed, error: %d\n",
response->error_code);
return;
}
bool ok = gltf_model_load_from_memory(
&state.scene_model, response->data.ptr, response->data.size,
"assets/models/treasure_smooth.gltf", 1.0f);
if (ok) {
state.model_loaded = true;
}
else {
printf("Input Attachments: failed to parse gltf model\n");
}
}
#endif /* __WAJIC__ */
static void load_model(void)
{
#ifdef __WAJIC__
sfetch_send(&(sfetch_request_t){
.path = "assets/models/treasure_smooth.gltf",
.callback = model_fetch_callback,
.channel = 0,
});
#else
gltf_model_load_from_file(&state.scene_model,
"assets/models/treasure_smooth.gltf", 1.0f);
state.model_loaded = true;
#endif
}
static void create_model_buffers(struct wgpu_context_t* wgpu_context)
{
if (!state.model_loaded) {
return;
}
WGPUDevice device = wgpu_context->device;
gltf_model_t* m = &state.scene_model;
size_t vb_size = m->vertex_count * sizeof(gltf_vertex_t);
/* Bake node transforms + pre-multiply vertex colors */
gltf_model_desc_t load_desc = {
.loading_flags = GltfLoadingFlag_PreTransformVertices
| GltfLoadingFlag_PreMultiplyVertexColors,
};
gltf_vertex_t* xformed = (gltf_vertex_t*)malloc(vb_size);
memcpy(xformed, m->vertices, vb_size);
gltf_model_bake_node_transforms(m, xformed, &load_desc);
/* Upload vertex buffer */
state.vertex_buffer
= wgpuDeviceCreateBuffer(device, &(WGPUBufferDescriptor){
.label = STRVIEW("Scene Vertex Buffer"),
.usage = WGPUBufferUsage_Vertex,
.size = vb_size,
.mappedAtCreation = true,
});
void* vdata = wgpuBufferGetMappedRange(state.vertex_buffer, 0, vb_size);
memcpy(vdata, xformed, vb_size);
wgpuBufferUnmap(state.vertex_buffer);
free(xformed);
/* Upload index buffer */
if (m->index_count > 0) {
size_t ib_size = m->index_count * sizeof(uint32_t);
state.index_buffer
= wgpuDeviceCreateBuffer(device, &(WGPUBufferDescriptor){
.label = STRVIEW("Scene Index Buffer"),
.usage = WGPUBufferUsage_Index,
.size = ib_size,
.mappedAtCreation = true,
});
void* idata = wgpuBufferGetMappedRange(state.index_buffer, 0, ib_size);
memcpy(idata, m->indices, ib_size);
wgpuBufferUnmap(state.index_buffer);
}
}
/* -------------------------------------------------------------------------- *
* Uniform buffers
* -------------------------------------------------------------------------- */
static void init_uniform_buffers(struct wgpu_context_t* wgpu_context)
{
WGPUDevice device = wgpu_context->device;
/* Matrices UBO: projection + model + view (3 x mat4 = 192 bytes) */
state.matrices_ubo = wgpuDeviceCreateBuffer(
device, &(WGPUBufferDescriptor){
.label = STRVIEW("Matrices UBO"),
.usage = WGPUBufferUsage_Uniform | WGPUBufferUsage_CopyDst,
.size = sizeof(state.ubo_matrices),
});
/* Params UBO: brightness, contrast, range, attachment_index + padding */
state.params_ubo = wgpuDeviceCreateBuffer(
device, &(WGPUBufferDescriptor){
.label = STRVIEW("Params UBO"),
.usage = WGPUBufferUsage_Uniform | WGPUBufferUsage_CopyDst,
.size = sizeof(state.ubo_params),
});
}
static void update_uniform_buffers(struct wgpu_context_t* wgpu_context)
{
WGPUQueue queue = wgpu_context->queue;
/* Update matrices */
glm_mat4_copy(state.camera.matrices.perspective,
state.ubo_matrices.projection);
glm_mat4_copy(state.camera.matrices.view, state.ubo_matrices.view);
glm_mat4_identity(state.ubo_matrices.model);
wgpuQueueWriteBuffer(queue, state.matrices_ubo, 0, &state.ubo_matrices,
sizeof(state.ubo_matrices));
/* Update params */
wgpuQueueWriteBuffer(queue, state.params_ubo, 0, &state.ubo_params,
sizeof(state.ubo_params));
}
/* -------------------------------------------------------------------------- *
* Bind group layouts & pipeline layouts
* -------------------------------------------------------------------------- */
static void init_bind_group_layouts(struct wgpu_context_t* wgpu_context)
{
WGPUDevice device = wgpu_context->device;
/* Attachment write: binding 0 = matrices UBO (vertex) */
{
WGPUBindGroupLayoutEntry entries[1] = {
[0] = {
.binding = 0,
.visibility = WGPUShaderStage_Vertex,
.buffer = {.type = WGPUBufferBindingType_Uniform},
},
};
state.write_bgl = wgpuDeviceCreateBindGroupLayout(
device, &(WGPUBindGroupLayoutDescriptor){
.label = STRVIEW("Attachment Write BGL"),
.entryCount = ARRAY_SIZE(entries),
.entries = entries,
});
}
/* Attachment read: b0=color texture, b1=color sampler,
b2=depth texture, b3=depth sampler, b4=params UBO */
{
WGPUBindGroupLayoutEntry entries[5] = {
[0] = {
.binding = 0,
.visibility = WGPUShaderStage_Fragment,
.texture = {
.sampleType = WGPUTextureSampleType_Float,
.viewDimension = WGPUTextureViewDimension_2D,
},
},
[1] = {
.binding = 1,
.visibility = WGPUShaderStage_Fragment,
.sampler = {.type = WGPUSamplerBindingType_Filtering},
},
[2] = {
.binding = 2,
.visibility = WGPUShaderStage_Fragment,
.texture = {
.sampleType = WGPUTextureSampleType_UnfilterableFloat,
.viewDimension = WGPUTextureViewDimension_2D,
},
},
[3] = {
.binding = 3,
.visibility = WGPUShaderStage_Fragment,
.sampler = {.type = WGPUSamplerBindingType_NonFiltering},
},
[4] = {
.binding = 4,
.visibility = WGPUShaderStage_Fragment,
.buffer = {.type = WGPUBufferBindingType_Uniform},
},
};
state.read_bgl = wgpuDeviceCreateBindGroupLayout(
device, &(WGPUBindGroupLayoutDescriptor){
.label = STRVIEW("Attachment Read BGL"),
.entryCount = ARRAY_SIZE(entries),
.entries = entries,
});
}
}
static void init_pipeline_layouts(struct wgpu_context_t* wgpu_context)
{
WGPUDevice device = wgpu_context->device;
state.write_pipeline_layout = wgpuDeviceCreatePipelineLayout(
device, &(WGPUPipelineLayoutDescriptor){
.label = STRVIEW("Attachment Write PL"),
.bindGroupLayoutCount = 1,
.bindGroupLayouts = &state.write_bgl,
});
state.read_pipeline_layout = wgpuDeviceCreatePipelineLayout(
device, &(WGPUPipelineLayoutDescriptor){
.label = STRVIEW("Attachment Read PL"),
.bindGroupLayoutCount = 1,
.bindGroupLayouts = &state.read_bgl,
});
}
/* -------------------------------------------------------------------------- *
* Bind groups
* -------------------------------------------------------------------------- */
static void init_bind_groups(struct wgpu_context_t* wgpu_context)
{
WGPUDevice device = wgpu_context->device;
/* Write bind group: matrices UBO */
{
WGPUBindGroupEntry entries[1] = {
[0] = {
.binding = 0,
.buffer = state.matrices_ubo,
.offset = 0,
.size = sizeof(state.ubo_matrices),
},
};
WGPU_RELEASE_RESOURCE(BindGroup, state.write_bind_group)
state.write_bind_group = wgpuDeviceCreateBindGroup(
device, &(WGPUBindGroupDescriptor){
.label = STRVIEW("Attachment Write BG"),
.layout = state.write_bgl,
.entryCount = ARRAY_SIZE(entries),
.entries = entries,
});
}
/* Read bind group: color tex, color sampler, depth tex, depth sampler,
* params UBO */
{
WGPUBindGroupEntry entries[5] = {
[0] = {
.binding = 0,
.textureView = state.attachments.color_view,
},
[1] = {
.binding = 1,
.sampler = state.attachments.sampler,
},
[2] = {
.binding = 2,
.textureView = state.attachments.depth_view,
},
[3] = {
.binding = 3,
.sampler = state.attachments.sampler,
},
[4] = {
.binding = 4,
.buffer = state.params_ubo,
.offset = 0,
.size = sizeof(state.ubo_params),
},
};
WGPU_RELEASE_RESOURCE(BindGroup, state.read_bind_group)
state.read_bind_group = wgpuDeviceCreateBindGroup(
device, &(WGPUBindGroupDescriptor){
.label = STRVIEW("Attachment Read BG"),
.layout = state.read_bgl,
.entryCount = ARRAY_SIZE(entries),
.entries = entries,
});
}
}
/* -------------------------------------------------------------------------- *
* Render pipelines
* -------------------------------------------------------------------------- */
static void init_pipelines(struct wgpu_context_t* wgpu_context)
{
WGPUDevice device = wgpu_context->device;
/* ---- Attachment write pipeline ---- */
{
WGPUShaderModule shader
= wgpu_create_shader_module(device, attachment_write_shader_wgsl);
/* Vertex buffer layout: position, color, normal from gltf_vertex_t */
WGPUVertexAttribute vertex_attrs[] = {
{
.shaderLocation = 0,
.offset = offsetof(gltf_vertex_t, position),
.format = WGPUVertexFormat_Float32x3,
},
{
.shaderLocation = 1,
.offset = offsetof(gltf_vertex_t, color),
.format = WGPUVertexFormat_Float32x4,
},
{
.shaderLocation = 2,
.offset = offsetof(gltf_vertex_t, normal),
.format = WGPUVertexFormat_Float32x3,
},
};
WGPUVertexBufferLayout vb_layout = {
.arrayStride = sizeof(gltf_vertex_t),
.stepMode = WGPUVertexStepMode_Vertex,
.attributeCount = ARRAY_SIZE(vertex_attrs),
.attributes = vertex_attrs,
};
WGPUDepthStencilState depth_stencil
= wgpu_create_depth_stencil_state(&(create_depth_stencil_state_desc_t){
.format = WGPUTextureFormat_Depth32Float,
.depth_write_enabled = true,
});
depth_stencil.depthCompare = WGPUCompareFunction_LessEqual;
WGPU_RELEASE_RESOURCE(RenderPipeline, state.write_pipeline)
state.write_pipeline = wgpuDeviceCreateRenderPipeline(
device,
&(WGPURenderPipelineDescriptor){
.label = STRVIEW("Attachment Write Pipeline"),
.layout = state.write_pipeline_layout,
.vertex = {
.module = shader,
.entryPoint = STRVIEW("vs_main"),
.bufferCount = 1,
.buffers = &vb_layout,
},
.primitive = {
.topology = WGPUPrimitiveTopology_TriangleList,
.frontFace = WGPUFrontFace_CCW,
.cullMode = WGPUCullMode_Back,
},
.depthStencil = &depth_stencil,
.multisample = {
.count = 1,
.mask = 0xFFFFFFFF,
},
.fragment = &(WGPUFragmentState){
.module = shader,
.entryPoint = STRVIEW("fs_main"),
.targetCount = 1,
.targets = &(WGPUColorTargetState){
.format = WGPUTextureFormat_RGBA8Unorm,
.writeMask = WGPUColorWriteMask_All,
},
},
});
wgpuShaderModuleRelease(shader);
}
/* ---- Attachment read pipeline (fullscreen triangle) ---- */
{
WGPUShaderModule shader
= wgpu_create_shader_module(device, attachment_read_shader_wgsl);
WGPUDepthStencilState depth_stencil
= wgpu_create_depth_stencil_state(&(create_depth_stencil_state_desc_t){
.format = wgpu_context->depth_stencil_format,
.depth_write_enabled = false,
});
depth_stencil.depthCompare = WGPUCompareFunction_Always;
WGPU_RELEASE_RESOURCE(RenderPipeline, state.read_pipeline)
state.read_pipeline = wgpuDeviceCreateRenderPipeline(
device,
&(WGPURenderPipelineDescriptor){
.label = STRVIEW("Attachment Read Pipeline"),
.layout = state.read_pipeline_layout,
.vertex = {
.module = shader,
.entryPoint = STRVIEW("vs_main"),
.bufferCount = 0,
},
.primitive = {
.topology = WGPUPrimitiveTopology_TriangleList,
.frontFace = WGPUFrontFace_CCW,
.cullMode = WGPUCullMode_None,
},
.depthStencil = &depth_stencil,
.multisample = {
.count = 1,
.mask = 0xFFFFFFFF,
},
.fragment = &(WGPUFragmentState){
.module = shader,
.entryPoint = STRVIEW("fs_main"),
.targetCount = 1,
.targets = &(WGPUColorTargetState){
.format = wgpu_context->render_format,
.writeMask = WGPUColorWriteMask_All,
},
},
});
wgpuShaderModuleRelease(shader);
}
}
/* -------------------------------------------------------------------------- *
* Model drawing
* -------------------------------------------------------------------------- */
static void draw_model(WGPURenderPassEncoder pass)
{
gltf_model_t* m = &state.scene_model;
wgpuRenderPassEncoderSetVertexBuffer(pass, 0, state.vertex_buffer, 0,
WGPU_WHOLE_SIZE);
if (state.index_buffer) {
wgpuRenderPassEncoderSetIndexBuffer(
pass, state.index_buffer, 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 == NULL) {
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);
}
}
}
}
/* -------------------------------------------------------------------------- *
* GUI
* -------------------------------------------------------------------------- */
static const char* attachment_names[] = {"Color", "Depth"};
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("Settings", NULL, ImGuiWindowFlags_AlwaysAutoResize);
if (igCollapsingHeader_BoolPtr("Settings", NULL,
ImGuiTreeNodeFlags_DefaultOpen)) {
igText("Input attachment");
imgui_overlay_combo_box("##attachment", &state.ubo_params.attachment_index,
attachment_names, 2);
switch (state.ubo_params.attachment_index) {
case 0: /* Color */
igText("Brightness");
imgui_overlay_slider_float("##b", &state.ubo_params.brightness, 0.0f,
2.0f, "%.2f");
igText("Contrast");
imgui_overlay_slider_float("##c", &state.ubo_params.contrast, 0.0f,
4.0f, "%.2f");
break;
case 1: /* Depth */
igText("Visible range");
imgui_overlay_slider_float("min", &state.ubo_params.range_min, 0.0f,
state.ubo_params.range_max, "%.2f");
imgui_overlay_slider_float("max", &state.ubo_params.range_max,
state.ubo_params.range_min, 1.0f, "%.2f");
break;
}
}
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) {
/* Recreate offscreen attachments + bind groups on resize */
init_offscreen_attachments(wgpu_context);
init_bind_groups(wgpu_context);
}
}
/* -------------------------------------------------------------------------- *
* Init / Frame / Shutdown
* -------------------------------------------------------------------------- */
static int init(struct wgpu_context_t* wgpu_context)
{
if (!wgpu_context) {
return EXIT_FAILURE;
}
stm_setup();
#ifdef __WAJIC__
/* WAjic: use sfetch for async model loading */
sfetch_setup(&(sfetch_desc_t){
.max_requests = 1,
.num_channels = 1,
.num_lanes = 1,
});
#endif
/* Camera: first-person */
camera_init(&state.camera);
state.camera.type = CameraType_FirstPerson;
state.camera.movement_speed = 2.5f;
camera_set_position(&state.camera, (vec3){1.65f, 1.75f, -6.15f});
camera_set_rotation(&state.camera, (vec3){12.75f, 380.0f, 0.0f});
camera_set_perspective(
&state.camera, 60.0f,
(float)wgpu_context->width / (float)wgpu_context->height, 0.1f, 256.0f);
/* Load model (native: sync; WAjic: async via sfetch) */
load_model();
#ifndef __WAJIC__
create_model_buffers(wgpu_context);
#endif
/* Create offscreen attachments */
init_offscreen_attachments(wgpu_context);
/* Create uniform buffers */
init_uniform_buffers(wgpu_context);
/* Create bind group layouts + pipeline layouts */
init_bind_group_layouts(wgpu_context);
init_pipeline_layouts(wgpu_context);
/* Create bind groups */
init_bind_groups(wgpu_context);
/* Create render pipelines */
init_pipelines(wgpu_context);
/* ImGui */
imgui_overlay_init(wgpu_context);
state.initialized = true;
return EXIT_SUCCESS;
}
static int frame(struct wgpu_context_t* wgpu_context)
{
if (!state.initialized) {
return EXIT_FAILURE;
}
#ifdef __WAJIC__
/* Pump async file loading */
sfetch_dowork();
/* Upload model GPU buffers once the async fetch completes */
if (state.model_loaded && !state.model_buffers_created) {
create_model_buffers(wgpu_context);
state.model_buffers_created = true;
}
#endif
if (!state.model_loaded) {
return EXIT_FAILURE;
}
/* Timing */
uint64_t current_time = stm_now();
if (state.last_frame_time == 0) {
state.last_frame_time = current_time;
}
float delta_time
= (float)stm_sec(stm_diff(current_time, state.last_frame_time));
state.last_frame_time = current_time;
/* Update camera */
camera_update(&state.camera, delta_time);
/* Update uniforms */
update_uniform_buffers(wgpu_context);
/* ImGui */
imgui_overlay_new_frame(wgpu_context, delta_time);
render_gui(wgpu_context);
/* ---- Render ---- */
WGPUDevice device = wgpu_context->device;
WGPUQueue queue = wgpu_context->queue;
UNUSED_VAR(queue);
WGPUCommandEncoder cmd_enc = wgpuDeviceCreateCommandEncoder(device, NULL);
/* ==== Pass 1: Attachment Write (offscreen) ==== */
{
state.offscreen_color_att.view = state.attachments.color_view;
state.offscreen_depth_att.view = state.attachments.depth_view;
WGPURenderPassEncoder pass = wgpuCommandEncoderBeginRenderPass(
cmd_enc, &state.offscreen_render_pass_desc);
uint32_t w = state.attachments.width;
uint32_t h = state.attachments.height;
wgpuRenderPassEncoderSetViewport(pass, 0, 0, (float)w, (float)h, 0.0f,
1.0f);
wgpuRenderPassEncoderSetScissorRect(pass, 0, 0, w, h);
wgpuRenderPassEncoderSetPipeline(pass, state.write_pipeline);
wgpuRenderPassEncoderSetBindGroup(pass, 0, state.write_bind_group, 0, NULL);
draw_model(pass);
wgpuRenderPassEncoderEnd(pass);
wgpuRenderPassEncoderRelease(pass);
}
/* ==== Pass 2: Attachment Read (main swap chain) ==== */
{
state.main_color_att.view = wgpu_context->swapchain_view;
state.main_depth_att.view = wgpu_context->depth_stencil_view;
WGPURenderPassEncoder pass = wgpuCommandEncoderBeginRenderPass(
cmd_enc, &state.main_render_pass_desc);
uint32_t w = (uint32_t)wgpu_context->width;
uint32_t h = (uint32_t)wgpu_context->height;
wgpuRenderPassEncoderSetViewport(pass, 0, 0, (float)w, (float)h, 0.0f,
1.0f);
wgpuRenderPassEncoderSetScissorRect(pass, 0, 0, w, h);
wgpuRenderPassEncoderSetPipeline(pass, state.read_pipeline);
wgpuRenderPassEncoderSetBindGroup(pass, 0, state.read_bind_group, 0, NULL);
/* Fullscreen triangle: 3 vertices, no vertex buffer */
wgpuRenderPassEncoderDraw(pass, 3, 1, 0, 0);
wgpuRenderPassEncoderEnd(pass);
wgpuRenderPassEncoderRelease(pass);
}
/* Submit */
WGPUCommandBuffer cmd_buffer = wgpuCommandEncoderFinish(cmd_enc, NULL);
wgpuQueueSubmit(wgpu_context->queue, 1, &cmd_buffer);
wgpuCommandBufferRelease(cmd_buffer);
wgpuCommandEncoderRelease(cmd_enc);
/* ImGui overlay render */
imgui_overlay_render(wgpu_context);
return EXIT_SUCCESS;
}
static void shutdown(struct wgpu_context_t* wgpu_context)
{
UNUSED_VAR(wgpu_context);
#ifdef __WAJIC__
sfetch_shutdown();
#endif
imgui_overlay_shutdown();
/* Destroy model */
gltf_model_destroy(&state.scene_model);
/* Release GPU buffers */
WGPU_RELEASE_RESOURCE(Buffer, state.vertex_buffer)
WGPU_RELEASE_RESOURCE(Buffer, state.index_buffer)
/* Uniform buffers */
WGPU_RELEASE_RESOURCE(Buffer, state.matrices_ubo)
WGPU_RELEASE_RESOURCE(Buffer, state.params_ubo)
/* Offscreen attachments */
destroy_offscreen_attachments();
WGPU_RELEASE_RESOURCE(Sampler, state.attachments.sampler)
/* Bind groups */
WGPU_RELEASE_RESOURCE(BindGroup, state.write_bind_group)
WGPU_RELEASE_RESOURCE(BindGroup, state.read_bind_group)
/* Bind group layouts */
WGPU_RELEASE_RESOURCE(BindGroupLayout, state.write_bgl)