-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathwireframe.c
More file actions
1333 lines (1148 loc) · 44.3 KB
/
Copy pathwireframe.c
File metadata and controls
1333 lines (1148 loc) · 44.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
#include "meshes.h"
#include "webgpu/imgui_overlay.h"
#include "webgpu/wgpu_common.h"
#include <cglm/cglm.h>
#include <string.h>
#ifdef __WAJIC__
#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
/* WAjic WebGPU handles are uint32_t, not pointers; redefine NULL to plain 0
* so WGPU handle assignments compile without pointer-to-integer errors.
* This must come AFTER all system headers to override any NULL redefinition. */
#ifdef __WAJIC__
#ifdef NULL
#undef NULL
#define NULL 0
#endif
#endif /* __WAJIC__ */
#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
/* -------------------------------------------------------------------------- *
* WebGPU Example - Wireframe
*
* This example demonstrates drawing wireframes from triangles in two ways:
* 1. Using line-list primitive topology with indexed vertex pulling
* 2. Using barycentric coordinates in the fragment shader
*
* The second method creates smoother lines with adjustable thickness and
* alpha threshold for anti-aliased edges.
*
* Ref:
* https://github.com/webgpu/webgpu-samples/tree/main/sample/wireframe
* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- *
* WGSL Shaders
* -------------------------------------------------------------------------- */
static const char* solid_color_lit_shader_wgsl;
static const char* wireframe_shader_wgsl;
/* -------------------------------------------------------------------------- *
* Constants
* -------------------------------------------------------------------------- */
#define NUM_OBJECTS (200)
#define DEPTH_FORMAT WGPUTextureFormat_Depth24Plus
/* -------------------------------------------------------------------------- *
* Model data structures
* -------------------------------------------------------------------------- */
typedef struct model_t {
WGPUBuffer vertex_buffer;
WGPUBuffer index_buffer;
uint32_t vertex_count;
uint32_t stride; /* Vertex stride in number of floats (6 = pos + normal) */
} model_t;
typedef struct object_info_t {
mat4 world_view_projection_matrix;
mat4 world_matrix;
float color[4];
model_t* model;
WGPUBuffer uniform_buffer;
WGPUBuffer line_uniform_buffer;
WGPUBindGroup lit_bind_group;
WGPUBindGroup wireframe_bind_group;
WGPUBindGroup barycentric_wireframe_bind_group;
} object_info_t;
/* Uniform buffer structures (must match shader layout) */
typedef struct uniforms_t {
mat4 world_view_projection_matrix;
mat4 world_matrix;
float color[4];
} uniforms_t;
typedef struct line_uniforms_t {
uint32_t stride;
float thickness;
float alpha_threshold;
uint32_t padding;
} line_uniforms_t;
/* -------------------------------------------------------------------------- *
* State struct
* -------------------------------------------------------------------------- */
static struct {
/* Models */
struct {
model_t teapot;
model_t sphere;
model_t jewel;
model_t rock;
model_t* all[4];
} models;
/* Mesh data */
utah_teapot_mesh_t teapot_mesh;
sphere_mesh_t sphere_mesh;
primitive_vertex_data_t jewel_data;
primitive_vertex_data_t rock_data;
/* Objects */
object_info_t objects[NUM_OBJECTS];
/* Pipelines */
WGPURenderPipeline lit_pipeline;
WGPURenderPipeline wireframe_pipeline;
WGPURenderPipeline barycentric_wireframe_pipeline;
/* Bind group layouts */
WGPUBindGroupLayout lit_bind_group_layout;
WGPUBindGroupLayout wireframe_bind_group_layout;
/* Depth texture */
wgpu_texture_t depth_texture;
/* View matrices */
mat4 projection_matrix;
mat4 view_matrix;
mat4 view_projection_matrix;
/* Render pass */
WGPURenderPassColorAttachment color_attachment;
WGPURenderPassDepthStencilAttachment depth_stencil_attachment;
WGPURenderPassDescriptor render_pass_descriptor;
/* Settings */
struct {
bool barycentric_coordinates_based;
float thickness;
float alpha_threshold;
bool animate;
bool lines;
int32_t depth_bias;
float depth_bias_slope_scale;
bool show_models;
} settings;
/* Timing */
float time;
uint64_t last_frame_time;
/* State */
WGPUBool initialized;
WGPUBool
models_loaded; /* true after teapot.json loaded and GPU objects created */
wgpu_context_t* wgpu_ctx; /* stored in init() for use in sfetch callbacks */
char* teapot_json_buf; /* malloc'd buffer for teapot.json sfetch */
} state = {
.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,
},
.render_pass_descriptor = {
.colorAttachmentCount = 1,
.colorAttachments = &state.color_attachment,
.depthStencilAttachment = &state.depth_stencil_attachment,
},
.settings = {
.barycentric_coordinates_based = false,
.thickness = 2.0f,
.alpha_threshold = 0.5f,
.animate = true,
.lines = true,
.depth_bias = 1,
.depth_bias_slope_scale = 0.5f,
.show_models = true,
},
};
/* -------------------------------------------------------------------------- *
* Random helper functions
* -------------------------------------------------------------------------- */
static float rand_float(void)
{
return (float)rand() / (float)RAND_MAX;
}
static void rand_color(float color[4])
{
color[0] = rand_float();
color[1] = rand_float();
color[2] = rand_float();
color[3] = 1.0f;
}
static model_t* rand_model(void)
{
return state.models.all[rand() % 4];
}
/* -------------------------------------------------------------------------- *
* Model creation functions
* -------------------------------------------------------------------------- */
static void create_model_from_mesh(wgpu_context_t* wgpu_context,
const float* vertices,
uint64_t vertices_byte_size,
const uint32_t* indices,
uint64_t indices_byte_size, model_t* model)
{
model->vertex_buffer = wgpuDeviceCreateBuffer(
wgpu_context->device,
&(WGPUBufferDescriptor){
.label = STRVIEW("Model - Vertex buffer"),
.size = vertices_byte_size,
.usage = WGPUBufferUsage_Vertex | WGPUBufferUsage_Storage
| WGPUBufferUsage_CopyDst,
});
wgpuQueueWriteBuffer(wgpu_context->queue, model->vertex_buffer, 0, vertices,
vertices_byte_size);
model->index_buffer = wgpuDeviceCreateBuffer(
wgpu_context->device,
&(WGPUBufferDescriptor){
.label = STRVIEW("Model - Index buffer"),
.size = indices_byte_size,
.usage = WGPUBufferUsage_Index | WGPUBufferUsage_Storage
| WGPUBufferUsage_CopyDst,
});
wgpuQueueWriteBuffer(wgpu_context->queue, model->index_buffer, 0, indices,
indices_byte_size);
model->vertex_count = (uint32_t)(indices_byte_size / sizeof(uint32_t));
model->stride = 6; /* position (3) + normal (3) */
}
/* Buffer size for the teapot JSON file (136 KB + 1 byte for null terminator) */
#define TEAPOT_JSON_BUF_SIZE (140 * 1024)
/* Forward declarations for sfetch callback */
static void create_teapot_model(wgpu_context_t* wgpu_context,
const char* json_data);
static void init_objects(wgpu_context_t* wgpu_context);
/* sfetch callback: fires when teapot.json has been downloaded */
static void teapot_fetch_cb(const sfetch_response_t* response)
{
if (!response->fetched) {
printf("File fetch failed, error: %d\n", response->error_code);
/* Allow rendering to proceed without the teapot */
state.models_loaded = true;
return;
}
/* Null-terminate the JSON data */
char* json_data = (char*)response->data.ptr;
json_data[response->data.size] = '\0';
/* Create teapot model from JSON, then create all per-object GPU resources */
create_teapot_model(state.wgpu_ctx, json_data);
free(state.teapot_json_buf);
state.teapot_json_buf = NULL;
init_objects(state.wgpu_ctx);
state.models_loaded = true;
}
static void create_teapot_model(wgpu_context_t* wgpu_context,
const char* json_data)
{
utah_teapot_mesh_init(&state.teapot_mesh, json_data);
utah_teapot_mesh_compute_normals(&state.teapot_mesh);
/* Create vertex buffer with positions and normals interleaved */
uint64_t vertex_count = state.teapot_mesh.positions.count;
uint64_t vertex_size = vertex_count * 6 * sizeof(float);
float* vertices = malloc(vertex_size);
const float scale = 1.5f;
for (uint64_t i = 0; i < vertex_count; ++i) {
vertices[i * 6 + 0] = state.teapot_mesh.positions.data[i][0] * scale;
vertices[i * 6 + 1] = state.teapot_mesh.positions.data[i][1] * scale;
vertices[i * 6 + 2] = state.teapot_mesh.positions.data[i][2] * scale;
vertices[i * 6 + 3] = state.teapot_mesh.normals.data[i][0];
vertices[i * 6 + 4] = state.teapot_mesh.normals.data[i][1];
vertices[i * 6 + 5] = state.teapot_mesh.normals.data[i][2];
}
/* Convert indices to uint32 */
uint64_t index_count = state.teapot_mesh.triangles.count * 3;
uint32_t* indices = malloc(index_count * sizeof(uint32_t));
for (uint64_t i = 0; i < state.teapot_mesh.triangles.count; ++i) {
indices[i * 3 + 0] = state.teapot_mesh.triangles.data[i][0];
indices[i * 3 + 1] = state.teapot_mesh.triangles.data[i][1];
indices[i * 3 + 2] = state.teapot_mesh.triangles.data[i][2];
}
create_model_from_mesh(wgpu_context, vertices, vertex_size, indices,
index_count * sizeof(uint32_t), &state.models.teapot);
free(vertices);
free(indices);
}
static void create_sphere_model(wgpu_context_t* wgpu_context)
{
sphere_mesh_init(&state.sphere_mesh, 20.0f, 32, 16, 0.0f);
/* Create vertex buffer - sphere mesh has 8 floats per vertex but we need 6 */
uint64_t src_vertex_count = state.sphere_mesh.vertices.length / 8;
uint64_t vertex_size = src_vertex_count * 6 * sizeof(float);
float* vertices = malloc(vertex_size);
for (uint64_t i = 0; i < src_vertex_count; ++i) {
/* Copy position (3 floats) and normal (3 floats), skip UV */
vertices[i * 6 + 0] = state.sphere_mesh.vertices.data[i * 8 + 0];
vertices[i * 6 + 1] = state.sphere_mesh.vertices.data[i * 8 + 1];
vertices[i * 6 + 2] = state.sphere_mesh.vertices.data[i * 8 + 2];
vertices[i * 6 + 3] = state.sphere_mesh.vertices.data[i * 8 + 3];
vertices[i * 6 + 4] = state.sphere_mesh.vertices.data[i * 8 + 4];
vertices[i * 6 + 5] = state.sphere_mesh.vertices.data[i * 8 + 5];
}
/* Convert indices to uint32 */
uint64_t index_count = state.sphere_mesh.indices.length;
uint32_t* indices = malloc(index_count * sizeof(uint32_t));
for (uint64_t i = 0; i < index_count; ++i) {
indices[i] = state.sphere_mesh.indices.data[i];
}
create_model_from_mesh(wgpu_context, vertices, vertex_size, indices,
index_count * sizeof(uint32_t), &state.models.sphere);
free(vertices);
free(indices);
}
static void create_jewel_model(wgpu_context_t* wgpu_context)
{
/* Create a low-poly sphere and flatten normals */
primitive_vertex_data_t sphere_data = {0};
primitive_create_sphere(
&(primitive_sphere_options_t){
.radius = 20.0f,
.subdivisions_axis = 5,
.subdivisions_height = 3,
},
&sphere_data);
/* Flatten normals (faceted look) */
primitive_facet(&sphere_data, &state.jewel_data);
primitive_vertex_data_destroy(&sphere_data);
/* Create vertex buffer - primitive has 8 floats per vertex, we need 6 */
uint64_t vertex_count = state.jewel_data.vertex_count;
uint64_t vertex_size = vertex_count * 6 * sizeof(float);
float* vertices = malloc(vertex_size);
for (uint64_t i = 0; i < vertex_count; ++i) {
/* position + normal, skip UV */
vertices[i * 6 + 0] = state.jewel_data.vertices[i * 8 + 0];
vertices[i * 6 + 1] = state.jewel_data.vertices[i * 8 + 1];
vertices[i * 6 + 2] = state.jewel_data.vertices[i * 8 + 2];
vertices[i * 6 + 3] = state.jewel_data.vertices[i * 8 + 3];
vertices[i * 6 + 4] = state.jewel_data.vertices[i * 8 + 4];
vertices[i * 6 + 5] = state.jewel_data.vertices[i * 8 + 5];
}
/* Create indices (after facet, indices are sequential) */
uint32_t* indices = malloc(vertex_count * sizeof(uint32_t));
for (uint64_t i = 0; i < vertex_count; ++i) {
indices[i] = (uint32_t)i;
}
create_model_from_mesh(wgpu_context, vertices, vertex_size, indices,
vertex_count * sizeof(uint32_t), &state.models.jewel);
free(vertices);
free(indices);
}
static void create_rock_model(wgpu_context_t* wgpu_context)
{
/* Create a sphere with randomness and flatten normals */
primitive_vertex_data_t sphere_data = {0};
/* First create a normal sphere */
primitive_create_sphere(
&(primitive_sphere_options_t){
.radius = 20.0f,
.subdivisions_axis = 32,
.subdivisions_height = 16,
},
&sphere_data);
/* Add randomness to positions */
for (uint64_t i = 0; i < sphere_data.vertex_count; ++i) {
float* pos = &sphere_data.vertices[i * 8];
float offset = 0.1f * 20.0f * (rand_float() - 0.5f);
/* Apply offset in radial direction */
float len = sqrtf(pos[0] * pos[0] + pos[1] * pos[1] + pos[2] * pos[2]);
if (len > 0.0f) {
pos[0] += (pos[0] / len) * offset;
pos[1] += (pos[1] / len) * offset;
pos[2] += (pos[2] / len) * offset;
}
}
/* Flatten normals */
primitive_facet(&sphere_data, &state.rock_data);
primitive_vertex_data_destroy(&sphere_data);
/* Create vertex buffer */
uint64_t vertex_count = state.rock_data.vertex_count;
uint64_t vertex_size = vertex_count * 6 * sizeof(float);
float* vertices = malloc(vertex_size);
for (uint64_t i = 0; i < vertex_count; ++i) {
vertices[i * 6 + 0] = state.rock_data.vertices[i * 8 + 0];
vertices[i * 6 + 1] = state.rock_data.vertices[i * 8 + 1];
vertices[i * 6 + 2] = state.rock_data.vertices[i * 8 + 2];
vertices[i * 6 + 3] = state.rock_data.vertices[i * 8 + 3];
vertices[i * 6 + 4] = state.rock_data.vertices[i * 8 + 4];
vertices[i * 6 + 5] = state.rock_data.vertices[i * 8 + 5];
}
uint32_t* indices = malloc(vertex_count * sizeof(uint32_t));
for (uint64_t i = 0; i < vertex_count; ++i) {
indices[i] = (uint32_t)i;
}
create_model_from_mesh(wgpu_context, vertices, vertex_size, indices,
vertex_count * sizeof(uint32_t), &state.models.rock);
free(vertices);
free(indices);
}
static void init_models(wgpu_context_t* wgpu_context)
{
/* Asynchronously fetch teapot.json; GPU model created in teapot_fetch_cb */
state.teapot_json_buf = (char*)malloc(TEAPOT_JSON_BUF_SIZE);
sfetch_send(&(sfetch_request_t){
.path = "assets/meshes/teapot.json",
.callback = teapot_fetch_cb,
.buffer = {.ptr = state.teapot_json_buf, .size = TEAPOT_JSON_BUF_SIZE - 1},
});
/* Create procedural models immediately (no file I/O needed) */
create_sphere_model(wgpu_context);
create_jewel_model(wgpu_context);
create_rock_model(wgpu_context);
state.models.all[0] = &state.models.teapot;
state.models.all[1] = &state.models.sphere;
state.models.all[2] = &state.models.jewel;
state.models.all[3] = &state.models.rock;
}
/* -------------------------------------------------------------------------- *
* Depth texture
* -------------------------------------------------------------------------- */
static void init_depth_texture(wgpu_context_t* wgpu_context)
{
wgpu_destroy_texture(&state.depth_texture);
WGPUExtent3D texture_extent = {
.width = wgpu_context->width,
.height = wgpu_context->height,
.depthOrArrayLayers = 1,
};
state.depth_texture.handle = wgpuDeviceCreateTexture(
wgpu_context->device, &(WGPUTextureDescriptor){
.label = STRVIEW("Depth - Texture"),
.size = texture_extent,
.mipLevelCount = 1,
.sampleCount = 1,
.dimension = WGPUTextureDimension_2D,
.format = DEPTH_FORMAT,
.usage = WGPUTextureUsage_RenderAttachment,
});
state.depth_texture.view = wgpuTextureCreateView(
state.depth_texture.handle, &(WGPUTextureViewDescriptor){
.label = STRVIEW("Depth - Texture view"),
.dimension = WGPUTextureViewDimension_2D,
.format = DEPTH_FORMAT,
.baseMipLevel = 0,
.mipLevelCount = 1,
.baseArrayLayer = 0,
.arrayLayerCount = 1,
});
}
/* -------------------------------------------------------------------------- *
* Pipeline creation
* -------------------------------------------------------------------------- */
static void init_lit_bind_group_layout(wgpu_context_t* wgpu_context)
{
/* Create bind group layout */
WGPUBindGroupLayoutEntry bgl_entries[1] = {
[0] = {
.binding = 0,
.visibility = WGPUShaderStage_Vertex | WGPUShaderStage_Fragment,
.buffer = {
.type = WGPUBufferBindingType_Uniform,
.minBindingSize = sizeof(uniforms_t),
},
},
};
state.lit_bind_group_layout = wgpuDeviceCreateBindGroupLayout(
wgpu_context->device, &(WGPUBindGroupLayoutDescriptor){
.label = STRVIEW("Lit - Bind group layout"),
.entryCount = ARRAY_SIZE(bgl_entries),
.entries = bgl_entries,
});
}
static void rebuild_lit_pipeline(wgpu_context_t* wgpu_context)
{
/* Release existing pipeline if any */
WGPU_RELEASE_RESOURCE(RenderPipeline, state.lit_pipeline)
/* Create pipeline layout */
WGPUPipelineLayout pipeline_layout = wgpuDeviceCreatePipelineLayout(
wgpu_context->device, &(WGPUPipelineLayoutDescriptor){
.label = STRVIEW("Lit - Pipeline layout"),
.bindGroupLayoutCount = 1,
.bindGroupLayouts = &state.lit_bind_group_layout,
});
/* Create shader module */
WGPUShaderModule shader_module = wgpu_create_shader_module(
wgpu_context->device, solid_color_lit_shader_wgsl);
/* Vertex buffer layout */
WGPUVertexAttribute vert_attrs[2] = {
[0]
= {.format = WGPUVertexFormat_Float32x3, .offset = 0, .shaderLocation = 0},
[1] = {.format = WGPUVertexFormat_Float32x3,
.offset = 3 * sizeof(float),
.shaderLocation = 1},
};
WGPUVertexBufferLayout vertex_buffer_layout = {
.arrayStride = 6 * sizeof(float),
.stepMode = WGPUVertexStepMode_Vertex,
.attributeCount = ARRAY_SIZE(vert_attrs),
.attributes = vert_attrs,
};
/* Depth stencil state */
WGPUDepthStencilState depth_stencil_state = {
.format = DEPTH_FORMAT,
.depthWriteEnabled = true,
.depthCompare = WGPUCompareFunction_Less,
.depthBias = state.settings.depth_bias,
.depthBiasSlopeScale = state.settings.depth_bias_slope_scale,
.stencilFront = {.compare = WGPUCompareFunction_Always},
.stencilBack = {.compare = WGPUCompareFunction_Always},
};
/* Blend state */
WGPUBlendState blend_state = wgpu_create_blend_state(true);
/* Render pipeline descriptor */
WGPURenderPipelineDescriptor pipeline_desc = {
.label = STRVIEW("Lit - Render pipeline"),
.layout = pipeline_layout,
.vertex = {
.module = shader_module,
.entryPoint = STRVIEW("vs"),
.bufferCount = 1,
.buffers = &vertex_buffer_layout,
},
.fragment = &(WGPUFragmentState){
.module = shader_module,
.entryPoint = STRVIEW("fs"),
.targetCount = 1,
.targets = &(WGPUColorTargetState){
.format = wgpu_context->render_format,
.blend = &blend_state,
.writeMask = WGPUColorWriteMask_All,
},
},
.primitive = {
.topology = WGPUPrimitiveTopology_TriangleList,
.cullMode = WGPUCullMode_Back,
.frontFace = WGPUFrontFace_CCW,
},
.depthStencil = &depth_stencil_state,
.multisample = {
.count = 1,
.mask = 0xFFFFFFFF,
},
};
state.lit_pipeline
= wgpuDeviceCreateRenderPipeline(wgpu_context->device, &pipeline_desc);
wgpuShaderModuleRelease(shader_module);
wgpuPipelineLayoutRelease(pipeline_layout);
}
static void init_wireframe_pipelines(wgpu_context_t* wgpu_context)
{
/* Create wireframe bind group layout */
WGPUBindGroupLayoutEntry bgl_entries[4] = {
[0] = {
.binding = 0,
.visibility = WGPUShaderStage_Vertex | WGPUShaderStage_Fragment,
.buffer = {
.type = WGPUBufferBindingType_Uniform,
.minBindingSize = sizeof(uniforms_t),
},
},
[1] = {
.binding = 1,
.visibility = WGPUShaderStage_Vertex,
.buffer = {
.type = WGPUBufferBindingType_ReadOnlyStorage,
.minBindingSize = 0,
},
},
[2] = {
.binding = 2,
.visibility = WGPUShaderStage_Vertex,
.buffer = {
.type = WGPUBufferBindingType_ReadOnlyStorage,
.minBindingSize = 0,
},
},
[3] = {
.binding = 3,
.visibility = WGPUShaderStage_Vertex | WGPUShaderStage_Fragment,
.buffer = {
.type = WGPUBufferBindingType_Uniform,
.minBindingSize = sizeof(line_uniforms_t),
},
},
};
state.wireframe_bind_group_layout = wgpuDeviceCreateBindGroupLayout(
wgpu_context->device, &(WGPUBindGroupLayoutDescriptor){
.label = STRVIEW("Wireframe - Bind group layout"),
.entryCount = ARRAY_SIZE(bgl_entries),
.entries = bgl_entries,
});
/* Create pipeline layout */
WGPUPipelineLayout pipeline_layout = wgpuDeviceCreatePipelineLayout(
wgpu_context->device,
&(WGPUPipelineLayoutDescriptor){
.label = STRVIEW("Wireframe - Pipeline layout"),
.bindGroupLayoutCount = 1,
.bindGroupLayouts = &state.wireframe_bind_group_layout,
});
/* Create shader module */
WGPUShaderModule shader_module
= wgpu_create_shader_module(wgpu_context->device, wireframe_shader_wgsl);
/* Depth stencil state */
WGPUDepthStencilState depth_stencil_state = {
.format = DEPTH_FORMAT,
.depthWriteEnabled = true,
.depthCompare = WGPUCompareFunction_LessEqual,
.stencilFront = {.compare = WGPUCompareFunction_Always},
.stencilBack = {.compare = WGPUCompareFunction_Always},
};
/* Blend state for barycentric method (alpha blending) */
WGPUBlendState alpha_blend_state = {
.color = {
.srcFactor = WGPUBlendFactor_One,
.dstFactor = WGPUBlendFactor_OneMinusSrcAlpha,
.operation = WGPUBlendOperation_Add,
},
.alpha = {
.srcFactor = WGPUBlendFactor_One,
.dstFactor = WGPUBlendFactor_OneMinusSrcAlpha,
.operation = WGPUBlendOperation_Add,
},
};
/* Line-list wireframe pipeline */
WGPURenderPipelineDescriptor wireframe_desc = {
.label = STRVIEW("Wireframe - Line list pipeline"),
.layout = pipeline_layout,
.vertex = {
.module = shader_module,
.entryPoint = STRVIEW("vsIndexedU32"),
},
.fragment = &(WGPUFragmentState){
.module = shader_module,
.entryPoint = STRVIEW("fs"),
.targetCount = 1,
.targets = &(WGPUColorTargetState){
.format = wgpu_context->render_format,
.writeMask = WGPUColorWriteMask_All,
},
},
.primitive = {
.topology = WGPUPrimitiveTopology_LineList,
},
.depthStencil = &depth_stencil_state,
.multisample = {
.count = 1,
.mask = 0xFFFFFFFF,
},
};
state.wireframe_pipeline
= wgpuDeviceCreateRenderPipeline(wgpu_context->device, &wireframe_desc);
/* Barycentric coordinates based wireframe pipeline */
WGPURenderPipelineDescriptor barycentric_desc = {
.label = STRVIEW("Wireframe - Barycentric pipeline"),
.layout = pipeline_layout,
.vertex = {
.module = shader_module,
.entryPoint = STRVIEW("vsIndexedU32BarycentricCoordinateBasedLines"),
},
.fragment = &(WGPUFragmentState){
.module = shader_module,
.entryPoint = STRVIEW("fsBarycentricCoordinateBasedLines"),
.targetCount = 1,
.targets = &(WGPUColorTargetState){
.format = wgpu_context->render_format,
.blend = &alpha_blend_state,
.writeMask = WGPUColorWriteMask_All,
},
},
.primitive = {
.topology = WGPUPrimitiveTopology_TriangleList,
},
.depthStencil = &depth_stencil_state,
.multisample = {
.count = 1,
.mask = 0xFFFFFFFF,
},
};
state.barycentric_wireframe_pipeline
= wgpuDeviceCreateRenderPipeline(wgpu_context->device, &barycentric_desc);
wgpuShaderModuleRelease(shader_module);
wgpuPipelineLayoutRelease(pipeline_layout);
}
/* -------------------------------------------------------------------------- *
* Object initialization
* -------------------------------------------------------------------------- */
static void init_objects(wgpu_context_t* wgpu_context)
{
for (uint32_t i = 0; i < NUM_OBJECTS; ++i) {
object_info_t* obj = &state.objects[i];
/* Assign random color and model */
rand_color(obj->color);
obj->model = rand_model();
/* Create uniform buffer */
obj->uniform_buffer = wgpuDeviceCreateBuffer(
wgpu_context->device,
&(WGPUBufferDescriptor){
.label = STRVIEW("Object - Uniform buffer"),
.size = sizeof(uniforms_t),
.usage = WGPUBufferUsage_Uniform | WGPUBufferUsage_CopyDst,
});
/* Create line uniform buffer */
line_uniforms_t line_uniforms = {
.stride = obj->model->stride,
.thickness = state.settings.thickness,
.alpha_threshold = state.settings.alpha_threshold,
};
obj->line_uniform_buffer = wgpuDeviceCreateBuffer(
wgpu_context->device,
&(WGPUBufferDescriptor){
.label = STRVIEW("Line - Uniform buffer"),
.size = sizeof(line_uniforms_t),
.usage = WGPUBufferUsage_Uniform | WGPUBufferUsage_CopyDst,
});
wgpuQueueWriteBuffer(wgpu_context->queue, obj->line_uniform_buffer, 0,
&line_uniforms, sizeof(line_uniforms));
/* Create lit bind group */
obj->lit_bind_group = wgpuDeviceCreateBindGroup(
wgpu_context->device, &(WGPUBindGroupDescriptor){
.label = STRVIEW("Lit - Bind group"),
.layout = state.lit_bind_group_layout,
.entryCount = 1,
.entries = &(WGPUBindGroupEntry){
.binding = 0,
.buffer = obj->uniform_buffer,
.size = sizeof(uniforms_t),
},
});
/* Create wireframe bind groups */
WGPUBindGroupEntry wf_entries[4] = {
[0] = {.binding = 0,
.buffer = obj->uniform_buffer,
.size = sizeof(uniforms_t)},
[1] = {.binding = 1,
.buffer = obj->model->vertex_buffer,
.size = WGPU_WHOLE_SIZE},
[2] = {.binding = 2,
.buffer = obj->model->index_buffer,
.size = WGPU_WHOLE_SIZE},
[3] = {.binding = 3,
.buffer = obj->line_uniform_buffer,
.size = sizeof(line_uniforms_t)},
};
obj->wireframe_bind_group = wgpuDeviceCreateBindGroup(
wgpu_context->device, &(WGPUBindGroupDescriptor){
.label = STRVIEW("Wireframe - Bind group"),
.layout = state.wireframe_bind_group_layout,
.entryCount = ARRAY_SIZE(wf_entries),
.entries = wf_entries,
});
obj->barycentric_wireframe_bind_group = wgpuDeviceCreateBindGroup(
wgpu_context->device,
&(WGPUBindGroupDescriptor){
.label = STRVIEW("Barycentric wireframe - Bind group"),
.layout = state.wireframe_bind_group_layout,
.entryCount = ARRAY_SIZE(wf_entries),
.entries = wf_entries,
});
}
}
/* -------------------------------------------------------------------------- *
* View matrices
* -------------------------------------------------------------------------- */
static void init_view_matrices(wgpu_context_t* wgpu_context)
{
const float aspect = (float)wgpu_context->width / (float)wgpu_context->height;
const float fov = TO_RADIANS(60.0f);
glm_perspective(fov, aspect, 0.1f, 1000.0f, state.projection_matrix);
glm_lookat((vec3){-300.0f, 0.0f, 300.0f}, (vec3){0.0f, 0.0f, 0.0f},
(vec3){0.0f, 1.0f, 0.0f}, state.view_matrix);
glm_mat4_mul(state.projection_matrix, state.view_matrix,
state.view_projection_matrix);
}
/* -------------------------------------------------------------------------- *
* Uniform updates
* -------------------------------------------------------------------------- */
static void update_line_uniforms(wgpu_context_t* wgpu_context)
{
for (uint32_t i = 0; i < NUM_OBJECTS; ++i) {
line_uniforms_t line_uniforms = {
.stride = state.objects[i].model->stride,
.thickness = state.settings.thickness,
.alpha_threshold = state.settings.alpha_threshold,
};
wgpuQueueWriteBuffer(wgpu_context->queue,
state.objects[i].line_uniform_buffer, 0,
&line_uniforms, sizeof(line_uniforms));
}
}
static void update_uniform_buffers(wgpu_context_t* wgpu_context)
{
for (uint32_t i = 0; i < NUM_OBJECTS; ++i) {
object_info_t* obj = &state.objects[i];
mat4 world;
glm_mat4_identity(world);
glm_translate(
world,
(vec3){0.0f, 0.0f, sinf((float)i * 3.721f + state.time * 0.1f) * 200.0f});
glm_rotate_x(world, (float)i * 4.567f, world);
glm_rotate_y(world, (float)i * 2.967f, world);
glm_translate(
world,
(vec3){0.0f, 0.0f, sinf((float)i * 9.721f + state.time * 0.1f) * 200.0f});
glm_rotate_x(world, state.time * 0.53f + (float)i, world);
glm_mat4_mul(state.view_projection_matrix, world,
obj->world_view_projection_matrix);
glm_mat4_copy(world, obj->world_matrix);
/* Pack uniforms */
uniforms_t uniforms;
glm_mat4_copy(obj->world_view_projection_matrix,
uniforms.world_view_projection_matrix);
glm_mat4_copy(obj->world_matrix, uniforms.world_matrix);
memcpy(uniforms.color, obj->color, sizeof(float) * 4);
wgpuQueueWriteBuffer(wgpu_context->queue, obj->uniform_buffer, 0, &uniforms,
sizeof(uniforms));
}
}
/* -------------------------------------------------------------------------- *
* GUI
* -------------------------------------------------------------------------- */
static void render_gui(wgpu_context_t* wgpu_context)
{
UNUSED_VAR(wgpu_context);
igSetNextWindowPos((ImVec2){10.0f, 10.0f}, ImGuiCond_FirstUseEver,
(ImVec2){0.0f, 0.0f});
igSetNextWindowSize((ImVec2){320.0f, 0.0f}, ImGuiCond_FirstUseEver);
igBegin("Wireframe Settings", NULL, ImGuiWindowFlags_AlwaysAutoResize);
/* Wireframe method */
if (igCheckbox("Barycentric Coordinates Based",
&state.settings.barycentric_coordinates_based)) {
/* Method changed - nothing else to do */
}
igCheckbox("Lines", &state.settings.lines);
igCheckbox("Models", &state.settings.show_models);
igCheckbox("Animate", &state.settings.animate);
igSeparator();
if (state.settings.barycentric_coordinates_based) {
/* Barycentric method settings */
if (imgui_overlay_slider_float("Thickness", &state.settings.thickness, 0.0f,
10.0f, "%.1f")) {
update_line_uniforms(wgpu_context);
}
if (imgui_overlay_slider_float("Alpha Threshold",
&state.settings.alpha_threshold, 0.0f, 1.0f,
"%.2f")) {
update_line_uniforms(wgpu_context);
}
}
else {
/* Line-list method settings (depth bias affects lit models) */
if (imgui_overlay_slider_int("Depth Bias", &state.settings.depth_bias, -3,
3)) {
rebuild_lit_pipeline(wgpu_context);
}
if (imgui_overlay_slider_float("Depth Bias Slope Scale",
&state.settings.depth_bias_slope_scale,
-1.0f, 1.0f, "%.2f")) {
rebuild_lit_pipeline(wgpu_context);
}
}
igEnd();
}
/* -------------------------------------------------------------------------- *
* Input handling
* -------------------------------------------------------------------------- */
static void input_event_cb(wgpu_context_t* wgpu_context,
const input_event_t* input_event)
{
imgui_overlay_handle_input(wgpu_context, input_event);
if (input_event->type == INPUT_EVENT_TYPE_RESIZED) {
init_depth_texture(wgpu_context);
init_view_matrices(wgpu_context);
}
}
/* -------------------------------------------------------------------------- *
* Initialization
* -------------------------------------------------------------------------- */
static int init(wgpu_context_t* wgpu_context)
{
if (wgpu_context) {