-
Notifications
You must be signed in to change notification settings - Fork 52
/
ResourceManager.cpp
3723 lines (3136 loc) · 110 KB
/
ResourceManager.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "stdafx.hpp"
#include "ResourceManager.hpp"
IGNORE_WARNINGS_PUSH
#if COMPILE_IMGUI
#include "imgui_internal.h" // for columns API
#endif
#include <ft2build.h>
#include FT_FREETYPE_H
#include <freetype/fttypes.h>
#include <freetype/fterrors.h>
IGNORE_WARNINGS_POP
#include "Graphics/RendererTypes.hpp"
#include "Graphics/Renderer.hpp"
#include "Cameras/BaseCamera.hpp"
#include "Cameras/CameraManager.hpp"
#include "Editor.hpp"
#include "FlexEngine.hpp"
#include "InputManager.hpp"
#include "JSONParser.hpp"
#include "Platform/Platform.hpp"
#include "Particles.hpp"
#include "Player.hpp"
#include "Scene/GameObject.hpp"
#include "Scene/LoadedMesh.hpp"
#include "Scene/Mesh.hpp"
#include "Scene/MeshComponent.hpp"
#include "Scene/SceneManager.hpp"
#include "Scene/BaseScene.hpp"
#include "StringBuilder.hpp"
#include "Window/Monitor.hpp"
#include "Window/Window.hpp"
namespace flex
{
// TODO: Support DDS
const char* ResourceManager::s_SupportedTextureFormats[] = { "jpg", "jpeg", "png", "tga", "bmp", "gif", "hdr", "pic" };
ResourceManager::ResourceManager() :
m_FontsFilePathAbs(RelativePathToAbsolute(FONT_DEFINITION_LOCATION))
{
}
ResourceManager::~ResourceManager()
{
}
void ResourceManager::Initialize()
{
PROFILE_AUTO("ResourceManager Initialize");
m_AudioDirectoryWatcher = new DirectoryWatcher(SFX_DIRECTORY, false);
m_PrefabDirectoryWatcher = new DirectoryWatcher(PREFAB_DIRECTORY, false);
m_MeshDirectoryWatcher = new DirectoryWatcher(MESH_DIRECTORY, false);
m_TextureDirectoryWatcher = new DirectoryWatcher(TEXTURE_DIRECTORY, true);
DiscoverTextures();
DiscoverAudioFiles();
ParseDebugOverlayNamesFile();
ParseGameObjectTypesFile();
DiscoverParticleParameterTypes();
DiscoverParticleSystemTemplates();
m_NonDefaultStackSizes[SID("battery")] = 1;
}
void ResourceManager::PostInitialize()
{
PROFILE_AUTO("ResourceManager PostInitialize");
tofuIconID = GetOrLoadTexture(ICON_DIRECTORY "tofu-icon-256.png");
}
void ResourceManager::Update()
{
PROFILE_AUTO("ResourceManager Update");
if (m_AudioRefreshFrameCountdown != -1)
{
--m_AudioRefreshFrameCountdown;
if (m_AudioRefreshFrameCountdown <= -1)
{
m_AudioRefreshFrameCountdown = -1;
DiscoverAudioFiles();
}
}
if (m_AudioDirectoryWatcher->Update())
{
// Delay discovery to allow temporary files to be resolved.
// Audacity for example, when replacing an existing file "file.wav", will
// first write to "file0.wav", then delete "file.wav", then rename "file0.wav"
// to "file.wav". This delay prevents us from trying to load the temporary file.
m_AudioRefreshFrameCountdown = 1;
}
if (m_PrefabDirectoryWatcher->Update())
{
DiscoverPrefabs();
}
if (m_MeshDirectoryWatcher->Update())
{
DiscoverMeshes();
}
if (m_TextureDirectoryWatcher->Update())
{
DiscoverTextures();
}
{
const std::lock_guard<std::mutex> lock(m_QueuedTextureLoadInfoMutex);
if (!m_QueuedTextureLoadInfos.empty())
{
// TODO: Kick off at other points in the frame?
auto iter = m_QueuedTextureLoadInfos.begin();
while (iter != m_QueuedTextureLoadInfos.end())
{
TextureID textureID = iter->first;
TextureLoadInfo& loadInfo = iter->second;
bool bIsLoading = loadedTextures[textureID]->IsLoading();
if (bIsLoading)
{
++iter;
continue;
}
Texture* texture = GetLoadedTexture(textureID, false);
u64 newTexSize = texture->Create(loadInfo.bGenerateMipMaps);
Print("[TEXTURE] Created texture: %s\n", loadInfo.relativeFilePath.c_str());
if (newTexSize == 0)
{
delete texture;
++iter;
continue;
}
iter = m_QueuedTextureLoadInfos.erase(iter);
}
}
}
}
void ResourceManager::Destroy()
{
delete m_AudioDirectoryWatcher;
m_AudioDirectoryWatcher = nullptr;
delete m_PrefabDirectoryWatcher;
m_PrefabDirectoryWatcher = nullptr;
delete m_MeshDirectoryWatcher;
m_MeshDirectoryWatcher = nullptr;
delete m_TextureDirectoryWatcher;
m_TextureDirectoryWatcher = nullptr;
for (BitmapFont* font : fontsScreenSpace)
{
delete font;
}
fontsScreenSpace.clear();
for (BitmapFont* font : fontsWorldSpace)
{
delete font;
}
fontsWorldSpace.clear();
{
FLEX_MUTEX_LOCK(m_LoadedTexturesMutex);
for (Texture* loadedTexture : loadedTextures)
{
delete loadedTexture;
}
loadedTextures.clear();
}
for (PrefabTemplateInfo& prefabTemplateInfo : prefabTemplates)
{
prefabTemplateInfo.templateObject->Destroy();
delete prefabTemplateInfo.templateObject;
}
prefabTemplates.clear();
JobSystem::Wait(m_TextureLoadingContext);
}
void ResourceManager::DestroyAllLoadedMeshes()
{
for (auto& loadedMeshPair : loadedMeshes)
{
cgltf_free(loadedMeshPair.second->data);
delete loadedMeshPair.second;
}
loadedMeshes.clear();
}
void ResourceManager::PreSceneChange()
{
for (PrefabTemplateInfo& prefabTemplateInfo : prefabTemplates)
{
prefabTemplateInfo.templateObject->Destroy();
delete prefabTemplateInfo.templateObject;
}
prefabTemplates.clear();
}
void ResourceManager::OnSceneChanged()
{
DiscoverMeshes();
}
bool ResourceManager::FindPreLoadedMesh(const std::string& relativeFilePath, LoadedMesh** loadedMesh)
{
auto iter = loadedMeshes.find(relativeFilePath);
if (iter == loadedMeshes.end())
{
return false;
}
else
{
*loadedMesh = iter->second;
return true;
}
}
LoadedMesh* ResourceManager::FindOrLoadMesh(const std::string& relativeFilePath, bool bForceReload /* = false */)
{
LoadedMesh* result = nullptr;
if (bForceReload || !FindPreLoadedMesh(relativeFilePath, &result))
{
// Mesh hasn't been loaded before, load it now
result = Mesh::LoadMesh(relativeFilePath);
}
return result;
}
bool ResourceManager::MeshFileNameConforms(const std::string& fileName)
{
return EndsWith(fileName, "glb") || EndsWith(fileName, "gltf");
}
void ResourceManager::ParseMeshJSON(i32 sceneFileVersion, GameObject* parent, const JSONObject& meshObj, const std::vector<MaterialID>& materialIDs, bool bCreateRenderObject)
{
std::string meshFilePath;
if (meshObj.TryGetString("mesh", meshFilePath))
{
if (sceneFileVersion >= 4)
{
meshFilePath = MESH_DIRECTORY + meshFilePath;
}
else
{
// "file" field stored mesh name without extension in versions <= 3, try to guess it
bool bMatched = false;
for (const std::string& path : discoveredMeshes)
{
std::string discoveredMeshName = StripFileType(path);
if (discoveredMeshName.compare(meshFilePath) == 0)
{
meshFilePath = MESH_DIRECTORY + path;
bMatched = true;
break;
}
}
if (!bMatched)
{
std::string glbFilePath = MESH_DIRECTORY + meshFilePath + ".glb";
std::string gltfFilePath = MESH_DIRECTORY + meshFilePath + ".gltf";
if (FileExists(glbFilePath))
{
meshFilePath = glbFilePath;
}
else if (FileExists(glbFilePath))
{
meshFilePath = gltfFilePath;
}
}
if (!FileExists(meshFilePath))
{
PrintError("Failed to upgrade scene file, unable to find path of mesh with name %s\n", meshFilePath.c_str());
return;
}
}
Mesh::ImportFromFile(meshFilePath, parent, materialIDs, bCreateRenderObject);
return;
}
std::string prefabName;
if (meshObj.TryGetString("prefab", prefabName))
{
Mesh::ImportFromPrefab(prefabName, parent, materialIDs, bCreateRenderObject);
return;
}
}
JSONField ResourceManager::SerializeMesh(Mesh* mesh)
{
JSONField meshObject = {};
switch (mesh->GetType())
{
case Mesh::Type::FILE:
{
const size_t prefixLen = strlen(MESH_DIRECTORY);
std::string meshFilepath = mesh->GetRelativeFilePath();
meshFilepath = meshFilepath.substr(prefixLen);
meshObject = JSONField("mesh", JSONValue(meshFilepath));
} break;
case Mesh::Type::PREFAB:
{
std::string prefabShapeStr = MeshComponent::PrefabShapeToString(mesh->GetSubMesh(0)->GetShape());
meshObject = JSONField("prefab", JSONValue(prefabShapeStr));
} break;
default:
{
PrintError("Unhandled mesh prefab type when attempting to serialize scene!\n");
} break;
}
return meshObject;
}
void ResourceManager::DiscoverMeshes()
{
std::vector<std::string> filePaths;
if (Platform::FindFilesInDirectory(MESH_DIRECTORY, filePaths, "*"))
{
i32 modifiedFileCount = 0;
for (const std::string& filePath : filePaths)
{
std::string fileName = StripLeadingDirectories(filePath);
if (MeshFileNameConforms(filePath))
{
if (Contains(discoveredMeshes, fileName))
{
// Existing mesh
if (Contains(m_MeshDirectoryWatcher->modifiedFilePaths, filePath))
{
// File has been modified, update all usages
g_SceneManager->CurrentScene()->OnExternalMeshChange(filePath);
++modifiedFileCount;
}
}
else
{
// Newly discovered mesh
// TODO: Support storing meshes in child directories
discoveredMeshes.push_back(fileName);
}
}
}
if (modifiedFileCount > 0)
{
Print("Found and re-imported %d modified mesh%s\n", modifiedFileCount, modifiedFileCount > 1 ? "es" : "");
}
}
}
bool ParsePrefabTemplate(const std::string& filePath, std::map<PrefabID, std::string>& prefabNames, std::vector<ResourceManager::PrefabTemplateInfo>& templateInfos)
{
JSONObject prefabObject;
if (JSONParser::ParseFromFile(filePath, prefabObject))
{
const std::string fileName = StripLeadingDirectories(filePath);
i32 prefabVersion = prefabObject.GetInt("version");
i32 sceneVersion = 6;
// Added in prefab v3, older files use scene version 6
prefabObject.TryGetInt("scene version", sceneVersion);
PrefabID prefabID;
if (prefabVersion >= 2)
{
// Added in prefab v2
std::string idStr = prefabObject.GetString("prefab id");
prefabID = GUID::FromString(idStr);
}
else
{
prefabID = Platform::GenerateGUID();
}
std::string prefabName = StripFileType(fileName);
prefabNames.emplace(prefabID, prefabName);
JSONObject prefabRootObject = prefabObject.GetObject("root");
using CopyFlags = GameObject::CopyFlags;
CopyFlags copyFlags = (CopyFlags)(
(u32)CopyFlags::ALL &
~(u32)CopyFlags::CREATE_RENDER_OBJECT &
~(u32)CopyFlags::ADD_TO_SCENE);
PrefabIDPair prefabIDPair;
prefabIDPair.m_PrefabID = prefabID;
prefabIDPair.m_SubGameObjectID = prefabRootObject.GetGameObjectID("id");
GameObject* prefabTemplate = GameObject::CreateObjectFromJSON(prefabRootObject, nullptr, sceneVersion, prefabIDPair, true, copyFlags);
CHECK(prefabTemplate->IsPrefabTemplate());
templateInfos.emplace_back(prefabTemplate, prefabID, fileName);
}
else
{
PrintError("Failed to parse prefab file: %s, error: %s\n", filePath.c_str(), JSONParser::GetErrorString());
return false;
}
return true;
}
void ResourceManager::DiscoverPrefabs()
{
for (PrefabTemplateInfo& prefabTemplateInfo : prefabTemplates)
{
prefabTemplateInfo.templateObject->Destroy();
delete prefabTemplateInfo.templateObject;
}
prefabTemplates.clear();
discoveredPrefabs.clear();
std::vector<std::string> foundFiles;
if (Platform::FindFilesInDirectory(PREFAB_DIRECTORY, foundFiles, ".json"))
{
for (const std::string& foundFilePath : foundFiles)
{
if (g_bEnableLogging_Loading)
{
const std::string fileName = StripLeadingDirectories(foundFilePath);
Print("Parsing prefab: %s\n", fileName.c_str());
}
ParsePrefabTemplate(foundFilePath, discoveredPrefabs, prefabTemplates);
}
}
else
{
PrintError("Failed to find prefab files in \"" PREFAB_DIRECTORY "\"!\n");
return;
}
if (g_bEnableLogging_Loading)
{
Print("Parsed %u prefabs\n", (u32)prefabTemplates.size());
}
}
void ResourceManager::DiscoverAudioFiles()
{
std::map<StringID, AudioFileMetaData> newDiscoveredAudioFiles;
i32 modifiedCount = 0;
i32 addedCount = 0;
i32 removedCount = 0;
StringBuilder errorStringBuilder;
std::vector<std::string> foundFiles;
if (Platform::FindFilesInDirectory(SFX_DIRECTORY, foundFiles, ".wav"))
{
for (std::string& foundFilePath : foundFiles)
{
std::string relativeFilePath = foundFilePath.substr(strlen(SFX_DIRECTORY));
StringID stringID = SID(relativeFilePath.c_str());
AudioFileMetaData metaData(relativeFilePath);
auto iter = discoveredAudioFiles.find(stringID);
if (iter != discoveredAudioFiles.end())
{
// Existing file
auto modifiedIter = std::find(m_AudioDirectoryWatcher->modifiedFilePaths.begin(), m_AudioDirectoryWatcher->modifiedFilePaths.end(), foundFilePath);
if (modifiedIter != m_AudioDirectoryWatcher->modifiedFilePaths.end())
{
++modifiedCount;
if (iter->second.sourceID != InvalidAudioSourceID)
{
// Reload existing audio file if already loaded, it's out of date
errorStringBuilder.Clear();
if (AudioManager::ReplaceAudioSource(foundFilePath, iter->second.sourceID, &errorStringBuilder) != InvalidAudioSourceID)
{
metaData.bInvalid = false;
}
else
{
// Failed to replace
metaData.bInvalid = true;
newDiscoveredAudioFiles.emplace(stringID, metaData);
continue;
}
}
}
metaData.sourceID = discoveredAudioFiles[stringID].sourceID;
}
else
{
// Newly discovered file
++addedCount;
}
newDiscoveredAudioFiles.emplace(stringID, metaData);
}
}
removedCount = (i32)discoveredAudioFiles.size() - (i32)(newDiscoveredAudioFiles.size() - addedCount);
discoveredAudioFiles.clear();
discoveredAudioFiles = newDiscoveredAudioFiles;
if (g_bEnableLogging_Loading)
{
if (modifiedCount != 0)
{
Print("%d audio file%s modified\n", modifiedCount, modifiedCount > 1 ? "s" : "");
}
if (addedCount != 0)
{
Print("%d audio file%s added\n", addedCount, addedCount > 1 ? "s" : "");
}
if (removedCount != 0)
{
Print("%d audio file%s removed\n", removedCount, removedCount > 1 ? "s" : "");
}
}
}
void ResourceManager::DiscoverTextures()
{
{
discoveredTextures.clear();
// Zeroth index represents no texture
discoveredTextures.emplace_back("");
std::vector<std::string> foundFiles;
if (Platform::FindFilesInDirectory(TEXTURE_DIRECTORY, foundFiles, s_SupportedTextureFormats, ARRAY_LENGTH(s_SupportedTextureFormats)))
{
for (const std::string& foundFilePath : foundFiles)
{
discoveredTextures.push_back(foundFilePath);
}
if (g_bEnableLogging_Loading)
{
Print("Discovered %u textures\n", (u32)(discoveredTextures.size() - 1));
}
}
else
{
PrintError("Failed to find texture files in \"" TEXTURE_DIRECTORY "\"!\n");
return;
}
}
{
discoveredIcons.clear();
std::vector<std::string> foundIconFiles;
if (Platform::FindFilesInDirectory(ICON_DIRECTORY, foundIconFiles, s_SupportedTextureFormats, ARRAY_LENGTH(s_SupportedTextureFormats), true))
{
for (const std::string& foundFilePath : foundIconFiles)
{
std::string trimmedFileName = RelativePathToAbsolute(foundFilePath);
trimmedFileName = StripLeadingDirectories(StripFileType(foundFilePath));
i32 resolution = 0;
size_t iconEnd = trimmedFileName.find_last_of("-icon-");
if (iconEnd != std::string::npos)
{
resolution = ParseInt(trimmedFileName.substr(iconEnd + 1));
trimmedFileName = trimmedFileName.substr(0, iconEnd - 6 + 1);
}
trimmedFileName = Replace(trimmedFileName, '-', ' ');
StringID prefabNameSID = Hash(trimmedFileName.c_str());
IconMetaData iconMetaData = {};
iconMetaData.relativeFilePath = foundFilePath;
iconMetaData.resolution = resolution;
discoveredIcons.emplace_back(prefabNameSID, iconMetaData);
}
}
}
// Check for modified files to reload
{
std::vector<std::string> foundFiles;
if (Platform::FindFilesInDirectory(TEXTURE_DIRECTORY, foundFiles, s_SupportedTextureFormats, ARRAY_LENGTH(s_SupportedTextureFormats), true))
{
FLEX_MUTEX_LOCK(m_LoadedTexturesMutex);
i32 modifiedTextureCount = 0;
for (const std::string& foundFilePath : foundFiles)
{
if (Contains(m_TextureDirectoryWatcher->modifiedFilePaths, foundFilePath))
{
for (Texture* texture : loadedTextures)
{
// File has been modified externally, reload its contents
if (texture != nullptr &&
texture->relativeFilePath == foundFilePath)
{
texture->Reload();
++modifiedTextureCount;
}
}
}
}
if (modifiedTextureCount > 0)
{
Print("Found and re-imported %d modified texture%s\n", modifiedTextureCount, modifiedTextureCount > 1 ? "s" : "");
}
}
}
}
void ResourceManager::DiscoverParticleSystemTemplates()
{
m_ParticleTemplates.clear();
std::string absoluteDirectory = RelativePathToAbsolute(PARTICLE_SYSTEMS_DIRECTORY);
if (Platform::DirectoryExists(absoluteDirectory))
{
std::vector<std::string> filePaths;
if (Platform::FindFilesInDirectory(absoluteDirectory, filePaths, ".json"))
{
for (const std::string& filePath : filePaths)
{
std::string fileName = StripLeadingDirectories(StripFileType(filePath));
ParticleSystemTemplate particleTemplate = {};
particleTemplate.filePath = filePath;
particleTemplate.nameSID = SID(fileName.c_str());
if (!ParticleParameters::Deserialize(filePath, particleTemplate.params))
{
PrintError("Failed to read particle parameters file at %s\n", filePath.c_str());
continue;
}
m_ParticleTemplates.emplace(particleTemplate.nameSID, particleTemplate);
}
}
}
}
void ResourceManager::SerializeAllParticleSystemTemplates()
{
for (auto& pair : m_ParticleTemplates)
{
ParticleParameters::Serialize(pair.second.filePath, pair.second.params);
}
}
void ResourceManager::ParseGameObjectTypesFile()
{
gameObjectTypeStringIDPairs.clear();
std::string fileContents;
// TODO: Gather this info from reflection?
if (ReadFile(GAME_OBJECT_TYPES_LOCATION, fileContents, false))
{
std::vector<std::string> lines = Split(fileContents, '\n');
for (const std::string& line : lines)
{
if (!line.empty())
{
const char* lineCStr = line.c_str();
StringID typeID = Hash(lineCStr);
if (gameObjectTypeStringIDPairs.find(typeID) != gameObjectTypeStringIDPairs.end())
{
PrintError("Game Object Type hash collision on %s!\n", lineCStr);
}
gameObjectTypeStringIDPairs.emplace(typeID, line);
}
}
}
else
{
PrintError("Failed to read game object types file from %s!\n", GAME_OBJECT_TYPES_LOCATION);
}
}
void ResourceManager::SerializeGameObjectTypesFile()
{
StringBuilder fileContents;
for (auto iter = gameObjectTypeStringIDPairs.begin(); iter != gameObjectTypeStringIDPairs.end(); ++iter)
{
fileContents.AppendLine(iter->second);
}
if (!WriteFile(GAME_OBJECT_TYPES_LOCATION, fileContents.ToString(), false))
{
PrintError("Failed to write game object types file to %s\n", GAME_OBJECT_TYPES_LOCATION);
}
}
const char* ResourceManager::TypeIDToString(StringID typeID)
{
for (const auto& pair : gameObjectTypeStringIDPairs)
{
if (pair.first == typeID)
{
return pair.second.c_str();
}
}
return "Unknown";
}
void ResourceManager::ParseFontFile()
{
PROFILE_AUTO("ResourceManager ParseFontFile");
if (!FileExists(m_FontsFilePathAbs))
{
PrintError("Fonts file missing!\n");
}
else
{
JSONObject fontSettings;
if (JSONParser::ParseFromFile(m_FontsFilePathAbs, fontSettings))
{
std::vector<JSONObject> fontObjs;
if (fontSettings.TryGetObjectArray("fonts", fontObjs))
{
for (const JSONObject& fontObj : fontObjs)
{
FontMetaData metaData = {};
fontObj.TryGetString("name", metaData.name);
std::string fileName;
fontObj.TryGetString("file path", fileName);
metaData.size = (i16)fontObj.GetInt("size");
fontObj.TryGetBool("screen space", metaData.bScreenSpace);
fontObj.TryGetFloat("threshold", metaData.threshold);
fontObj.TryGetFloat("shadow opacity", metaData.shadowOpacity);
fontObj.TryGetVec2("shadow offset", metaData.shadowOffset);
fontObj.TryGetFloat("soften", metaData.soften);
if (fileName.empty())
{
PrintError("Font doesn't contain file name!\n");
continue;
}
metaData.filePath = FONT_DIRECTORY + fileName;
SetRenderedSDFFilePath(metaData);
std::string fontName = fontObj.GetString("name");
StringID fontNameID = Hash(fontName.c_str());
if (fontMetaData.find(fontNameID) != fontMetaData.end())
{
// TODO: Handle collision
PrintError("Hash collision detected in font meta data for %s : %lu\n", fontName.c_str(), fontNameID);
}
fontMetaData[fontNameID] = metaData;
}
}
}
else
{
PrintError("Failed to parse font config file %s\n\terror: %s\n", m_FontsFilePathAbs.c_str(), JSONParser::GetErrorString());
}
}
}
void ResourceManager::SerializeFontFile()
{
std::vector<JSONObject> fontObjs;
for (auto& fontPair : fontMetaData)
{
FontMetaData metaData = fontMetaData[fontPair.first];
JSONObject fontObj = {};
fontObj.fields.emplace_back("name", JSONValue(metaData.name));
std::string relativeFilePath = StripLeadingDirectories(metaData.filePath);
fontObj.fields.emplace_back("file path", JSONValue(relativeFilePath));
fontObj.fields.emplace_back("size", JSONValue((i32)metaData.size));
fontObj.fields.emplace_back("screen space", JSONValue(metaData.bScreenSpace));
fontObj.fields.emplace_back("threshold", JSONValue(metaData.threshold, 2));
fontObj.fields.emplace_back("shadow opacity", JSONValue(metaData.shadowOpacity, 2));
fontObj.fields.emplace_back("shadow offset", JSONValue(VecToString(metaData.shadowOffset, 2)));
fontObj.fields.emplace_back("soften", JSONValue(metaData.soften, 2));
fontObjs.push_back(fontObj);
}
JSONObject fontSettings;
fontSettings.fields.emplace_back("fonts", JSONValue(fontObjs));
std::string fileContents = fontSettings.ToString();
if (!WriteFile(m_FontsFilePathAbs, fileContents, false))
{
PrintError("Failed to write font file to %s\n", m_FontsFilePathAbs.c_str());
}
}
void ResourceManager::ParseMaterialsFiles()
{
PROFILE_AUTO("ResourceManager ParseMaterialsFiles");
parsedMaterialInfos.clear();
std::vector<std::string> filePaths;
if (Platform::FindFilesInDirectory(MATERIALS_DIRECTORY, filePaths, "*", false))
{
for (const std::string& filePath : filePaths)
{
JSONObject parentObj;
if (JSONParser::ParseFromFile(filePath, parentObj))
{
i32 fileVersion = parentObj.GetInt("version");
MaterialCreateInfo matCreateInfo = {};
JSONObject materialObj = parentObj.GetObject("material");
Material::ParseJSONObject(materialObj, matCreateInfo, fileVersion);
parsedMaterialInfos.push_back(matCreateInfo);
}
else
{
PrintError("Failed to parse material file at %s\n\terror: %s\n", filePath.c_str(), JSONParser::GetErrorString());
}
}
}
else
{
PrintError("Failed to find any material files in %s\n", MATERIALS_DIRECTORY);
return;
}
if (g_bEnableLogging_Loading)
{
Print("Parsed %u materials\n", (u32)parsedMaterialInfos.size());
}
}
bool ResourceManager::SerializeAllMaterials() const
{
bool bAllSucceeded = true;
for (const MaterialCreateInfo& materialInfo : parsedMaterialInfos)
{
MaterialID matID;
if (g_Renderer->FindOrCreateMaterialByName(materialInfo.name, matID))
{
if (!SerializeMaterial(g_Renderer->GetMaterial(matID)))
{
bAllSucceeded = false;
}
}
}
return bAllSucceeded;
}
bool ResourceManager::SerializeLoadedMaterials() const
{
const std::map<MaterialID, Material*>& materials = g_Renderer->GetLoadedMaterials();
bool bAllSucceeded = true;
for (auto& matPair : materials)
{
Material* material = matPair.second;
if (!SerializeMaterial(material))
{
bAllSucceeded = false;
}
}
return bAllSucceeded;
}
bool ResourceManager::SerializeMaterial(Material* material) const
{
if (material->bSerializable)
{
JSONObject materialObj = material->Serialize();
std::string fileContents = materialObj.ToString();
std::string hypenatedName = Replace(material->name, ' ', '-');
const std::string fileName = MATERIALS_DIRECTORY + hypenatedName + ".json";
if (!WriteFile(fileName, fileContents, false))
{
PrintWarn("Failed to serialize material %s to file %s\n", material->name.c_str(), fileName.c_str());
return false;
}
}
return true;
}
void ResourceManager::ParseDebugOverlayNamesFile()
{
debugOverlayNames.clear();
std::string fileContents;
if (!ReadFile(DEBUG_OVERLAY_NAMES_LOCATION, fileContents, false))
{
PrintError("Failed to read debug overlay names definition file\n");
return;
}
JSONObject rootObject;
if (!JSONParser::Parse(fileContents, rootObject))
{
PrintError("Failed to parse debug overlay names definition file\n");
return;
}
std::vector<JSONField> nameFields = rootObject.GetFieldArray("debug overlay names");
debugOverlayNames.reserve(nameFields.size());
for (JSONField& field : nameFields)
{
debugOverlayNames.emplace_back(field.value.strValue);
}
}
void ResourceManager::SetRenderedSDFFilePath(FontMetaData& metaData)
{
static const std::string DPIStr = FloatToString(g_Monitor->DPI.x, 0) + "DPI";
metaData.renderedTextureFilePath = StripFileType(StripLeadingDirectories(metaData.filePath));
metaData.renderedTextureFilePath += "-" + IntToString(metaData.size, 2) + "-" + DPIStr + m_FontImageExtension;
metaData.renderedTextureFilePath = FONT_SDF_DIRECTORY + metaData.renderedTextureFilePath;
}
bool ResourceManager::LoadFontMetrics(const std::vector<char>& fileMemory,
FT_Library ft,
FontMetaData& metaData,
std::map<i32, FontMetric*>* outCharacters,
std::array<glm::vec2i, 4>* outMaxPositions,
FT_Face* outFace)
{
PROFILE_AUTO("LoadFontMetrics");
CHECK_EQ(metaData.bitmapFont, nullptr);
// TODO: Save in common place
u32 sampleDensity = 32;
FT_Error error = FT_New_Memory_Face(ft, (FT_Byte*)fileMemory.data(), (FT_Long)fileMemory.size(), 0, outFace);
FT_Face& face = *outFace;
if (error == FT_Err_Unknown_File_Format)
{
PrintError("Unhandled font file format: %s\n", metaData.filePath.c_str());
return false;
}
else if (error != FT_Err_Ok || !face)
{
PrintError("Failed to create new font face: %s\n", metaData.filePath.c_str());
return false;
}
i32 fontHeight = metaData.size * sampleDensity;
error = FT_Set_Char_Size(face,
0, fontHeight,
(FT_UInt)g_Monitor->DPI.x,
(FT_UInt)g_Monitor->DPI.y);
if (error != FT_Err_Ok)
{
PrintError("Failed to set font size to %d for font %s\n", fontHeight, metaData.filePath.c_str());
return false;
}
if (g_bEnableLogging_Loading)
{
const std::string fileName = StripLeadingDirectories(metaData.filePath);
Print("Loaded font file %s\n", fileName.c_str());
}
std::string fontName = std::string(face->family_name) + " - " + face->style_name;
metaData.bitmapFont = new BitmapFont(metaData, fontName, face->num_glyphs);
BitmapFont* newFont = metaData.bitmapFont;
if (metaData.bScreenSpace)
{
fontsScreenSpace.push_back(newFont);
}
else
{
fontsWorldSpace.push_back(newFont);