-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathModel.cpp
More file actions
396 lines (341 loc) · 10.4 KB
/
Copy pathModel.cpp
File metadata and controls
396 lines (341 loc) · 10.4 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
#include "Model.h"
#include "ModelLoader.h"
#include "ModelAssetFormat.h"
#include "Benchmark.hpp"
#include "PathFinder.h"
#include "Mesh.h"
#include "Material.h"
#include "Texture.h"
#include "ReflectionYml.h"
#include <assimp/Importer.hpp>
#include <assimp/Exporter.hpp>
#include <assimp/postprocess.h>
#include <assimp/scene.h>
#include <fstream>
#include <stdexcept>
namespace anim
{
constexpr uint32_t empty = 0;
}
Model::Model()
{
}
Model::~Model()
{
// Mesh/Material/Texture는 shared_ptr가 관리하므로 수동 해제하지 않는다.
// 다른 곳(컴포넌트·프록시)이 아직 참조 중이면 그쪽 수명이 끝날 때 해제된다.
for (auto& node : m_nodes)
{
//delete node;
delete node;
}
Memory::SafeDelete(m_animator);
if (m_Skeleton)
{
delete m_Skeleton;
}
}
namespace
{
bool HasCurrentModelAssetFormat(const file::path& assetPath)
{
std::ifstream input(assetPath, std::ios::binary);
ModelAssetFormat::FileHeader header{};
input.read(reinterpret_cast<char*>(&header), sizeof(header));
return input && ModelAssetFormat::IsCurrent(header);
}
void RequireImportSource(const file::path& sourcePath)
{
if (sourcePath.extension() == ".asset")
{
throw std::runtime_error(
"model asset cache cannot be rebuilt without its source: " +
sourcePath.string());
}
}
// .asset 캐시를 그대로 써도 되는가.
//
// 예전에는 존재 여부만 봤다. 그래서 원본(.glb/.fbx)을 다시 내보내도 캐시가
// 있으면 그것을 읽었고, 바뀐 내용이 반영되지 않았다. 증상이 고약하다 —
// 저작 도구에서 텍스처를 넣어 다시 뽑았는데 엔진에서는 재질이 계속 비어
// 있고, 파일에는 텍스처가 멀쩡히 들어 있으니 임포터를 의심하게 된다.
// 실제로 그 길로 한참 갔다.
//
// 원본이 캐시보다 새것이면 캐시를 버린다. 원본이 없으면(.asset만 배포된
// 경우) 캐시가 유일한 진실이므로 그대로 쓴다.
bool IsModelAssetUsable(const file::path& sourcePath, const file::path& assetPath)
{
std::error_code errorCode;
if (!file::exists(assetPath, errorCode)) return false;
if (!HasCurrentModelAssetFormat(assetPath))
{
Debug->LogWarning("[임포터] 모델 캐시 포맷이 오래되어 다시 임포트한다: "
+ assetPath.filename().string());
return false;
}
if (!file::exists(sourcePath, errorCode)) return true;
if (sourcePath == assetPath) return true;
const auto assetTime = file::last_write_time(assetPath, errorCode);
if (errorCode) return true;
const auto sourceTime = file::last_write_time(sourcePath, errorCode);
if (errorCode) return true;
if (sourceTime <= assetTime) return true;
Debug->LogWarning("[임포터] 원본이 캐시보다 새것이라 다시 임포트한다: "
+ sourcePath.filename().string());
return false;
}
}
Model* Model::LoadModel(std::string_view filePath)
{
file::path path_ = filePath.data();
Model* model{};
try
{
file::path assetPath = filePath.data();
assetPath = assetPath.replace_extension(".asset");
if (IsModelAssetUsable(path_, assetPath))
{
Benchmark asset;
ModelLoader loader = ModelLoader(nullptr, assetPath.string());
model = loader.LoadModel();
model->path = path_;
model->m_numTotalMeshes = static_cast<int>(model->m_Meshes.size());
std::cout << asset.GetElapsedTime() << " ms to load model from asset file: " << assetPath.string() << std::endl;
return model;
}
else
{
RequireImportSource(path_);
Benchmark assimp;
flag settings = aiProcess_LimitBoneWeights
| aiProcessPreset_TargetRealtime_Fast
| aiProcess_ConvertToLeftHanded
| aiProcess_TransformUVCoords
| aiProcess_GenBoundingBoxes;
bool isCreateMeshCollider{ false };
file::path metaPath = path_.string() + ".meta";
if (file::exists(metaPath))
{
auto node = MetaYml::LoadFile(metaPath.string());
if (node["ModelImporter"])
{
const MetaYml::Node& modelImporterNode = node["ModelImporter"];
if (modelImporterNode)
{
if (modelImporterNode["OptimizeMeshes"] && modelImporterNode["OptimizeMeshes"].as<bool>())
{
settings |= aiProcess_OptimizeMeshes;
}
if (modelImporterNode["ImproveCacheLocality"] && modelImporterNode["ImproveCacheLocality"].as<bool>())
{
settings |= aiProcess_ImproveCacheLocality;
}
if (modelImporterNode["CreateMeshCollider"])
{
isCreateMeshCollider = modelImporterNode["CreateMeshCollider"].as<bool>();
}
}
}
else
{
settings |= aiProcess_OptimizeMeshes;
settings |= aiProcess_ImproveCacheLocality;
}
}
Assimp::Importer importer;
Assimp::Exporter exproter;
importer.SetPropertyBool(AI_CONFIG_IMPORT_FBX_PRESERVE_PIVOTS, false);
importer.SetPropertyInteger(AI_CONFIG_PP_LBW_MAX_WEIGHTS, 4);
const aiScene* assimpScene = importer.ReadFile(filePath.data(), settings);
if (nullptr == assimpScene)
{
throw std::exception("ModelLoader::Model file not found");
}
if (anim::empty == assimpScene->mNumAnimations)
{
importer.ApplyPostProcessing(aiProcess_PreTransformVertices);
importer.ApplyPostProcessing(aiProcess_GenBoundingBoxes);
}
ModelLoader loader = ModelLoader(assimpScene, path_.string());
model = loader.LoadModel(isCreateMeshCollider);
model->path = path_;
model->m_numTotalMeshes = static_cast<int>(model->m_Meshes.size());
std::cout << assimp.GetElapsedTime() << " ms to load model from assimp file: " << path_.string() << std::endl;
return model;
}
}
catch (const std::exception& e)
{
Debug->Log(e.what());
return nullptr;
}
}
std::shared_ptr<Model> Model::LoadModelShared(std::string_view filePath)
{
file::path path_ = filePath.data();
std::shared_ptr<Model> model{};
try
{
file::path assetPath = filePath.data();
assetPath = assetPath.replace_extension(".asset");
if (IsModelAssetUsable(path_, assetPath))
{
//Benchmark asset;
ModelLoader loader = ModelLoader(nullptr, assetPath.string());
model = std::shared_ptr<Model>(loader.LoadModel());
model->path = path_;
model->m_numTotalMeshes = static_cast<int>(model->m_Meshes.size());
//std::cout << asset.GetElapsedTime() << " ms to load model from asset file: " << assetPath.string() << std::endl;
return model;
}
else
{
RequireImportSource(path_);
//Benchmark assimp;
flag settings = aiProcess_LimitBoneWeights
| aiProcessPreset_TargetRealtime_Fast
| aiProcess_ConvertToLeftHanded
| aiProcess_TransformUVCoords
| aiProcess_GenBoundingBoxes;
bool isCreateMeshCollider{ false };
file::path metaPath = path_.string() + ".meta";
if (file::exists(metaPath))
{
auto node = MetaYml::LoadFile(metaPath.string());
if (node["ModelImporter"])
{
const MetaYml::Node& modelImporterNode = node["ModelImporter"];
if (modelImporterNode)
{
if (modelImporterNode["OptimizeMeshes"] && modelImporterNode["OptimizeMeshes"].as<bool>())
{
settings |= aiProcess_OptimizeMeshes;
}
if (modelImporterNode["ImproveCacheLocality"] && modelImporterNode["ImproveCacheLocality"].as<bool>())
{
settings |= aiProcess_ImproveCacheLocality;
}
if (modelImporterNode["CreateMeshCollider"])
{
isCreateMeshCollider = modelImporterNode["CreateMeshCollider"].as<bool>();
}
}
}
else
{
settings |= aiProcess_OptimizeMeshes;
settings |= aiProcess_ImproveCacheLocality;
}
}
Assimp::Importer importer;
Assimp::Exporter exproter;
importer.SetPropertyBool(AI_CONFIG_IMPORT_FBX_PRESERVE_PIVOTS, false);
importer.SetPropertyInteger(AI_CONFIG_PP_LBW_MAX_WEIGHTS, 4);
const aiScene* assimpScene = importer.ReadFile(filePath.data(), settings);
if (nullptr == assimpScene)
{
throw std::exception("ModelLoader::Model file not found");
}
if (anim::empty == assimpScene->mNumAnimations)
{
importer.ApplyPostProcessing(aiProcess_PreTransformVertices);
importer.ApplyPostProcessing(aiProcess_GenBoundingBoxes);
}
ModelLoader loader = ModelLoader(assimpScene, path_.string());
model = std::shared_ptr<Model>(loader.LoadModel(isCreateMeshCollider));
model->path = path_;
model->m_numTotalMeshes = static_cast<int>(model->m_Meshes.size());
//std::cout << assimp.GetElapsedTime() << " ms to load model from assimp file: " << path_.string() << std::endl;
return model;
}
}
catch (const std::exception& e)
{
Debug->Log(e.what());
return nullptr;
}
}
// ── 소유권을 공유하는 조회 ──
// 참조를 보관하는 쪽(컴포넌트·프록시)은 이쪽을 써야 에셋 언로드에 안전하다.
std::shared_ptr<Mesh> Model::GetMeshShared(std::string_view name)
{
std::string meshName = name.data();
for (auto& mesh : m_Meshes)
{
if (mesh && mesh->GetName() == meshName)
{
return mesh;
}
}
return nullptr;
}
std::shared_ptr<Mesh> Model::GetMeshShared(int index)
{
if (index < 0 || index >= m_Meshes.size())
{
return nullptr;
}
return m_Meshes[index];
}
std::shared_ptr<Material> Model::GetMaterialShared(std::string_view name)
{
std::string materialName = name.data();
for (auto& material : m_Materials)
{
if (material && material->m_name == materialName)
{
return material;
}
}
return nullptr;
}
std::shared_ptr<Material> Model::GetMaterialShared(int index)
{
if (index < 0 || index >= m_Materials.size())
{
return nullptr;
}
return m_Materials[index];
}
std::shared_ptr<Texture> Model::GetTextureShared(int index)
{
if (index < 0 || index >= m_Textures.size())
{
return nullptr;
}
return m_Textures[index];
}
// ── 원시 포인터 조회 (기존 호출부 호환) ──
// Model이 살아 있는 동안에만 유효하다.
Mesh* Model::GetMesh(std::string_view name)
{
return GetMeshShared(name).get();
}
Mesh* Model::GetMesh(int index)
{
return GetMeshShared(index).get();
}
Material* Model::GetMaterial(std::string_view name)
{
return GetMaterialShared(name).get();
}
Material* Model::GetMaterial(int index)
{
return GetMaterialShared(index).get();
}
Texture* Model::GetTexture(std::string_view name)
{
std::string textureName = name.data();
for (auto& texture : m_Textures)
{
if (texture && texture->m_name == textureName)
{
return texture.get();
}
}
return nullptr;
}
Texture* Model::GetTexture(int index)
{
return GetTextureShared(index).get();
}