-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathModelLoader.cpp
More file actions
1290 lines (1116 loc) · 43.8 KB
/
Copy pathModelLoader.cpp
File metadata and controls
1290 lines (1116 loc) · 43.8 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 "ModelLoader.h"
#include "ModelAssetFormat.h"
#include "PathFinder.h"
#include "DataSystem.h"
#include "Interfaces/AssetAuthoringPort.h"
#include "assimp/material.h"
#include "assimp/Gltfmaterial.h"
#include "ReflectionYml.h"
#include "meshoptimizer.h"
#include <algorithm>
#include <chrono>
#include <execution>
#include <iterator>
#include <sstream>
#include <stdexcept>
namespace
{
constexpr std::uint32_t kMaxLegacyMaterialStringBytes = 1024u * 1024u;
// 기존 DirectX 전치 경로와 같은 숫자 배치를 명시한다.
// Assimp의 column-vector 행렬을 엔진의 row-vector 규약으로 옮기는 경계다.
[[nodiscard]] math::matrix4x4 ModelLoaderMatrixFromAssimp(
const aiMatrix4x4& source) noexcept
{
return math::matrix4x4{
source.a1, source.b1, source.c1, source.d1,
source.a2, source.b2, source.c2, source.d2,
source.a3, source.b3, source.c3, source.d3,
source.a4, source.b4, source.c4, source.d4 };
}
// CEMA v2의 skeleton/animation payload는 타입 이름이 아니라 이 packed
// float 폭으로 고정돼 있다. Mathematics 치환 뒤에도 기존 v2 캐시를 그대로
// 읽고 쓸 수 있어야 한다.
static_assert(sizeof(math::matrix4x4) == sizeof(float) * 16);
static_assert(sizeof(math::vector4) == sizeof(float) * 4);
static_assert(sizeof(math::quaternion) == sizeof(float) * 4);
static_assert(sizeof(math::vector3) == sizeof(float) * 3);
// vector4는 네 개의 named member를 가진 packed DTO다. &x 포인터 산술로 다른
// member에 접근하지 않고, 기존 Mathf bone-lane helper처럼 명시적으로 고른다.
[[nodiscard]] float& ModelLoaderVector4Lane(
math::vector4& value, uint32_t lane) noexcept
{
switch (lane)
{
case 0: return value.x;
case 1: return value.y;
case 2: return value.z;
default: return value.w;
}
}
template <typename T>
bool ReadLegacyValue(std::istream& input, T& value)
{
input.read(reinterpret_cast<char*>(&value), sizeof(value));
return static_cast<bool>(input);
}
bool ReadLegacyString(std::istream& input, std::string& value)
{
std::uint32_t size{};
if (!ReadLegacyValue(input, size) || size > kMaxLegacyMaterialStringBytes)
return false;
value.resize(size);
if (size != 0) input.read(value.data(), size);
return static_cast<bool>(input);
}
}
//ThreadPool<std::function<void()>> ModelLoadPool{};
ModelLoader::ModelLoader()
{
}
ModelLoader::~ModelLoader()
{
}
ModelLoader::ModelLoader(Model* model, Scene* scene) :
m_model(model),
m_scene(scene)
{
}
ModelLoader::ModelLoader(std::string_view fileName)
{
}
ModelLoader::ModelLoader(const aiScene* assimpScene, std::string_view fileName) :
m_AIScene(assimpScene),
m_skeletonLoader(assimpScene)
{
file::path filepath(fileName);
m_directory = filepath.parent_path().string() + "\\";
m_metaDirectory = filepath.string() + ".meta";
if (filepath.extension() == ".obj")
{
m_loadType = LoadType::OBJ;
}
else if (filepath.extension() == ".gltf" || filepath.extension() == ".glb")
{
m_loadType = LoadType::GLTF;
}
else if (filepath.extension() == ".fbx")
{
m_loadType = LoadType::FBX;
}
else if (filepath.extension() == ".asset")
{
m_loadType = LoadType::ASSET;
}
m_model = new Model;
if(m_loadType == LoadType::ASSET)
{
m_model->loadType = ModelLoadType::FormAsset;
}
m_model->lastWriteTime = file::last_write_time(filepath);
m_fileGuid = DataSystems->GetStemToGuid(filepath.stem().string());
m_model->guid = m_fileGuid;
m_model->path = filepath.string();
m_model->name = filepath.stem().string();
if(m_AIScene)
{
if (0 < m_AIScene->mNumAnimations)
{
m_model->m_animator = new AnimatorData();
}
}
}
size_t ModelLoader::CountNodes(aiNode* root)
{
if (!root)
return 0u;
size_t count = 1u;
for (uint32_t i = 0; i < root->mNumChildren; ++i)
count += CountNodes(root->mChildren[i]);
return count;
}
void ModelLoader::ProcessNodes()
{
m_model->m_numTotalMeshes = m_AIScene->mNumMeshes;
ProcessNode(m_AIScene->mRootNode, 0);
}
ModelNode* ModelLoader::ProcessNode(aiNode* node, int parentIndex)
{
ModelNode* nodeObj = new ModelNode(node->mName.C_Str());
nodeObj->m_index = m_model->m_nodes.size();
nodeObj->m_parentIndex = parentIndex;
nodeObj->m_numMeshes = node->mNumMeshes;
nodeObj->m_transform = ModelLoaderMatrixFromAssimp(node->mTransformation);
nodeObj->m_numChildren = node->mNumChildren;
m_model->m_nodes.push_back(nodeObj);
for (uint32 i = 0; i < node->mNumMeshes; i++)
{
nodeObj->m_meshes.push_back(node->mMeshes[i]);
}
for (uint32 i = 0; i < node->mNumChildren; i++)
{
ModelNode* child = ProcessNode(node->mChildren[i], nodeObj->m_index);
nodeObj->m_childrenIndex.push_back(child->m_index);
}
return nodeObj;
}
void ModelLoader::ProcessFlatMeshes()
{
m_model->m_Meshes.reserve(m_AIScene->mNumMeshes);
for (uint32 i = 0; i < m_AIScene->mNumMeshes; i++)
{
aiMesh* aimesh = m_AIScene->mMeshes[i];
Mesh* meshObj = GenerateMesh(aimesh);
const math::vector3 meshMin{
aimesh->mAABB.mMin.x, aimesh->mAABB.mMin.y, aimesh->mAABB.mMin.z };
const math::vector3 meshMax{
aimesh->mAABB.mMax.x, aimesh->mAABB.mMax.y, aimesh->mAABB.mMax.z };
meshObj->m_boundingBox = math::aabb::from_min_max(meshMin, meshMax);
meshObj->m_boundingSphere = math::bounding_sphere(meshObj->m_boundingBox);
}
}
Model* ModelLoader::LoadModel(bool isCreateMeshCollider)
{
if (m_loadType == LoadType::ASSET)
{
LoadModelFromAsset();
}
else
{
auto count = CountNodes(m_AIScene->mRootNode);
m_model->m_nodes.reserve(count);
ProcessNodes();
ProcessFlatMeshes();
ProcessMaterials();
if (m_model->m_hasBones)
{
Skeleton* skeleton = m_skeletonLoader.GenerateSkeleton(m_AIScene->mRootNode);
m_model->m_Skeleton = skeleton;
AnimatorData* animator = m_model->m_animator;
animator->m_Motion = m_fileGuid;
animator->m_Skeleton = skeleton;
}
// The binary .asset file is an Editor-owned import artifact. Runtime owns
// only the in-memory serialization request; Player has no installed writer.
RequestModelCacheWrite();
}
m_model->m_isMakeMeshCollider = isCreateMeshCollider;
return m_model;
}
Mesh* ModelLoader::GenerateMesh(aiMesh* mesh)
{
std::vector<Vertex> vertices;
std::vector<uint32> indices;
m_numUVChannel = mesh->GetNumUVChannels(); //테스트 해보고 어떻게 되는지 확인해보기
vertices.reserve(mesh->mNumVertices);
indices.reserve(mesh->mNumFaces * 3);
for (uint32 i = 0; i < mesh->mNumVertices; i++)
{
Vertex vertex = Vertex::ConvertToAiMesh(mesh, i);
vertices.push_back(vertex);
}
for (uint32 i = 0; i < mesh->mNumFaces; i++)
{
const aiFace& face = mesh->mFaces[i];
for (uint32 j = 0; j < face.mNumIndices; j++)
{
indices.push_back((uint32)face.mIndices[j]);
}
}
if(mesh->mNumBones > 0)
{
m_model->m_hasBones = true;
ProcessBones(mesh, vertices);
}
std::string baseName = mesh->mName.C_Str();
std::string uniqueName = baseName;
int suffix = 1;
while (true)
{
Mesh* mesh = m_model->GetMesh(uniqueName);
if (nullptr != mesh)
{
bool isVertexDeff = mesh->m_vertices.size() != vertices.size();
bool isIndexDeff = mesh->m_indices.size() != indices.size();
if(isVertexDeff || isIndexDeff)
{
uniqueName = baseName + "(" + std::to_string(suffix++) + ")";
break;
}
}
else
{
break;
}
}
Mesh* meshObj = new Mesh(uniqueName, vertices, indices);
meshObj->m_materialIndex = mesh->mMaterialIndex;
meshObj->m_modelName = m_model->name;
//if(!m_model->m_hasBones)
//{
// MeshOptimizer::Optimize(*meshObj, 1.05f);
// MeshOptimizer::GenerateShadowMesh(*meshObj);
//}
// Mesh는 meta::polymorphic 파생이라 operator delete가 커스텀 힙으로 라우팅된다.
// 따라서 shared_ptr의 기본 deleter로 감싸도 해제 경로는 기존과 동일하다.
m_model->m_Meshes.push_back(std::shared_ptr<Mesh>(meshObj));
return meshObj;
}
void ModelLoader::ProcessMaterials()
{
ResolveFileGuidFromMeta();
if (m_AIScene->mNumMaterials == 0)
{
m_model->m_Materials.push_back(GenerateMaterial());
}
else
{
for (UINT i = 0; i < m_AIScene->mNumMaterials; i++)
{
m_model->m_Materials.push_back(GenerateMaterial(i));
}
}
}
void ModelLoader::ResolveFileGuidFromMeta()
{
MetaYml::Node modelFileNode = MetaYml::LoadFile(m_metaDirectory);
m_fileGuid = modelFileNode["guid"].as<std::string>();
}
std::shared_ptr<Material> ModelLoader::GenerateMaterial(int index)
{
std::string baseName{};
if (index > -1)
{
baseName = m_AIScene->mMaterials[index]->GetName().C_Str();
}
if (baseName.empty())
{
// glTF의 material.name은 선택 항목이라 파일 전체가 무명인 경우가 흔하다
// (스폰자 GLB는 25개 재질 전부 이름이 없다). 전부 "DefaultMaterial"로
// 접으면 아래 중복 판정이 서로를 같은 재질로 보고 하나로 붕괴시킨다.
// 파일 내 인덱스를 이름에 담아 애초에 겹치지 않게 한다.
baseName = (index > -1)
? m_model->name + "_Mat" + std::to_string(index)
: "DefaultMaterial";
}
std::string uniqueName = baseName;
int suffix = 1;
while (true)
{
// 이번 임포트에서 이미 내준 이름이면 같은 파일 안의 다른 재질이다.
// 여기서 재사용하면 텍스처가 서로 다른 재질들이 하나로 접혀,
// 대부분의 메시가 남의 재질(대개 검게 보이는 컷아웃)을 쓰게 된다.
if (m_issuedMaterialNames.contains(uniqueName))
{
uniqueName = baseName + "(" + std::to_string(suffix++) + ")";
continue;
}
std::shared_ptr<Material> cached =
DataSystems->FindCachedMaterial(uniqueName);
if (!cached)
{
break;
}
if (cached->m_fileGuid == m_fileGuid)
{
// 같은 파일을 다시 임포트하는 경우다. 재질을 인덱스 순서대로
// 훑고 이름도 인덱스에서 나오므로, 각 인덱스가 제 짝을 다시 찾는다.
m_issuedMaterialNames.insert(uniqueName);
return cached;
}
// 다른 파일과의 이름 충돌 → 이름 뒤에 (숫자) 붙이기
uniqueName = baseName + "(" + std::to_string(suffix++) + ")";
}
m_issuedMaterialNames.insert(uniqueName);
auto material = std::make_shared<Material>();
material->m_name = uniqueName;
material->m_fileGuid = m_fileGuid;
if (index > -1)
{
aiMaterial* mat = m_AIScene->mMaterials[index];
Texture* normal = GenerateTexture(mat, aiTextureType_NORMALS);
Texture* bump = GenerateTexture(mat, aiTextureType_HEIGHT);
if (normal)
{
material->UseNormalMap(FindTextureOwner(normal));
material->m_normalTexName = normal->m_name;
}
else if (bump)
{
material->UseBumpMap(FindTextureOwner(bump));
material->m_normalTexName = bump->m_name;
}
Texture* ao = GenerateTexture(mat, aiTextureType_LIGHTMAP);
if (ao)
{
material->UseAOMap(FindTextureOwner(ao));
material->m_AO_TexName = ao->m_name;
}
Texture* emissive = GenerateTexture(mat, aiTextureType_EMISSIVE);
if (emissive)
{
material->UseEmissiveMap(FindTextureOwner(emissive));
material->m_EmissiveTexName = emissive->m_name;
}
if (m_loadType == LoadType::GLTF)
{
material->ConvertToLinearSpace(true);
// glTF의 baseColorTexture가 어느 슬롯으로 들어오는지는 Assimp 버전을
// 탄다. BASE_COLOR로 넣는 버전도 있고 DIFFUSE로만 넣는 버전도 있다.
// 하나만 보면 '텍스처가 있는데 재질이 비어 있다'가 되고, 그 증상은
// 화면에서 '검게 나온다'로만 드러나 원인이 멀다(실측으로 겪었다).
Texture* albedo = GenerateTextureFromAny(mat,
{ aiTextureType_BASE_COLOR, aiTextureType_DIFFUSE }, "baseColor");
if (albedo)
{
material->UseBaseColorMap(FindTextureOwner(albedo));
material->m_baseColorTexName = albedo->m_name;
}
// 금속·거칠기도 같은 사정이다. glTF는 한 텍스처에 담지만 Assimp는
// 버전에 따라 METALNESS/DIFFUSE_ROUGHNESS/UNKNOWN 중 하나로 준다.
Texture* occlusionMetalRough = GenerateTextureFromAny(mat,
{ aiTextureType_METALNESS, aiTextureType_DIFFUSE_ROUGHNESS,
aiTextureType_UNKNOWN }, "metallicRoughness");
if (occlusionMetalRough)
{
material->UseOccRoughMetalMap(FindTextureOwner(occlusionMetalRough));
material->m_ORM_TexName = occlusionMetalRough->m_name;
}
float metallic;
if (mat->Get(AI_MATKEY_METALLIC_FACTOR, metallic) == AI_SUCCESS)
{
material->SetMetallic(metallic);
}
float roughness;
if (mat->Get(AI_MATKEY_ROUGHNESS_FACTOR, roughness) == AI_SUCCESS)
{
material->SetRoughness(roughness);
}
// OBJ/FBX 경로는 알파 채널을 보고 Transparent로 넘기는데 이쪽만 없었다.
// glTF는 알파 처리 방식을 텍스처가 아니라 material.alphaMode로 선언하므로
// 그 값을 봐야 한다. 안 보면 사슬·화분 같은 컷아웃 재질이 불투명으로
// 디퍼드 큐에 실려 잘려야 할 부분이 검은 판으로 남는다.
aiString alphaMode;
if (mat->Get(AI_MATKEY_GLTF_ALPHAMODE, alphaMode) == AI_SUCCESS)
{
const std::string_view mode{ alphaMode.C_Str() };
// 엔진의 렌더링 모드는 Opaque/Transparent 둘뿐이라 MASK도 함께 태운다.
if ("MASK" == mode || "BLEND" == mode)
{
material->m_renderingMode = MaterialRenderingMode::Transparent;
}
}
}
else
{
material->ConvertToLinearSpace(true);
Texture* albedo = GenerateTexture(mat, aiTextureType_DIFFUSE);
if (albedo)
{
material->UseBaseColorMap(FindTextureOwner(albedo));
material->m_baseColorTexName = albedo->m_name;
if (albedo->IsTextureAlpha())
{
material->m_renderingMode = MaterialRenderingMode::Transparent;
}
}
aiColor3D colour;
aiReturn res = mat->Get(AI_MATKEY_COLOR_DIFFUSE, colour);
if (res == aiReturn_SUCCESS)
material->SetBaseColor(colour[0], colour[1], colour[2]);
material->SetRoughness(0.9f);
material->SetMetallic(0.0f);
float shininess;
res = mat->Get(AI_MATKEY_SHININESS, shininess);
if (res == aiReturn_SUCCESS)
{
float roughness = sqrt(2.0f / (shininess + 2.0f));
material->SetRoughness(roughness);
}
}
}
else
{
material->SetBaseColor(1, 0, 1);
}
material = DataSystems->RegisterImportedMaterial(material, baseName);
if (material) m_issuedMaterialNames.insert(material->m_name);
return material;
}
void ModelLoader::RequestModelCacheWrite()
{
if (!AssetAuthoringPort::IsInstalled()) return;
std::ostringstream output(std::ios::out | std::ios::binary);
const ModelAssetFormat::FileHeader header{};
output.write(reinterpret_cast<const char*>(&header), sizeof(header));
uint32_t nodeCount = static_cast<uint32_t>(m_model->m_nodes.size());
uint32_t meshCount = static_cast<uint32_t>(m_model->m_Meshes.size());
uint32_t materialCnt = static_cast<uint32_t>(m_model->m_Materials.size());
output.write(reinterpret_cast<char*>(&nodeCount), sizeof(nodeCount));
output.write(reinterpret_cast<char*>(&meshCount), sizeof(meshCount));
output.write(reinterpret_cast<char*>(&materialCnt), sizeof(materialCnt));
bool hasSkeleton = m_model->m_hasBones && m_model->m_Skeleton;
output.write(reinterpret_cast<char*>(&hasSkeleton), sizeof(hasSkeleton));
if (hasSkeleton) SerializeSkeleton(output);
SerializeNodes(output);
SerializeMeshes(output);
SerializeMaterials(output);
if (!output.good())
{
Debug->LogWarning("모델 캐시 직렬화 실패: " + m_model->name);
return;
}
const std::string payload = output.str();
const file::path destination =
PathFinder::Relative("Models\\") / (m_model->name + ".asset");
const auto bytes = std::span<const std::byte>(
reinterpret_cast<const std::byte*>(payload.data()), payload.size());
if (!AssetAuthoringPort::WriteModelCache(destination, bytes))
Debug->LogWarning("Editor model-cache write failed: " + destination.string());
}
void ModelLoader::SerializeNodes(std::ostream& output)
{
for (const ModelNode* node : m_model->m_nodes)
{
SerializeNode(output, node);
}
}
void ModelLoader::SerializeNode(std::ostream& output, const ModelNode* node)
{
uint32_t nameSize = static_cast<uint32_t>(node->m_name.size());
output.write(reinterpret_cast<char*>(&nameSize), sizeof(nameSize));
output.write(node->m_name.data(), nameSize);
output.write(reinterpret_cast<const char*>(&node->m_index), sizeof(node->m_index));
output.write(reinterpret_cast<const char*>(&node->m_parentIndex), sizeof(node->m_parentIndex));
output.write(reinterpret_cast<const char*>(&node->m_numMeshes), sizeof(node->m_numMeshes));
output.write(reinterpret_cast<const char*>(&node->m_numChildren), sizeof(node->m_numChildren));
output.write(reinterpret_cast<const char*>(&node->m_transform),
sizeof(math::matrix4x4));
if (!node->m_meshes.empty())
output.write(reinterpret_cast<const char*>(node->m_meshes.data()), node->m_meshes.size() * sizeof(uint32_t));
if (!node->m_childrenIndex.empty())
output.write(reinterpret_cast<const char*>(node->m_childrenIndex.data()), node->m_childrenIndex.size() * sizeof(uint32_t));
}
void ModelLoader::SerializeMeshes(std::ostream& output)
{
for (const auto& mesh : m_model->m_Meshes)
{
uint32_t nameSize = static_cast<uint32_t>(mesh->m_name.size());
output.write(reinterpret_cast<char*>(&nameSize), sizeof(nameSize));
output.write(mesh->m_name.data(), nameSize);
output.write(reinterpret_cast<const char*>(&mesh->m_materialIndex), sizeof(mesh->m_materialIndex));
uint32_t vertexCount = static_cast<uint32_t>(mesh->m_vertices.size());
output.write(reinterpret_cast<char*>(&vertexCount), sizeof(vertexCount));
if (vertexCount)
output.write(reinterpret_cast<const char*>(mesh->m_vertices.data()), vertexCount * sizeof(Vertex));
uint32_t indexCount = static_cast<uint32_t>(mesh->m_indices.size());
output.write(reinterpret_cast<char*>(&indexCount), sizeof(indexCount));
if (indexCount)
output.write(reinterpret_cast<const char*>(mesh->m_indices.data()), indexCount * sizeof(uint32_t));
output.write(reinterpret_cast<const char*>(&mesh->m_boundingBox), sizeof(math::aabb));
output.write(reinterpret_cast<const char*>(&mesh->m_boundingSphere), sizeof(math::sphere));
}
}
void ModelLoader::SerializeMaterials(std::ostream& output)
{
for (const auto& mat : m_model->m_Materials)
{
if (!mat || !DataSystems->SerializeMaterialBinaryPayload(*mat, output))
{
output.setstate(std::ios::failbit);
return;
}
}
}
void SetParentIndexRecursive(Bone* bone, int parent)
{
bone->m_parentIndex = parent;
for (Bone* child : bone->m_children)
{
SetParentIndexRecursive(child, bone->m_index);
}
}
void ModelLoader::SerializeSkeleton(std::ostream& output)
{
Skeleton* skeleton = m_model->m_Skeleton;
AnimatorData* animator = m_model->m_animator;
if (!skeleton || !animator)
return;
SetParentIndexRecursive(skeleton->m_rootBone, -1);
output.write(reinterpret_cast<const char*>(&skeleton->m_rootTransform),
sizeof(math::matrix4x4));
output.write(reinterpret_cast<const char*>(&skeleton->m_globalInverseTransform),
sizeof(math::matrix4x4));
uint32_t boneCount = static_cast<uint32_t>(skeleton->m_bones.size());
output.write(reinterpret_cast<char*>(&boneCount), sizeof(boneCount));
for (Bone* bone : skeleton->m_bones)
{
uint32_t nameSize = static_cast<uint32_t>(bone->m_name.size());
output.write(reinterpret_cast<char*>(&nameSize), sizeof(nameSize));
output.write(bone->m_name.data(), nameSize);
output.write(reinterpret_cast<char*>(&bone->m_index), sizeof(bone->m_index));
output.write(reinterpret_cast<char*>(&bone->m_parentIndex), sizeof(bone->m_parentIndex));
output.write(reinterpret_cast<const char*>(&bone->m_offset),
sizeof(math::matrix4x4));
}
uint32_t animCount = static_cast<uint32_t>(skeleton->m_animations.size());
output.write(reinterpret_cast<char*>(&animCount), sizeof(animCount));
for (const Animation& anim : skeleton->m_animations)
{
uint32_t animNameSize = static_cast<uint32_t>(anim.m_name.size());
output.write(reinterpret_cast<char*>(&animNameSize), sizeof(animNameSize));
output.write(anim.m_name.data(), animNameSize);
output.write(reinterpret_cast<const char*>(&anim.m_duration), sizeof(anim.m_duration));
output.write(reinterpret_cast<const char*>(&anim.m_ticksPerSecond), sizeof(anim.m_ticksPerSecond));
output.write(reinterpret_cast<const char*>(&anim.m_totalKeyFrames), sizeof(anim.m_totalKeyFrames));
output.write(reinterpret_cast<const char*>(&anim.m_isLoop), sizeof(anim.m_isLoop));
uint32_t nodeAnimCount = static_cast<uint32_t>(anim.m_nodeAnimations.size());
output.write(reinterpret_cast<char*>(&nodeAnimCount), sizeof(nodeAnimCount));
for (const auto& [nodeName, nodeAnim] : anim.m_nodeAnimations)
{
uint32_t nodeNameSize = static_cast<uint32_t>(nodeName.size());
output.write(reinterpret_cast<char*>(&nodeNameSize), sizeof(nodeNameSize));
output.write(nodeName.data(), nodeNameSize);
uint32_t posKeyCount = static_cast<uint32_t>(nodeAnim.m_positionKeys.size());
output.write(reinterpret_cast<char*>(&posKeyCount), sizeof(posKeyCount));
for (const auto& key : nodeAnim.m_positionKeys)
{
output.write(reinterpret_cast<const char*>(&key.m_position),
sizeof(math::vector4));
output.write(reinterpret_cast<const char*>(&key.m_time), sizeof(key.m_time));
}
uint32_t rotKeyCount = static_cast<uint32_t>(nodeAnim.m_rotationKeys.size());
output.write(reinterpret_cast<char*>(&rotKeyCount), sizeof(rotKeyCount));
for (const auto& key : nodeAnim.m_rotationKeys)
{
output.write(reinterpret_cast<const char*>(&key.m_rotation),
sizeof(math::quaternion));
output.write(reinterpret_cast<const char*>(&key.m_time), sizeof(key.m_time));
}
uint32_t scaleKeyCount = static_cast<uint32_t>(nodeAnim.m_scaleKeys.size());
output.write(reinterpret_cast<char*>(&scaleKeyCount), sizeof(scaleKeyCount));
for (const auto& key : nodeAnim.m_scaleKeys)
{
output.write(reinterpret_cast<const char*>(&key.m_scale),
sizeof(math::vector3));
output.write(reinterpret_cast<const char*>(&key.m_time), sizeof(key.m_time));
}
}
}
// 16바이트를 통째로 적는다. Uuid16의 배치가 boost::uuids::uuid와 같아야
// 이미 구워진 자산을 계속 읽을 수 있다 — Uuid.h의 static_assert가 지킨다.
Uuid::Uuid16 guid = animator->m_Motion.m_guid;
output.write(reinterpret_cast<const char*>(&guid), sizeof(Uuid::Uuid16));
}
const ModelLoader::CookedLoadBreakdown& ModelLoader::LastCookedLoadBreakdown() noexcept
{
return MutableCookedLoadBreakdown();
}
ModelLoader::CookedLoadBreakdown& ModelLoader::MutableCookedLoadBreakdown() noexcept
{
// 클래스 스코프 안에 둔다. 익명 namespace 에 두면 유니티 빌드에서 같은
// namespace 의 다른 TU 와 합쳐질 수 있다.
thread_local CookedLoadBreakdown breakdown{};
return breakdown;
}
void ModelLoader::LoadModelFromAsset()
{
using CookClock = std::chrono::steady_clock;
const auto elapsedMs = [](CookClock::time_point since)
{
return std::chrono::duration<double, std::milli>(
CookClock::now() - since).count();
};
CookedLoadBreakdown& breakdown = MutableCookedLoadBreakdown();
breakdown = CookedLoadBreakdown{}; // 이전 로드의 잔재를 끌고 가지 않는다
const auto entry = CookClock::now();
file::path filepath = PathFinder::Relative("Models\\") / (m_model->name + ".asset");
std::ifstream file(filepath, std::ios::binary);
if (!file)
throw std::runtime_error("model asset cache open failed: " + filepath.string());
breakdown.openMs = elapsedMs(entry);
ModelAssetFormat::FileHeader header{};
file.read(reinterpret_cast<char*>(&header), sizeof(header));
if (!file || !ModelAssetFormat::IsCurrent(header))
{
throw std::runtime_error("model asset cache format mismatch: " +
filepath.string() + " (rebuild required)");
}
uint32_t nodeCount{};
uint32_t meshCount{};
uint32_t materialCount{};
file.read(reinterpret_cast<char*>(&nodeCount), sizeof(nodeCount));
file.read(reinterpret_cast<char*>(&meshCount), sizeof(meshCount));
file.read(reinterpret_cast<char*>(&materialCount), sizeof(materialCount));
auto cursor = CookClock::now();
LoadSkeleton(file);
breakdown.skeletonMs = elapsedMs(cursor); cursor = CookClock::now();
LoadNodes(file, nodeCount);
breakdown.nodesMs = elapsedMs(cursor); cursor = CookClock::now();
LoadMesh(file, meshCount);
breakdown.meshesMs = elapsedMs(cursor); cursor = CookClock::now();
LoadMaterial(file, materialCount);
breakdown.materialsMs = elapsedMs(cursor);
if (!file)
{
throw std::runtime_error("model asset cache is truncated or invalid: " +
filepath.string());
}
breakdown.totalMs = elapsedMs(entry);
breakdown.valid = true;
}
void ModelLoader::LoadNodes(std::ifstream& infile, uint32_t size)
{
m_model->m_nodes.reserve(size);
for (uint32_t i = 0; i < size; ++i)
{
ModelNode* node{};
LoadNode(infile, node);
m_model->m_nodes.push_back(node);
}
}
void ModelLoader::LoadNode(std::ifstream& infile, ModelNode*& node)
{
uint32_t nameSize{};
infile.read(reinterpret_cast<char*>(&nameSize), sizeof(nameSize));
std::string name;
name.resize(nameSize);
infile.read(name.data(), nameSize);
node = new ModelNode(name);
infile.read(reinterpret_cast<char*>(&node->m_index), sizeof(node->m_index));
infile.read(reinterpret_cast<char*>(&node->m_parentIndex), sizeof(node->m_parentIndex));
infile.read(reinterpret_cast<char*>(&node->m_numMeshes), sizeof(node->m_numMeshes));
infile.read(reinterpret_cast<char*>(&node->m_numChildren), sizeof(node->m_numChildren));
infile.read(reinterpret_cast<char*>(&node->m_transform),
sizeof(math::matrix4x4));
node->m_meshes.resize(node->m_numMeshes);
node->m_childrenIndex.resize(node->m_numChildren);;
if (node->m_numMeshes)
{
infile.read(reinterpret_cast<char*>(node->m_meshes.data()), node->m_numMeshes * sizeof(uint32_t));
}
if (node->m_numChildren)
{
infile.read(reinterpret_cast<char*>(node->m_childrenIndex.data()), node->m_numChildren * sizeof(uint32_t));
}
}
void ModelLoader::LoadMesh(std::ifstream& infile, uint32_t size)
{
//Benchmark asset;
m_model->m_Meshes.reserve(size);
for (uint32_t i = 0; i < size; ++i)
{
uint32_t nameSize{};
infile.read(reinterpret_cast<char*>(&nameSize), sizeof(nameSize));
std::string name;
name.resize(nameSize);
infile.read(name.data(), nameSize);
auto* mesh = new Mesh();
mesh->m_name = name;
infile.read(reinterpret_cast<char*>(&mesh->m_materialIndex), sizeof(mesh->m_materialIndex));
uint32_t vertexCount{};
infile.read(reinterpret_cast<char*>(&vertexCount), sizeof(vertexCount));
mesh->m_vertices.resize(vertexCount);
if (vertexCount)
infile.read(reinterpret_cast<char*>(mesh->m_vertices.data()), vertexCount * sizeof(Vertex));
uint32_t indexCount{};
infile.read(reinterpret_cast<char*>(&indexCount), sizeof(indexCount));
mesh->m_indices.resize(indexCount);
if (indexCount)
infile.read(reinterpret_cast<char*>(mesh->m_indices.data()), indexCount * sizeof(uint32_t));
infile.read(reinterpret_cast<char*>(&mesh->m_boundingBox), sizeof(math::aabb));
infile.read(reinterpret_cast<char*>(&mesh->m_boundingSphere), sizeof(math::sphere));
mesh->AssetInit();
m_model->m_Meshes.push_back(std::shared_ptr<Mesh>(mesh));
}
//std::cout << "LoadMesh base : " << asset.GetElapsedTime() << std::endl;
}
void ModelLoader::LoadMaterial(std::ifstream& infile, uint32_t size)
{
m_model->m_Materials.reserve(size);
const bool versioned = size != 0
&& DataSystems->HasVersionedMaterialBinaryPayload(infile);
for (uint32_t i = 0; i < size; ++i)
{
auto mat = std::make_shared<Material>();
if (versioned)
{
if (!DataSystems->DeserializeMaterialBinaryPayload(*mat, infile))
{
Debug->LogError("모델 material payload v1 복원 실패: "
+ m_model->name + "[" + std::to_string(i) + "]");
infile.setstate(std::ios::failbit);
return;
}
}
else
{
if (!ReadLegacyString(infile, mat->m_name)
|| !ReadLegacyValue(infile, mat->m_materialInfo)
|| !ReadLegacyValue(infile, mat->m_renderingMode)
|| !ReadLegacyValue(infile, mat->m_fileGuid)
|| !ReadLegacyString(infile, mat->m_baseColorTexName)
|| !ReadLegacyString(infile, mat->m_normalTexName)
|| !ReadLegacyString(infile, mat->m_ORM_TexName)
|| !ReadLegacyString(infile, mat->m_AO_TexName)
|| !ReadLegacyString(infile, mat->m_EmissiveTexName))
{
Debug->LogError("legacy 모델 material payload 복원 실패: "
+ m_model->name + "[" + std::to_string(i) + "]");
infile.setstate(std::ios::failbit);
return;
}
DataSystems->FinalizeMaterialRuntime(*mat);
}
mat->ConvertToLinearSpace(true);
mat = DataSystems->RegisterImportedMaterial(mat, mat->m_name);
if (!mat)
{
infile.setstate(std::ios::failbit);
return;
}
// 텍스처 유지는 재질 시간에 섞여 있지만 **공유 비용**이라 따로 센다.
// 임포터를 바꿔도 그대로 남는 비용을 합쳐서 재면 비교가 무의미해진다.
{
const auto textureBegin = std::chrono::steady_clock::now();
RetainMaterialTextures(*mat);
MutableCookedLoadBreakdown().materialTextureMs +=
std::chrono::duration<double, std::milli>(
std::chrono::steady_clock::now() - textureBegin).count();
}
m_model->m_Materials.push_back(std::move(mat));
}
}
void ModelLoader::RetainMaterialTextures(Material& material)
{
auto retain = [this](const std::string& name,
const std::shared_ptr<Texture>& existing, bool compress)
{
std::shared_ptr<Texture> texture = existing;
if (!texture && !name.empty())
texture = DataSystems->LoadSharedMaterialTexture(name, compress);
if (!texture) return std::shared_ptr<Texture>{};
const bool alreadyRetained = std::ranges::any_of(m_model->m_Textures,
[&texture](const std::shared_ptr<Texture>& candidate)
{
return candidate.get() == texture.get();
});
if (!alreadyRetained) m_model->m_Textures.push_back(texture);
return texture;
};
material.UseBaseColorMap(retain(material.m_baseColorTexName,
material.GetBaseColorMapShared(), true));
material.UseNormalMap(retain(material.m_normalTexName,
material.GetNormalMapShared(), false));
material.UseOccRoughMetalMap(retain(material.m_ORM_TexName,
material.GetOccRoughMetalMapShared(), false));
material.UseAOMap(retain(material.m_AO_TexName,
material.GetAOMapShared(), false));
material.UseEmissiveMap(retain(material.m_EmissiveTexName,
material.GetEmissiveMapShared(), false));
}
std::shared_ptr<Texture> ModelLoader::FindTextureOwner(Texture* texture)
{
if (!texture || !m_model) return {};
std::unique_lock lock(m_modelMutex);
const auto found = std::ranges::find_if(m_model->m_Textures,
[texture](const std::shared_ptr<Texture>& candidate)
{
return candidate.get() == texture;
});
return found == m_model->m_Textures.end() ? std::shared_ptr<Texture>{} : *found;
}
void ModelLoader::LoadSkeleton(std::ifstream& infile)
{
//Benchmark asset;
bool hasSkeleton{};
infile.read(reinterpret_cast<char*>(&hasSkeleton), sizeof(hasSkeleton));
if (!hasSkeleton)
return;
Skeleton* skeleton = new Skeleton();
infile.read(reinterpret_cast<char*>(&skeleton->m_rootTransform),
sizeof(math::matrix4x4));
infile.read(reinterpret_cast<char*>(&skeleton->m_globalInverseTransform),
sizeof(math::matrix4x4));
uint32_t boneCount{};
infile.read(reinterpret_cast<char*>(&boneCount), sizeof(boneCount));
skeleton->m_bones.reserve(boneCount);
for (uint32_t i = 0; i < boneCount; ++i)
{
uint32_t nameSize{};
infile.read(reinterpret_cast<char*>(&nameSize), sizeof(nameSize));
std::string name;
name.resize(nameSize);
infile.read(name.data(), nameSize);
Bone* bone = new Bone();
bone->m_name = name;
infile.read(reinterpret_cast<char*>(&bone->m_index), sizeof(bone->m_index));
infile.read(reinterpret_cast<char*>(&bone->m_parentIndex), sizeof(bone->m_parentIndex));
infile.read(reinterpret_cast<char*>(&bone->m_offset),
sizeof(math::matrix4x4));
skeleton->m_bones.push_back(bone);
}
for (Bone* bone : skeleton->m_bones)
{
if (bone->m_parentIndex >= 0 && bone->m_parentIndex < static_cast<int>(boneCount))
{
skeleton->m_bones[bone->m_parentIndex]->m_children.push_back(bone);
}
else
{
skeleton->m_rootBone = bone;
}
}
uint32_t animCount{};
infile.read(reinterpret_cast<char*>(&animCount), sizeof(animCount));
skeleton->m_animations.reserve(animCount);
for (uint32_t i = 0; i < animCount; ++i)
{
Animation anim{};