-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmesh_catalog.cpp
1928 lines (1564 loc) · 79.2 KB
/
mesh_catalog.cpp
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
// @Incomplete: Put a check in Pass 1 to see if there is a model that requires multiple primitives per triangle list!
// @Incomplete: Put a check in Pass 1 to see if there is a model that requires multiple primitives per triangle list!
// @Incomplete: Put a check in Pass 1 to see if there is a model that requires multiple primitives per triangle list!
#include "mesh_catalog.h"
/*
#include <assimp/cimport.h>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
*/
#include <stb_image.h>
#include "file_utils.h"
#include "opengl.h"
#include "main.h"
#include <glm/gtc/type_ptr.hpp> // for glm::make_mat4
#include "time_info.h"
/*
void assimp_mat4_to_glm(aiMatrix4x4 src, Matrix4 *dest)
{
(*dest)[0][0]=src.a1; (*dest)[1][0]=src.b1; (*dest)[2][0]=src.c1; (*dest)[3][0]=src.d1;
(*dest)[0][1]=src.a2; (*dest)[1][1]=src.b2; (*dest)[2][1]=src.c2; (*dest)[3][1]=src.d2;
(*dest)[0][2]=src.a3; (*dest)[1][2]=src.b3; (*dest)[2][2]=src.c3; (*dest)[3][2]=src.d3;
(*dest)[0][3]=src.a4; (*dest)[1][3]=src.b4; (*dest)[2][3]=src.c4; (*dest)[3][3]=src.d4;
}
void glm_mat4_to_assimp(Matrix4 src, aiMatrix4x4 *dest)
{
dest->a1=src[0][0]; dest->a2=src[1][0]; dest->a3=src[2][0]; dest->a4=src[3][0];
dest->b1=src[0][1]; dest->b2=src[1][1]; dest->b3=src[2][1]; dest->b4=src[3][1];
dest->c1=src[0][2]; dest->c2=src[1][2]; dest->c3=src[2][2]; dest->c4=src[3][2];
dest->d1=src[0][3]; dest->d2=src[1][3]; dest->d3=src[2][3]; dest->d4=src[3][3];
}
*/
void init_bounding_box(Bounding_Box *box) // @Incomplete: Not using bounding box.
{
constexpr auto inf = 1e10f;
box->min = Vector3(+inf, +inf, +inf);
box->max = Vector3(-inf, -inf, -inf);
}
void expand(Bounding_Box *box, Vector3 v)
{
if (v.x < box->min.x) box->min.x = v.x;
if (v.y < box->min.y) box->min.y = v.y;
if (v.z < box->min.z) box->min.z = v.z;
if (v.x > box->max.x) box->max.x = v.x;
if (v.y > box->max.y) box->max.y = v.y;
if (v.z > box->max.z) box->max.z = v.z;
}
inline
void allocate_texture_colors(Triangle_Mesh *triangle_mesh)
{
assert(triangle_mesh->texture_colors.count == 0);
auto num_vertices = triangle_mesh->vertices.count;
assert(num_vertices != 0);
triangle_mesh->texture_colors = NewArray<Vector4>(num_vertices);
}
inline
void allocate_materials(Triangle_Mesh *triangle_mesh, i32 n)
{
assert(triangle_mesh->material_info.count == 0);
triangle_mesh->material_info = NewArray<Render_Material>(n);
}
inline
void allocate_triangle_list_info(Triangle_Mesh *triangle_mesh, i32 n)
{
assert(triangle_mesh->triangle_list_info.count == 0);
triangle_mesh->triangle_list_info = NewArray<Triangle_List_Info>(n);
}
inline
void allocate_color_data(Triangle_Mesh *triangle_mesh)
{
assert(triangle_mesh->colors.count == 0);
auto num_vertices = triangle_mesh->vertices.count;
assert(num_vertices != 0);
triangle_mesh->colors = NewArray<Vector4>(num_vertices);
}
inline
void allocate_geometry(Triangle_Mesh *triangle_mesh, i32 num_vertices, i32 face_count)
{
assert(triangle_mesh->vertices.count == 0 &&
triangle_mesh->uvs.count == 0 &&
triangle_mesh->vertex_frames.count == 0 // &&
/* triangle_mesh->canonical_vertex_map.count == 0 */);
triangle_mesh->vertices = NewArray<Vector3>(num_vertices);
triangle_mesh->uvs = NewArray<Vector2>(num_vertices);
triangle_mesh->vertex_frames = NewArray<Frame3>(num_vertices);
// triangle_mesh->canonical_vertex_map = NewArray<i32>(num_vertices);
triangle_mesh->index_array = NewArray<i32>(face_count * 3);
}
/*
void process_assimp_model(aiScene *model, Triangle_Mesh *triangle_mesh, String model_path_relative_to_exe) // :DeprecateMe
{
Bounding_Box bounding_box;
init_bounding_box(&bounding_box);
i32 total_vertices = 0;
i32 total_faces = 0;
i32 total_bones = 0;
// The number of meshes corresponds to the number of triangle list infos in our triangle mesh.
// This is because our definition of mesh is different from that of Assimp. With Assimp,
// a model can contain multiple meshes, but with us, everything is stored under one giant
// mesh. But when we render, we use the triangle lists to query for the index of the vertices
// of each mesh and we can render it with different textures and materials.
i32 total_triangle_list_info = model->mNumMeshes;
//
// Pass 1: Get total number of vertices by traversing through the assimp model
//
bool use_colors = true;
bool use_textures = true;
for (i32 assimp_mesh_i = 0; assimp_mesh_i < total_triangle_list_info; ++assimp_mesh_i)
{
auto assimp_mesh = model->mMeshes[assimp_mesh_i];
total_vertices += assimp_mesh->mNumVertices;
total_faces += assimp_mesh->mNumFaces;
total_bones += assimp_mesh->mNumBones;
if (assimp_mesh->mColors[0] == NULL) use_colors = false;
if (assimp_mesh->mTextureCoords[0] == NULL) use_textures = false;
}
printf("Total mesh: %d\n", total_triangle_list_info);
printf("Total faces: %d\n", total_faces);
printf("Total vertices: %d\n", total_vertices);
printf("Total bones: %d\n", total_bones);
// @Incomplete: Not parsing the bones of the mesh.
// @Incomplete: Also, we are not allocating the array to store the bones.
// Allocate the geometry arrays and the color/texture arrays
if (!(total_vertices && total_faces))
{
fprintf(stderr, "ERROR: Model '%s' contains no vertices or faces, so cannot read.\n",
temp_c_string(triangle_mesh->name));
return;
}
if (!(total_triangle_list_info))
{
fprintf(stderr, "ERROR: Model '%s' contains no mesh components/parts, so cannot read.\n",
temp_c_string(triangle_mesh->name));
return;
}
allocate_geometry(triangle_mesh, total_vertices, total_faces);
allocate_triangle_list_info(triangle_mesh, total_triangle_list_info);
if (use_colors) allocate_color_data(triangle_mesh);
if (use_textures) allocate_texture_colors(triangle_mesh);
auto num_materials = model->mNumMaterials;
if (num_materials) allocate_materials(triangle_mesh, num_materials);
//
// Pass 2: Go through the assimp model and insert the data into the triangle list
//
i32 current_index = 0;
i32 vertices_previous_lists = 0;
for (i32 assimp_mesh_i = 0; assimp_mesh_i < total_triangle_list_info; ++assimp_mesh_i)
{
auto assimp_mesh = model->mMeshes[assimp_mesh_i];
//
// Process all the vertices for this assimp mesh first.
//
auto vertices_this_list = assimp_mesh->mNumVertices;
for (i32 vertex_i = 0; vertex_i < vertices_this_list; ++vertex_i)
{
auto assimp_vertex = assimp_mesh->mVertices[vertex_i];
Vector3 mesh_vertex = Vector3(assimp_vertex.x, assimp_vertex.y, assimp_vertex.z);
expand(&bounding_box, mesh_vertex);
Vector3 vertex = mesh_vertex;
Vector2 uv;
Frame3 vertex_frame;
Vector4 color;
if (assimp_mesh->mNormals != NULL)
{
vertex_frame.normal.x = assimp_mesh->mNormals[vertex_i].x;
vertex_frame.normal.y = assimp_mesh->mNormals[vertex_i].y;
vertex_frame.normal.z = assimp_mesh->mNormals[vertex_i].z;
}
// Only get the first texture coordinate and color
if (assimp_mesh->mTextureCoords[0] != NULL)
{
uv.x = assimp_mesh->mTextureCoords[0][vertex_i].x;
uv.y = assimp_mesh->mTextureCoords[0][vertex_i].y;
}
if (assimp_mesh->mColors[0] != NULL)
{
color.x = assimp_mesh->mColors[0][vertex_i].r;
color.y = assimp_mesh->mColors[0][vertex_i].g;
color.z = assimp_mesh->mColors[0][vertex_i].b;
color.w = assimp_mesh->mColors[0][vertex_i].a;
}
if (assimp_mesh->mTangents != NULL)
{
vertex_frame.tangent.x = assimp_mesh->mTangents[vertex_i].x;
vertex_frame.tangent.y = assimp_mesh->mTangents[vertex_i].y;
vertex_frame.tangent.z = assimp_mesh->mTangents[vertex_i].z;
vertex_frame.bitangent.x = assimp_mesh->mBitangents[vertex_i].x;
vertex_frame.bitangent.y = assimp_mesh->mBitangents[vertex_i].y;
vertex_frame.bitangent.z = assimp_mesh->mBitangents[vertex_i].z;
}
auto v_i = vertex_i + vertices_previous_lists;
triangle_mesh->vertices [v_i] = vertex;
triangle_mesh->uvs [v_i] = uv;
triangle_mesh->vertex_frames[v_i] = vertex_frame;
if (use_colors)
{
triangle_mesh->colors[v_i] = color;
}
if (use_textures)
{
// @Temporary:
triangle_mesh->texture_colors[v_i] = Vector4(1, 1, 1, 1);
}
}
//
// Then, we store the index data and the triangle list for the assimp mesh.
//
auto faces_for_this_list = assimp_mesh->mNumFaces;
auto current_list_info = &triangle_mesh->triangle_list_info[assimp_mesh_i];
current_list_info->num_indices = 3 * faces_for_this_list;
current_list_info->first_index = current_index;
// @Temporary:
current_list_info->material_index = -1;
current_list_info->map = NULL;
for (i32 face_i = 0; face_i < faces_for_this_list; ++face_i)
{
auto face = assimp_mesh->mFaces[face_i];
auto indices_count = face.mNumIndices;
assert((indices_count == 3)); // Because we triangulated the mesh.
for (i32 it = 0; it < indices_count; ++it)
{
auto vertex_index = face.mIndices[it];
auto v_i = vertex_index + vertices_previous_lists;
triangle_mesh->index_array[current_index] = v_i;
current_index += 1;
}
}
vertices_previous_lists += vertices_this_list;
// //
// // We then start to process the bones for this particular assimp mesh of the model.
// //
// {
// auto bones_for_this_mesh = assimp_mesh->mNumBones;
// if (assimp_mesh->mBones && (bones_for_this_mesh > 0)) // If we have any bones to process.
// {
// for (i32 bone_index = 0; bone_index < bones_for_this_mesh; ++bone_index)
// {
// auto assimp_bone = assimp_mesh->mBones[bone_index]; // This is a pointer to aiBone.
// auto bone_name = assimp_bone->mName.data; // This char* name needs to be copied.
// auto total_weights_for_this_bone = assimp_bone->mNumWeights;
// for (i32 weight_index = 0; weight_index < total_weights_for_this_bone; ++weight_index) // For all the influence weights of this bone.
// {
// auto vertex_weight = &assimp_bone->mWeights[weight_index];
// auto vertex_id = vertex_weight->mVertexId; // What vertex is being influenced by this bone.
// // This is the strength of the influence in the range of [0..1],
// // The influence from all bones at one vertex amounts to 1, always.
// auto weight = vertex_weight->mWeight;
// }
// // @Incomplete:
// }
// }
// }
//
// Next, we load the materials to the triangle mesh
//
auto material_index = assimp_mesh->mMaterialIndex;
current_list_info->material_index = material_index;
auto assimp_material = model->mMaterials[material_index];
auto assimp_texture_type = aiTextureType_DIFFUSE;
auto diffuse_texture_count = aiGetMaterialTextureCount(assimp_material, assimp_texture_type);
auto diffuse_material = &triangle_mesh->material_info[material_index];
diffuse_material->texture_map_name.count = 0;
if (!diffuse_texture_count)
{
fprintf(stderr, "[triangle_mesh]: WARNING, MESH '%s' DOES NOT CONTAINS A DIFFUSE TEXTURE!\n", temp_c_string(triangle_mesh->name));
current_list_info->map = NULL;
}
else
{
// @Note: This path is relative to the location of the model.
aiString assimp_material_path;
// @Temporary Getting the first diffuse texture because our renderer isn't sophisticated for now.
auto success = aiGetMaterialTexture(assimp_material, assimp_texture_type, 0, &assimp_material_path);
if (success != AI_SUCCESS)
{
fprintf(stderr, "[triangle_mesh]: Unable to get material diffuse texture of mesh, continuing...\n");
goto set_triangle_mesh_color;
}
// @Incomplete: Before loading the embedded texture, we must check if the texture is in
// the texture_catalog, if yes, load from there. Else, load the embedded texture and
// put it inside the texture_catalog.
auto assimp_embedded_texture = model->GetEmbeddedTexture(assimp_material_path.data);
if (assimp_embedded_texture)
{
auto width = assimp_embedded_texture->mWidth;
auto height = assimp_embedded_texture->mHeight;
if (height == 0) height = width;
// Our policy for the embedded texture maps is that we don't add them to the texture catalog, unlike
// the external textures. This is because we have mesh catalog that stores the meshes, so we don't
// have to worry about loading the same embedded texture map twice since we will have catalog to
// store meshes.
// ^ @Fixme: This is wrong, we should store it in the texture catalog, because the same texture can be loaded more than once in a mesh, even if it is an embedded one.
auto resulting_map = New<Texture_Map>(false);
init_texture_map(resulting_map);
i32 components;
u8 *data = stbi_load_from_memory(reinterpret_cast<u8*>(assimp_embedded_texture->pcData),
width * height, &resulting_map->width, &resulting_map->height,
&components, 4);
if (!data)
{
fprintf(stderr, "FAILED to load embedded bitmap for mesh '%s'\n", temp_c_string(triangle_mesh->name));
goto set_triangle_mesh_color;
}
auto bitmap = New<Bitmap>(false);
bitmap->width = resulting_map->width;
bitmap->height = resulting_map->height;
bitmap->data = data;
bitmap->length_in_bytes = bitmap->width * bitmap->height * components;
// @Temporary @Hack @Fixme @Incomplete
if (components == 3)
{
bitmap->format = Texture_Format::RGB888;
}
else
{
bitmap->format = Texture_Format::ARGB8888;
}
resulting_map->data = bitmap;
update_texture(resulting_map);
current_list_info->map = resulting_map;
}
else
{
String material_path_relative_to_model = String(assimp_material_path.data);
auto rel_model_path = model_path_relative_to_exe;
auto index_of_last_slash = find_index_from_right(rel_model_path, '/');
rel_model_path.count -= rel_model_path.count - index_of_last_slash;
auto material_path_relative_to_exe = tprint(String("%s/%s"), temp_c_string(rel_model_path), temp_c_string(material_path_relative_to_model));
String file_name = find_character_from_right(material_path_relative_to_model, '/');
if (file_name.count == 0) file_name = material_path_relative_to_model;
else advance(&file_name, 1);
if (file_name.count <= 0)
{
logprint("triangle_mesh", "Could not find the filename of the material path '%s'.\n", assimp_material_path.data);
goto set_triangle_mesh_color;
}
String name_without_extension = find_character_from_left(file_name, '.');
name_without_extension.count -= 1;
if (name_without_extension.count <= 0)
{
logprint("triangle_mesh", "File name without extension is malformed '%s'.\n", assimp_material_path.data);
goto set_triangle_mesh_color;
}
// @Incomplete: If multiple models has the same name for the texture, we will load the wrong one.
// @Incomplete: If multiple models has the same name for the texture, we will load the wrong one.
// @Incomplete: If multiple models has the same name for the texture, we will load the wrong one.
// @Incomplete: If multiple models has the same name for the texture, we will load the wrong one.
// ^ @Fixme: Unless we fix the catalog_find to compare with the full name if the short name matches.
// ^ @Fixme: Unless we fix the catalog_find to compare with the full name if the short name matches.
diffuse_material->texture_map_name = copy_string(name_without_extension);
my_register_loose_file<Texture_Map>(&texture_catalog.base, diffuse_material->texture_map_name, material_path_relative_to_exe);
}
}
set_triangle_mesh_color:
aiColor4D assimp_diffuse_color;
auto success = aiGetMaterialColor(assimp_material, AI_MATKEY_COLOR_DIFFUSE, &assimp_diffuse_color);
if (success != AI_SUCCESS)
{
fprintf(stderr, "[triangle_mesh]: Unable to get the material color for mesh, reverting to the color white...\n");
diffuse_material->color = Vector4(1, 1, 1, 1);
}
diffuse_material->color = Vector4(assimp_diffuse_color.r, assimp_diffuse_color.g, assimp_diffuse_color.b, assimp_diffuse_color.a);
}
assert((current_index == triangle_mesh->index_array.count));
triangle_mesh->approximate_bounding_box_p0 = bounding_box.min;
triangle_mesh->approximate_bounding_box_p1 = bounding_box.max;
triangle_mesh->approximate_bounding_box_p1.z = bounding_box.min.z;
}
*/
bool load_mesh_into_memory(Triangle_Mesh *mesh)
{
assert((mesh->full_path));
auto full_path = mesh->full_path;
auto c_path = (char*)(temp_c_string(full_path));
auto extension = find_character_from_right(full_path, '.');
if (!extension) return false; // No extension meaning that we don't know how to handle it.
advance(&extension, 1);
if ((extension == String("gltf")) || (extension == String("glb")))
{
auto success = load_gltf_model_2024(mesh);
return success;
}
else
{
assert(0);
}
/* Assimp loading stuff
auto supported_extension = aiIsExtensionSupported(c_extension);
if (supported_extension == AI_FALSE)
{
logprint("mesh_catalog", "ERROR: Extension '%s' is not supported.\n", c_extension);
return false;
}
aiScene *model = const_cast<aiScene*>(aiImportFile(c_path, aiProcessPreset_TargetRealtime_Quality));
defer { aiReleaseImport(model); };
if (!model)
{
logprint("mesh_catalog", "Failed to load the model at path '%s'.\n", c_path);
return false;
}
process_assimp_model(model, mesh, full_path);
*/
return false;
}
//
// Catalog stuff
//
// This is used in loading gltf materials' textures.
// The textures stored in here are either:
// a) Loaded from the embedded model file, or
// b) Retrieved using the texture catalog.
RArr<Texture_Map*> textures_lookup;
void init_mesh_catalog(Mesh_Catalog *catalog)
{
catalog->base.my_name = String("Triangle Mesh");
// array_add(&catalog->base.extensions, String("obj"));
// array_add(&catalog->base.extensions, String("fbx"));
array_add(&catalog->base.extensions, String("gltf"));
array_add(&catalog->base.extensions, String("glb"));
textures_lookup.allocator = {global_context.temporary_storage, __temporary_allocator};
do_polymorphic_catalog_init(catalog);
}
Triangle_Mesh *make_placeholder(Mesh_Catalog *catalog, String short_name, String full_name)
{
auto mesh = New<Triangle_Mesh>();
mesh->name = copy_string(short_name);
mesh->full_path = copy_string(full_name);
mesh->dirty = true;
return mesh;
}
void free_resources(Triangle_Mesh *mesh)
{
array_free(&mesh->vertices);
array_free(&mesh->uvs);
array_free(&mesh->vertex_frames);
array_free(&mesh->colors);
array_free(&mesh->texture_colors);
array_free(&mesh->index_array);
array_free(&mesh->triangle_list_info);
array_free(&mesh->material_info);
// Freeing the skeleton info.
{
auto info = mesh->skeleton_info;
for (auto &node : info->skeleton_node_info)
{
free_string(&node.name);
}
array_free(&info->skeleton_node_info);
array_free(&info->vertex_blend_info);
my_free(info);
}
}
inline
void make_vertex_buffer_non_skinned(Triangle_Mesh *mesh)
{
auto count = mesh->vertices.count;
auto dest_buffer = NewArray<Vertex_XCNUU>(count);
i64 it_index = 0;
for (auto &dest : dest_buffer)
{
// Every mesh supposed to have a vertex, but what the heyy, consistency!!?!?!?
if (mesh->vertices) dest.position = mesh->vertices[it_index];
else dest.position = Vector3(0, 0, 0);
if (mesh->colors)
{
auto c = mesh->colors[it_index];
c.w = 1.0f;
dest.color_scale = argb_color(c);
}
else
{
dest.color_scale = 0xffffffff;
}
if (mesh->vertex_frames) dest.normal = mesh->vertex_frames[it_index].normal;
else dest.normal = Vector3(1, 0, 0);
if (mesh->uvs) dest.uv0 = mesh->uvs[it_index];
else dest.uv0 = Vector2(0, 0);
dest.uv1 = Vector2(0, 0);
it_index += 1;
}
assert(dest_buffer.count);
assert(mesh->index_array.count);
glGenBuffers(1, &mesh->vertex_vbo);
glGenBuffers(1, &mesh->index_vbo);
DumpGLErrors("glGenBuffers for mesh's vertices");
glBindBuffer(GL_ARRAY_BUFFER, mesh->vertex_vbo);
DumpGLErrors("glBindBuffer for mesh's vertices");
glBufferData(GL_ARRAY_BUFFER, sizeof(dest_buffer[0]) * count, dest_buffer.data, GL_STREAM_DRAW);
DumpGLErrors("glBufferData for mesh's vertices");
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh->index_vbo);
DumpGLErrors("glBindBuffer for mesh's indices");
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(mesh->index_array[0]) * mesh->index_array.count, mesh->index_array.data, GL_STREAM_DRAW);
DumpGLErrors("glBufferData for mesh's indices");
}
//
// This is just a @Cutnpaste from the above. I'm not making this a polymorphic
// procedure because all of this XCNUU(S) format will go away later and so
// making 2 seperate procedure is also faster for compilation than one with some
// compile time if's in it.
//
inline
void make_vertex_buffer_skinned(Triangle_Mesh *mesh)
{
assert(mesh->skeleton_info);
assert(mesh->skeleton_info->vertex_blend_info.count);
auto count = mesh->vertices.count;
auto dest_buffer = NewArray<Vertex_XCNUUS>(count);
i64 it_index = 0;
for (auto &dest : dest_buffer)
{
// Every mesh supposed to have a vertex, but what the heyy, consistency!!?!?!?
if (mesh->vertices) dest.position = mesh->vertices[it_index];
else dest.position = Vector3(0, 0, 0);
if (mesh->colors)
{
auto c = mesh->colors[it_index];
c.w = 1.0f;
dest.color_scale = argb_color(c);
}
else
{
dest.color_scale = 0xffffffff;
}
if (mesh->vertex_frames) dest.normal = mesh->vertex_frames[it_index].normal;
else dest.normal = Vector3(1, 0, 0);
if (mesh->uvs) dest.uv0 = mesh->uvs[it_index];
else dest.uv0 = Vector2(0, 0);
// This is the part that is different compared to the non_skinned version.
dest.lightmap_uv = Vector2(0, 0); // @Incomplete: No lightmap data for now...
u32 blend_indices = 0; // This gets unpacked as a vec4 of unsigned bytes in the shader.
Vector4 blend_weights(0, 0, 0, 0);
auto blend = &mesh->skeleton_info->vertex_blend_info[it_index];
for (auto i = 0; i < blend->num_matrices; ++i) // @Speed:
{
auto piece = &blend->pieces[i];
blend_indices |= static_cast<u8>(piece->matrix_index) << ((i) * 8);
blend_weights[i] = piece->matrix_weight;
}
dest.blend_weights = blend_weights;
dest.blend_indices = blend_indices;
it_index += 1;
}
assert(dest_buffer.count);
assert(mesh->index_array.count);
glGenBuffers(1, &mesh->vertex_vbo);
glGenBuffers(1, &mesh->index_vbo);
DumpGLErrors("glGenBuffers for mesh's vertices");
glBindBuffer(GL_ARRAY_BUFFER, mesh->vertex_vbo);
DumpGLErrors("glBindBuffer for mesh's vertices");
glBufferData(GL_ARRAY_BUFFER, sizeof(dest_buffer[0]) * count, dest_buffer.data, GL_STREAM_DRAW);
DumpGLErrors("glBufferData for mesh's vertices");
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh->index_vbo);
DumpGLErrors("glBindBuffer for mesh's indices");
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(mesh->index_array[0]) * mesh->index_array.count, mesh->index_array.data, GL_STREAM_DRAW);
DumpGLErrors("glBufferData for mesh's indices");
}
void reload_asset(Mesh_Catalog *catalog, Triangle_Mesh *mesh)
{
// auto start_time = get_time();
// printf("Started loading mesh '%s'\n", temp_c_string(mesh->name));
if (mesh->loaded)
{
logprint("mesh_catalog", "Freeing the mesh '%s'!!!!!\n", temp_c_string(mesh->full_path));
free_resources(mesh);
}
auto load_success = load_mesh_into_memory(mesh);
if (!load_success)
{
logprint("mesh_catalog", "Was not able to load the mesh '%s' into memory!\n", temp_c_string(mesh->full_path));
return;
}
// Make vertex buffer for the mesh with respect to its skinning data.
if (mesh->skeleton_info) make_vertex_buffer_skinned(mesh);
else make_vertex_buffer_non_skinned(mesh);
// auto end_time = get_time() - start_time;
// printf("Loaded the mesh '%s', took %f seconds!\n", temp_c_string(mesh->name), end_time);
// newline();
}
#include <cgltf.h>
inline
cgltf_sampler *get_sampler_of_image(cgltf_data *parsed_gltf_data, i64 image_index, cgltf_image *gltf_image)
{
auto probe_index = image_index;
assert(probe_index < parsed_gltf_data->textures_count);
do
{
auto gltf_texture = &parsed_gltf_data->textures[probe_index];
if (gltf_texture->image == gltf_image)
{
auto sampler = gltf_texture->sampler;
return sampler;
}
probe_index += 1;
if (probe_index >= parsed_gltf_data->textures_count) probe_index = 0;
}
while (probe_index != image_index); // If we wrap around to where we start, we bail
assert(0); // @Incomplete: Unhandled case.
return NULL;
}
//
// Given an accessor (in GLTF, this is the main way to read data), we load the
// copy the content of that accessor (we are not allocating any data, just assigning
// the pointer elsewhere) to a given memory address.
// If the count or type address(es) is provided, we also store the count of the accessor
// and the type of it.
//
template <typename T>
inline
void load_accessor_into_memory_buffer(cgltf_accessor *accessor, T **memory_buffer_address, i64 *desired_count = NULL, cgltf_type *desired_type = NULL)
{
assert(accessor->buffer_view && accessor->buffer_view->buffer);
auto gltf_buffer = accessor->buffer_view->buffer;
auto buffer_offset = accessor->offset + accessor->buffer_view->offset;
*memory_buffer_address = reinterpret_cast<T*>(reinterpret_cast<u8*>(gltf_buffer->data) + buffer_offset);
if (desired_count) *desired_count = accessor->count;
if (desired_type) *desired_type = accessor->type;
}
void gltf_process_triangle_list_info(cgltf_data *parsed_gltf_data, Triangle_Mesh *triangle_mesh)
{
i32 vertices_previous_lists = 0;
i32 indices_previous_lists = 0;
auto c_path = (char*)(temp_c_string(triangle_mesh->full_path));
bool use_colors = triangle_mesh->colors.count != 0;
auto total_triangle_list_info = triangle_mesh->triangle_list_info.count;
for (i32 it_index = 0; it_index < total_triangle_list_info; ++it_index)
{
auto sub_mesh = &parsed_gltf_data->meshes[it_index];
auto total_primitives = sub_mesh->primitives_count;
auto triangle_list_info = &triangle_mesh->triangle_list_info[it_index];
assert(triangle_list_info->num_indices == 0); // Sanity check.
assert(triangle_list_info->first_index == 0);
for (i32 primitive_index = 0; primitive_index < total_primitives; ++primitive_index)
{
auto primitive = &sub_mesh->primitives[primitive_index];
//
// These are the memory buffers to the vertices data for this triangle list.
// The *_counts are really just for validating the data of the model.
//
f32 *positions_memory = NULL;
f32 *normals_memory = NULL;
i64 normals_count;
f32 *tangents_memory = NULL;
i64 tangents_count;
f32 *colors_memory = NULL;
i64 colors_count;
f32 *texture_uvs_memory = NULL;
i64 texture_uvs_count;
//
// The invariant for these is that they must have the same count as the number of
// vertices for each triangle list. Given this, any vertex in Blender/Maya that
// has more than one UVs will be exported as multiple vertices in the same place.
// I don't know how I should feel about this, but the way GLTF format works is
// kind of like how GPU handle vertices so I can live with that.
//
u32 *bone_influences_memory = NULL;
i64 bone_influences_count = 0;
i64 num_bone_influences_per_vertex = 0;
f32 *vertex_weights_memory = NULL;
i64 weights_count = 0;
i64 vertices_this_list = 0;
for (i32 attrib_index = 0; attrib_index < primitive->attributes_count; ++attrib_index)
{
auto attrib = &primitive->attributes[attrib_index];
auto accessor = attrib->data;
switch (attrib->type)
{
// Reading the vertices for this sub-mesh.
case cgltf_attribute_type_position: {
if (!positions_memory && (accessor->type == cgltf_type_vec3))
{
assert(accessor->component_type == cgltf_component_type_r_32f);
load_accessor_into_memory_buffer(accessor, &positions_memory, &vertices_this_list);
}
} break;
case cgltf_attribute_type_normal: {
if (!normals_memory && (accessor->type == cgltf_type_vec3))
{
assert(accessor->component_type == cgltf_component_type_r_32f);
load_accessor_into_memory_buffer(accessor, &normals_memory, &normals_count);
}
} break;
case cgltf_attribute_type_tangent: {
if (!tangents_memory && (accessor->type == cgltf_type_vec4))
{
assert(accessor->component_type == cgltf_component_type_r_32f);
load_accessor_into_memory_buffer(accessor, &tangents_memory, &tangents_count);
}
} break;
case cgltf_attribute_type_color: {
if (!colors_memory && (accessor->type == cgltf_type_vec3))
{
assert(accessor->component_type == cgltf_component_type_r_32f);
load_accessor_into_memory_buffer(accessor, &colors_memory, &colors_count);
}
} break;
case cgltf_attribute_type_texcoord: {
if (!texture_uvs_memory && (accessor->type == cgltf_type_vec2))
{
assert(accessor->component_type == cgltf_component_type_r_32f);
load_accessor_into_memory_buffer(accessor, &texture_uvs_memory, &texture_uvs_count);
}
} break;
case cgltf_attribute_type_joints: {
if (!bone_influences_memory) load_accessor_into_memory_buffer(accessor, &bone_influences_memory, &bone_influences_count);
else break;
num_bone_influences_per_vertex = cgltf_num_components(accessor->type);
assert(num_bone_influences_per_vertex <= MAX_MATRICES_PER_VERTEX); // Should not exceed the maximum amount otherwise, we are in trouble.
auto component_type = accessor->component_type;
assert((component_type == cgltf_component_type_r_8) || (component_type == cgltf_component_type_r_8u));
} break;
case cgltf_attribute_type_weights: {
if (!vertex_weights_memory) load_accessor_into_memory_buffer(accessor, &vertex_weights_memory, &weights_count);
else break;
assert(accessor->component_type == cgltf_component_type_r_32f);
} break;
}
}
//
// Checking the validity of the data...
//
{
assert(normals_count == vertices_this_list);
if (tangents_memory) assert(tangents_count == normals_count);
if (texture_uvs_memory) assert(texture_uvs_count == vertices_this_list);
if (colors_memory) assert(colors_count == vertices_this_list);
// The number of vertex blend infos, or [bones influences and weights] must be the same as
// the total number of vertices.
if (bone_influences_memory || vertex_weights_memory) // Although we are doing an OR, both must be present at once.
{
assert((bone_influences_count == vertices_this_list) && (weights_count == vertices_this_list));
}
}
//
// Process the positions, uvs, normals, tangents, bitangents, and colors.
//
for (i64 i = 0; i < vertices_this_list; ++i)
{
auto v_i = vertices_previous_lists + i;
// Positions.
assert(positions_memory);
auto p = &positions_memory[i * 3];
triangle_mesh->vertices[v_i] = Vector3(p[0], p[1], p[2]);
// Frame3
assert(normals_memory);
auto v_frame = &triangle_mesh->vertex_frames[v_i];
auto n = &normals_memory[i * 3];
v_frame->normal = Vector3(n[0], n[1], n[2]);
if (tangents_memory)
{
auto t = &tangents_memory[i * 4]; // The fourth component is the scalar of the first 3.
v_frame->tangent = Vector3(t[0], t[1], t[2]) * t[3];
}
// Texture UVs.
if (texture_uvs_memory)
{
auto uv = &texture_uvs_memory[i * 2];
triangle_mesh->uvs[v_i] = Vector2(uv[0], 1 - uv[1]); // Flipping the y coordinate here because GLTF stores the images in the right order and stbi image flipped them....
}
// Colors.
if (use_colors)
{
if (colors_memory)
{
auto c = &colors_memory[i * 3]; // 3 components because the last one is automatically 1.0f.
triangle_mesh->colors[v_i] = Vector4(c[0], c[1], c[2], 1.0f);
}
else
{
triangle_mesh->colors[v_i] = Vector4(1, 1, 1, 1);
}
}
// Bones and vertex weights
if (bone_influences_memory && vertex_weights_memory)
{
assert(triangle_mesh->skeleton_info->vertex_blend_info);
auto ids = &reinterpret_cast<u8*>(bone_influences_memory)[i * num_bone_influences_per_vertex];
auto weights = &vertex_weights_memory[i * num_bone_influences_per_vertex];
auto blend_info = &triangle_mesh->skeleton_info->vertex_blend_info[v_i];
auto num_matrices = 0;
for (i32 j = 0; j < MAX_MATRICES_PER_VERTEX; ++j)
{
if (!weights[j]) continue; // If weight is 0, then that matrix doesn't influence the vertex.
auto piece = &blend_info->pieces[num_matrices];
// @Note: This index is the joint/skeleton node index
// inside the joints array of the skin.
auto matrix_index = static_cast<i32>(ids[j]);
assert(matrix_index < triangle_mesh->skeleton_info->skeleton_node_info.count);
piece->matrix_index = matrix_index;
piece->matrix_weight = weights[j];
num_matrices += 1;
}
assert(num_matrices <= num_bone_influences_per_vertex);
blend_info->num_matrices = num_matrices;
}
}
if (!tangents_memory)
{
// @Incomplete: Supposed to calculate the tangents and bitangents based on the normals and vertices...
logprint("mesh_catalog", "We need to calculate tangents and bitangents for the model '%s'!\n", c_path);
}
// @Incomplete: Not handling texture color... or should we??
//
// Process the indices for this sub-mesh.
//
{
auto indices_accessor = primitive->indices;
auto indices_this_list = indices_accessor->count;
auto indices_offset = indices_previous_lists;