-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDataSystem.cpp
More file actions
1996 lines (1829 loc) · 68.8 KB
/
Copy pathDataSystem.cpp
File metadata and controls
1996 lines (1829 loc) · 68.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 "DataSystem.h"
#include "Experiment/Cooked/CookedAssetCatalog.h" // I7-C1 (MBC9: ExperimentModelMigration.cpp에서 이주)
#include "Assets/ModelAssetGeneration.h"
#include "Material.h" // MBC9: Model.h 전이 include가 사라져 직접 든다
#include "Mesh.h"
#include "Texture.h"
#include <fstream> // I7-C1: manifest 읽기
#include <unordered_set>
#include <future>
#include <ppltasks.h>
#include <ppl.h>
#include "AuthoringBase64.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 "AuthoringParsedDocument.h"
#include "AuthoringCookedDocument.h"
#include "SerializationProfiler.h" // D0: 부팅 catalog 파싱 기준선
#include "AuthoringNodeViewAccess.h" // D3-a-5b
#include "ShaderMeta.h"
#include "ShaderPermutationDomain.h"
#include "StandardMaterialProperty.h"
#include "Experiment/MaterialAuthoringCodec.h"
#include "ExperimentMaterialMigration.h"
#include "Assets/ModelSidecarV2.h"
#include "RHI/RHIFormat.h" // MBC7: generation embedded texture 포맷
#include <algorithm>
#include <array>
#include <cctype>
#include <chrono>
#include <istream>
#include <limits>
#include <ostream>
#include <sstream>
#include <stdexcept>
// 검색 함수
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 = 2;
constexpr std::uint16_t kMaterialPayloadCookedDocumentEncoding = 2;
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>();
const bool authoring = PathFinder::IsAssetAuthoringEnabled();
if (authoring)
{
// Editor는 source catalog가 정본이다. efsw change publication도 이 표를
// 갱신하므로 부팅 때 sidecar를 읽는 기존 계약을 유지한다.
LoadAssetCatalog(PathFinder::Relative());
}
// D5 cutover — packaged Player는 CEMF source identity table을 정본으로 삼고
// `.meta` tree를 전혀 열거하지 않는다. Editor의 optional cooked cache mount는
// source registry를 건드리지 않는다.
const auto cookedCatalogStart = std::chrono::steady_clock::now();
std::string cookedCatalogError;
const bool mounted = MountCookedCatalog(
PathFinder::Relative(), cookedCatalogError);
if (!mounted && !cookedCatalogError.empty())
{
if (!authoring)
throw std::runtime_error("Packaged cooked catalog mount failed: "
+ cookedCatalogError);
Debug->LogWarning("[cooked.catalog] 마운트 실패: " + cookedCatalogError);
}
if (!authoring)
{
if (!mounted)
throw std::runtime_error(
"Packaged cooked catalog is missing: Assets/Derived/asset-manifest.cemf");
const std::size_t sourceAssets = CookedCatalogSourceAssetCount();
if (sourceAssets == 0u)
throw std::runtime_error(
"Packaged cooked catalog has no source identity table");
const auto elapsed = std::chrono::steady_clock::now() - cookedCatalogStart;
SerializationProfile::RecordBootStage(
SerializationProfile::Stage::AssetCatalog,
static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::nanoseconds>(
elapsed).count()),
static_cast<uint64_t>(sourceAssets));
std::printf("[asset.catalog] source=cemf identities=%zu metaParsed=0\n",
sourceAssets);
}
}
void DataSystem::Finalize()
{
m_modelAssetGenerations.Clear();
{
std::lock_guard lock(m_modelGenerationTextureMutex);
m_modelGenerationTextures.clear();
m_modelGenerationTextureOwners.clear();
m_modelGenerationTextureStats = {};
}
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;
// D0(SerializationPlan §1.7 ②): 부팅 시 `.meta` 전수 파싱 비용. CLI가 프로파일러를
// 켜기 전에 이미 끝나는 구간이라 Scope가 아니라 부팅 슬롯에 직접 적재한다.
// D5-c가 이 함수를 cooked catalog로 대체할 때 대조할 기준선이다.
const auto catalogStart = std::chrono::steady_clock::now();
uint64_t parsedMetaCount = 0;
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))
{
std::string parseError;
const Authoring::ParsedDocument document =
Authoring::ParsedDocument::ParseFile(
entry.path().string(), parseError);
if (!document)
{
Debug->LogWarning("Asset catalog ignored invalid meta: " +
entry.path().string() + " (" + parseError + ")");
}
else
{
++parsedMetaCount;
const Authoring::ReadNode node = document.Root();
// MBC5 — schema-v2 model sidecar에는 legacy `guid`가 없다.
// startup catalog가 `assetId`를 읽지 않으면 MBC4가 rewrite한 scene
// ModelId를 경로로 풀 수 없어 새 generation loader에 도달하지 못한다.
const Authoring::ReadNode identity =
(node["schemaVersion"].As(0u) == assets::kModelSidecarSchemaVersion)
? node["assetId"] : node["guid"];
if (identity && identity.IsScalar())
{
const FileGuid guid(identity.AsString());
if (guid != FileGuid{})
RegisterAssetMeta(*m_assetMetaRegistry, guid, targetPath);
}
}
}
}
error.clear();
iterator.increment(error);
}
// calls는 호출 횟수가 아니라 실제로 파싱한 `.meta` 개수다 — 이 단계는 부팅 1회이므로
// 그 값을 세는 편이 판정에 쓸모 있다(회귀 게이트가 "0개를 성공으로 읽는" 것을 막는다).
const auto catalogElapsed = std::chrono::steady_clock::now() - catalogStart;
SerializationProfile::RecordBootStage(
SerializationProfile::Stage::AssetCatalog,
static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::nanoseconds>(
catalogElapsed).count()),
parsedMetaCount);
}
assets::ModelAssetGeneration::Shared DataSystem::LoadModelAssetGeneration(
FileGuid guid)
{
if (FileGuid{} == guid || !assets::IsUuidV8(guid.m_guid)) return {};
if (auto current = m_modelAssetGenerations.ResolveCurrent(guid.m_guid))
return current;
// MBC11 — cooked catalog가 마운트돼 있고 이 모델의 generation 레코드가 신선하면
// 그 레코드(Derived/Models/xx/<id>/<gen>/generation.asset)를 읽는다. Player는 이
// 경로뿐이고 Editor는 마운트 없이 Library(저작 정본)를 읽는다. 어느 쪽도 실패하면
// 다른 쪽으로 우회하지 않는다(§0.1-4 — silent fallback 0).
assets::ModelAssetGenerationLoadRequest request;
request.identityHeaderPath = PathFinder::ProjectSettingPath("AssetIdentity.asset");
request.expectedModelId = guid.m_guid;
const file::path cookedRecord = ResolveCookedArtifact(experiment::AssetId{ guid.m_guid });
const bool fromCatalog = !cookedRecord.empty()
&& cookedRecord.filename() == file::path("generation.asset");
std::string sourceLabel;
if (fromCatalog)
{
request.generationPath = cookedRecord.parent_path();
request.canonicalSidecarPath = request.generationPath / "sidecar.meta";
sourceLabel = cookedRecord.string();
}
else
{
const file::path sourcePath = GetFilePath(guid);
if (sourcePath.empty()) return {};
file::path sidecarPath = sourcePath;
sidecarPath += ".meta";
request.generationRoot = PathFinder::DynamicSolutionPath(
"Library/ModelAssetGenerations");
request.canonicalSidecarPath = sidecarPath;
sourceLabel = sourcePath.string();
}
assets::ModelAssetGenerationLoadResult loaded =
assets::LoadModelAssetGeneration(request);
if (!loaded.Succeeded())
{
m_generationLoadFailed.fetch_add(1, std::memory_order_relaxed);
const std::string detail = loaded.issues.empty()
? "알 수 없는 generation load 실패"
: loaded.issues.front().context + ": "
+ loaded.issues.front().message;
Debug->LogError(std::string("[model.generation] 게시 전 검증 실패(")
+ (fromCatalog ? "catalog" : "library") + "): " + sourceLabel
+ " (" + detail + ")");
return {};
}
(fromCatalog ? m_generationFromCatalog : m_generationFromLibrary)
.fetch_add(1, std::memory_order_relaxed);
const std::string sourcePathString = sourceLabel;
assets::ModelAssetPublishResult published =
m_modelAssetGenerations.Publish(std::move(loaded.generation));
if (!published.Succeeded())
{
Debug->LogError("[model.generation] cache publish 거부: "
+ sourcePathString + " (outcome "
+ std::to_string(static_cast<unsigned>(published.outcome)) + ")");
return {};
}
// MBC7 — 교체된 generation의 embedded texture owner는 새 generation과
// 섞이지 않는다(§6.2 "이전 texture generation 재사용 금지").
if (published.retired)
RetireModelGenerationTextures(published.retired->Handle());
return published.current;
}
namespace
{
// generation이 검증·디코드해 둔 RGBA8 subresource를 텍스처 캐시가 읽는
// 중립 CPU 이미지로 옮긴다. 두 번째 디코드는 없다 — 바이트를 옮길 뿐이다.
//
// ★ 예전에는 이 자리가 왕복이었다(축 A 전). generation 의 텍스처는 이미
// RHIFormat + raw 픽셀로 백엔드 중립인데, 그것을 DXGI_FORMAT 으로
// 되돌려 DirectX::ScratchImage 를 세웠고, Vulkan 캐시가 그 DXGI_FORMAT
// 을 다시 RHIFormat 으로 환원했다. 포맷 왕복 두 번이 순수한 어댑터
// 비용이었다 — 지금은 양쪽 어휘가 처음부터 같아 옮기기만 한다.
[[nodiscard]] TextureImage BuildGenerationCpuImage(
const assets::ModelTextureAsset& texture, std::string& outError)
{
if (RHIFormat::RGBA8Unorm != texture.format
&& RHIFormat::RGBA8UnormSrgb != texture.format)
{
outError = "generation texture 포맷이 RGBA8 계열이 아니다";
return {};
}
if (texture.isCube || 0 == texture.width || 0 == texture.height
|| 0 == texture.mipLevels || 0 == texture.arraySize
|| texture.subresources.size()
!= static_cast<std::size_t>(texture.mipLevels) * texture.arraySize)
{
outError = "generation texture descriptor와 subresource 수가 맞지 않는다";
return {};
}
TextureImage image = TextureImage::Allocate(texture.format, texture.width,
texture.height, texture.arraySize, texture.mipLevels);
if (!image.IsValid())
{
outError = "중립 CPU 이미지 초기화 실패";
return {};
}
for (std::uint32_t item = 0; item < texture.arraySize; ++item)
{
for (std::uint32_t mip = 0; mip < texture.mipLevels; ++mip)
{
// CopyTexturePixels(ModelAssetGeneration.cpp)의 적재 순서와 같다:
// item 바깥, mip 안쪽. TextureImage 도 같은 규약이다.
const assets::ModelTextureSubresource& source =
texture.subresources[static_cast<std::size_t>(item) * texture.mipLevels + mip];
const TextureSubimage* destination = image.Find(mip, item);
std::byte* destinationPixels = (nullptr != destination)
? image.MutablePixelsAt(*destination) : nullptr;
if (nullptr == destination || nullptr == destinationPixels
|| 0 == source.rowPitch
|| source.offset + source.slicePitch > texture.pixels.size()
|| destination->width != source.width
|| destination->height != source.height)
{
outError = "generation texture subresource가 이미지 기술과 어긋난다";
return {};
}
const std::uint32_t sourceRows = static_cast<std::uint32_t>(
source.slicePitch / source.rowPitch);
CopyImageRows(destinationPixels, destination->rowPitch,
texture.pixels.data() + source.offset,
static_cast<std::size_t>(source.rowPitch),
(std::min)(sourceRows, destination->height),
destination->rowPitch);
}
}
return image;
}
}
std::shared_ptr<Texture> DataSystem::ResolveModelGenerationTexture(
const assets::ModelAssetGeneration& generation, const Uuid::Uuid16& textureId)
{
const assets::ModelTextureAsset* texture = generation.FindTexture(textureId);
if (nullptr == texture) return nullptr;
const assets::ModelTextureHandle key{ textureId, generation.Identity().generation };
{
std::lock_guard lock(m_modelGenerationTextureMutex);
if (const auto found = m_modelGenerationTextures.find(key);
found != m_modelGenerationTextures.end())
{
++m_modelGenerationTextureStats.hits;
return found->second;
}
}
std::string error;
TextureImage image = BuildGenerationCpuImage(*texture, error);
std::shared_ptr<Texture> owner = image.IsValid()
? Texture::CreateSharedFromImage(texture->name, std::move(image))
: nullptr;
if (!owner)
{
std::lock_guard lock(m_modelGenerationTextureMutex);
++m_modelGenerationTextureStats.rejected;
Debug->LogError("[model.generation] embedded texture owner 생성 실패: "
+ texture->name + " (" + error + ")");
return nullptr;
}
// 큰 픽셀 복사는 잠금 밖에서 끝낸다. 동시에 준비된 경우 먼저 게시된 owner를 쓴다.
std::lock_guard lock(m_modelGenerationTextureMutex);
const auto [entry, inserted] = m_modelGenerationTextures.emplace(key, owner);
if (!inserted)
{
++m_modelGenerationTextureStats.hits;
return entry->second;
}
m_modelGenerationTextureOwners[generation.Handle()].push_back(key);
++m_modelGenerationTextureStats.created;
m_modelGenerationTextureStats.live = m_modelGenerationTextures.size();
return owner;
}
DataSystem::ModelGenerationTextureCacheSnapshot
DataSystem::SnapshotModelGenerationTextures() const
{
std::lock_guard lock(m_modelGenerationTextureMutex);
ModelGenerationTextureCacheSnapshot snapshot = m_modelGenerationTextureStats;
snapshot.live = m_modelGenerationTextures.size();
return snapshot;
}
void DataSystem::RetireModelGenerationTextures(
assets::ModelAssetGenerationHandle handle)
{
std::lock_guard lock(m_modelGenerationTextureMutex);
const auto owners = m_modelGenerationTextureOwners.find(handle);
if (owners == m_modelGenerationTextureOwners.end()) return;
for (const assets::ModelTextureHandle& key : owners->second)
{
if (0 != m_modelGenerationTextures.erase(key))
++m_modelGenerationTextureStats.retired;
}
m_modelGenerationTextureOwners.erase(owners);
m_modelGenerationTextureStats.live = m_modelGenerationTextures.size();
}
std::size_t DataSystem::BindModelGenerationTextures(Material& material,
const assets::ModelAssetGeneration& generation)
{
std::size_t bound = 0;
for (const MaterialPropertyValue& value : material.m_propertyValues)
{
if (value.m_name.empty() || FileGuid{} == value.m_textureGuid) continue;
if (nullptr == generation.FindTexture(value.m_textureGuid.m_guid)) continue;
std::shared_ptr<Texture> owner =
ResolveModelGenerationTexture(generation, value.m_textureGuid.m_guid);
if (!owner) continue;
material.UseTextureMap(value.m_name, std::move(owner));
++bound;
}
return bound;
}
assets::ModelAssetGeneration::Shared DataSystem::ResolveModelAssetGeneration(
assets::ModelAssetGenerationHandle handle) const
{
return m_modelAssetGenerations.Resolve(handle);
}
assets::ModelAssetGenerationCacheSnapshot
DataSystem::SnapshotModelAssetGenerations() const
{
return m_modelAssetGenerations.Snapshot();
}
std::vector<assets::ModelAssetGeneration::Shared>
DataSystem::SnapshotCurrentModelAssetGenerations() const
{
return m_modelAssetGenerations.SnapshotCurrent();
}
DataSystem::ModelGenerationSourceSnapshot
DataSystem::SnapshotModelGenerationSources() const noexcept
{
ModelGenerationSourceSnapshot snapshot;
snapshot.fromCatalog = m_generationFromCatalog.load(std::memory_order_relaxed);
snapshot.fromLibrary = m_generationFromLibrary.load(std::memory_order_relaxed);
snapshot.failed = m_generationLoadFailed.load(std::memory_order_relaxed);
return snapshot;
}
void DataSystem::InsertMaterial(std::shared_ptr<Material> material)
{
if (material) (void)RegisterImportedMaterial(material, material->m_name);
}
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;
// PHASE 3.75 MBC7 — UUIDv8 texture GUID는 모델 generation closure의 subasset
// 신원이다. 파일이 없으니 아래 이름 역해석(Materials\<이름>.png)은 legacy
// Assimp 추출물의 **다른 자산** v4 GUID를 되살려 신원을 덮어쓰던 자리였다
// (실측: Gunner 저장 씬의 texture GUID가 v8 → v4로 바뀌어 콜드 로드가 closure
// 를 못 찾았다). closure 신원은 이름에 지지 않고, legacy 이름 필드도 채우지
// 않는다 — 이름 폴백 자체가 §6.2가 없애는 축이다.
if (assets::IsUuidV8(guid.m_guid)) return;
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());
}
bool DataSystem::SerializeMaterialPayload(Material& material,
Authoring::WriteNode outNode) const
{
SynchronizeLegacyMaterialProperties(material);
Authoring::WriteDocument staging;
const Authoring::WriteNode node = staging.Root();
// I5-M5 S2b — writer 전환. ShaderMeta를 아는 재질은 새 정본(schema+
// shaderAssetId)으로 적는다. meta 부재 재질, legacy 전용 잔여
// (m_cbufferValues — 코퍼스 실저작 0), 변환·인코딩 실패는 legacy 표기로
// 폴백한다(조용한 소실 금지 — 폴백은 로그를 남긴다).
if (FileGuid{} != material.m_shaderMetaGuid && material.m_cbufferValues.empty())
{
std::string error;
// LoadShaderMetaHandle은 캐시 적재만 하는 논리적 const다 — 이 함수의
// const 계약(재질 형상 관찰)은 유지된다.
const ShaderMetaHandle handle = const_cast<DataSystem*>(this)
->LoadShaderMetaHandle(material.m_shaderMetaGuid, error);
if (const std::shared_ptr<const ShaderMeta> meta = ResolveShaderMeta(handle))
{
experiment::Material authored;
if (ExperimentMaterialMigration::ConvertLegacyMaterial(material,
*meta, authored, error)
&& experiment::SerializeMaterialAuthoring(authored, node,
error))
{
outNode.Assign(node);
return true;
}
}
Debug->LogWarning("Material 새 정본 writer 실패 — legacy 표기로 폴백"
" (" + material.m_name + "): " + error);
}
if (!Meta::SerializeInto(&material, node)) return false;
if (material.m_cbufferValues.empty())
{
outNode.Assign(node);
return true;
}
// 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);
const Authoring::WriteNode buffers = node.Child("constant_buffers");
buffers.SetSequence();
for (const std::string_view name : names)
{
const auto& data = material.m_cbufferValues.at(std::string(name));
const Authoring::WriteNode entry = buffers.Append();
entry.SetMap();
entry.Child("name").SetScalar(name);
entry.Child("data").SetScalar(
Authoring::Base64::Encode(data.data(), data.size()));
}
outNode.Assign(node);
return true;
}
bool DataSystem::DeserializeMaterialPayload(Material& material,
const Authoring::NodeView& view)
{
return DeserializeMaterialPayload(material, view, nullptr);
}
bool DataSystem::DeserializeMaterialPayload(Material& material,
const Authoring::NodeView& view, experiment::Material* outAuthored)
{
const Authoring::ReadNode readNode = Authoring::NodeViewAccess::Node(view);
if (!readNode || !readNode.IsMap()) return false;
// I5-M5 S1 — 읽기 이중화. 새 정본(schema + shaderAssetId)을 만나면
// experiment 코덱으로 읽고 legacy 런타임 재질로 변환한다. 런타임 소유가
// 아직 legacy인 동안(S2 이전)의 전환기 경로이며, 이름 기반 keywords는
// 실제 ShaderMeta를 로드해 인덱스로 정규화한다 — 짐작하지 않는다.
if (readNode["schema"] && readNode["shaderAssetId"])
{
experiment::Material authored;
std::string error;
if (!experiment::DeserializeMaterialAuthoring(readNode, authored, error))
{
Debug->LogError("Material 새 정본 decode 실패: " + error);
return false;
}
const ShaderMeta* metaForKeywords = nullptr;
std::shared_ptr<const ShaderMeta> metaOwner;
if (!authored.keywords.empty())
{
FileGuid shaderGuid{};
shaderGuid.m_guid = authored.shaderAssetId.value;
const ShaderMetaHandle handle =
LoadShaderMetaHandle(shaderGuid, error);
metaOwner = ResolveShaderMeta(handle);
if (!metaOwner)
{
Debug->LogError("Material 새 정본 keywords 정규화용 ShaderMeta"
" 로드 실패: " + error);
return false;
}
metaForKeywords = metaOwner.get();
}
if (!ExperimentMaterialMigration::ConvertToLegacyMaterial(authored,
metaForKeywords, material, error))
{
Debug->LogError("Material 새 정본 변환 실패: " + error);
return false;
}
FinalizeMaterialRuntime(material);
// I5-D5c1 — 저작 원본을 버리지 않는다. 여기서 놓치면 소비자는 legacy를
// 다시 experiment로 되돌리는 수밖에 없고, 그 왕복이 colorSpace·string
// property를 깎는다(변환기 헤더가 명시한 손실).
if (nullptr != outAuthored) *outAuthored = std::move(authored);
return true;
}
try
{
Meta::Deserialize(&material, readNode);
material.m_cbufferValues.clear();
if (const Authoring::ReadNode buffers = readNode["constant_buffers"])
{
if (!buffers.IsSequence()) return false;
for (const Authoring::ReadNode entry : buffers)
{
if (!entry.IsMap() || !entry["name"] || !entry["data"])
return false;
std::string name = entry["name"].AsString();
if (name.empty() || material.m_cbufferValues.contains(name))
return false;
const std::string encoded = entry["data"].AsString();
std::vector<std::uint8_t> binary;
if (!Authoring::Base64::Decode(encoded, binary)) return false;
material.m_cbufferValues.emplace(std::move(name), std::move(binary));
}
}
}
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
{
Authoring::WriteDocument document;
if (!SerializeMaterialPayload(material, document.Root())) return false;
std::vector<std::byte> payload;
std::string encodeError;
if (!Authoring::EncodeCookedDocument(document.Root().Read(), payload, encodeError))
{
Debug->LogError("Material binary payload encode failed: " + encodeError);
return false;
}
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, kMaterialPayloadCookedDocumentEncoding);
WriteU32(output, static_cast<std::uint32_t>(payload.size()));
output.write(reinterpret_cast<const char*>(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 != kMaterialPayloadCookedDocumentEncoding
|| payloadSize > kMaxMaterialPayloadBytes)
{
return false;
}
std::vector<std::byte> payload(payloadSize);
if (payloadSize != 0)
input.read(reinterpret_cast<char*>(payload.data()),
static_cast<std::streamsize>(payload.size()));
if (!input) return false;
std::string parseError;
const Authoring::ParsedDocument document =
Authoring::ParsedDocument::ParseCooked(payload, parseError);
if (!document)
{
Debug->LogError("Material binary payload decode failed: " + parseError);
return false;
}
const Authoring::ReadNode payloadNode = document.Root();
return DeserializeMaterialPayload(material,
Authoring::NodeViewAccess::Make(payloadNode));
}
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)
{
const bool srgb = property == standard_material::property::BaseColorMap
|| property == standard_material::property::EmissiveMap;
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{})