-
Notifications
You must be signed in to change notification settings - Fork 22
/
blinn_phong_lighting.c
1243 lines (1082 loc) · 41.6 KB
/
blinn_phong_lighting.c
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 "example_base.h"
#include <cJSON.h>
#include <string.h>
#include "../core/log.h"
#include "../webgpu/imgui_overlay.h"
/* -------------------------------------------------------------------------- *
* WebGPU Example - Blinn-Phong Lighting example
*
* This example demonstrates how to render a torus knot mesh with blinn-phong
* lighting model.
*
* Ref:
* https://github.com/Konstantin84UKR/webgpu_examples/tree/master/phong
* https://github.com/jack1232/ebook-webgpu-lighting/tree/main/src/examples/ch04
*
* Note:
* https://learnopengl.com/Advanced-Lighting/Advanced-Lighting
* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- *
* Vertex data - Torus Knot
* -------------------------------------------------------------------------- */
#define TORUS_KNOT_VERTEX_COUNT 7893
#define TORUS_KNOT_FACES_COUNT 3000
#define TORUS_KNOT_INDEX_COUNT (TORUS_KNOT_FACES_COUNT * 3)
#define TORUS_KNOT_UV_COUNT 5262
#define TORUS_KNOT_NORMAL_COUNT 7893
static struct torus_knot_mesh {
float vertices[TORUS_KNOT_VERTEX_COUNT];
uint32_t indices[TORUS_KNOT_INDEX_COUNT];
float uvs[TORUS_KNOT_UV_COUNT];
float normals[TORUS_KNOT_NORMAL_COUNT];
} torus_knot_mesh = {0};
int prepare_torus_knot_mesh(void)
{
int res = EXIT_FAILURE;
file_read_result_t file_read_result = {0};
read_file("meshes/model.json", &file_read_result, true);
const char* const json_data = (const char* const)file_read_result.data;
const cJSON* meshes_array = NULL;
const cJSON* meshes_item = NULL;
const cJSON* vertex_array = NULL;
const cJSON* vertex_item = NULL;
const cJSON* faces_array = NULL;
const cJSON* face_item = NULL;
const cJSON* texturecoord_array = NULL;
const cJSON* texturecoords_item = NULL;
const cJSON* texturecoord_item = NULL;
const cJSON* normal_array = NULL;
const cJSON* normal_item = NULL;
cJSON* model_json = cJSON_Parse(json_data);
if (model_json == NULL) {
const char* error_ptr = cJSON_GetErrorPtr();
if (error_ptr != NULL) {
log_error("Error before: %s", error_ptr);
}
goto load_json_end;
}
if (!cJSON_IsObject(model_json)
|| !cJSON_HasObjectItem(model_json, "meshes")) {
log_error("Invalid mesh file, does not contain 'meshes' array");
goto load_json_end;
}
/* Get first mesh */
meshes_array = cJSON_GetObjectItemCaseSensitive(model_json, "meshes");
if (!cJSON_IsArray(meshes_array)) {
log_error("'meshes' object item is not an array");
goto load_json_end;
}
if (!(cJSON_GetArraySize(meshes_array) > 0)) {
log_error("'meshes' array does not contain any mesh object");
goto load_json_end;
}
meshes_item = cJSON_GetArrayItem(meshes_array, 0);
if (!cJSON_IsObject(meshes_item)
|| !cJSON_HasObjectItem(meshes_item, "vertices")
|| !cJSON_HasObjectItem(meshes_item, "faces")
|| !cJSON_HasObjectItem(meshes_item, "texturecoords")
|| !cJSON_HasObjectItem(meshes_item, "normals")) {
log_error(
"Invalid mesh object, does not contain 'vertices', 'faces', "
"'texturecoords', 'normals' array");
goto load_json_end;
}
/* Parse vertices */
{
vertex_array = cJSON_GetObjectItemCaseSensitive(meshes_item, "vertices");
if (!cJSON_IsArray(vertex_array)) {
log_error("vertices object item is not an array");
goto load_json_end;
}
ASSERT(cJSON_GetArraySize(vertex_array) == TORUS_KNOT_VERTEX_COUNT);
uint32_t c = 0;
cJSON_ArrayForEach(vertex_item, vertex_array)
{
torus_knot_mesh.vertices[c++] = (float)vertex_item->valuedouble;
}
}
/* Parse indices */
{
faces_array = cJSON_GetObjectItemCaseSensitive(meshes_item, "faces");
if (!cJSON_IsArray(faces_array)) {
log_error("'faces' object item is not an array");
goto load_json_end;
}
ASSERT(cJSON_GetArraySize(faces_array) == TORUS_KNOT_FACES_COUNT);
uint32_t c = 0;
cJSON_ArrayForEach(face_item, faces_array)
{
if (!(cJSON_GetArraySize(face_item) == 3)) {
log_error("'face' item is not an array of size 3");
goto load_json_end;
}
for (uint32_t i = 0; i < 3; ++i) {
torus_knot_mesh.indices[c++]
= (uint32_t)cJSON_GetArrayItem(face_item, i)->valueint;
}
}
}
/* Parse uvs */
{
texturecoord_array
= cJSON_GetObjectItemCaseSensitive(meshes_item, "texturecoords");
if (!(cJSON_GetArraySize(texturecoord_array) > 0)) {
log_error("'texturecoords' array does not contain any object");
goto load_json_end;
}
texturecoords_item = cJSON_GetArrayItem(texturecoord_array, 0);
if (!cJSON_IsArray(texturecoords_item)) {
log_error("'texturecoords' object item is not an array");
goto load_json_end;
}
ASSERT(cJSON_GetArraySize(texturecoords_item) == TORUS_KNOT_UV_COUNT);
uint32_t c = 0;
cJSON_ArrayForEach(texturecoord_item, texturecoords_item)
{
torus_knot_mesh.uvs[c++] = (float)texturecoord_item->valuedouble;
}
}
/* Parse normals */
{
normal_array = cJSON_GetObjectItemCaseSensitive(meshes_item, "normals");
if (!cJSON_IsArray(normal_array)) {
log_error("'normals' object item is not an array");
goto load_json_end;
}
ASSERT(cJSON_GetArraySize(normal_array) == TORUS_KNOT_NORMAL_COUNT);
uint32_t c = 0;
cJSON_ArrayForEach(normal_item, normal_array)
{
torus_knot_mesh.normals[c++] = (float)normal_item->valuedouble;
}
}
res = EXIT_SUCCESS;
load_json_end:
cJSON_Delete(model_json);
free(file_read_result.data);
return res;
}
/* -------------------------------------------------------------------------- *
* Vertex data - Sphere Geometry
* -------------------------------------------------------------------------- */
typedef struct range_t {
void* ptr;
size_t byte_length;
size_t length;
} range_t;
typedef struct sphere_geometry_t {
float radius;
uint32_t width_segments;
uint32_t height_segments;
float phi_start;
float phi_length;
float theta_start;
float theta_length;
// vertex positions, texture coordinates, normals, tangents, and vertex
// indices
range_t vertices;
range_t uvs;
range_t normals;
range_t tangents;
range_t indices;
} sphere_geometry_t;
static sphere_geometry_t sphere_geometry = {0};
static void sphere_geometry_init_defaults(sphere_geometry_t* this)
{
memset(this, 0, sizeof(*this));
}
void sphere_geometry_init(sphere_geometry_t* this, float radius,
uint32_t width_segments, uint32_t height_segments,
float phi_start, float phi_length, float theta_start,
float theta_length)
{
sphere_geometry_init_defaults(this);
this->radius = radius;
this->width_segments = width_segments;
this->height_segments = height_segments;
this->phi_start = phi_start;
this->phi_length = phi_length;
this->theta_start = theta_start;
this->theta_length = theta_length;
// Generate vertex positions, texture coordinates, normals, tangents, and
// vertex indices
const uint32_t vertex_count = (width_segments + 1) * (height_segments + 1);
float* vertices = (float*)malloc(vertex_count * 3 * sizeof(float));
float* uvs = (float*)malloc(vertex_count * 2 * sizeof(float));
float* normals = (float*)malloc(vertex_count * 3 * sizeof(float));
float* tangents = (float*)malloc(vertex_count * 3 * sizeof(float));
uint32_t* indices = (uint32_t*)malloc(vertex_count * 6 * sizeof(uint32_t));
size_t vertices_length = 0, uvs_length = 0, normals_length = 0,
tangents_length = 0, indices_length = 0;
for (uint32_t iy = 0; iy <= height_segments; iy++) {
const float v = iy / (float)height_segments;
const float theta = theta_start + v * theta_length;
for (uint32_t ix = 0; ix <= width_segments; ix++) {
const float u = ix / (float)width_segments;
const float phi = phi_start + u * phi_length;
// Calculate vertex position
const float x = -radius * cos(phi) * sin(theta);
const float y = radius * cos(theta);
const float z = radius * sin(phi) * sin(theta);
vertices[vertices_length++] = x;
vertices[vertices_length++] = y;
vertices[vertices_length++] = z;
// Calculate texture coordinates
uvs[uvs_length++] = u;
uvs[uvs_length++] = v; // Invert v-axis to match the typical convention
// Calculate normal vector
normals[normals_length++] = x;
normals[normals_length++] = y;
normals[normals_length++] = z;
// Calculate tangent vector (same for all vertices)
// Assuming the tangent vector points along the positive X-axis
tangents[tangents_length++] = radius * sin(phi);
tangents[tangents_length++] = 0.0f;
tangents[tangents_length++] = radius * cos(phi);
if (iy < height_segments && ix < width_segments) {
const uint32_t current_index = ix + iy * (width_segments + 1);
const uint32_t next_index_x = current_index + 1;
const uint32_t next_index_y = current_index + width_segments + 1;
const uint32_t next_index_xy = next_index_y + 1;
// Generate indices for two triangles of each face
indices[indices_length++] = current_index;
indices[indices_length++] = next_index_y;
indices[indices_length++] = next_index_x;
indices[indices_length++] = next_index_y;
indices[indices_length++] = next_index_xy;
indices[indices_length++] = next_index_x;
}
}
}
// Initialize sphere geometry
this->vertices.ptr = vertices;
this->vertices.byte_length = vertices_length * sizeof(float);
this->vertices.length = vertices_length;
this->uvs.ptr = uvs;
this->uvs.byte_length = uvs_length * sizeof(float);
this->uvs.length = uvs_length;
this->normals.ptr = normals;
this->normals.byte_length = normals_length * sizeof(float);
this->normals.length = normals_length;
this->tangents.ptr = tangents;
this->tangents.byte_length = tangents_length * sizeof(float);
this->tangents.length = tangents_length;
this->indices.ptr = indices;
this->indices.byte_length = indices_length * sizeof(uint32_t);
this->indices.length = indices_length;
}
static void sphere_geometry_destroy(sphere_geometry_t* this)
{
range_t* sphere_data[5] = {
&this->vertices, &this->uvs, &this->normals,
&this->tangents, &this->indices,
};
for (uint32_t i = 0; i < 5; ++i) {
range_t* r = sphere_data[i];
if ((r->ptr != NULL) && (r->length > 0)) {
free(r->ptr);
r->ptr = NULL;
r->length = 0;
}
r->byte_length = 0;
}
}
void prepare_sphere_geometry(void)
{
sphere_geometry_init(&sphere_geometry, 0.1f, 16, 8, 0.0f, PI2, 0.0f, PI);
}
/* -------------------------------------------------------------------------- *
* WGSL Shaders
* -------------------------------------------------------------------------- */
static const char* blinn_phong_lighting_torus_knot_vertex_shader_wgsl;
static const char* blinn_phong_lighting_torus_knot_fragment_shader_wgsl;
static const char* blinn_phong_lighting_sphere_vertex_shader_wgsl;
static const char* blinn_phong_lighting_sphere_fragment_shader_wgsl;
/* -------------------------------------------------------------------------- *
* Blinn-Phong Lighting example
* -------------------------------------------------------------------------- */
/* Buffers */
static struct {
struct {
wgpu_buffer_t vertex;
wgpu_buffer_t index;
wgpu_buffer_t uv;
wgpu_buffer_t normal;
wgpu_buffer_t vs_uniform;
wgpu_buffer_t fs_uniform;
} torus_knot;
struct {
wgpu_buffer_t vertex;
wgpu_buffer_t index;
wgpu_buffer_t vs_uniform;
} sphere;
} buffers = {0};
/* Texture and sampler */
static struct {
texture_t torus_knot_face;
texture_t depth;
} textures = {0};
/* Uniform bind group and render pipeline (and layout) */
static struct {
WGPUBindGroup torus_knot;
WGPUBindGroup sphere;
} bind_groups = {0};
static struct {
WGPURenderPipeline torus_knot;
WGPURenderPipeline sphere;
} pipelines = {0};
/* Render pass descriptor for frame buffer writes */
static struct {
WGPURenderPassColorAttachment color_attachments[1];
WGPURenderPassDepthStencilAttachment depth_stencil_attachment;
WGPURenderPassDescriptor descriptor;
} render_pass = {0};
/* Uniform data */
static struct {
mat4 projection_matrix;
mat4 view_matrix;
mat4 model_matrix;
} torus_knot_view_matrices = {
.projection_matrix = GLM_MAT4_IDENTITY_INIT,
.view_matrix = GLM_MAT4_IDENTITY_INIT,
.model_matrix = GLM_MAT4_IDENTITY_INIT,
};
static struct {
mat4 projection_matrix;
mat4 view_matrix;
mat4 model_matrix;
} sphere_view_matrices = {
.projection_matrix = GLM_MAT4_IDENTITY_INIT,
.view_matrix = GLM_MAT4_IDENTITY_INIT,
.model_matrix = GLM_MAT4_IDENTITY_INIT,
};
static float time_old = 0.0f;
static struct {
vec4 eye_position;
vec4 light_position;
} light_positions = {
.eye_position = {0.0f, 1.0f, 8.0f, 1.0f},
.light_position = {0.0f, 0.0f, 1.0f, 1.0f},
};
// Other variables
static const char* example_title = "Blinn-Phong Lighting";
static bool prepared = false;
static void prepare_uniform_data(wgpu_context_t* wgpu_context)
{
/* View matrix */
glm_lookat(light_positions.eye_position, // eye vector
(vec3){0.0f, 0.0f, 0.0f}, // center vector
(vec3){0.0f, 1.0f, 0.0f}, // up vector
torus_knot_view_matrices.view_matrix // result matrix
);
glm_mat4_copy(torus_knot_view_matrices.view_matrix,
sphere_view_matrices.view_matrix);
/* View projection matrix */
const float aspect_ratio
= (float)wgpu_context->surface.width / (float)wgpu_context->surface.height;
const float fovy = 40.0f * PI / 180.0f;
glm_perspective(fovy, aspect_ratio, 1.f, 25.0f,
torus_knot_view_matrices.projection_matrix);
glm_mat4_copy(torus_knot_view_matrices.projection_matrix,
sphere_view_matrices.projection_matrix);
/* Translate model matrix for the sphere geometry */
glm_translate(sphere_view_matrices.model_matrix,
light_positions.light_position);
}
static void update_uniform_buffers(wgpu_example_context_t* context)
{
/* Time */
const float now = context->frame.timestamp_millis;
const float dt = now - time_old;
time_old = now;
/* Update view matrix update */
{
glm_rotate_x(torus_knot_view_matrices.model_matrix, dt * 0.0002f,
torus_knot_view_matrices.model_matrix);
glm_rotate_y(torus_knot_view_matrices.model_matrix, dt * 0.0002f,
torus_knot_view_matrices.model_matrix);
glm_rotate_z(torus_knot_view_matrices.model_matrix, dt * 0.0002f,
torus_knot_view_matrices.model_matrix);
// Map uniform buffer and update it
wgpu_queue_write_buffer(
context->wgpu_context, buffers.torus_knot.vs_uniform.buffer, 64 + 64,
&torus_knot_view_matrices.model_matrix[0], sizeof(mat4));
}
/* Update light position */
{
light_positions.light_position[0] = sin(now * 0.001f) * 4.0f;
/* Update the shere view matrix based on the light position */
{
glm_mat4_identity(sphere_view_matrices.model_matrix);
glm_translate(sphere_view_matrices.model_matrix,
light_positions.light_position);
/* Map uniform buffer and update it */
wgpu_queue_write_buffer(context->wgpu_context,
buffers.sphere.vs_uniform.buffer, 64 + 64,
sphere_view_matrices.model_matrix, sizeof(mat4));
}
/* Map uniform buffer and update it */
wgpu_queue_write_buffer(context->wgpu_context,
buffers.torus_knot.fs_uniform.buffer, 16,
&light_positions.light_position[0], sizeof(vec4));
}
}
static void prepare_buffers(wgpu_context_t* wgpu_context)
{
//******************************* Torus Knot *******************************//
/* Vertex buffer */
buffers.torus_knot.vertex = wgpu_create_buffer(
wgpu_context, &(wgpu_buffer_desc_t){
.label = "Torus knot vertex buffer",
.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_Vertex,
.size = sizeof(torus_knot_mesh.vertices),
.initial.data = torus_knot_mesh.vertices,
});
/* Index buffer */
buffers.torus_knot.index = wgpu_create_buffer(
wgpu_context, &(wgpu_buffer_desc_t){
.label = "Torus knot index buffer",
.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_Index,
.size = sizeof(torus_knot_mesh.indices),
.initial.data = torus_knot_mesh.indices,
});
/* UV buffer */
buffers.torus_knot.uv = wgpu_create_buffer(
wgpu_context, &(wgpu_buffer_desc_t){
.label = "UV buffer",
.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_Vertex,
.size = sizeof(torus_knot_mesh.uvs),
.initial.data = torus_knot_mesh.uvs,
});
/* Normal buffer */
buffers.torus_knot.normal = wgpu_create_buffer(
wgpu_context, &(wgpu_buffer_desc_t){
.label = "Normal buffer",
.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_Vertex,
.size = sizeof(torus_knot_mesh.normals),
.initial.data = torus_knot_mesh.normals,
});
/* Vertex shader uniform buffer */
buffers.torus_knot.vs_uniform = wgpu_create_buffer(
wgpu_context, &(wgpu_buffer_desc_t){
.label = "Torus knot vertex shader uniform buffer",
.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_Uniform,
.size = sizeof(torus_knot_view_matrices),
.initial.data = &torus_knot_view_matrices,
});
/* Fragment shader uniform buffer */
buffers.torus_knot.fs_uniform = wgpu_create_buffer(
wgpu_context, &(wgpu_buffer_desc_t){
.label = "Torus knot fragment shader uniform buffer",
.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_Uniform,
.size = sizeof(light_positions),
.initial.data = &light_positions,
});
//**************************** Sphere Geometry *****************************//
/* Vertex buffer */
buffers.sphere.vertex = wgpu_create_buffer(
wgpu_context, &(wgpu_buffer_desc_t){
.label = "Sphere vertex buffer",
.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_Vertex,
.size = sphere_geometry.vertices.byte_length,
.initial.data = sphere_geometry.vertices.ptr,
});
/* Index buffer */
buffers.sphere.index = wgpu_create_buffer(
wgpu_context, &(wgpu_buffer_desc_t){
.label = "Sphere index buffer",
.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_Index,
.size = sphere_geometry.indices.byte_length,
.initial.data = sphere_geometry.indices.ptr,
.count = sphere_geometry.indices.length,
});
/* Vertex shader uniform buffer */
buffers.sphere.vs_uniform = wgpu_create_buffer(
wgpu_context, &(wgpu_buffer_desc_t){
.label = "Sphere vertex shader uniform buffer",
.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_Uniform,
.size = sizeof(sphere_view_matrices),
.initial.data = &sphere_view_matrices,
});
}
static void prepare_textures(wgpu_context_t* wgpu_context)
{
/* Torus knot face texture*/
{
const char* file = "textures/uv.jpg";
textures.torus_knot_face
= wgpu_create_texture_from_file(wgpu_context, file, NULL);
}
/* Depth texture */
{
textures.depth.texture = wgpuDeviceCreateTexture(wgpu_context->device,
&(WGPUTextureDescriptor) {
.label = "Depth texture",
.usage = WGPUTextureUsage_RenderAttachment,
.dimension = WGPUTextureDimension_2D,
.format = WGPUTextureFormat_Depth24Plus,
.mipLevelCount = 1,
.sampleCount = 1,
.size = (WGPUExtent3D) {
.width = wgpu_context->surface.width,
.height = wgpu_context->surface.height,
.depthOrArrayLayers = 1,
},
});
textures.depth.view = wgpuTextureCreateView(
textures.depth.texture, &(WGPUTextureViewDescriptor){
.label = "Depth texture view",
.dimension = WGPUTextureViewDimension_2D,
.format = WGPUTextureFormat_Depth24Plus,
.mipLevelCount = 1,
.arrayLayerCount = 1,
});
}
}
static void setup_render_pass(void)
{
/* Color attachment */
render_pass.color_attachments[0] = (WGPURenderPassColorAttachment) {
.view = NULL, /* Assigned later */
.depthSlice = ~0,
.loadOp = WGPULoadOp_Clear,
.storeOp = WGPUStoreOp_Store,
.clearValue = (WGPUColor) {
.r = 0.1f,
.g = 0.2f,
.b = 0.3f,
.a = 1.0f,
},
};
/* Depth-stecil attachment */
render_pass.depth_stencil_attachment = (WGPURenderPassDepthStencilAttachment){
.view = textures.depth.view,
.depthClearValue = 1.0f,
.depthLoadOp = WGPULoadOp_Clear,
.depthStoreOp = WGPUStoreOp_Store,
};
// Render pass descriptor
render_pass.descriptor = (WGPURenderPassDescriptor){
.label = "Render pass descriptor",
.colorAttachmentCount = 1,
.colorAttachments = render_pass.color_attachments,
.depthStencilAttachment = &render_pass.depth_stencil_attachment,
};
}
static void setup_torus_bind_group(wgpu_context_t* wgpu_context)
{
WGPUBindGroupEntry bg_entries[4] = {
[0] = (WGPUBindGroupEntry) {
.binding = 0,
.buffer = buffers.torus_knot.vs_uniform.buffer,
.offset = 0,
.size = buffers.torus_knot.vs_uniform.size,
},
[1] = (WGPUBindGroupEntry) {
.binding = 1,
.sampler = textures.torus_knot_face.sampler,
},
[2] = (WGPUBindGroupEntry) {
.binding = 2,
.textureView = textures.torus_knot_face.view,
},
[3] = (WGPUBindGroupEntry) {
.binding = 3,
.buffer = buffers.torus_knot.fs_uniform.buffer,
.offset = 0,
.size = buffers.torus_knot.fs_uniform.size,
},
};
WGPUBindGroupDescriptor bg_desc = {
.label = "Torus knot uniform buffer bind group",
.layout = wgpuRenderPipelineGetBindGroupLayout(pipelines.torus_knot, 0),
.entryCount = (uint32_t)ARRAY_SIZE(bg_entries),
.entries = bg_entries,
};
bind_groups.torus_knot
= wgpuDeviceCreateBindGroup(wgpu_context->device, &bg_desc);
ASSERT(bind_groups.torus_knot != NULL);
}
static void setup_sphere_bind_group(wgpu_context_t* wgpu_context)
{
WGPUBindGroupEntry bg_entries[1] = {
[0] = (WGPUBindGroupEntry) {
.binding = 0,
.buffer = buffers.sphere.vs_uniform.buffer,
.offset = 0,
.size = buffers.sphere.vs_uniform.size,
},
};
WGPUBindGroupDescriptor bg_desc = {
.label = "Sphere uniform buffer bind group",
.layout = wgpuRenderPipelineGetBindGroupLayout(pipelines.sphere, 0),
.entryCount = (uint32_t)ARRAY_SIZE(bg_entries),
.entries = bg_entries,
};
bind_groups.sphere
= wgpuDeviceCreateBindGroup(wgpu_context->device, &bg_desc);
ASSERT(bind_groups.sphere != NULL);
}
static void prepare_torus_knot_pipeline(wgpu_context_t* wgpu_context)
{
// Primitive state
WGPUPrimitiveState primitive_state = {
.topology = WGPUPrimitiveTopology_TriangleList,
.frontFace = WGPUFrontFace_CCW,
.cullMode = WGPUCullMode_None,
};
// Color target state
WGPUBlendState blend_state = wgpu_create_blend_state(true);
WGPUColorTargetState color_target_state = (WGPUColorTargetState){
.format = wgpu_context->swap_chain.format,
.blend = &blend_state,
.writeMask = WGPUColorWriteMask_All,
};
// Depth stencil state
// Enable depth testing so that the fragment closest to the camera is rendered
// in front.
WGPUDepthStencilState depth_stencil_state
= wgpu_create_depth_stencil_state(&(create_depth_stencil_state_desc_t){
.format = WGPUTextureFormat_Depth24Plus,
.depth_write_enabled = true,
});
depth_stencil_state.depthCompare = WGPUCompareFunction_Less;
// Vertex buffer layout
WGPUVertexBufferLayout textured_torus_knot_vertex_buffer_layouts[3] = {0};
{
WGPUVertexAttribute attribute = {
// Shader location 0 : position attribute
.shaderLocation = 0,
.offset = 0,
.format = WGPUVertexFormat_Float32x3,
};
textured_torus_knot_vertex_buffer_layouts[0] = (WGPUVertexBufferLayout){
.arrayStride = 3 * sizeof(float),
.stepMode = WGPUVertexStepMode_Vertex,
.attributeCount = 1,
.attributes = &attribute,
};
}
{
WGPUVertexAttribute attribute = {
// Shader location 1 : uv attribute
.shaderLocation = 1,
.offset = 0,
.format = WGPUVertexFormat_Float32x2,
};
textured_torus_knot_vertex_buffer_layouts[1] = (WGPUVertexBufferLayout){
.arrayStride = 2 * sizeof(float),
.stepMode = WGPUVertexStepMode_Vertex,
.attributeCount = 1,
.attributes = &attribute,
};
}
{
WGPUVertexAttribute attribute = {
// Shader location 2 : Normal attribute
.shaderLocation = 2,
.offset = 0,
.format = WGPUVertexFormat_Float32x3,
};
textured_torus_knot_vertex_buffer_layouts[2] = (WGPUVertexBufferLayout){
.arrayStride = 3 * sizeof(float),
.stepMode = WGPUVertexStepMode_Vertex,
.attributeCount = 1,
.attributes = &attribute,
};
}
// Vertex state
WGPUVertexState vertex_state = wgpu_create_vertex_state(
wgpu_context, &(wgpu_vertex_state_t){
.shader_desc = (wgpu_shader_desc_t){
// Vertex shader WGSL
.label = "Blinn-Phong lighting torus knot vertex shader WGSL",
.wgsl_code.source = blinn_phong_lighting_torus_knot_vertex_shader_wgsl,
.entry = "main",
},
.buffer_count = (uint32_t)ARRAY_SIZE(textured_torus_knot_vertex_buffer_layouts),
.buffers = textured_torus_knot_vertex_buffer_layouts,
});
// Fragment state
WGPUFragmentState fragment_state = wgpu_create_fragment_state(
wgpu_context, &(wgpu_fragment_state_t){
.shader_desc = (wgpu_shader_desc_t){
// Fragment shader WGSL
.label = "Blinn-Phong lighting torus knot fragment shader WGSL",
.wgsl_code.source = blinn_phong_lighting_torus_knot_fragment_shader_wgsl,
.entry = "main",
},
.target_count = 1,
.targets = &color_target_state,
});
// Multisample state
WGPUMultisampleState multisample_state
= wgpu_create_multisample_state_descriptor(
&(create_multisample_state_desc_t){
.sample_count = 1,
});
// Create rendering pipeline using the specified states
pipelines.torus_knot = wgpuDeviceCreateRenderPipeline(
wgpu_context->device,
&(WGPURenderPipelineDescriptor){
.label = "Blinn phong lighting torus knot render pipeline",
.primitive = primitive_state,
.vertex = vertex_state,
.fragment = &fragment_state,
.depthStencil = &depth_stencil_state,
.multisample = multisample_state,
});
ASSERT(pipelines.torus_knot != NULL);
// Partial cleanup
WGPU_RELEASE_RESOURCE(ShaderModule, vertex_state.module);
WGPU_RELEASE_RESOURCE(ShaderModule, fragment_state.module);
}
static void prepare_sphere_pipeline(wgpu_context_t* wgpu_context)
{
// Primitive state
WGPUPrimitiveState primitive_state = {
.topology = WGPUPrimitiveTopology_TriangleList,
.frontFace = WGPUFrontFace_CCW,
.cullMode = WGPUCullMode_None,
};
// Color target state
WGPUBlendState blend_state = wgpu_create_blend_state(true);
WGPUColorTargetState color_target_state = (WGPUColorTargetState){
.format = wgpu_context->swap_chain.format,
.blend = &blend_state,
.writeMask = WGPUColorWriteMask_All,
};
// Depth stencil state
// Enable depth testing so that the fragment closest to the camera is rendered
// in front.
WGPUDepthStencilState depth_stencil_state
= wgpu_create_depth_stencil_state(&(create_depth_stencil_state_desc_t){
.format = WGPUTextureFormat_Depth24Plus,
.depth_write_enabled = true,
});
depth_stencil_state.depthCompare = WGPUCompareFunction_Less;
// Vertex buffer layout
WGPUVertexBufferLayout shere_vertex_buffer_layouts[1] = {0};
{
WGPUVertexAttribute attribute = {
// Shader location 0 : position attribute
.shaderLocation = 0,
.offset = 0,
.format = WGPUVertexFormat_Float32x3,
};
shere_vertex_buffer_layouts[0] = (WGPUVertexBufferLayout){
.arrayStride = 3 * sizeof(float),
.stepMode = WGPUVertexStepMode_Vertex,
.attributeCount = 1,
.attributes = &attribute,
};
}
// Vertex state
WGPUVertexState vertex_state = wgpu_create_vertex_state(
wgpu_context, &(wgpu_vertex_state_t){
.shader_desc = (wgpu_shader_desc_t){
// Vertex shader WGSL
.label = "Blinn-Phong lighting sphere vertex shader WGSL",
.wgsl_code.source = blinn_phong_lighting_sphere_vertex_shader_wgsl,
.entry = "main",
},
.buffer_count = (uint32_t)ARRAY_SIZE(shere_vertex_buffer_layouts),
.buffers = shere_vertex_buffer_layouts,
});
// Fragment state
WGPUFragmentState fragment_state = wgpu_create_fragment_state(
wgpu_context, &(wgpu_fragment_state_t){
.shader_desc = (wgpu_shader_desc_t){
// Fragment shader WGSL
.label = "Blinn-Phong lighting sphere fragment shader WGSL",
.wgsl_code.source = blinn_phong_lighting_sphere_fragment_shader_wgsl,
.entry = "main",
},
.target_count = 1,
.targets = &color_target_state,
});
// Multisample state
WGPUMultisampleState multisample_state
= wgpu_create_multisample_state_descriptor(
&(create_multisample_state_desc_t){
.sample_count = 1,
});
// Create rendering pipeline using the specified states
pipelines.sphere = wgpuDeviceCreateRenderPipeline(
wgpu_context->device,
&(WGPURenderPipelineDescriptor){
.label = "Blinn-Phong lighting sphere render pipeline",
.primitive = primitive_state,
.vertex = vertex_state,
.fragment = &fragment_state,
.depthStencil = &depth_stencil_state,
.multisample = multisample_state,
});
ASSERT(pipelines.sphere != NULL);
// Partial cleanup
WGPU_RELEASE_RESOURCE(ShaderModule, vertex_state.module);
WGPU_RELEASE_RESOURCE(ShaderModule, fragment_state.module);
}
static int example_initialize(wgpu_example_context_t* context)
{
if (context) {
prepare_torus_knot_mesh();
prepare_sphere_geometry();
prepare_uniform_data(context->wgpu_context);
prepare_buffers(context->wgpu_context);
prepare_textures(context->wgpu_context);
prepare_torus_knot_pipeline(context->wgpu_context);
prepare_sphere_pipeline(context->wgpu_context);
setup_torus_bind_group(context->wgpu_context);
setup_sphere_bind_group(context->wgpu_context);
setup_render_pass();
prepared = true;
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
static void example_on_update_ui_overlay(wgpu_example_context_t* context)
{
if (imgui_overlay_header("Settings")) {
imgui_overlay_checkBox(context->imgui_overlay, "Paused", &context->paused);
}
}
static WGPUCommandBuffer build_command_buffer(wgpu_context_t* wgpu_context)
{
render_pass.color_attachments[0].view = wgpu_context->swap_chain.frame_buffer;
wgpu_context->cmd_enc
= wgpuDeviceCreateCommandEncoder(wgpu_context->device, NULL);
/* Begin render pass */
wgpu_context->rpass_enc = wgpuCommandEncoderBeginRenderPass(
wgpu_context->cmd_enc, &render_pass.descriptor);
/* Record torus knot render pass */
{
wgpuRenderPassEncoderSetPipeline(wgpu_context->rpass_enc,
pipelines.torus_knot);
wgpuRenderPassEncoderSetVertexBuffer(wgpu_context->rpass_enc, 0,
buffers.torus_knot.vertex.buffer, 0,
WGPU_WHOLE_SIZE);
wgpuRenderPassEncoderSetVertexBuffer(wgpu_context->rpass_enc, 1,
buffers.torus_knot.uv.buffer, 0,
WGPU_WHOLE_SIZE);
wgpuRenderPassEncoderSetVertexBuffer(wgpu_context->rpass_enc, 2,
buffers.torus_knot.normal.buffer, 0,
WGPU_WHOLE_SIZE);
wgpuRenderPassEncoderSetIndexBuffer(
wgpu_context->rpass_enc, buffers.torus_knot.index.buffer,
WGPUIndexFormat_Uint32, 0, WGPU_WHOLE_SIZE);
wgpuRenderPassEncoderSetBindGroup(wgpu_context->rpass_enc, 0,
bind_groups.torus_knot, 0, 0);
wgpuRenderPassEncoderDrawIndexed(wgpu_context->rpass_enc,
TORUS_KNOT_INDEX_COUNT, 1, 0, 0, 0);
}
/* Record sphere render pass */
{
wgpuRenderPassEncoderSetPipeline(wgpu_context->rpass_enc, pipelines.sphere);
wgpuRenderPassEncoderSetVertexBuffer(wgpu_context->rpass_enc, 0,
buffers.sphere.vertex.buffer, 0,
WGPU_WHOLE_SIZE);
wgpuRenderPassEncoderSetIndexBuffer(
wgpu_context->rpass_enc, buffers.sphere.index.buffer,