-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathfur.c
More file actions
1492 lines (1297 loc) · 51.7 KB
/
Copy pathfur.c
File metadata and controls
1492 lines (1297 loc) · 51.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "webgpu/imgui_overlay.h"
#include "webgpu/wgpu_common.h"
#include <cglm/cglm.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef __WAJIC__
#define WAJIC_IMAGE_IMPL
#include <wajic_image.h>
#define WAJIC_SFETCH_IMPL
#include <wajic_sfetch.h>
#define WAJIC_TIME_IMPL
#include <wajic_time.h>
#else
#define SOKOL_FETCH_IMPL
#include <sokol_fetch.h>
#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/image_loader.h"
/* In WAjic, WGPU handles are uint32_t */
#ifdef __WAJIC__
#ifdef NULL
#undef NULL
#define NULL 0
#endif
#endif
/* -------------------------------------------------------------------------- *
* WebGPU Example - Fur Rendering
*
* Demonstrates GPU-accelerated fur/grass rendering using the "shell fur"
* technique. The model geometry is rendered in multiple instanced passes,
* each pass displacing vertices outward along normals by an increasing amount.
* A sinusoidal wave animation simulates wind-driven fur movement. Five fur
* presets are provided (Leopard, Cow, Chick, Timber Wolf, Moss) with
* adjustable layer count and layer thickness.
*
* Ported from the WebGL 2 Fur demo:
* https://github.com/keaukraine/webgl-fur
* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- *
* WGSL Shaders (declared here, defined at bottom of file)
* -------------------------------------------------------------------------- */
static const char* fur_vignette_shader_wgsl;
static const char* fur_diffuse_shader_wgsl;
static const char* fur_shell_shader_wgsl;
/* -------------------------------------------------------------------------- *
* Constants
* -------------------------------------------------------------------------- */
/* Depth texture format */
#define FUR_DEPTH_FORMAT (WGPUTextureFormat_Depth24PlusStencil8)
/* Animation speeds (from WebGL demo) */
#define FUR_YAW_SPEED (12000.0f) /* ms per degree */
#define FUR_ANIM_SPEED (1500.0f) /* ms per 0..1 cycle */
#define FUR_WIND_SPEED (8310.0f) /* ms per 0..1 cycle */
#define FUR_STIFFNESS (2.75f)
/* Camera / projection */
#define FUR_FOV_DEG (15.0f) /* 25 * 0.6 multiplier */
#define FUR_CAM_NEAR (20.0f)
#define FUR_CAM_FAR (1000.0f)
/* File buffer sizes */
#define FUR_IDX_BUF_SIZE (8u * 1024u) /* 7200 bytes needed */
#define FUR_STR_BUF_SIZE (24u * 1024u) /* 23040 bytes needed */
#define FUR_TEX_BUF_SIZE (64u * 1024u) /* 46 KB max texture */
/* Maximum layers */
#define FUR_MAX_LAYERS (30)
/* Number of preset textures (bg + 5 diffuse + 3 alpha) */
#define FUR_TEX_COUNT (9u)
/* -------------------------------------------------------------------------- *
* Types
* -------------------------------------------------------------------------- */
/* Texture slot indices */
typedef enum {
FUR_TEX_BG = 0,
FUR_TEX_DIFFUSE_LEO = 1,
FUR_TEX_DIFFUSE_COW = 2,
FUR_TEX_DIFFUSE_CHICK = 3,
FUR_TEX_DIFFUSE_WOLF = 4,
FUR_TEX_DIFFUSE_MOSS = 5,
FUR_TEX_ALPHA_UNEVEN = 6,
FUR_TEX_ALPHA_EVEN = 7,
FUR_TEX_ALPHA_MOSS = 8,
} fur_tex_id_t;
/* Fur preset */
typedef struct {
const char* name;
int layers;
float thickness;
float wave_scale;
fur_tex_id_t diffuse;
fur_tex_id_t alpha;
vec4 start_color;
vec4 end_color;
} fur_preset_t;
/* Vignette uniform buffer (vertex stage) */
typedef struct {
mat4 ortho_matrix; /* 64 bytes */
} fur_vignette_uniforms_t;
/* Diffuse colored uniform buffer (vertex stage) */
typedef struct {
mat4 view_proj_matrix; /* 64 bytes */
vec4 color; /* 16 bytes */
} fur_diffuse_uniforms_t;
/* Fur shell uniform buffer (vertex + fragment stages) */
typedef struct {
mat4 view_proj_matrix; /* offset 0, 64 bytes */
vec4 color_start; /* offset 64, 16 bytes */
vec4 color_end; /* offset 80, 16 bytes */
float layer_thickness; /* offset 96, 4 bytes */
float layers_count; /* offset 100, 4 bytes */
float time; /* offset 104, 4 bytes */
float wave_scale; /* offset 108, 4 bytes */
float stiffness; /* offset 112, 4 bytes */
float _pad[3]; /* offset 116, 12 bytes (align to 128) */
} fur_shell_uniforms_t;
/* -------------------------------------------------------------------------- *
* Preset definitions
* -------------------------------------------------------------------------- */
// clang-format off
static const fur_preset_t fur_presets[] = {
{ "Leopard", 20, 0.15f, 0.50f, FUR_TEX_DIFFUSE_LEO, FUR_TEX_ALPHA_UNEVEN, {0.60f, 0.60f, 0.60f, 1.0f}, {1.00f, 1.00f, 1.00f, 0.0f} },
{ "Cow", 10, 0.15f, 0.20f, FUR_TEX_DIFFUSE_COW, FUR_TEX_ALPHA_UNEVEN, {0.70f, 0.70f, 0.70f, 1.0f}, {1.00f, 1.00f, 1.00f, 0.0f} },
{ "Chick", 13, 0.13f, 0.12f, FUR_TEX_DIFFUSE_CHICK, FUR_TEX_ALPHA_EVEN, {1.15f, 1.15f, 1.15f, 1.0f}, {0.95f, 0.95f, 0.95f, 0.2f} },
{ "Timber Wolf", 20, 0.15f, 0.30f, FUR_TEX_DIFFUSE_WOLF, FUR_TEX_ALPHA_UNEVEN, {0.00f, 0.00f, 0.00f, 1.0f}, {1.00f, 1.00f, 1.00f, 0.0f} },
{ "Moss", 7, 0.13f, 0.00f, FUR_TEX_DIFFUSE_MOSS, FUR_TEX_ALPHA_MOSS, {0.20f, 0.20f, 0.20f, 1.0f}, {1.00f, 1.00f, 1.00f, 0.8f} },
};
// clang-format on
#define FUR_PRESET_COUNT ((int)(ARRAY_SIZE(fur_presets)))
/* -------------------------------------------------------------------------- *
* Fur Example State
* -------------------------------------------------------------------------- */
static struct {
/* WebGPU context reference (set during init, used in callbacks) */
wgpu_context_t* wgpu_context;
/* Box model loaded from binary files (pos3 + uv2 + normal3, uint16 indices)
*/
struct {
wgpu_buffer_t vertex_buffer;
wgpu_buffer_t index_buffer;
uint32_t index_count; /* = 3600 */
bool is_ready;
/* Pending binary data before GPU upload */
uint8_t* pending_index_data;
size_t pending_index_size;
bool index_pending;
uint8_t* pending_stride_data;
size_t pending_stride_size;
bool stride_pending;
} model;
/* Fullscreen quad for background vignette (pos3 + uv2) */
wgpu_buffer_t vignette_vb;
/* Textures */
wgpu_texture_t textures[FUR_TEX_COUNT];
WGPUSampler sampler;
/* Uniform buffers */
wgpu_buffer_t vignette_ubo;
wgpu_buffer_t diffuse_ubo;
wgpu_buffer_t fur_ubo;
/* Bind group layouts */
WGPUBindGroupLayout
common_bgl; /* UBO + sampler + 1 texture (vignette/diffuse) */
WGPUBindGroupLayout fur_bgl; /* UBO + sampler + 2 textures (shell fur) */
/* Bind groups (rebuilt on preset change) */
WGPUBindGroup vignette_bg;
WGPUBindGroup diffuse_bg;
WGPUBindGroup fur_bg;
/* Pipeline layouts and pipelines */
WGPUPipelineLayout vignette_pipeline_layout;
WGPUPipelineLayout diffuse_pipeline_layout;
WGPUPipelineLayout fur_pipeline_layout;
WGPURenderPipeline vignette_pipeline;
WGPURenderPipeline diffuse_pipeline;
WGPURenderPipeline fur_pipeline;
/* Depth texture */
wgpu_texture_t depth_texture;
/* Render pass */
WGPURenderPassColorAttachment color_attachment;
WGPURenderPassDepthStencilAttachment depth_stencil_attachment;
WGPURenderPassDescriptor render_pass_desc;
/* Animation */
float angle_yaw; /* degrees, wraps at 360 */
float fur_timer; /* [0..1) fur wave phase */
float wind_timer; /* [0..1) wind phase */
uint64_t last_time;
/* Current preset and GUI-editable overrides */
int preset_idx;
int preset_layers;
float preset_thickness;
bool bind_groups_dirty;
/* Number of textures successfully loaded */
uint32_t textures_loaded;
/* Frame timing for ImGui */
uint64_t last_frame_time;
/* Ready to render */
bool initialized;
} state = {
/* Render pass setup */
// clang-format off
.color_attachment = {
.loadOp = WGPULoadOp_Clear,
.storeOp = WGPUStoreOp_Store,
.clearValue = {0.3f, 0.3f, 0.3f, 1.0f},
.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED,
},
.depth_stencil_attachment = {
.depthLoadOp = WGPULoadOp_Clear,
.depthStoreOp = WGPUStoreOp_Store,
.depthClearValue = 1.0f,
.stencilLoadOp = WGPULoadOp_Clear,
.stencilStoreOp = WGPUStoreOp_Store,
.stencilClearValue = 0,
},
.render_pass_desc = {
.colorAttachmentCount = 1,
.colorAttachments = &state.color_attachment,
.depthStencilAttachment = &state.depth_stencil_attachment,
},
// clang-format on
.preset_idx = 0,
.preset_layers = 20,
.preset_thickness = 0.15f,
};
/* -------------------------------------------------------------------------- *
* Depth texture
* -------------------------------------------------------------------------- */
static void init_depth_texture(wgpu_context_t* wgpu_context)
{
wgpu_destroy_texture(&state.depth_texture);
WGPUTextureDescriptor desc = {
.label = STRVIEW("Fur - Depth texture"),
.dimension = WGPUTextureDimension_2D,
.format = FUR_DEPTH_FORMAT,
.mipLevelCount = 1,
.sampleCount = 1,
.size = {wgpu_context->width, wgpu_context->height, 1},
.usage = WGPUTextureUsage_RenderAttachment,
};
state.depth_texture.handle
= wgpuDeviceCreateTexture(wgpu_context->device, &desc);
ASSERT(state.depth_texture.handle != NULL);
WGPUTextureViewDescriptor vdesc = {
.label = STRVIEW("Fur - Depth texture view"),
.format = FUR_DEPTH_FORMAT,
.dimension = WGPUTextureViewDimension_2D,
.baseMipLevel = 0,
.mipLevelCount = 1,
.baseArrayLayer = 0,
.arrayLayerCount = 1,
};
state.depth_texture.view
= wgpuTextureCreateView(state.depth_texture.handle, &vdesc);
ASSERT(state.depth_texture.view != NULL);
}
/* -------------------------------------------------------------------------- *
* Sampler
* -------------------------------------------------------------------------- */
static void init_sampler(wgpu_context_t* wgpu_context)
{
state.sampler = wgpuDeviceCreateSampler(
wgpu_context->device, &(WGPUSamplerDescriptor){
.label = STRVIEW("Fur - Sampler"),
.addressModeU = WGPUAddressMode_Repeat,
.addressModeV = WGPUAddressMode_Repeat,
.addressModeW = WGPUAddressMode_Repeat,
.minFilter = WGPUFilterMode_Linear,
.magFilter = WGPUFilterMode_Linear,
.mipmapFilter = WGPUMipmapFilterMode_Linear,
.lodMinClamp = 0.0f,
.lodMaxClamp = 1.0f,
.maxAnisotropy = 1,
});
ASSERT(state.sampler != NULL);
}
/* -------------------------------------------------------------------------- *
* Uniform buffers
* -------------------------------------------------------------------------- */
static void init_uniform_buffers(wgpu_context_t* wgpu_context)
{
state.vignette_ubo = wgpu_create_buffer(
wgpu_context, &(wgpu_buffer_desc_t){
.label = "Fur - Vignette uniform buffer",
.usage = WGPUBufferUsage_Uniform | WGPUBufferUsage_CopyDst,
.size = sizeof(fur_vignette_uniforms_t),
});
state.diffuse_ubo = wgpu_create_buffer(
wgpu_context, &(wgpu_buffer_desc_t){
.label = "Fur - Diffuse uniform buffer",
.usage = WGPUBufferUsage_Uniform | WGPUBufferUsage_CopyDst,
.size = sizeof(fur_diffuse_uniforms_t),
});
state.fur_ubo = wgpu_create_buffer(
wgpu_context, &(wgpu_buffer_desc_t){
.label = "Fur - Shell uniform buffer",
.usage = WGPUBufferUsage_Uniform | WGPUBufferUsage_CopyDst,
.size = sizeof(fur_shell_uniforms_t),
});
}
/* -------------------------------------------------------------------------- *
* Bind group layouts
* -------------------------------------------------------------------------- */
static void init_bind_group_layouts(wgpu_context_t* wgpu_context)
{
/* Common layout: UBO + sampler + 1 texture (used by vignette and diffuse) */
{
WGPUBindGroupLayoutEntry entries[3] = {
[0] = (WGPUBindGroupLayoutEntry){
.binding = 0,
.visibility = WGPUShaderStage_Vertex | WGPUShaderStage_Fragment,
.buffer = (WGPUBufferBindingLayout){
.type = WGPUBufferBindingType_Uniform,
.minBindingSize = 0, /* flexible: vignette uses 64, diffuse uses 80 */
},
},
[1] = (WGPUBindGroupLayoutEntry){
.binding = 1,
.visibility = WGPUShaderStage_Fragment,
.sampler = (WGPUSamplerBindingLayout){
.type = WGPUSamplerBindingType_Filtering,
},
},
[2] = (WGPUBindGroupLayoutEntry){
.binding = 2,
.visibility = WGPUShaderStage_Fragment,
.texture = (WGPUTextureBindingLayout){
.sampleType = WGPUTextureSampleType_Float,
.viewDimension = WGPUTextureViewDimension_2D,
},
},
};
state.common_bgl = wgpuDeviceCreateBindGroupLayout(
wgpu_context->device,
&(WGPUBindGroupLayoutDescriptor){
.label = STRVIEW("Fur - Common bind group layout"),
.entryCount = (uint32_t)ARRAY_SIZE(entries),
.entries = entries,
});
ASSERT(state.common_bgl != NULL);
}
/* Fur layout: UBO + sampler + diffuse texture + alpha texture */
{
WGPUBindGroupLayoutEntry entries[4] = {
[0] = (WGPUBindGroupLayoutEntry){
.binding = 0,
.visibility = WGPUShaderStage_Vertex | WGPUShaderStage_Fragment,
.buffer = (WGPUBufferBindingLayout){
.type = WGPUBufferBindingType_Uniform,
.minBindingSize = sizeof(fur_shell_uniforms_t),
},
},
[1] = (WGPUBindGroupLayoutEntry){
.binding = 1,
.visibility = WGPUShaderStage_Fragment,
.sampler = (WGPUSamplerBindingLayout){
.type = WGPUSamplerBindingType_Filtering,
},
},
[2] = (WGPUBindGroupLayoutEntry){
.binding = 2,
.visibility = WGPUShaderStage_Fragment,
.texture = (WGPUTextureBindingLayout){
.sampleType = WGPUTextureSampleType_Float,
.viewDimension = WGPUTextureViewDimension_2D,
},
},
[3] = (WGPUBindGroupLayoutEntry){
.binding = 3,
.visibility = WGPUShaderStage_Fragment,
.texture = (WGPUTextureBindingLayout){
.sampleType = WGPUTextureSampleType_Float,
.viewDimension = WGPUTextureViewDimension_2D,
},
},
};
state.fur_bgl = wgpuDeviceCreateBindGroupLayout(
wgpu_context->device, &(WGPUBindGroupLayoutDescriptor){
.label = STRVIEW("Fur - Shell bind group layout"),
.entryCount = (uint32_t)ARRAY_SIZE(entries),
.entries = entries,
});
ASSERT(state.fur_bgl != NULL);
}
}
/* -------------------------------------------------------------------------- *
* Bind groups (rebuilt on preset change once textures are ready)
* -------------------------------------------------------------------------- */
static void init_bind_groups(wgpu_context_t* wgpu_context)
{
/* Vignette bind group */
{
WGPU_RELEASE_RESOURCE(BindGroup, state.vignette_bg)
WGPUBindGroupEntry entries[3] = {
[0] = {.binding = 0,
.buffer = state.vignette_ubo.buffer,
.size = state.vignette_ubo.size},
[1] = {.binding = 1, .sampler = state.sampler},
[2] = {.binding = 2, .textureView = state.textures[FUR_TEX_BG].view},
};
state.vignette_bg = wgpuDeviceCreateBindGroup(
wgpu_context->device, &(WGPUBindGroupDescriptor){
.label = STRVIEW("Fur - Vignette bind group"),
.layout = state.common_bgl,
.entryCount = (uint32_t)ARRAY_SIZE(entries),
.entries = entries,
});
ASSERT(state.vignette_bg != NULL);
}
/* Diffuse (base cube) bind group - uses current preset's diffuse texture */
{
WGPU_RELEASE_RESOURCE(BindGroup, state.diffuse_bg)
fur_tex_id_t diff_tex = fur_presets[state.preset_idx].diffuse;
WGPUBindGroupEntry entries[3] = {
[0] = {.binding = 0,
.buffer = state.diffuse_ubo.buffer,
.size = state.diffuse_ubo.size},
[1] = {.binding = 1, .sampler = state.sampler},
[2] = {.binding = 2, .textureView = state.textures[diff_tex].view},
};
state.diffuse_bg = wgpuDeviceCreateBindGroup(
wgpu_context->device, &(WGPUBindGroupDescriptor){
.label = STRVIEW("Fur - Diffuse bind group"),
.layout = state.common_bgl,
.entryCount = (uint32_t)ARRAY_SIZE(entries),
.entries = entries,
});
ASSERT(state.diffuse_bg != NULL);
}
/* Fur shell bind group */
{
WGPU_RELEASE_RESOURCE(BindGroup, state.fur_bg)
fur_tex_id_t diff_tex = fur_presets[state.preset_idx].diffuse;
fur_tex_id_t alpha_tex = fur_presets[state.preset_idx].alpha;
WGPUBindGroupEntry entries[4] = {
[0] = {.binding = 0,
.buffer = state.fur_ubo.buffer,
.size = state.fur_ubo.size},
[1] = {.binding = 1, .sampler = state.sampler},
[2] = {.binding = 2, .textureView = state.textures[diff_tex].view},
[3] = {.binding = 3, .textureView = state.textures[alpha_tex].view},
};
state.fur_bg = wgpuDeviceCreateBindGroup(
wgpu_context->device, &(WGPUBindGroupDescriptor){
.label = STRVIEW("Fur - Shell bind group"),
.layout = state.fur_bgl,
.entryCount = (uint32_t)ARRAY_SIZE(entries),
.entries = entries,
});
ASSERT(state.fur_bg != NULL);
}
state.bind_groups_dirty = false;
}
/* -------------------------------------------------------------------------- *
* Render pipelines
* -------------------------------------------------------------------------- */
static void init_pipelines(wgpu_context_t* wgpu_context)
{
WGPUTextureFormat swap_fmt = wgpu_context->render_format;
/* --- Vignette pipeline --- */
{
state.vignette_pipeline_layout = wgpuDeviceCreatePipelineLayout(
wgpu_context->device,
&(WGPUPipelineLayoutDescriptor){
.label = STRVIEW("Fur - Vignette pipeline layout"),
.bindGroupLayoutCount = 1,
.bindGroupLayouts = &state.common_bgl,
});
WGPUShaderModule vert = wgpu_create_shader_module(wgpu_context->device,
fur_vignette_shader_wgsl);
/* Vertex layout: pos3 + uv2 (stride = 20 bytes) */
WGPU_VERTEX_BUFFER_LAYOUT(
vignette, 5 * sizeof(float),
WGPU_VERTATTR_DESC(0, WGPUVertexFormat_Float32x3, 0),
WGPU_VERTATTR_DESC(1, WGPUVertexFormat_Float32x2, 3 * sizeof(float)))
WGPUDepthStencilState ds
= wgpu_create_depth_stencil_state(&(create_depth_stencil_state_desc_t){
.format = FUR_DEPTH_FORMAT,
.depth_write_enabled = false, /* vignette must not write depth */
});
ds.depthCompare = WGPUCompareFunction_Always; /* always draw vignette */
state.vignette_pipeline = wgpuDeviceCreateRenderPipeline(
wgpu_context->device,
&(WGPURenderPipelineDescriptor){
.label = STRVIEW("Fur - Vignette pipeline"),
.layout = state.vignette_pipeline_layout,
.vertex = {
.module = vert,
.entryPoint = STRVIEW("vertexMain"),
.bufferCount = 1,
.buffers = &vignette_vertex_buffer_layout,
},
.fragment = &(WGPUFragmentState){
.module = vert,
.entryPoint = STRVIEW("fragmentMain"),
.targetCount = 1,
.targets = &(WGPUColorTargetState){
.format = swap_fmt,
.writeMask = WGPUColorWriteMask_All,
},
},
.primitive = {
.topology = WGPUPrimitiveTopology_TriangleStrip,
.cullMode = WGPUCullMode_None,
.frontFace = WGPUFrontFace_CCW,
},
.depthStencil = &ds,
.multisample = {.count = 1, .mask = 0xffffffff},
});
ASSERT(state.vignette_pipeline != NULL);
wgpuShaderModuleRelease(vert);
}
/* --- Diffuse colored pipeline (base cube) --- */
{
state.diffuse_pipeline_layout = wgpuDeviceCreatePipelineLayout(
wgpu_context->device, &(WGPUPipelineLayoutDescriptor){
.label = STRVIEW("Fur - Diffuse pipeline layout"),
.bindGroupLayoutCount = 1,
.bindGroupLayouts = &state.common_bgl,
});
WGPUShaderModule vert = wgpu_create_shader_module(wgpu_context->device,
fur_diffuse_shader_wgsl);
/* Vertex layout: pos3 + uv2 + normal3 (stride = 32 bytes) */
WGPU_VERTEX_BUFFER_LAYOUT(
model, 8 * sizeof(float),
WGPU_VERTATTR_DESC(0, WGPUVertexFormat_Float32x3, 0),
WGPU_VERTATTR_DESC(1, WGPUVertexFormat_Float32x2, 3 * sizeof(float)),
WGPU_VERTATTR_DESC(2, WGPUVertexFormat_Float32x3, 5 * sizeof(float)))
WGPUDepthStencilState ds
= wgpu_create_depth_stencil_state(&(create_depth_stencil_state_desc_t){
.format = FUR_DEPTH_FORMAT,
.depth_write_enabled = true,
});
ds.depthCompare = WGPUCompareFunction_Less;
state.diffuse_pipeline = wgpuDeviceCreateRenderPipeline(
wgpu_context->device,
&(WGPURenderPipelineDescriptor){
.label = STRVIEW("Fur - Diffuse pipeline"),
.layout = state.diffuse_pipeline_layout,
.vertex = {
.module = vert,
.entryPoint = STRVIEW("vertexMain"),
.bufferCount = 1,
.buffers = &model_vertex_buffer_layout,
},
.fragment = &(WGPUFragmentState){
.module = vert,
.entryPoint = STRVIEW("fragmentMain"),
.targetCount = 1,
.targets = &(WGPUColorTargetState){
.format = swap_fmt,
.writeMask = WGPUColorWriteMask_All,
},
},
.primitive = {
.topology = WGPUPrimitiveTopology_TriangleList,
.cullMode = WGPUCullMode_Back,
.frontFace = WGPUFrontFace_CCW,
},
.depthStencil = &ds,
.multisample = {.count = 1, .mask = 0xffffffff},
});
ASSERT(state.diffuse_pipeline != NULL);
wgpuShaderModuleRelease(vert);
}
/* --- Fur shell pipeline (instanced, alpha blend, no culling) --- */
{
state.fur_pipeline_layout = wgpuDeviceCreatePipelineLayout(
wgpu_context->device, &(WGPUPipelineLayoutDescriptor){
.label = STRVIEW("Fur - Shell pipeline layout"),
.bindGroupLayoutCount = 1,
.bindGroupLayouts = &state.fur_bgl,
});
WGPUShaderModule vert
= wgpu_create_shader_module(wgpu_context->device, fur_shell_shader_wgsl);
/* Vertex layout: pos3 + uv2 + normal3 (stride = 32 bytes) - same as model
*/
WGPU_VERTEX_BUFFER_LAYOUT(
fur_model, 8 * sizeof(float),
WGPU_VERTATTR_DESC(0, WGPUVertexFormat_Float32x3, 0),
WGPU_VERTATTR_DESC(1, WGPUVertexFormat_Float32x2, 3 * sizeof(float)),
WGPU_VERTATTR_DESC(2, WGPUVertexFormat_Float32x3, 5 * sizeof(float)))
/* Alpha blending: SRC_ALPHA / (1-SRC_ALPHA) for RGB; preserve alpha */
WGPUBlendState blend = {
.color = {
.operation = WGPUBlendOperation_Add,
.srcFactor = WGPUBlendFactor_SrcAlpha,
.dstFactor = WGPUBlendFactor_OneMinusSrcAlpha,
},
.alpha = {
.operation = WGPUBlendOperation_Add,
.srcFactor = WGPUBlendFactor_Zero,
.dstFactor = WGPUBlendFactor_One,
},
};
WGPUDepthStencilState ds
= wgpu_create_depth_stencil_state(&(create_depth_stencil_state_desc_t){
.format = FUR_DEPTH_FORMAT,
.depth_write_enabled = true,
});
ds.depthCompare = WGPUCompareFunction_LessEqual;
state.fur_pipeline = wgpuDeviceCreateRenderPipeline(
wgpu_context->device,
&(WGPURenderPipelineDescriptor){
.label = STRVIEW("Fur - Shell pipeline"),
.layout = state.fur_pipeline_layout,
.vertex = {
.module = vert,
.entryPoint = STRVIEW("vertexMain"),
.bufferCount = 1,
.buffers = &fur_model_vertex_buffer_layout,
},
.fragment = &(WGPUFragmentState){
.module = vert,
.entryPoint = STRVIEW("fragmentMain"),
.targetCount = 1,
.targets = &(WGPUColorTargetState){
.format = swap_fmt,
.blend = &blend,
.writeMask = WGPUColorWriteMask_All,
},
},
.primitive = {
.topology = WGPUPrimitiveTopology_TriangleList,
.cullMode = WGPUCullMode_None, /* no culling for fur layers */
.frontFace = WGPUFrontFace_CCW,
},
.depthStencil = &ds,
.multisample = {.count = 1, .mask = 0xffffffff},
});
ASSERT(state.fur_pipeline != NULL);
wgpuShaderModuleRelease(vert);
}
}
/* -------------------------------------------------------------------------- *
* Vignette quad geometry
* -------------------------------------------------------------------------- */
static void init_vignette_buffer(wgpu_context_t* wgpu_context)
{
/* Fullscreen quad: X, Y, Z, U, V (triangle strip, 4 vertices)
* WebGL demo uses ortho(-1,1,-1,1,2,250) with z=-5 vertices */
// clang-format off
static const float verts[] = {
-1.0f, -1.0f, -5.0f, 0.0f, 0.0f, /* left-bottom */
1.0f, -1.0f, -5.0f, 1.0f, 0.0f, /* right-bottom */
-1.0f, 1.0f, -5.0f, 0.0f, 1.0f, /* left-top */
1.0f, 1.0f, -5.0f, 1.0f, 1.0f, /* right-top */
};
// clang-format on
state.vignette_vb = wgpu_create_buffer(
wgpu_context, &(wgpu_buffer_desc_t){
.label = "Fur - Vignette vertex buffer",
.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_Vertex,
.size = sizeof(verts),
.initial.data = verts,
});
}
/* -------------------------------------------------------------------------- *
* Model GPU buffers (uploaded after binary data is fetched)
* -------------------------------------------------------------------------- */
static void init_model_buffers(wgpu_context_t* wgpu_context)
{
/* Pre-allocate buffers; data filled by upload_pending_model_data() */
state.model.index_buffer = wgpu_create_buffer(
wgpu_context, &(wgpu_buffer_desc_t){
.label = "Fur - Model index buffer",
.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_Index,
.size = FUR_IDX_BUF_SIZE,
});
state.model.vertex_buffer = wgpu_create_buffer(
wgpu_context, &(wgpu_buffer_desc_t){
.label = "Fur - Model vertex buffer",
.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_Vertex,
.size = FUR_STR_BUF_SIZE,
});
}
/* Upload pending binary model data (called from frame loop) */
static void upload_pending_model_data(wgpu_context_t* wgpu_context)
{
if (state.model.index_pending && state.model.pending_index_data) {
wgpuQueueWriteBuffer(wgpu_context->queue, state.model.index_buffer.buffer,
0, state.model.pending_index_data,
state.model.pending_index_size);
free(state.model.pending_index_data);
state.model.pending_index_data = NULL;
state.model.index_pending = false;
/* index_count is set when the callback fires */
}
if (state.model.stride_pending && state.model.pending_stride_data) {
wgpuQueueWriteBuffer(wgpu_context->queue, state.model.vertex_buffer.buffer,
0, state.model.pending_stride_data,
state.model.pending_stride_size);
free(state.model.pending_stride_data);
state.model.pending_stride_data = NULL;
state.model.stride_pending = false;
}
if (!state.model.is_ready && !state.model.index_pending
&& !state.model.stride_pending && state.model.index_count > 0) {
state.model.is_ready = true;
}
}
/* Upload pending textures (called from frame loop) */
static void upload_pending_textures(wgpu_context_t* wgpu_context)
{
bool any_rebuilt = false;
for (uint32_t i = 0; i < FUR_TEX_COUNT; ++i) {
if (state.textures[i].desc.is_dirty) {
wgpu_recreate_texture(wgpu_context, &state.textures[i]);
FREE_TEXTURE_PIXELS(state.textures[i]);
any_rebuilt = true;
}
}
if (any_rebuilt) {
state.bind_groups_dirty = true;
}
}
/* -------------------------------------------------------------------------- *
* Asset loading callbacks
* -------------------------------------------------------------------------- */
/* Index buffer fetch callback */
static void fetch_indices_cb(const sfetch_response_t* response)
{
if (!response->fetched) {
printf("[FUR] Index file fetch failed (error %d)\n", response->error_code);
free((void*)response->buffer.ptr);
return;
}
state.model.pending_index_data = (uint8_t*)malloc(response->data.size);
if (state.model.pending_index_data) {
memcpy(state.model.pending_index_data, response->data.ptr,
response->data.size);
state.model.pending_index_size = response->data.size;
/* numIndices = byteLength / sizeof(uint16) / 3 triangles */
state.model.index_count = (uint32_t)(response->data.size / 2);
state.model.index_pending = true;
}
free((void*)response->buffer.ptr);
}
/* Stride buffer fetch callback */
static void fetch_strides_cb(const sfetch_response_t* response)
{
if (!response->fetched) {
printf("[FUR] Stride file fetch failed (error %d)\n", response->error_code);
free((void*)response->buffer.ptr);
return;
}
state.model.pending_stride_data = (uint8_t*)malloc(response->data.size);
if (state.model.pending_stride_data) {
memcpy(state.model.pending_stride_data, response->data.ptr,
response->data.size);
state.model.pending_stride_size = response->data.size;
state.model.stride_pending = true;
}
free((void*)response->buffer.ptr);
}
/* Texture fetch callback - user_data points to the target wgpu_texture_t* */
static void fetch_texture_cb(const sfetch_response_t* response)
{
if (!response->fetched) {
printf("[FUR] Texture fetch failed (error %d)\n", response->error_code);
free((void*)response->buffer.ptr);
return;
}
int w, h, channels;
uint8_t* pixels
= image_pixels_from_memory((const uint8_t*)response->data.ptr,
(int)response->data.size, &w, &h, &channels, 4);
if (pixels) {
wgpu_texture_t* tex = *(wgpu_texture_t**)response->user_data;
tex->desc = (wgpu_texture_desc_t){
.extent = {(uint32_t)w, (uint32_t)h, 1},
.format = WGPUTextureFormat_RGBA8Unorm,
.pixels = {.ptr = pixels, .size = (size_t)(w * h * 4)},
};
tex->desc.is_dirty = true;
state.textures_loaded++;
}
free((void*)response->buffer.ptr);
}
/* -------------------------------------------------------------------------- *
* Asset loading kick-off
* -------------------------------------------------------------------------- */
/* Texture asset paths for each FUR_TEX_* slot */
// clang-format off
static const char* const fur_tex_paths[FUR_TEX_COUNT] = {
[FUR_TEX_BG] = "assets/models/Fur/textures/bg-gradient.png",
[FUR_TEX_DIFFUSE_LEO] = "assets/models/Fur/textures/fur-leo.png",
[FUR_TEX_DIFFUSE_COW] = "assets/models/Fur/textures/fur-cow.png",
[FUR_TEX_DIFFUSE_CHICK]= "assets/models/Fur/textures/fur-chick.png",
[FUR_TEX_DIFFUSE_WOLF] = "assets/models/Fur/textures/fur-wolf.png",
[FUR_TEX_DIFFUSE_MOSS] = "assets/models/Fur/textures/moss.png",
[FUR_TEX_ALPHA_UNEVEN] = "assets/models/Fur/textures/uneven-alpha.png",
[FUR_TEX_ALPHA_EVEN] = "assets/models/Fur/textures/even-alpha.png",
[FUR_TEX_ALPHA_MOSS] = "assets/models/Fur/textures/moss-alpha.png",
};
// clang-format on
static void load_assets(wgpu_context_t* wgpu_context)
{
/* Create placeholder textures for all slots */
for (uint32_t i = 0; i < FUR_TEX_COUNT; ++i) {
state.textures[i] = wgpu_create_color_bars_texture(
wgpu_context,
&(wgpu_texture_desc_t){
.format = WGPUTextureFormat_RGBA8Unorm,
.usage = WGPUTextureUsage_TextureBinding | WGPUTextureUsage_CopyDst
| WGPUTextureUsage_RenderAttachment,
});
/* Fetch each texture.
* Store the pointer to the texture slot so the callback can access it.
* user_data.ptr must point to the pointer VALUE (ptr-to-ptr). */
wgpu_texture_t* tex_ptr = &state.textures[i];
uint8_t* buf = (uint8_t*)malloc(FUR_TEX_BUF_SIZE);
sfetch_send(&(sfetch_request_t){
.path = fur_tex_paths[i],
.callback = fetch_texture_cb,
.buffer = {.ptr = buf, .size = FUR_TEX_BUF_SIZE},
.user_data = {.ptr = &tex_ptr, .size = sizeof(wgpu_texture_t*)},
});
}
/* Fetch binary model files */
{
uint8_t* buf = (uint8_t*)malloc(FUR_IDX_BUF_SIZE);
sfetch_send(&(sfetch_request_t){
.path = "assets/models/Fur/models/box10_rounded-indices.bin",
.callback = fetch_indices_cb,
.buffer = {.ptr = buf, .size = FUR_IDX_BUF_SIZE},
});
}
{
uint8_t* buf = (uint8_t*)malloc(FUR_STR_BUF_SIZE);
sfetch_send(&(sfetch_request_t){
.path = "assets/models/Fur/models/box10_rounded-strides.bin",
.callback = fetch_strides_cb,
.buffer = {.ptr = buf, .size = FUR_STR_BUF_SIZE},
});
}
}
/* -------------------------------------------------------------------------- *
* Matrix / uniform update helpers
* -------------------------------------------------------------------------- */
static void compute_view_proj(wgpu_context_t* wgpu_context, mat4 out_vp)
{
/* Camera: Z-up coordinate system, looking at origin from (190, 0, 270) */
mat4 view, proj;
glm_lookat((vec3){190.0f, 0.0f, 270.0f}, (vec3){0.0f, 0.0f, 0.0f},
(vec3){0.0f, 0.0f, 1.0f}, view);
const float aspect = (float)wgpu_context->width / (float)wgpu_context->height;
glm_perspective(TO_RADIANS(FUR_FOV_DEG), aspect, FUR_CAM_NEAR, FUR_CAM_FAR,
proj);
/* Model matrix: rotate around Z by angleYaw */
mat4 model;
glm_mat4_identity(model);
glm_rotate_z(model, state.angle_yaw, model);
/* VP = proj * view, MVP = VP * model */
mat4 vp;
glm_mat4_mul(proj, view, vp);
glm_mat4_mul(vp, model, out_vp);
}
static void update_uniforms(wgpu_context_t* wgpu_context)
{
mat4 mvp;
compute_view_proj(wgpu_context, mvp);
/* Vignette: orthographic projection */
{
fur_vignette_uniforms_t u;
glm_ortho(-1.0f, 1.0f, -1.0f, 1.0f, 2.0f, 250.0f, u.ortho_matrix);
wgpuQueueWriteBuffer(wgpu_context->queue, state.vignette_ubo.buffer, 0, &u,
sizeof(u));
}
/* Diffuse colored: MVP + preset start color */
{
fur_diffuse_uniforms_t u;
glm_mat4_copy(mvp, u.view_proj_matrix);
const fur_preset_t* p = &fur_presets[state.preset_idx];
glm_vec4_copy((float*)p->start_color, u.color);
wgpuQueueWriteBuffer(wgpu_context->queue, state.diffuse_ubo.buffer, 0, &u,
sizeof(u));
}
/* Fur shell: all fur animation parameters */
{
fur_shell_uniforms_t u = {0};
glm_mat4_copy(mvp, u.view_proj_matrix);