-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDataSystem.cpp
More file actions
1324 lines (1188 loc) · 39.9 KB
/
Copy pathDataSystem.cpp
File metadata and controls
1324 lines (1188 loc) · 39.9 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 "DataSystem.h"
#include "Model.h"
#include <future>
#include <ppltasks.h>
#include <ppl.h>
#include <yaml-cpp/yaml.h>
#include "Benchmark.hpp"
// SceneManager.h가 여기 있었다. LoadAssetBundle이 씬 매니저가 들고 있던
// 스레드풀을 빌려 쓰느라 층 3이 층 4를 올려다봤다. 풀의 소유를 층 1로
// 내리면서(WorkerPool.h) 그 이유가 사라졌다 — PHASE 4-3 슬라이스 3.
#include "WorkerPool.h"
// Meta::Serialize / Deserialize. SceneManager.h가 ReflectionYml.h를 대신
// 끌어와 주던 자리다 — 빌려 쓰던 것을 직접 든다.
#include "ReflectionYml.h"
#include "ShaderMeta.h"
#include "ShaderPermutationDomain.h"
#include "StandardMaterialProperty.h"
#include <algorithm>
#include <array>
#include <cctype>
#include <istream>
#include <limits>
#include <ostream>
#include <sstream>
// 검색 함수
bool HasImageFile(const file::path& directory)
{
for (const auto& entry : file::directory_iterator(directory))
{
if (entry.is_regular_file())
{
std::string ext = entry.path().extension().string();
if (ext == ".png" || ext == ".jpg")
{
return true;
}
}
}
return false;
}
namespace
{
constexpr std::array<char, 4> kMaterialPayloadMagic{ 'C', 'E', 'M', 'T' };
constexpr std::uint16_t kMaterialPayloadVersion = 1;
constexpr std::uint16_t kMaterialPayloadYamlEncoding = 1;
constexpr std::uint32_t kMaxMaterialPayloadBytes = 4u * 1024u * 1024u;
void WriteU16(std::ostream& output, std::uint16_t value)
{
const std::array<char, 2> bytes{
static_cast<char>(value & 0xffu),
static_cast<char>((value >> 8u) & 0xffu)
};
output.write(bytes.data(), bytes.size());
}
void WriteU32(std::ostream& output, std::uint32_t value)
{
const std::array<char, 4> bytes{
static_cast<char>(value & 0xffu),
static_cast<char>((value >> 8u) & 0xffu),
static_cast<char>((value >> 16u) & 0xffu),
static_cast<char>((value >> 24u) & 0xffu)
};
output.write(bytes.data(), bytes.size());
}
bool ReadU16(std::istream& input, std::uint16_t& value)
{
std::array<unsigned char, 2> bytes{};
input.read(reinterpret_cast<char*>(bytes.data()), bytes.size());
if (!input) return false;
value = static_cast<std::uint16_t>(bytes[0])
| (static_cast<std::uint16_t>(bytes[1]) << 8u);
return true;
}
bool ReadU32(std::istream& input, std::uint32_t& value)
{
std::array<unsigned char, 4> bytes{};
input.read(reinterpret_cast<char*>(bytes.data()), bytes.size());
if (!input) return false;
value = static_cast<std::uint32_t>(bytes[0])
| (static_cast<std::uint32_t>(bytes[1]) << 8u)
| (static_cast<std::uint32_t>(bytes[2]) << 16u)
| (static_cast<std::uint32_t>(bytes[3]) << 24u);
return true;
}
std::string Lowercase(std::string value)
{
std::ranges::transform(value, value.begin(), [](unsigned char character)
{
return static_cast<char>(std::tolower(character));
});
return value;
}
RuntimeAssetType ResolveRuntimeAssetType(const file::path& path)
{
const std::string extension = Lowercase(path.extension().string());
if (extension == ".fbx" || extension == ".gltf" ||
extension == ".glb" || extension == ".obj")
{
return RuntimeAssetType::Model;
}
const std::string parent = Lowercase(path.parent_path().filename().string());
if (extension == ".asset")
{
if (parent == "models") return RuntimeAssetType::Model;
if (parent == "materials") return RuntimeAssetType::Material;
return RuntimeAssetType::CatalogOnly;
}
if (extension == ".png" || extension == ".dds" ||
extension == ".jpg" || extension == ".jpeg" || extension == ".hdr")
{
if (parent == "ui") return RuntimeAssetType::UITexture;
if (parent == "spritesheets") return RuntimeAssetType::SpriteSheet;
return RuntimeAssetType::Texture;
}
if (extension == ".shadermeta") return RuntimeAssetType::ShaderMeta;
return RuntimeAssetType::CatalogOnly;
}
file::path ResolveRuntimeAssetPath(std::string_view requestedPath,
std::string_view fallbackDirectory)
{
const file::path requested(requestedPath);
std::error_code error;
if (file::is_regular_file(requested, error) && !error) return requested;
return PathFinder::Relative(std::string(fallbackDirectory)) / requested.filename();
}
bool RegisterAssetMeta(AssetMetaRegistry& registry, const FileGuid& guid,
const file::path& path)
{
const AssetMetaRegistrationResult result = registry.Register(guid, path);
if (AssetMetaRegistrationResult::Registered == result
|| AssetMetaRegistrationResult::AlreadyRegistered == result)
{
return true;
}
std::string reason;
switch (result)
{
case AssetMetaRegistrationResult::Invalid:
reason = "invalid GUID/path";
break;
case AssetMetaRegistrationResult::GuidConflict:
reason = "GUID already maps to " + registry.GetPath(guid).string();
break;
case AssetMetaRegistrationResult::PathConflict:
reason = "path already maps to " + registry.GetGuid(path).ToString();
break;
default:
reason = "unknown registration result";
break;
}
Debug->LogError("Asset catalog rejected meta registration: guid="
+ guid.ToString() + " path=" + path.string() + " reason=" + reason);
return false;
}
}
DataSystem::~DataSystem()
{
Finalize();
}
void DataSystem::Initialize()
{
m_assetMetaRegistry = std::make_shared<AssetMetaRegistry>();
LoadAssetCatalog(PathFinder::Relative());
}
void DataSystem::Finalize()
{
Models.clear();
Textures.clear();
Materials.clear();
UITextures.clear();
SpriteSheets.clear();
m_retainedAssets.clear();
{
std::lock_guard lock(m_retiredTextureMutex);
m_retiredTextureGenerations.clear();
}
{
std::lock_guard lock(m_shaderMetaMutex);
m_shaderMetaSlotByGuid.clear();
m_shaderMetaSlots.clear();
m_shaderMetaFreeSlots.clear();
}
{
std::lock_guard lock(m_pendingAssetChangeMutex);
m_pendingAssetChanges.clear();
}
m_assetMetaRegistry.reset();
}
void DataSystem::LoadAssetCatalog(const file::path& root)
{
if (!file::exists(root)) return;
std::error_code error;
file::recursive_directory_iterator iterator(
root, file::directory_options::skip_permission_denied, error);
const file::recursive_directory_iterator end;
while (iterator != end)
{
if (error)
{
error.clear();
iterator.increment(error);
continue;
}
const file::directory_entry& entry = *iterator;
if (entry.is_regular_file(error) && !error &&
entry.path().extension() == ".meta")
{
file::path targetPath = entry.path();
targetPath.replace_extension();
if (file::exists(targetPath))
{
try
{
const YAML::Node node = YAML::LoadFile(entry.path().string());
if (node["guid"] && node["guid"].IsScalar())
{
const FileGuid guid(node["guid"].as<std::string>());
if (guid != FileGuid{})
RegisterAssetMeta(*m_assetMetaRegistry, guid, targetPath);
}
}
catch (const std::exception& exception)
{
Debug->LogWarning("Asset catalog ignored invalid meta: " +
entry.path().string() + " (" + exception.what() + ")");
}
}
}
error.clear();
iterator.increment(error);
}
}
Model* DataSystem::LoadModelGUID(FileGuid guid)
{
file::path modelPath = m_assetMetaRegistry->GetPath(guid);
std::string name = modelPath.stem().string();
{
std::unique_lock lock(m_modelMutex);
if (Models.find(name) != Models.end())
{
Debug->Log("ModelLoader::LoadModel : Model already loaded");
auto model = Models[name].get();
return model;
}
}
Model* model = Model::LoadModel(modelPath.string());
if (model)
{
{
std::unique_lock lock(m_modelMutex);
Models[name] = std::shared_ptr<Model>(model);
}
return model;
}
else
{
Debug->LogError("ModelLoader::LoadModel : Model file not found");
}
return nullptr;
}
void DataSystem::LoadModel(std::string_view filePath)
{
const file::path assetPath = ResolveRuntimeAssetPath(filePath, "Models\\");
std::string name = assetPath.stem().string();
{
std::lock_guard<std::mutex> guard(m_modelMutex);
auto iter = Models.find(name);
if (iter != Models.end() && iter->second)
{
Debug->Log("ModelLoader::LoadModel : Model already loaded");
return;
}
}
std::shared_ptr<Model> model = Model::LoadModelShared(assetPath.string());
if (model)
{
{
std::unique_lock lock(m_modelMutex);
Models[name] = model;
}
}
else
{
Debug->LogError("ModelLoader::LoadModel : Model file not found");
}
}
std::shared_ptr<Model> DataSystem::LoadCachedModelShared(std::string_view filePath)
{
const file::path assetPath = ResolveRuntimeAssetPath(filePath, "Models\\");
std::string name = assetPath.stem().string();
{
std::unique_lock lock(m_modelMutex);
if (Models.find(name) != Models.end() && Models[name].get() != nullptr)
{
Debug->Log("ModelLoader::LoadModel : Model already loaded");
return Models[name];
}
}
std::shared_ptr<Model> model{};
try
{
std::string modelPath = assetPath.string();
model = Model::LoadModelShared(modelPath);
}
catch (const std::exception& e)
{
Debug->LogError(e.what());
return {};
}
if (model)
{
{
std::unique_lock lock(m_modelMutex);
Models[name] = model;
}
return model;
}
return {};
}
Model* DataSystem::LoadCashedModel(std::string_view filePath)
{
return LoadCachedModelShared(filePath).get();
}
void DataSystem::InsertMaterial(std::shared_ptr<Material> material)
{
if (material) (void)RegisterImportedMaterial(material, material->m_name);
}
std::shared_ptr<Model> DataSystem::FindCachedModel(std::string_view name)
{
std::lock_guard<std::mutex> guard(m_modelMutex);
auto iter = Models.find(std::string(name));
return iter == Models.end() ? nullptr : iter->second;
}
std::vector<std::pair<std::string, std::shared_ptr<Model>>> DataSystem::SnapshotModels()
{
std::lock_guard<std::mutex> guard(m_modelMutex);
return { Models.begin(), Models.end() };
}
std::vector<std::pair<std::string, std::shared_ptr<Texture>>> DataSystem::SnapshotTextures()
{
std::lock_guard<std::mutex> guard(m_textureMutex);
return { Textures.begin(), Textures.end() };
}
std::shared_ptr<Material> DataSystem::FindCachedMaterial(std::string_view name)
{
std::lock_guard<std::mutex> guard(m_materialMutex);
auto iter = Materials.find(std::string(name));
return iter == Materials.end() ? nullptr : iter->second;
}
std::vector<std::pair<std::string, std::shared_ptr<Material>>> DataSystem::SnapshotMaterials()
{
std::lock_guard<std::mutex> guard(m_materialMutex);
return { Materials.begin(), Materials.end() };
}
std::shared_ptr<Material> DataSystem::RegisterImportedMaterial(
std::shared_ptr<Material> material, std::string_view baseName)
{
if (!material) return nullptr;
std::lock_guard<std::mutex> guard(m_materialMutex);
const std::string base = baseName.empty() ? material->m_name : std::string(baseName);
std::string candidate = material->m_name.empty() ? base : material->m_name;
int suffix = 1;
while (true)
{
auto iter = Materials.find(candidate);
if (iter == Materials.end() || !iter->second)
{
material->m_name = candidate;
Materials[candidate] = material;
return material;
}
if (iter->second->m_fileGuid == material->m_fileGuid)
return iter->second;
candidate = base + "(" + std::to_string(suffix++) + ")";
}
}
void DataSystem::SynchronizeLegacyMaterialProperties(Material& material) const
{
auto resolveGuid = [this](std::string_view textureName)
{
if (textureName.empty() || !m_assetMetaRegistry) return FileGuid{};
const file::path filename = file::path(textureName).filename();
const file::path materialPath = PathFinder::Relative("Materials\\") / filename;
if (const FileGuid exact = m_assetMetaRegistry->GetGuid(materialPath);
exact != FileGuid{})
{
return exact;
}
if (const FileGuid byFilename =
m_assetMetaRegistry->GetFilenameToGuid(filename.string());
byFilename != FileGuid{})
{
return byFilename;
}
return m_assetMetaRegistry->GetStemToGuid(filename.stem().string());
};
auto synchronize = [this, &material, &resolveGuid](std::string_view property,
std::string& legacyName, Texture* runtimeTexture)
{
auto value = std::find_if(material.m_propertyValues.begin(),
material.m_propertyValues.end(), [property](const MaterialPropertyValue& candidate)
{
return candidate.m_name == property;
});
FileGuid guid = value == material.m_propertyValues.end()
? FileGuid{} : value->m_textureGuid;
bool runtimeTextureSelected = false;
if (runtimeTexture && !runtimeTexture->m_name.empty())
{
runtimeTextureSelected = true;
file::path runtimeName(runtimeTexture->m_name);
if (!runtimeName.has_extension() && !runtimeTexture->m_extension.empty())
runtimeName += runtimeTexture->m_extension;
legacyName = runtimeName.filename().string();
guid = resolveGuid(legacyName);
}
else if (guid != FileGuid{} && m_assetMetaRegistry)
{
const file::path path = m_assetMetaRegistry->GetPath(guid);
if (!path.empty()) legacyName = path.filename().string();
}
else
{
guid = resolveGuid(legacyName);
}
if (guid == FileGuid{})
{
// legacy pointer API가 catalog 밖 texture로 바뀌었다면 예전 GUID를
// 남겨 두지 않는다. 이름 fallback은 보존되어 다음 load가 같은 파일을 찾는다.
if (runtimeTextureSelected && value != material.m_propertyValues.end())
value->m_textureGuid = {};
return;
}
if (value == material.m_propertyValues.end())
{
MaterialPropertyValue inserted;
inserted.m_name = std::string(property);
inserted.m_textureGuid = guid;
material.m_propertyValues.push_back(std::move(inserted));
}
else
{
value->m_textureGuid = guid;
}
};
synchronize(standard_material::property::BaseColorMap,
material.m_baseColorTexName, material.GetBaseColorMapShared().get());
synchronize(standard_material::property::NormalMap,
material.m_normalTexName, material.GetNormalMapShared().get());
synchronize(standard_material::property::OrmMap,
material.m_ORM_TexName, material.GetOccRoughMetalMapShared().get());
synchronize(standard_material::property::AoMap,
material.m_AO_TexName, material.GetAOMapShared().get());
synchronize(standard_material::property::EmissiveMap,
material.m_EmissiveTexName, material.GetEmissiveMapShared().get());
}
YAML::Node DataSystem::SerializeMaterialPayload(Material& material) const
{
SynchronizeLegacyMaterialProperties(material);
YAML::Node node = Meta::Serialize(&material);
if (material.m_cbufferValues.empty()) return node;
// unordered_map 순회 순서를 디스크 형상으로 새지 않는다. legacy CB payload도
// 이름순으로 고정해야 save-load-resave diff 0을 안정적으로 판정할 수 있다.
std::vector<std::string_view> names;
names.reserve(material.m_cbufferValues.size());
for (const auto& [name, data] : material.m_cbufferValues)
{
(void)data;
names.push_back(name);
}
std::ranges::sort(names);
YAML::Node buffers(YAML::NodeType::Sequence);
for (const std::string_view name : names)
{
const auto& data = material.m_cbufferValues.at(std::string(name));
YAML::Node entry;
entry["name"] = std::string(name);
entry["data"] = YAML::Binary(data.data(), data.size());
buffers.push_back(entry);
}
node["constant_buffers"] = buffers;
return node;
}
bool DataSystem::DeserializeMaterialPayload(Material& material, const YAML::Node& node)
{
if (!node || !node.IsMap()) return false;
try
{
Meta::Deserialize(&material, node);
material.m_cbufferValues.clear();
if (const YAML::Node buffers = node["constant_buffers"])
{
if (!buffers.IsSequence()) return false;
for (const YAML::Node& entry : buffers)
{
if (!entry.IsMap() || !entry["name"] || !entry["data"])
return false;
std::string name = entry["name"].as<std::string>();
if (name.empty() || material.m_cbufferValues.contains(name))
return false;
const YAML::Binary binary = entry["data"].as<YAML::Binary>();
material.m_cbufferValues.emplace(std::move(name),
std::vector<std::uint8_t>(binary.data(), binary.data() + binary.size()));
}
}
}
catch (const std::exception& exception)
{
Debug->LogError("Material payload deserialize failed: "
+ std::string(exception.what()));
return false;
}
FinalizeMaterialRuntime(material);
return true;
}
bool DataSystem::HasVersionedMaterialBinaryPayload(std::istream& input) const
{
const std::istream::pos_type position = input.tellg();
if (position == std::istream::pos_type(-1)) return false;
std::array<char, kMaterialPayloadMagic.size()> magic{};
input.read(magic.data(), magic.size());
const bool matches = input.gcount() == static_cast<std::streamsize>(magic.size())
&& magic == kMaterialPayloadMagic;
input.clear();
input.seekg(position);
return matches && static_cast<bool>(input);
}
bool DataSystem::SerializeMaterialBinaryPayload(Material& material,
std::ostream& output) const
{
std::ostringstream yaml;
yaml << SerializeMaterialPayload(material);
const std::string payload = yaml.str();
if (payload.size() > kMaxMaterialPayloadBytes
|| payload.size() > std::numeric_limits<std::uint32_t>::max())
{
return false;
}
output.write(kMaterialPayloadMagic.data(), kMaterialPayloadMagic.size());
WriteU16(output, kMaterialPayloadVersion);
WriteU16(output, kMaterialPayloadYamlEncoding);
WriteU32(output, static_cast<std::uint32_t>(payload.size()));
output.write(payload.data(), static_cast<std::streamsize>(payload.size()));
return output.good();
}
bool DataSystem::DeserializeMaterialBinaryPayload(Material& material,
std::istream& input)
{
std::array<char, kMaterialPayloadMagic.size()> magic{};
input.read(magic.data(), magic.size());
std::uint16_t version{};
std::uint16_t encoding{};
std::uint32_t payloadSize{};
if (!input || magic != kMaterialPayloadMagic
|| !ReadU16(input, version) || !ReadU16(input, encoding)
|| !ReadU32(input, payloadSize))
{
return false;
}
if (version != kMaterialPayloadVersion
|| encoding != kMaterialPayloadYamlEncoding
|| payloadSize > kMaxMaterialPayloadBytes)
{
return false;
}
std::string payload(payloadSize, '\0');
if (payloadSize != 0)
input.read(payload.data(), static_cast<std::streamsize>(payload.size()));
if (!input) return false;
try
{
return DeserializeMaterialPayload(material, YAML::Load(payload));
}
catch (const std::exception& exception)
{
Debug->LogError("Material binary payload decode failed: "
+ std::string(exception.what()));
return false;
}
}
void DataSystem::FinalizeMaterialRuntime(Material& material)
{
// 디스크/scene 논리 값이 바뀌면 기존 schema가 가리키는 applied generation도
// 더는 유효한 runtime 상태가 아니다. legacy CB bytes는 Configure에서 새 layout에
// repack할 입력이므로 ResetShaderRuntime은 그것을 보존한다.
material.ResetShaderRuntime();
if (0.04f > material.m_materialInfo.m_IOR || 4.f < material.m_materialInfo.m_IOR)
material.m_materialInfo.m_IOR = 1.5f;
// property GUID가 저장 정본이다. decode 대상에 남아 있을 수 있는 generic/
// Standard runtime owner를 함께 버려 낡은 generation과 이름이 새 GUID를
// 역으로 덮지 못하게 한다.
material.ResetTextureRuntime();
SynchronizeLegacyMaterialProperties(material);
auto loadTexture = [this, &material](std::string_view property,
const std::string& name, bool compress)
{
std::shared_ptr<Texture> texture;
const auto value = std::find_if(material.m_propertyValues.begin(),
material.m_propertyValues.end(), [property](const MaterialPropertyValue& candidate)
{
return candidate.m_name == property;
});
if (value != material.m_propertyValues.end()
&& value->m_textureGuid != FileGuid{})
{
const file::path path = GetFilePath(value->m_textureGuid);
if (!path.empty()) texture = LoadSharedMaterialTexture(path.string(), compress);
}
if (!texture && !name.empty())
texture = LoadSharedMaterialTexture(name, compress);
return texture;
};
material.UseBaseColorMap(loadTexture(standard_material::property::BaseColorMap,
material.m_baseColorTexName, true));
material.UseNormalMap(loadTexture(standard_material::property::NormalMap,
material.m_normalTexName, false));
material.UseOccRoughMetalMap(loadTexture(standard_material::property::OrmMap,
material.m_ORM_TexName, false));
material.UseAOMap(loadTexture(standard_material::property::AoMap,
material.m_AO_TexName, false));
material.UseEmissiveMap(loadTexture(standard_material::property::EmissiveMap,
material.m_EmissiveTexName, false));
// P2d-c: Standard 다섯 이름 밖의 texture property도 같은 GUID 경로로 owner를
// 복원한다. MaterialPropertyValue는 type tag를 중복 저장하지 않으므로 nil이
// 아닌 texture GUID만 후보로 삼고, 실제 ShaderMeta type/register 대조는 frame
// sealing과 reflection gate가 담당한다.
const auto isLegacyTextureProperty = [](std::string_view property)
{
return property == standard_material::property::BaseColorMap
|| property == standard_material::property::NormalMap
|| property == standard_material::property::OrmMap
|| property == standard_material::property::AoMap
|| property == standard_material::property::EmissiveMap;
};
for (const MaterialPropertyValue& value : material.m_propertyValues)
{
if (value.m_name.empty() || value.m_textureGuid == FileGuid{}
|| isLegacyTextureProperty(value.m_name))
{
continue;
}
const file::path path = GetFilePath(value.m_textureGuid);
if (path.empty()) continue;
material.UseTextureMap(value.m_name,
LoadSharedMaterialTexture(path.string(), false));
}
}
Material* DataSystem::LoadMaterial(std::string_view name)
{
std::string materialName(name);
// 조회와 삽입만 락으로 감싼다. 중간의 파일 로딩은 LoadMaterialTexture를 호출하는데
// 그쪽이 m_textureMutex를 잡으므로, 여기서 락을 유지하면 material→texture 순서의
// 락 중첩이 생긴다. 락을 겹치지 않게 두어 데드락 여지를 없앤다.
{
std::lock_guard<std::mutex> guard(m_materialMutex);
if (Materials.find(materialName) != Materials.end())
{
Debug->Log("MaterialLoader::LoadMaterial : Material already loaded");
return Materials[materialName].get();
}
}
file::path loadPath = PathFinder::Relative("Materials\\") / (materialName + ".asset");
if (!file::exists(loadPath))
{
return nullptr;
}
MetaYml::Node node = MetaYml::LoadFile(loadPath.string());
auto material = std::make_shared<Material>();
if (!DeserializeMaterialPayload(*material, node)) return nullptr;
// 파일 stem이 cache key의 정본이다. 내부 m_name이 낡았거나 비어 있어도
// LoadMaterialShared(name)가 같은 세대를 찾도록 게시 직전에 맞춘다.
material->m_name = materialName;
{
std::lock_guard<std::mutex> guard(m_materialMutex);
// 로딩 중 다른 스레드가 같은 머티리얼을 먼저 넣었을 수 있다.
// 그 경우 맵에 있는 쪽을 반환해 인스턴스가 갈라지지 않게 한다.
auto& slot = Materials[material->m_name];
if (!slot)
{
slot = material;
}
return slot.get();
}
}
std::shared_ptr<Material> DataSystem::LoadMaterialShared(std::string_view name)
{
// LoadMaterial이 로딩·캐시 삽입을 모두 처리하므로 그대로 태운 뒤,
// 맵에서 shared_ptr을 꺼내 돌려준다(참조 카운트를 증가시켜 공동 소유).
Material* loaded = LoadMaterial(name);
if (nullptr == loaded)
{
return nullptr;
}
std::lock_guard<std::mutex> guard(m_materialMutex);
auto it = Materials.find(loaded->m_name);
return (it != Materials.end()) ? it->second : nullptr;
}
Texture* DataSystem::LoadTextureGUID(FileGuid guid)
{
if (!m_assetMetaRegistry) return nullptr;
const file::path texturePath = m_assetMetaRegistry->GetPath(guid);
return texturePath.empty() ? nullptr : LoadTexture(texturePath.string());
}
Texture* DataSystem::LoadTexture(std::string_view filePath, TextureFileType type)
{
return LoadSharedTexture(filePath, type).get();
}
std::shared_ptr<Texture> DataSystem::LoadSharedTexture(std::string_view filePath, TextureFileType type)
{
std::string_view fallbackDirectory;
switch (type)
{
case DataSystem::TextureFileType::Texture:
fallbackDirectory = "Textures\\";
break;
case DataSystem::TextureFileType::MaterialTexture:
fallbackDirectory = "Materials\\";
break;
case DataSystem::TextureFileType::TerrainTexture:
fallbackDirectory = "Terrain\\Texture\\";
break;
case DataSystem::TextureFileType::HDR:
fallbackDirectory = "HDR\\";
break;
case DataSystem::TextureFileType::UITexture:
fallbackDirectory = "UI\\";
break;
case DataSystem::TextureFileType::SpriteSheet:
fallbackDirectory = "SpriteSheets\\";
break;
default:
break;
}
const file::path assetPath = ResolveRuntimeAssetPath(filePath, fallbackDirectory);
std::string name = assetPath.stem().string();
// 캐시 조회와 삽입만 락으로 감싼다.
// 이 함수는 LoadAssetBundle이 스레드풀로 병렬 호출하는데 예전에는 무잠금이라
// 동시 삽입 시 unordered_map 리해시와 겹쳐 힙이 손상될 수 있었다.
// 디스크 로딩은 오래 걸리므로 락 밖에서 수행한다(같은 파일을 두 번 읽는
// 낭비는 있을 수 있으나 삽입 시 정리되며, 정확성에는 문제가 없다).
{
std::lock_guard<std::mutex> guard(m_textureMutex);
if (Textures.find(name) != Textures.end())
{
Debug->Log("TextureLoader::LoadTexture : Texture already loaded");
return Textures[name];
}
}
std::shared_ptr<Texture> texture = Texture::LoadSharedFromPath(assetPath.string());
if (texture)
{
{
std::lock_guard<std::mutex> guard(m_textureMutex);
switch (type)
{
case DataSystem::TextureFileType::Texture:
Textures[name] = texture;
break;
case DataSystem::TextureFileType::UITexture:
UITextures[name] = texture;
break;
case DataSystem::TextureFileType::SpriteSheet:
SpriteSheets[name] = texture;
break;
default:
break;
}
}
texture->m_name = name;
texture->m_extension = assetPath.extension().string();
return texture;
}
else
{
Debug->LogError("ModelLoader::LoadModel : Model file not found");
}
return nullptr;
}
Texture* DataSystem::LoadMaterialTexture(std::string_view filePath, bool isCompress)
{
const file::path destination = ResolveRuntimeAssetPath(filePath, "Materials\\");
std::string name = file::path(filePath).stem().string();
{
std::unique_lock lock(m_textureMutex);
if (Textures.find(name) != Textures.end())
{
Debug->Log("TextureLoader::LoadTexture : Texture already loaded");
return Textures[name].get();
}
}
auto texture = Texture::LoadSharedFromPath(destination.string(), isCompress);
if (texture)
{
{
std::unique_lock lock(m_textureMutex);
Textures[name] = texture;
}
return texture.get();
}
else
{
Debug->LogError("ModelLoader::LoadModel : Model file not found");
}
return nullptr;
}
std::shared_ptr<Texture> DataSystem::LoadSharedMaterialTexture(std::string_view filePath, bool isCompress)
{
file::path destination = PathFinder::Relative("Materials\\") / file::path(filePath).filename();
std::string key = file::path(destination).stem().string();
// 1차 조회 (락 짧게)
{
std::unique_lock lock(m_textureMutex);
if (auto it = Textures.find(key); it != Textures.end())
return it->second; // shared_ptr 복사로 참조 증가
}
// 로드 (락 없이 I/O)
auto loaded = Texture::LoadSharedFromPath(destination.string(), isCompress);
if (!loaded)
{
Debug->LogError("TextureLoader::LoadTexture : file not found");
return nullptr;
}
// 삽입 단계: 이미 다른 스레드가 넣었을 수 있으니 '덮어쓰지 말고' 기존 걸 사용
{
std::unique_lock lock(m_textureMutex);
auto [it, inserted] = Textures.emplace(key, loaded);
if (!inserted)
{
// 누군가 먼저 넣은 경우: 그걸 사용 (중복 로드였지만 dangling 방지)
return it->second;
}
}
return loaded;
}
Material* DataSystem::CreateMaterial()
{
std::shared_ptr<Material> material = std::make_shared<Material>();
if (material)
{
std::lock_guard<std::mutex> guard(m_materialMutex);
std::string name = "NewMaterial";
int index = 1;
while (Materials.find(name) != Materials.end())
{
name = "NewMaterial" + std::to_string(index++);
}
material->m_name = name;
material->m_fileGuid = FileGuid::CreateRandomV4();
Materials[name] = material;
return material.get();
}
return nullptr;
}
// ★ LoadSFont(DirectXTK SpriteFont)를 걷었다 (D4, 2026-08-09).
// ID3D11Device로 폰트를 만들던 유일한 자리였고, 그 결과를 그리는 쪽은
// T6에서 사라졌다. 게다가 Assets/Font/ 가 비어 있어 읽을 자산도 없었다.
// 폰트는 SDF 계통으로 새로 세운다.
// ★ 콘텐츠 브라우저 UI 전체가 여기 있었다 (PHASE 4-3 슬라이스 2).
// 창 등록과 그리기 함수 일곱, 그리고 그 상태(현재 폴더·검색 필터·
// 선택 메타)가 EngineGUIWindow/ContentsBrowserWindow로 옮겨 갔다.
// 자산 시스템은 캐시와 아이콘·폰트를 가질 뿐, 이제 그리지 않는다.
FileGuid DataSystem::GetFileGuid(const file::path& filepath) const
{
return m_assetMetaRegistry ? m_assetMetaRegistry->GetGuid(filepath) : FileGuid{};
}
ShaderMetaHandle DataSystem::LoadShaderMetaHandle(FileGuid guid,
std::string& outError)
{
if (!m_assetMetaRegistry || FileGuid{} == guid)
{
outError = "ShaderMeta catalog GUID가 비었거나 catalog가 초기화되지 않았다";
return {};
}
std::lock_guard lock(m_shaderMetaMutex);
const auto cached = m_shaderMetaSlotByGuid.find(guid);
if (cached != m_shaderMetaSlotByGuid.end())
{
ShaderMetaCacheSlot& slot = m_shaderMetaSlots[cached->second];
if (slot.occupied && slot.value)
{
outError.clear();
return { cached->second + 1, slot.generation };
}
}
const file::path path = m_assetMetaRegistry->GetPath(guid);
if (path.empty())
{
outError = "ShaderMeta catalog GUID 경로를 찾지 못했다: " + guid.ToString();
return {};
}
ShaderMeta loaded;
if (!ShaderMetaLoader::LoadFile(path, guid, loaded, outError)) return {};
ShaderMetaPermutationStats stats;
if (!ShaderPermutationDomain::Measure(loaded, stats, outError)) return {};
Debug->Log("ShaderMeta loaded: " + loaded.name + " [" + guid.ToString()
+ "] variants/pass=" + std::to_string(stats.variantsPerPass)
+ ", compile requests=" + std::to_string(stats.compileRequests));