-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathbloom.c
More file actions
1932 lines (1690 loc) · 62.3 KB
/
Copy pathbloom.c
File metadata and controls
1932 lines (1690 loc) · 62.3 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 - Bloom (Fullscreen Blur)
*
* Implements a separable two-pass fullscreen Gaussian blur (bloom) effect.
* Bright parts of a glTF model ("glow" mesh) are rendered to an offscreen
* texture, then blurred in two passes (vertical + horizontal) using a 9-tap
* Gaussian kernel. The blurred result is composited onto the main scene with
* additive blending, creating a bloom halo around bright areas.
*
* Rendering passes:
* 1. Offscreen glow render: Render glow mesh vertex colors to FB[0]
* 2. Vertical blur: Fullscreen triangle reads FB[0], writes to FB[1]
* 3. Main scene: Skybox + Phong-lit UFO + horizontal blur composite
* (additive)
*
* Features:
* - Separable 9-tap Gaussian blur (5 weights, 2 passes)
* - Additive blending for bloom composition
* - Cubemap skybox rendering (fullscreen triangle technique)
* - Phong lighting with ambient glow boost for bright vertex colors
* - GUI controls for bloom toggle and blur scale
* - LookAt camera with mouse orbit
*
* Ref:
* https://github.com/SaschaWillems/Vulkan/blob/master/examples/bloom
* -------------------------------------------------------------------------- */
#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>
/* 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_LOG_IMPL
#include <sokol_log.h>
#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 "core/camera.h"
#include "core/gltf_model.h"
#include "core/image_loader.h"
#include <math.h>
#include <stdlib.h>
#include <string.h>
/* -------------------------------------------------------------------------- *
* WGSL Shaders (forward declarations - defined at bottom of file)
* -------------------------------------------------------------------------- */
static const char* bloom_colorpass_shader_wgsl;
static const char* bloom_phongpass_shader_wgsl;
static const char* bloom_gaussblur_vert_shader_wgsl;
static const char* bloom_gaussblur_horz_shader_wgsl;
static const char* bloom_skybox_shader_wgsl;
/* -------------------------------------------------------------------------- *
* Constants
* -------------------------------------------------------------------------- */
#define OFFSCREEN_WIDTH (256)
#define OFFSCREEN_HEIGHT (256)
#define NUM_CUBEMAP_FACES (6)
#define CUBEMAP_FACE_SIZE (512)
#define CUBEMAP_FACE_NUM_BYTES (CUBEMAP_FACE_SIZE * CUBEMAP_FACE_SIZE * 4)
/* -------------------------------------------------------------------------- *
* State
* -------------------------------------------------------------------------- */
static struct {
/* Camera */
camera_t camera;
/* Timer for UFO animation */
float timer;
float animation_speed;
/* Models */
gltf_model_t ufo_model;
gltf_model_t ufo_glow_model;
bool models_loaded;
int models_load_count; /* WAjic: number of async-loaded model files */
bool models_buffers_created; /* WAjic: GPU buffers created from loaded data */
/* GPU vertex/index buffers for UFO body */
WGPUBuffer ufo_vertex_buffer;
WGPUBuffer ufo_index_buffer;
/* GPU vertex/index buffers for UFO glow */
WGPUBuffer glow_vertex_buffer;
WGPUBuffer glow_index_buffer;
/* Cubemap texture */
struct {
WGPUTexture handle;
WGPUTextureView view;
WGPUSampler sampler;
bool is_dirty;
} cubemap_texture;
uint8_t* cubemap_pixels[NUM_CUBEMAP_FACES];
int cubemap_load_count;
/* Offscreen framebuffers (2 for ping-pong blur) */
struct {
WGPUTexture color_texture;
WGPUTextureView color_view;
WGPUTexture depth_texture;
WGPUTextureView depth_view;
} offscreen_fb[2];
WGPUSampler offscreen_sampler;
/* Uniform buffers */
WGPUBuffer scene_ubo; /* MVP for scene objects */
WGPUBuffer skybox_ubo; /* MVP for skybox (no translation) */
WGPUBuffer blur_params_ubo; /* blur scale + strength */
/* Uniform data */
struct {
mat4 projection;
mat4 view;
mat4 model;
} scene_ubo_data;
struct {
mat4 projection;
mat4 view;
mat4 model;
} skybox_ubo_data;
/* Bind group layouts */
WGPUBindGroupLayout scene_bgl;
WGPUBindGroupLayout blur_bgl;
WGPUBindGroupLayout skybox_bgl;
/* Pipeline layouts */
WGPUPipelineLayout scene_pipeline_layout;
WGPUPipelineLayout blur_pipeline_layout;
WGPUPipelineLayout skybox_pipeline_layout;
/* Render pipelines (5 total) */
WGPURenderPipeline glow_pipeline; /* Offscreen glow render */
WGPURenderPipeline blur_vert_pipeline; /* Vertical blur */
WGPURenderPipeline blur_horz_pipeline; /* Horizontal blur (additive) */
WGPURenderPipeline phong_pipeline; /* Phong-lit scene */
WGPURenderPipeline skybox_pipeline; /* Cubemap skybox */
/* Bind groups */
WGPUBindGroup scene_bind_group;
WGPUBindGroup blur_vert_bind_group; /* reads FB[0] */
WGPUBindGroup blur_horz_bind_group; /* reads FB[1] */
WGPUBindGroup skybox_bind_group;
/* Render pass descriptors for offscreen */
WGPURenderPassColorAttachment offscreen_color_att;
WGPURenderPassDepthStencilAttachment offscreen_depth_att;
WGPURenderPassDescriptor offscreen_render_pass_desc;
/* Main render pass */
WGPURenderPassColorAttachment main_color_att;
WGPURenderPassDepthStencilAttachment main_depth_att;
WGPURenderPassDescriptor main_render_pass_desc;
/* Settings */
struct {
bool bloom;
float blur_scale;
float blur_strength;
} settings;
/* Timing */
uint64_t last_frame_time;
WGPUBool initialized;
} state = {
.animation_speed = 0.25f,
.settings = {
.bloom = true,
.blur_scale = 1.0f,
.blur_strength = 1.5f,
},
.main_color_att = {
.loadOp = WGPULoadOp_Clear,
.storeOp = WGPUStoreOp_Store,
.clearValue = {0.0f, 0.0f, 0.0f, 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_color_att = {
.loadOp = WGPULoadOp_Clear,
.storeOp = WGPUStoreOp_Store,
.clearValue = {0.0f, 0.0f, 0.0f, 1.0f},
.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED,
},
.offscreen_depth_att = {
.depthLoadOp = WGPULoadOp_Clear,
.depthStoreOp = WGPUStoreOp_Store,
.depthClearValue = 1.0f,
.stencilLoadOp = WGPULoadOp_Clear,
.stencilStoreOp = WGPUStoreOp_Store,
.stencilClearValue = 0,
},
.offscreen_render_pass_desc = {
.colorAttachmentCount = 1,
.colorAttachments = &state.offscreen_color_att,
.depthStencilAttachment = &state.offscreen_depth_att,
},
};
/* -------------------------------------------------------------------------- *
* Offscreen framebuffer setup
* -------------------------------------------------------------------------- */
static void init_offscreen_framebuffers(struct wgpu_context_t* wgpu_context)
{
WGPUDevice device = wgpu_context->device;
for (int i = 0; i < 2; i++) {
/* Color texture */
WGPUTextureDescriptor color_desc = {
.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,
};
state.offscreen_fb[i].color_texture
= wgpuDeviceCreateTexture(device, &color_desc);
state.offscreen_fb[i].color_view = wgpuTextureCreateView(
state.offscreen_fb[i].color_texture,
&(WGPUTextureViewDescriptor){
.label = STRVIEW("Offscreen Color - Texture View"),
.format = WGPUTextureFormat_RGBA8Unorm,
.dimension = WGPUTextureViewDimension_2D,
.baseMipLevel = 0,
.mipLevelCount = 1,
.baseArrayLayer = 0,
.arrayLayerCount = 1,
.aspect = WGPUTextureAspect_All,
});
/* Depth texture */
WGPUTextureDescriptor depth_desc = {
.label = STRVIEW("Offscreen Depth - Texture"),
.usage = WGPUTextureUsage_RenderAttachment,
.dimension = WGPUTextureDimension_2D,
.size = {OFFSCREEN_WIDTH, OFFSCREEN_HEIGHT, 1},
.format = WGPUTextureFormat_Depth24PlusStencil8,
.mipLevelCount = 1,
.sampleCount = 1,
};
state.offscreen_fb[i].depth_texture
= wgpuDeviceCreateTexture(device, &depth_desc);
state.offscreen_fb[i].depth_view
= wgpuTextureCreateView(state.offscreen_fb[i].depth_texture,
&(WGPUTextureViewDescriptor){
.format = WGPUTextureFormat_Depth24PlusStencil8,
.dimension = WGPUTextureViewDimension_2D,
.baseMipLevel = 0,
.mipLevelCount = 1,
.baseArrayLayer = 0,
.arrayLayerCount = 1,
.aspect = WGPUTextureAspect_All,
});
}
/* Shared sampler for offscreen textures */
WGPUSamplerDescriptor sampler_desc = {
.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,
};
state.offscreen_sampler = wgpuDeviceCreateSampler(device, &sampler_desc);
}
static void destroy_offscreen_framebuffers(void)
{
for (int i = 0; i < 2; i++) {
WGPU_RELEASE_RESOURCE(TextureView, state.offscreen_fb[i].color_view)
WGPU_RELEASE_RESOURCE(Texture, state.offscreen_fb[i].color_texture)
WGPU_RELEASE_RESOURCE(TextureView, state.offscreen_fb[i].depth_view)
WGPU_RELEASE_RESOURCE(Texture, state.offscreen_fb[i].depth_texture)
}
WGPU_RELEASE_RESOURCE(Sampler, state.offscreen_sampler)
}
/* -------------------------------------------------------------------------- *
* Cubemap loading
* -------------------------------------------------------------------------- */
static void init_cubemap_texture(struct wgpu_context_t* wgpu_context)
{
WGPUDevice device = wgpu_context->device;
/* Create cubemap texture (6 array layers) */
WGPUTextureDescriptor tex_desc = {
.label = STRVIEW("Cubemap Texture"),
.usage = WGPUTextureUsage_TextureBinding | WGPUTextureUsage_CopyDst
| WGPUTextureUsage_RenderAttachment,
.dimension = WGPUTextureDimension_2D,
.size = {CUBEMAP_FACE_SIZE, CUBEMAP_FACE_SIZE, NUM_CUBEMAP_FACES},
.format = WGPUTextureFormat_RGBA8Unorm,
.mipLevelCount = 1,
.sampleCount = 1,
};
state.cubemap_texture.handle = wgpuDeviceCreateTexture(device, &tex_desc);
/* Create cube view */
WGPUTextureViewDescriptor view_desc = {
.label = STRVIEW("Cubemap - Texture View"),
.format = WGPUTextureFormat_RGBA8Unorm,
.dimension = WGPUTextureViewDimension_Cube,
.baseMipLevel = 0,
.mipLevelCount = 1,
.baseArrayLayer = 0,
.arrayLayerCount = NUM_CUBEMAP_FACES,
.aspect = WGPUTextureAspect_All,
};
state.cubemap_texture.view
= wgpuTextureCreateView(state.cubemap_texture.handle, &view_desc);
/* Sampler */
WGPUSamplerDescriptor sampler_desc = {
.label = STRVIEW("Cubemap - 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,
};
state.cubemap_texture.sampler
= wgpuDeviceCreateSampler(device, &sampler_desc);
}
static void cubemap_fetch_callback(const sfetch_response_t* response)
{
if (!response->fetched) {
printf("Cubemap face fetch failed, error: %d\n", response->error_code);
return;
}
int img_w, img_h, num_ch;
uint8_t* pixels = image_pixels_from_memory(
response->data.ptr, (int)response->data.size, &img_w, &img_h, &num_ch, 4);
if (pixels) {
ASSERT(img_w == CUBEMAP_FACE_SIZE && img_h == CUBEMAP_FACE_SIZE);
memcpy((void*)response->buffer.ptr, pixels, (size_t)(img_w * img_h * 4));
image_free(pixels);
state.cubemap_load_count++;
}
}
static void fetch_cubemap_faces(void)
{
/* Face order: +X, -X, +Y, -Y, +Z, -Z */
static const char* face_paths[NUM_CUBEMAP_FACES] = {
"assets/textures/cubemaps/cubemap_space_px.png",
"assets/textures/cubemaps/cubemap_space_nx.png",
"assets/textures/cubemaps/cubemap_space_py.png",
"assets/textures/cubemaps/cubemap_space_ny.png",
"assets/textures/cubemaps/cubemap_space_pz.png",
"assets/textures/cubemaps/cubemap_space_nz.png",
};
state.cubemap_texture.is_dirty = true;
state.cubemap_load_count = 0;
for (int i = 0; i < NUM_CUBEMAP_FACES; i++) {
state.cubemap_pixels[i] = (uint8_t*)malloc(CUBEMAP_FACE_NUM_BYTES);
sfetch_send(&(sfetch_request_t){
.path = face_paths[i],
.callback = cubemap_fetch_callback,
.buffer
= {.ptr = state.cubemap_pixels[i], .size = CUBEMAP_FACE_NUM_BYTES},
.channel = 0,
});
}
}
static void upload_cubemap_pixels(struct wgpu_context_t* wgpu_context)
{
#ifdef __WAJIC__
WGPUQueue queue = wgpu_context->queue;
/* WAjic: wgpuQueueWriteTexture avoids staging buffers with mappedAtCreation
* which is not supported in WAjic WebGPU. */
for (int face = 0; face < NUM_CUBEMAP_FACES; face++) {
wgpuQueueWriteTexture(
queue,
&(WGPUTexelCopyTextureInfo){
.texture = state.cubemap_texture.handle,
.mipLevel = 0,
.origin = {0, 0, (uint32_t)face},
.aspect = WGPUTextureAspect_All,
},
state.cubemap_pixels[face], CUBEMAP_FACE_NUM_BYTES,
&(WGPUTexelCopyBufferLayout){
.offset = 0,
.bytesPerRow = CUBEMAP_FACE_SIZE * 4,
.rowsPerImage = CUBEMAP_FACE_SIZE,
},
&(WGPUExtent3D){CUBEMAP_FACE_SIZE, CUBEMAP_FACE_SIZE, 1});
free(state.cubemap_pixels[face]);
state.cubemap_pixels[face] = NULL;
}
state.cubemap_texture.is_dirty = false;
#else
WGPUDevice device = wgpu_context->device;
WGPUQueue queue = wgpu_context->queue;
WGPUCommandEncoder enc = wgpuDeviceCreateCommandEncoder(device, NULL);
for (int face = 0; face < NUM_CUBEMAP_FACES; face++) {
uint32_t bytes_per_row = CUBEMAP_FACE_SIZE * 4;
uint32_t data_size = CUBEMAP_FACE_NUM_BYTES;
WGPUBufferDescriptor staging_desc = {
.usage = WGPUBufferUsage_MapWrite | WGPUBufferUsage_CopySrc,
.size = data_size,
.mappedAtCreation = true,
};
WGPUBuffer staging = wgpuDeviceCreateBuffer(device, &staging_desc);
void* mapped = wgpuBufferGetMappedRange(staging, 0, data_size);
memcpy(mapped, state.cubemap_pixels[face], data_size);
wgpuBufferUnmap(staging);
WGPUTexelCopyBufferLayout src_layout = {
.offset = 0,
.bytesPerRow = bytes_per_row,
.rowsPerImage = CUBEMAP_FACE_SIZE,
};
WGPUTexelCopyTextureInfo dst_info = {
.texture = state.cubemap_texture.handle,
.mipLevel = 0,
.origin = {0, 0, (uint32_t)face},
.aspect = WGPUTextureAspect_All,
};
WGPUExtent3D copy_size = {CUBEMAP_FACE_SIZE, CUBEMAP_FACE_SIZE, 1};
wgpuCommandEncoderCopyBufferToTexture(enc,
&(WGPUTexelCopyBufferInfo){
.buffer = staging,
.layout = src_layout,
},
&dst_info, ©_size);
wgpuBufferRelease(staging);
}
WGPUCommandBuffer cmd = wgpuCommandEncoderFinish(enc, NULL);
wgpuQueueSubmit(queue, 1, &cmd);
wgpuCommandBufferRelease(cmd);
wgpuCommandEncoderRelease(enc);
state.cubemap_texture.is_dirty = false;
/* Free face pixel buffers - data uploaded to GPU */
for (int face = 0; face < NUM_CUBEMAP_FACES; face++) {
free(state.cubemap_pixels[face]);
state.cubemap_pixels[face] = NULL;
}
#endif /* __WAJIC__ */
}
/* -------------------------------------------------------------------------- *
* Model loading
* -------------------------------------------------------------------------- */
#ifdef __WAJIC__
/* Async model fetch callback (WAjic only).
* The fetch 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("Bloom: model fetch failed, error: %d\n", response->error_code);
return;
}
int model_index = *(const int*)response->user_data;
gltf_model_t* model
= (model_index == 0) ? &state.ufo_model : &state.ufo_glow_model;
bool ok = gltf_model_load_from_memory(model, response->data.ptr,
response->data.size, NULL, 1.0f);
if (ok) {
state.models_load_count++;
if (state.models_load_count == 2) {
state.models_loaded = true;
}
}
else {
printf("Bloom: failed to parse gltf model index %d\n", model_index);
}
}
#endif /* __WAJIC__ */
static void load_models(void)
{
#ifdef __WAJIC__
/* In WAjic, use dynamic sfetch (NULL buffer) to load the gltf files.
* Callbacks fire asynchronously; models_loaded is set when both complete. */
static const int idx_ufo = 0;
static const int idx_glow = 1;
sfetch_send(&(sfetch_request_t){
.path = "assets/models/retroufo.gltf",
.callback = model_fetch_callback,
.user_data = {.ptr = &idx_ufo, .size = sizeof(idx_ufo)},
.channel = 0,
});
sfetch_send(&(sfetch_request_t){
.path = "assets/models/retroufo_glow.gltf",
.callback = model_fetch_callback,
.user_data = {.ptr = &idx_glow, .size = sizeof(idx_glow)},
.channel = 0,
});
#else
/* Native: synchronous file loading. */
bool ok = gltf_model_load_from_file(&state.ufo_model,
"assets/models/retroufo.gltf", 1.0f);
if (!ok) {
printf("Failed to load retroufo.gltf\n");
return;
}
/* Load UFO glow mesh */
ok = gltf_model_load_from_file(&state.ufo_glow_model,
"assets/models/retroufo_glow.gltf", 1.0f);
if (!ok) {
printf("Failed to load retroufo_glow.gltf\n");
return;
}
state.models_loaded = true;
#endif /* !__WAJIC__ */
}
/* Loading descriptor: pre-transform vertices by node world matrices and
* pre-multiply vertex colors by material baseColorFactor.
*
* The Vulkan reference uses PreTransformVertices | PreMultiplyVertexColors
* | FlipY. FlipY is omitted here (WebGPU uses Y-up like OpenGL). */
static const gltf_model_desc_t ufo_load_desc = {
.loading_flags = GltfLoadingFlag_PreTransformVertices
| GltfLoadingFlag_PreMultiplyVertexColors,
};
static void create_model_buffers(struct wgpu_context_t* wgpu_context)
{
WGPUDevice device = wgpu_context->device;
if (!state.models_loaded) {
return;
}
/* Process both UFO body and UFO glow models */
struct {
gltf_model_t* model;
WGPUBuffer* vb;
WGPUBuffer* ib;
const char* vb_label;
const char* ib_label;
} items[2] = {
{&state.ufo_model, &state.ufo_vertex_buffer, &state.ufo_index_buffer,
"UFO Vertex Buffer", "UFO Index Buffer"},
{&state.ufo_glow_model, &state.glow_vertex_buffer, &state.glow_index_buffer,
"Glow Vertex Buffer", "Glow Index Buffer"},
};
for (int mi = 0; mi < 2; mi++) {
gltf_model_t* m = items[mi].model;
size_t vb_size = m->vertex_count * sizeof(gltf_vertex_t);
/* Create a copy of vertex data and bake node world transforms */
gltf_vertex_t* xformed = (gltf_vertex_t*)malloc(vb_size);
memcpy(xformed, m->vertices, vb_size);
gltf_model_bake_node_transforms(m, xformed, &ufo_load_desc);
/* Upload transformed vertices to GPU.
* wgpuBufferGetMappedRange/wgpuBufferUnmap are implemented in
* wajic_webgpu.h so this path is shared between native and WAjic. */
*items[mi].vb = wgpuDeviceCreateBuffer(
device, &(WGPUBufferDescriptor){
.label = STRVIEW(items[mi].vb_label),
.usage = WGPUBufferUsage_Vertex | WGPUBufferUsage_CopyDst,
.size = vb_size,
.mappedAtCreation = true,
});
void* vdata = wgpuBufferGetMappedRange(*items[mi].vb, 0, vb_size);
memcpy(vdata, xformed, vb_size);
wgpuBufferUnmap(*items[mi].vb);
free(xformed);
/* Upload index buffer */
if (m->index_count > 0) {
size_t ib_size = m->index_count * sizeof(uint32_t);
*items[mi].ib = wgpuDeviceCreateBuffer(
device, &(WGPUBufferDescriptor){
.label = STRVIEW(items[mi].ib_label),
.usage = WGPUBufferUsage_Index | WGPUBufferUsage_CopyDst,
.size = ib_size,
.mappedAtCreation = true,
});
void* idata = wgpuBufferGetMappedRange(*items[mi].ib, 0, ib_size);
memcpy(idata, m->indices, ib_size);
wgpuBufferUnmap(*items[mi].ib);
}
}
}
/* -------------------------------------------------------------------------- *
* Uniform buffers
* -------------------------------------------------------------------------- */
static void init_uniform_buffers(struct wgpu_context_t* wgpu_context)
{
WGPUDevice device = wgpu_context->device;
/* Scene UBO: projection + view + model (3 × mat4 = 192 bytes) */
state.scene_ubo = wgpuDeviceCreateBuffer(
device, &(WGPUBufferDescriptor){
.label = STRVIEW("Scene - UBO"),
.usage = WGPUBufferUsage_Uniform | WGPUBufferUsage_CopyDst,
.size = 3 * sizeof(mat4),
});
/* Skybox UBO: projection + view + model (3 × mat4 = 192 bytes) */
state.skybox_ubo = wgpuDeviceCreateBuffer(
device, &(WGPUBufferDescriptor){
.label = STRVIEW("Skybox - UBO"),
.usage = WGPUBufferUsage_Uniform | WGPUBufferUsage_CopyDst,
.size = 3 * sizeof(mat4),
});
/* Blur params UBO: blur_scale + blur_strength (2 × float = 8 bytes) */
/* Pad to 16 bytes for alignment */
state.blur_params_ubo = wgpuDeviceCreateBuffer(
device, &(WGPUBufferDescriptor){
.label = STRVIEW("Blur Params - UBO"),
.usage = WGPUBufferUsage_Uniform | WGPUBufferUsage_CopyDst,
.size = 16,
});
}
static void update_uniform_buffers(struct wgpu_context_t* wgpu_context)
{
WGPUQueue queue = wgpu_context->queue;
float aspect = (float)wgpu_context->width / (float)wgpu_context->height;
/* ---- Scene UBO ---- */
glm_perspective(glm_rad(45.0f), aspect, 0.1f, 256.0f,
state.scene_ubo_data.projection);
glm_mat4_copy(state.camera.matrices.view, state.scene_ubo_data.view);
/* UFO animation: bob + rotate */
float angle_rad = state.timer * GLM_PIf * 2.0f;
mat4 model;
glm_mat4_identity(model);
glm_translate(
model, (vec3){sinf(angle_rad) * 0.25f, -1.0f, cosf(angle_rad) * 0.25f});
glm_rotate(model, -sinf(angle_rad) * 0.15f, (vec3){1, 0, 0});
glm_rotate(model, angle_rad, (vec3){0, 1, 0});
glm_mat4_copy(model, state.scene_ubo_data.model);
wgpuQueueWriteBuffer(queue, state.scene_ubo, 0, &state.scene_ubo_data,
3 * sizeof(mat4));
/* ---- Skybox UBO ---- */
glm_mat4_copy(state.scene_ubo_data.projection,
state.skybox_ubo_data.projection);
/* Strip translation from the view matrix for skybox */
mat4 view_no_translate;
glm_mat4_copy(state.camera.matrices.view, view_no_translate);
view_no_translate[3][0] = 0.0f;
view_no_translate[3][1] = 0.0f;
view_no_translate[3][2] = 0.0f;
glm_mat4_copy(view_no_translate, state.skybox_ubo_data.view);
glm_mat4_identity(state.skybox_ubo_data.model);
wgpuQueueWriteBuffer(queue, state.skybox_ubo, 0, &state.skybox_ubo_data,
3 * sizeof(mat4));
/* ---- Blur params UBO ---- */
float blur_data[4] = {
state.settings.blur_scale, state.settings.blur_strength, 0.0f,
0.0f /* padding */
};
wgpuQueueWriteBuffer(queue, state.blur_params_ubo, 0, blur_data,
sizeof(blur_data));
}
/* -------------------------------------------------------------------------- *
* Bind group layouts
* -------------------------------------------------------------------------- */
static void init_bind_group_layouts(struct wgpu_context_t* wgpu_context)
{
WGPUDevice device = wgpu_context->device;
/* Scene bind group layout: UBO (vert) */
{
WGPUBindGroupLayoutEntry entries[1] = {
[0] = {
.binding = 0,
.visibility = WGPUShaderStage_Vertex,
.buffer = {
.type = WGPUBufferBindingType_Uniform,
.minBindingSize = 3 * sizeof(mat4),
},
},
};
state.scene_bgl = wgpuDeviceCreateBindGroupLayout(
device, &(WGPUBindGroupLayoutDescriptor){
.label = STRVIEW("Scene - Bind group layout"),
.entryCount = ARRAY_SIZE(entries),
.entries = entries,
});
}
/* Blur bind group layout: UBO (frag) + sampler (frag) + texture (frag) */
{
WGPUBindGroupLayoutEntry entries[3] = {
[0] = {
.binding = 0,
.visibility = WGPUShaderStage_Fragment,
.buffer = {
.type = WGPUBufferBindingType_Uniform,
.minBindingSize = 16,
},
},
[1] = {
.binding = 1,
.visibility = WGPUShaderStage_Fragment,
.sampler = {
.type = WGPUSamplerBindingType_Filtering,
},
},
[2] = {
.binding = 2,
.visibility = WGPUShaderStage_Fragment,
.texture = {
.sampleType = WGPUTextureSampleType_Float,
.viewDimension = WGPUTextureViewDimension_2D,
},
},
};
state.blur_bgl = wgpuDeviceCreateBindGroupLayout(
device, &(WGPUBindGroupLayoutDescriptor){
.label = STRVIEW("Blur BGL"),
.entryCount = ARRAY_SIZE(entries),
.entries = entries,
});
}
/* Skybox bind group layout: UBO (vert) + sampler (frag) + cubemap (frag) */
{
WGPUBindGroupLayoutEntry entries[3] = {
[0] = {
.binding = 0,
.visibility = WGPUShaderStage_Vertex,
.buffer = {
.type = WGPUBufferBindingType_Uniform,
.minBindingSize = 3 * sizeof(mat4),
},
},
[1] = {
.binding = 1,
.visibility = WGPUShaderStage_Fragment,
.sampler = {
.type = WGPUSamplerBindingType_Filtering,
},
},
[2] = {
.binding = 2,
.visibility = WGPUShaderStage_Fragment,
.texture = {
.sampleType = WGPUTextureSampleType_Float,
.viewDimension = WGPUTextureViewDimension_Cube,
},
},
};
state.skybox_bgl = wgpuDeviceCreateBindGroupLayout(
device, &(WGPUBindGroupLayoutDescriptor){
.label = STRVIEW("Skybox BGL"),
.entryCount = ARRAY_SIZE(entries),
.entries = entries,
});
}
}
/* -------------------------------------------------------------------------- *
* Pipeline layouts
* -------------------------------------------------------------------------- */
static void init_pipeline_layouts(struct wgpu_context_t* wgpu_context)
{
WGPUDevice device = wgpu_context->device;
/* Scene pipeline layout */
state.scene_pipeline_layout = wgpuDeviceCreatePipelineLayout(
device, &(WGPUPipelineLayoutDescriptor){
.label = STRVIEW("Scene Pipeline Layout"),
.bindGroupLayoutCount = 1,
.bindGroupLayouts = &state.scene_bgl,
});
/* Blur pipeline layout */
state.blur_pipeline_layout = wgpuDeviceCreatePipelineLayout(
device, &(WGPUPipelineLayoutDescriptor){
.label = STRVIEW("Blur Pipeline Layout"),
.bindGroupLayoutCount = 1,
.bindGroupLayouts = &state.blur_bgl,
});
/* Skybox pipeline layout */
state.skybox_pipeline_layout = wgpuDeviceCreatePipelineLayout(
device, &(WGPUPipelineLayoutDescriptor){
.label = STRVIEW("Skybox Pipeline Layout"),
.bindGroupLayoutCount = 1,
.bindGroupLayouts = &state.skybox_bgl,
});
}
/* -------------------------------------------------------------------------- *
* Bind groups
* -------------------------------------------------------------------------- */
static void init_bind_groups(struct wgpu_context_t* wgpu_context)
{
WGPUDevice device = wgpu_context->device;
/* Scene bind group */
{
WGPUBindGroupEntry entries[1] = {
[0] = {
.binding = 0,
.buffer = state.scene_ubo,
.offset = 0,
.size = 3 * sizeof(mat4),
},
};
state.scene_bind_group = wgpuDeviceCreateBindGroup(
device, &(WGPUBindGroupDescriptor){
.label = STRVIEW("Scene Bind Group"),
.layout = state.scene_bgl,
.entryCount = ARRAY_SIZE(entries),
.entries = entries,
});
}
/* Blur vertical bind group: reads FB[0] */
{
WGPUBindGroupEntry entries[3] = {
[0] = {
.binding = 0,
.buffer = state.blur_params_ubo,
.offset = 0,
.size = 16,
},
[1] = {
.binding = 1,
.sampler = state.offscreen_sampler,
},
[2] = {
.binding = 2,
.textureView = state.offscreen_fb[0].color_view,
},
};
state.blur_vert_bind_group = wgpuDeviceCreateBindGroup(
device, &(WGPUBindGroupDescriptor){
.label = STRVIEW("Blur Vert Bind Group"),
.layout = state.blur_bgl,
.entryCount = ARRAY_SIZE(entries),
.entries = entries,
});
}
/* Blur horizontal bind group: reads FB[1] */
{
WGPUBindGroupEntry entries[3] = {
[0] = {
.binding = 0,
.buffer = state.blur_params_ubo,
.offset = 0,
.size = 16,
},
[1] = {
.binding = 1,
.sampler = state.offscreen_sampler,
},
[2] = {
.binding = 2,
.textureView = state.offscreen_fb[1].color_view,
},
};
state.blur_horz_bind_group = wgpuDeviceCreateBindGroup(
device, &(WGPUBindGroupDescriptor){
.label = STRVIEW("Blur Horz Bind Group"),
.layout = state.blur_bgl,
.entryCount = ARRAY_SIZE(entries),
.entries = entries,
});
}
/* Skybox bind group */
{
WGPUBindGroupEntry entries[3] = {
[0] = {
.binding = 0,
.buffer = state.skybox_ubo,
.offset = 0,
.size = 3 * sizeof(mat4),
},
[1] = {
.binding = 1,
.sampler = state.cubemap_texture.sampler,
},
[2] = {
.binding = 2,
.textureView = state.cubemap_texture.view,
},
};
state.skybox_bind_group = wgpuDeviceCreateBindGroup(
device, &(WGPUBindGroupDescriptor){
.label = STRVIEW("Skybox Bind Group"),
.layout = state.skybox_bgl,
.entryCount = ARRAY_SIZE(entries),
.entries = entries,
});
}
}
/* -------------------------------------------------------------------------- *
* Render pipelines
* -------------------------------------------------------------------------- */
static void init_pipelines(struct wgpu_context_t* wgpu_context)
{
WGPUDevice device = wgpu_context->device;
/* Vertex buffer layout for glTF model (gltf_vertex_t) */
WGPUVertexAttribute vertex_attrs[] = {
/* position: vec3 at offset 0 */
{