-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAssetManager.cpp
More file actions
1526 lines (1278 loc) · 70.8 KB
/
AssetManager.cpp
File metadata and controls
1526 lines (1278 loc) · 70.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 "AssetManager.hpp"
#include "Queue.hpp"
#include "PhysicalDevice.hpp"
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include <filesystem>
#include "stb/stb_image.h"
#include <ft2build.h>
#include FT_FREETYPE_H
namespace Lca{
namespace Core{
static glm::mat4 toGlmMat4(const aiMatrix4x4& m) {
glm::mat4 out(1.0f);
out[0][0] = m.a1; out[1][0] = m.a2; out[2][0] = m.a3; out[3][0] = m.a4;
out[0][1] = m.b1; out[1][1] = m.b2; out[2][1] = m.b3; out[3][1] = m.b4;
out[0][2] = m.c1; out[1][2] = m.c2; out[2][2] = m.c3; out[3][2] = m.c4;
out[0][3] = m.d1; out[1][3] = m.d2; out[2][3] = m.d3; out[3][3] = m.d4;
return out;
}
// Global AssetManager Instance
static AssetManager globalAssetManager;
AssetManager& GetAssetManager() {
return globalAssetManager;
}
AssetManager::MeshInfo AssetManager::getMeshInfo(uint32_t meshId) const {
LCA_ASSERT(meshId < meshInfos.size, "AssetManager", "getMeshInfo", "Invalid mesh ID.");
MeshInfo info{};
std::memcpy(&info,
static_cast<const char*>(meshInfos.interface.pMemory) + meshId * sizeof(MeshInfo),
sizeof(MeshInfo));
return info;
}
void AssetManager::recordSync(const Command& command) {
meshInfos.recordSync(command);
skeletonMeshInfos.recordSync(command);
materials.recordSync(command);
}
void AssetManager::init(){
vertexBuffer = createBuffer(MAX_VERTICES, sizeof(Vertex::Mesh), VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT);
indexBuffer = createBuffer(MAX_INDICES, sizeof(uint32_t), VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT);
skeletonVertexBuffer = createBuffer(MAX_VERTICES, sizeof(Vertex::Skeleton), VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT);
skeletonIndexBuffer = createBuffer(MAX_INDICES, sizeof(uint32_t), VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT);
skeletonBuffer = createBuffer(MAX_SKELETONS * MAX_NODES_PER_SKELETON, sizeof(VkNode), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT);
skeletonNodeCountBuffer = createBuffer(MAX_SKELETONS, sizeof(uint32_t), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT);
materials = createSlotBufferGPU(MAX_MATERIALS, sizeof(Material), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT);
meshInfos = createSlotBufferGPU(MAX_MESHES, sizeof(MeshInfo), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT);
skeletonMeshInfos = createSlotBufferGPU(MAX_MESHES, sizeof(MeshInfo), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT);
currentVertexOffset = 0;
currentIndexOffset = 0;
currentSkeletonVertexOffset = 0;
currentSkeletonIndexOffset = 0;
freeVertexRanges.clear();
freeIndexRanges.clear();
freeSkeletonVertexRanges.clear();
freeSkeletonIndexRanges.clear();
materialMap.clear();
meshMap.clear();
skeletonMeshMap.clear();
skeletonMap.clear();
modelMap.clear();
skeletonModelMap.clear();
animationMap.clear();
skeletonDataMap.clear();
freeSkeletonSlots.clear();
for (uint32_t i = MAX_SKELETONS; i > 0; --i) {
freeSkeletonSlots.push_back(i - 1);
}
uint32_t fallbackPixel = 0xFFFFFFFF;
auto fallbackTexture = createTexture(1, 1, &fallbackPixel);
for (uint32_t i = 0; i < MAX_TEXTURES; ++i) {
textures[i] = fallbackTexture;
textureSlotOwned[i] = false;
}
textureSlotOwned[0] = true;
freeTextureSlots.clear();
for (uint32_t i = MAX_TEXTURES - 1; i > 0; --i) {
freeTextureSlots.push_back(i);
}
textureMap.clear();
}
void AssetManager::shutdown(){
for (uint32_t id = 0; id < MAX_TEXTURES; ++id) {
if (textureSlotOwned[id]) {
destroyTexture(textures[id]);
}
}
textureMap.clear();
freeTextureSlots.clear();
materialMap.clear();
meshMap.clear();
skeletonMeshMap.clear();
skeletonMap.clear();
modelMap.clear();
skeletonModelMap.clear();
animationMap.clear();
skeletonDataMap.clear(); animationMap.clear();
skeletonDataMap.clear(); freeSkeletonSlots.clear();
freeVertexRanges.clear();
freeIndexRanges.clear();
freeSkeletonVertexRanges.clear();
freeSkeletonIndexRanges.clear();
fontMap.clear();
fontDataStore.clear();
destroySlotBufferGPU(skeletonMeshInfos);
destroySlotBufferGPU(meshInfos);
destroySlotBufferGPU(materials);
destroyBuffer(skeletonIndexBuffer);
destroyBuffer(skeletonVertexBuffer);
destroyBuffer(skeletonBuffer);
destroyBuffer(skeletonNodeCountBuffer);
destroyBuffer(indexBuffer);
destroyBuffer(vertexBuffer);
}
uint32_t AssetManager::loadSkeleton(const std::string& name, const std::string& filePath) {
{
std::lock_guard<std::mutex> lock(assetMutex);
auto existing = skeletonMap.find(name);
if (existing != skeletonMap.end()) {
return existing->second;
}
LCA_ASSERT(!freeSkeletonSlots.empty(), "AssetManager", "loadSkeleton", "No free skeleton slots available.");
}
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile(filePath,
aiProcess_Triangulate |
aiProcess_GenNormals |
aiProcess_FlipUVs |
aiProcess_CalcTangentSpace |
aiProcess_JoinIdenticalVertices);
LCA_ASSERT(scene && !(scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE) && scene->mRootNode,
"AssetManager", "loadSkeleton", "Failed to load model: " + std::string(importer.GetErrorString()));
std::unordered_map<std::string, int32_t> boneNameToIndex;
std::unordered_map<std::string, glm::mat4> boneOffsetByName;
int32_t nextBoneIndex = 0;
for (uint32_t m = 0; m < scene->mNumMeshes; ++m) {
const aiMesh* aiMeshPtr = scene->mMeshes[m];
for (uint32_t b = 0; b < aiMeshPtr->mNumBones; ++b) {
const aiBone* bone = aiMeshPtr->mBones[b];
const std::string boneName = bone->mName.C_Str();
if (boneNameToIndex.find(boneName) == boneNameToIndex.end()) {
LCA_ASSERT(nextBoneIndex < static_cast<int32_t>(MAX_NODES_PER_SKELETON), "AssetManager", "loadSkeleton", "Exceeded max bones per skeleton for '" + name + "'.");
boneNameToIndex[boneName] = nextBoneIndex++;
boneOffsetByName[boneName] = toGlmMat4(bone->mOffsetMatrix);
}
}
}
std::array<VkNode, MAX_NODES_PER_SKELETON> skeletonNodes{};
for (uint32_t i = 0; i < MAX_NODES_PER_SKELETON; ++i) {
skeletonNodes[i].isBone_parentIndex_boneIndex = glm::ivec4(0, -1, -1, 0);
skeletonNodes[i].offset = glm::mat4(1.0f);
}
int32_t nextNodeIndex = 0;
std::unordered_map<std::string, int32_t> nodeNameToIndex;
std::function<void(aiNode*, int32_t)> fillNodes = [&](aiNode* node, int32_t parentIndex) {
LCA_ASSERT(nextNodeIndex < static_cast<int32_t>(MAX_NODES_PER_SKELETON), "AssetManager", "loadSkeleton", "Exceeded max nodes (256) for skeleton '" + name + "'.");
const int32_t nodeIndex = nextNodeIndex++;
const std::string nodeName = node->mName.C_Str();
nodeNameToIndex[nodeName] = nodeIndex;
const auto boneIt = boneNameToIndex.find(nodeName);
const bool isBone = boneIt != boneNameToIndex.end();
const int32_t boneIndex = isBone ? boneIt->second : -1;
skeletonNodes[nodeIndex].isBone_parentIndex_boneIndex = glm::ivec4(isBone ? 1 : 0, parentIndex, boneIndex, 0);
if (isBone) {
skeletonNodes[nodeIndex].offset = boneOffsetByName[nodeName];
} else {
skeletonNodes[nodeIndex].offset = toGlmMat4(node->mTransformation);
}
for (uint32_t i = 0; i < node->mNumChildren; ++i) {
fillNodes(node->mChildren[i], nodeIndex);
}
};
fillNodes(scene->mRootNode, -1);
uint32_t skeletonId;
{
std::lock_guard<std::mutex> lock(assetMutex);
LCA_ASSERT(!freeSkeletonSlots.empty(), "AssetManager", "loadSkeleton", "No free skeleton slots available.");
skeletonId = freeSkeletonSlots.back();
freeSkeletonSlots.pop_back();
}
BufferInterface stagingNodes = createBufferInterface(MAX_NODES_PER_SKELETON, sizeof(VkNode), VK_BUFFER_USAGE_TRANSFER_SRC_BIT);
std::memcpy(stagingNodes.pMemory, skeletonNodes.data(), MAX_NODES_PER_SKELETON * sizeof(VkNode));
BufferInterface stagingNodeCount = createBufferInterface(1, sizeof(uint32_t), VK_BUFFER_USAGE_TRANSFER_SRC_BIT);
const uint32_t nodeCount = static_cast<uint32_t>(nextNodeIndex);
std::memcpy(stagingNodeCount.pMemory, &nodeCount, sizeof(uint32_t));
beginSingleCommand(singleCommand);
VkBufferCopy copyRegion{};
copyRegion.srcOffset = 0;
copyRegion.dstOffset = static_cast<VkDeviceSize>(skeletonId) * MAX_NODES_PER_SKELETON * sizeof(VkNode);
copyRegion.size = MAX_NODES_PER_SKELETON * sizeof(VkNode);
vkCmdCopyBuffer(singleCommand.vkCommandBuffer, stagingNodes.vkBuffer, skeletonBuffer.vkBuffer, 1, ©Region);
VkBufferCopy nodeCountCopyRegion{};
nodeCountCopyRegion.srcOffset = 0;
nodeCountCopyRegion.dstOffset = static_cast<VkDeviceSize>(skeletonId) * sizeof(uint32_t);
nodeCountCopyRegion.size = sizeof(uint32_t);
vkCmdCopyBuffer(singleCommand.vkCommandBuffer, stagingNodeCount.vkBuffer, skeletonNodeCountBuffer.vkBuffer, 1, &nodeCountCopyRegion);
endSingleCommand(singleCommand);
submitSingleCommand(singleCommand);
destroyBufferInterface(stagingNodes);
destroyBufferInterface(stagingNodeCount);
// Build CPU-side skeleton hierarchy for bone matrix computation
std::vector<SkeletonNodeInfo> cpuNodes(static_cast<size_t>(nextNodeIndex));
for (int32_t i = 0; i < nextNodeIndex; ++i) {
cpuNodes[i].parentIndex = skeletonNodes[i].isBone_parentIndex_boneIndex.y;
cpuNodes[i].isBone = (skeletonNodes[i].isBone_parentIndex_boneIndex.x != 0);
cpuNodes[i].offsetMatrix = skeletonNodes[i].offset;
}
{
std::lock_guard<std::mutex> lock(assetMutex);
skeletonMap[name] = skeletonId;
SkeletonData skelData;
skelData.skeletonId = skeletonId;
skelData.nodeCount = static_cast<uint32_t>(nextNodeIndex);
skelData.nodeNameToIndex = std::move(nodeNameToIndex);
skelData.nodes = std::move(cpuNodes);
skeletonDataMap[name] = std::move(skelData);
}
LCA_LOGI("AssetManager", "loadSkeleton", "Loaded skeleton '" + name + "' with " + std::to_string(nextNodeIndex) + " node(s) from " + filePath);
return skeletonId;
}
void AssetManager::loadTexture(const std::string& name, const std::string& filePath) {
Core::TextureCPU textureCPU = Core::loadTexture(filePath);
Core::Texture texture = Core::createTexture(textureCPU.width, textureCPU.height, textureCPU.pixels);
Core::freeTexture(textureCPU);
addTexture(name, texture);
}
void AssetManager::addTexture(const std::string& name, const Texture& texture){
std::lock_guard<std::mutex> lock(assetMutex);
auto existing = textureMap.find(name);
if (existing != textureMap.end()) {
uint32_t id = existing->second;
if (id < MAX_TEXTURES) {
if (textureSlotOwned[id]) {
destroyTexture(textures[id]);
}
textures[id] = texture;
textureSlotOwned[id] = true;
}
return;
}
if (freeTextureSlots.empty()) {
LCA_LOGE("AssetManager", "addTexture", "No free texture slots available.");
}
uint32_t id = freeTextureSlots.back();
freeTextureSlots.pop_back();
textures[id] = texture;
textureSlotOwned[id] = true;
textureMap[name] = id;
}
void AssetManager::removeTexture(const std::string& name){
std::lock_guard<std::mutex> lock(assetMutex);
auto it = textureMap.find(name);
if (it == textureMap.end()) {
LCA_LOGE("AssetManager", "removeTexture", "Texture with name " + name + " not found.");
}
uint32_t id = it->second;
if (textureSlotOwned[id]) {
destroyTexture(textures[id]);
}
textures[id] = textures[0];
textureSlotOwned[id] = false;
freeTextureSlots.push_back(id);
textureMap.erase(it);
}
uint32_t AssetManager::getTextureId(const std::string& name) const {
std::lock_guard<std::mutex> lock(assetMutex);
auto it = textureMap.find(name);
if (it != textureMap.end()) {
return it->second;
}
LCA_LOGE("AssetManager", "getTextureId", "Texture with name " + name + " not found.");
}
VkDescriptorImageInfo AssetManager::getTextureDescriptorInfo(uint32_t id) const {
const Texture* selected = &textures[0];
if (id < textures.size()) {
selected = &textures[id];
}
VkDescriptorImageInfo info{};
info.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
info.imageView = selected->vkImageView;
info.sampler = selected->vkSampler;
return info;
}
uint32_t AssetManager::addMaterial(const std::string& name, const Material& material){
std::lock_guard<std::mutex> lock(assetMutex);
if (materialMap.find(name) != materialMap.end()) {
uint32_t id = materialMap[name];
VkDeviceSize offset = id * materials.interface.elementSize;
uint8_t* dst = static_cast<uint8_t*>(materials.interface.pMemory) + offset;
memcpy(dst, &material, sizeof(Material));
return id;
}
uint32_t id = materials.add((void*)&material);
materialMap[name] = id;
return id;
}
void AssetManager::removeMaterial(const std::string& name){
std::lock_guard<std::mutex> lock(assetMutex);
if (materialMap.find(name) != materialMap.end()) {
uint32_t id = materialMap[name];
materials.remove(id);
materialMap.erase(name);
return;
}
LCA_LOGE("AssetManager", "removeMaterial", "Material with name " + name + " not found.");
}
uint32_t AssetManager::getMaterialId(const std::string& name) const {
std::lock_guard<std::mutex> lock(assetMutex);
auto it = materialMap.find(name);
if (it != materialMap.end()) {
return it->second;
}
LCA_LOGE("AssetManager", "getMaterialId", "Material with name " + name + " not found.");
}
uint32_t AssetManager::allocateRange(std::vector<BufferRange>& freeList, uint32_t& currentTop, uint32_t size) {
// First-fit strategy with efficient removal
for (size_t i = 0; i < freeList.size(); ++i) {
if (freeList[i].size >= size) {
uint32_t offset = freeList[i].offset;
if (freeList[i].size > size) {
// Split the block
freeList[i].offset += size;
freeList[i].size -= size;
} else {
// Exact match, remove the block
freeList.erase(freeList.begin() + i);
}
return offset;
}
}
// No suitable block found, allocate at the end
uint32_t offset = currentTop;
currentTop += size;
return offset;
}
void AssetManager::freeRange(std::vector<BufferRange>& freeList, uint32_t offset, uint32_t size) {
freeList.push_back({offset, size});
// Optional: Coalesce free blocks here if desired to reduce fragmentation
}
uint32_t AssetManager::addMesh(const std::string& name, const std::vector<Vertex::Mesh>& vertices, const std::vector<uint32_t>& indices){
LCA_ASSERT(vertices.size() > 0, "AssetManager", "addMesh", "Vertex list is empty for mesh " + name + ".");
LCA_ASSERT(indices.size() > 0, "AssetManager", "addMesh", "Index list is empty for mesh " + name + ".");
uint32_t vertexCount = static_cast<uint32_t>(vertices.size());
uint32_t indexCount = static_cast<uint32_t>(indices.size());
uint32_t vertexOffsetVal, indexOffsetVal;
{
std::lock_guard<std::mutex> lock(assetMutex);
LCA_ASSERT(meshMap.find(name) == meshMap.end(), "AssetManager", "addMesh", "Mesh with name " + name + " already exists.");
vertexOffsetVal = allocateRange(freeVertexRanges, currentVertexOffset, vertexCount);
indexOffsetVal = allocateRange(freeIndexRanges, currentIndexOffset, indexCount);
}
VkDeviceSize vertexByteSize = vertexCount * sizeof(Vertex::Mesh);
BufferInterface stagingVertex = createBufferInterface(vertexCount, sizeof(Vertex::Mesh), VK_BUFFER_USAGE_TRANSFER_SRC_BIT);
memcpy(stagingVertex.pMemory, vertices.data(), vertexByteSize);
VkDeviceSize indexByteSize = indexCount * sizeof(uint32_t);
BufferInterface stagingIndex = createBufferInterface(indexCount, sizeof(uint32_t), VK_BUFFER_USAGE_TRANSFER_SRC_BIT);
memcpy(stagingIndex.pMemory, indices.data(), indexByteSize);
beginSingleCommand(singleCommand);
VkBufferCopy copyRegion{};
copyRegion.srcOffset = 0;
copyRegion.dstOffset = vertexOffsetVal * sizeof(Vertex::Mesh);
copyRegion.size = vertexByteSize;
vkCmdCopyBuffer(singleCommand.vkCommandBuffer, stagingVertex.vkBuffer, vertexBuffer.vkBuffer, 1, ©Region);
VkBufferCopy copyRegionIndex{};
copyRegionIndex.srcOffset = 0;
copyRegionIndex.dstOffset = indexOffsetVal * sizeof(uint32_t);
copyRegionIndex.size = indexByteSize;
vkCmdCopyBuffer(singleCommand.vkCommandBuffer, stagingIndex.vkBuffer, indexBuffer.vkBuffer, 1, ©RegionIndex);
endSingleCommand(singleCommand);
submitSingleCommand(singleCommand);
destroyBufferInterface(stagingIndex);
destroyBufferInterface(stagingVertex);
// 3. Register MeshInfo
MeshInfo info{};
info.indexCount = indexCount;
info.firstIndex = indexOffsetVal;
info.vertexCount = vertexCount;
info.vertexOffset = static_cast<int32_t>(vertexOffsetVal);
glm::vec3 minPos = vertices[0].position;
glm::vec3 maxPos = vertices[0].position;
for (const auto& v : vertices) {
minPos = glm::min(minPos, v.position);
maxPos = glm::max(maxPos, v.position);
}
glm::vec3 center = (minPos + maxPos) * 0.5f;
float radius = 0.0f;
for (const auto& v : vertices) {
float dist = glm::distance(v.position, center);
if (dist > radius) {
radius = dist;
}
}
info.boundingSphere = glm::vec4(center, radius);
uint32_t id;
{
std::lock_guard<std::mutex> lock(assetMutex);
id = meshInfos.add(&info);
meshMap[name] = id;
}
return id;
}
void AssetManager::removeMesh(const std::string& name){
std::lock_guard<std::mutex> lock(assetMutex);
auto it = meshMap.find(name);
if (it != meshMap.end()) {
uint32_t id = it->second;
MeshInfo info;
meshInfos.remove(id, &info);
freeRange(freeVertexRanges, static_cast<uint32_t>(info.vertexOffset), info.vertexCount);
freeRange(freeIndexRanges, info.firstIndex, info.indexCount);
meshMap.erase(name);
return;
}
LCA_LOGE("AssetManager", "removeMesh", "Mesh with name " + name + " not found.");
}
uint32_t AssetManager::getMeshId(const std::string& name) const {
std::lock_guard<std::mutex> lock(assetMutex);
auto it = meshMap.find(name);
if (it != meshMap.end()) {
return it->second;
}
LCA_LOGE("AssetManager", "getMeshId", "Mesh with name " + name + " not found.");
}
Model AssetManager::loadModel(const std::string& name, const std::string& filePath) {
LCA_ASSERT(modelMap.find(name) == modelMap.end(), "AssetManager", "loadModel", "Model with name " + name + " already exists.");
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile(filePath,
aiProcess_Triangulate |
aiProcess_GenNormals |
aiProcess_FlipUVs |
aiProcess_CalcTangentSpace |
aiProcess_JoinIdenticalVertices);
LCA_ASSERT(scene && !(scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE) && scene->mRootNode,
"AssetManager", "loadModel", "Failed to load model: " + std::string(importer.GetErrorString()));
std::filesystem::path modelPath(filePath);
std::string directory = modelPath.parent_path().string();
Model model;
// --- Pre-process materials (once per unique aiMaterial) ---
// Maps assimp material index -> our material id / name
std::unordered_map<uint32_t, uint32_t> processedMaterials;
std::unordered_map<uint32_t, std::string> processedMaterialNames;
for (uint32_t matIdx = 0; matIdx < scene->mNumMaterials; ++matIdx) {
const aiMaterial* aiMat = scene->mMaterials[matIdx];
aiString aiMatName;
std::string materialName = (aiMat->Get(AI_MATKEY_NAME, aiMatName) == AI_SUCCESS && aiMatName.length > 0)
? std::string(aiMatName.C_Str())
: name + "_material_" + std::to_string(matIdx);
Material material{};
material.textureId = -1;
material.roughness = 0.5f;
material.metallic = 0.0f;
// Try to load diffuse texture
if (aiMat->GetTextureCount(aiTextureType_DIFFUSE) > 0) {
aiString texPath;
if (aiMat->GetTexture(aiTextureType_DIFFUSE, 0, &texPath) == AI_SUCCESS) {
std::string textureName = name + "_tex_" + std::to_string(matIdx);
// Only load the texture if it hasn't been loaded yet
if (textureMap.find(textureName) == textureMap.end()) {
const aiTexture* embeddedTex = scene->GetEmbeddedTexture(texPath.C_Str());
if (embeddedTex) {
if (embeddedTex->mHeight == 0) {
int width, height, nrChannels;
auto* pixels = stbi_load_from_memory(
reinterpret_cast<unsigned char*>(embeddedTex->pcData),
embeddedTex->mWidth, &width, &height, &nrChannels, 4);
Texture tex = createTexture(width, height, pixels);
stbi_image_free(pixels);
addTexture(textureName, tex);
} else {
// Raw ARGB8888 data
int width, height, nrChannels;
auto* pixels = stbi_load_from_memory(
reinterpret_cast<unsigned char*>(embeddedTex->pcData),
embeddedTex->mWidth * embeddedTex->mHeight * 4, &width, &height, &nrChannels, 4);
Texture tex = createTexture(width, height, pixels);
stbi_image_free(pixels);
addTexture(textureName, tex);
}
} else {
// External texture file
std::string fullPath = directory + "/" + texPath.C_Str();
loadTexture(textureName, fullPath);
}
}
material.textureId = static_cast<int32_t>(getTextureId(textureName));
}
}
// Extract roughness/metallic if available
float roughness = 0.5f;
float metallic = 0.0f;
if (aiMat->Get(AI_MATKEY_ROUGHNESS_FACTOR, roughness) == AI_SUCCESS) {
material.roughness = roughness;
}
if (aiMat->Get(AI_MATKEY_METALLIC_FACTOR, metallic) == AI_SUCCESS) {
material.metallic = metallic;
}
uint32_t materialId = addMaterial(materialName, material);
processedMaterials[matIdx] = materialId;
processedMaterialNames[matIdx] = materialName;
}
// --- Process each mesh in the scene ---
for (uint32_t m = 0; m < scene->mNumMeshes; ++m) {
const aiMesh* aiMeshPtr = scene->mMeshes[m];
std::string meshName = aiMeshPtr->mName.length > 0
? std::string(aiMeshPtr->mName.C_Str())
: name + "_mesh_" + std::to_string(m);
// --- Extract vertices ---
std::vector<Vertex::Mesh> vertices;
vertices.reserve(aiMeshPtr->mNumVertices);
for (uint32_t v = 0; v < aiMeshPtr->mNumVertices; ++v) {
Vertex::Mesh vertex{};
vertex.position = glm::vec3(
aiMeshPtr->mVertices[v].x,
aiMeshPtr->mVertices[v].y,
aiMeshPtr->mVertices[v].z
);
if (aiMeshPtr->HasNormals()) {
vertex.normal = glm::vec3(
aiMeshPtr->mNormals[v].x,
aiMeshPtr->mNormals[v].y,
aiMeshPtr->mNormals[v].z
);
}
if (aiMeshPtr->HasVertexColors(0)) {
vertex.color = glm::vec4(
aiMeshPtr->mColors[0][v].r,
aiMeshPtr->mColors[0][v].g,
aiMeshPtr->mColors[0][v].b,
aiMeshPtr->mColors[0][v].a
);
} else {
vertex.color = glm::vec4(1.0f);
}
if (aiMeshPtr->HasTextureCoords(0)) {
vertex.texCoord = glm::vec2(
aiMeshPtr->mTextureCoords[0][v].x,
aiMeshPtr->mTextureCoords[0][v].y
);
}
vertices.push_back(vertex);
}
// --- Extract indices ---
std::vector<uint32_t> indices;
for (uint32_t f = 0; f < aiMeshPtr->mNumFaces; ++f) {
const aiFace& face = aiMeshPtr->mFaces[f];
indices.push_back(face.mIndices[0]);
indices.push_back(face.mIndices[2]);
indices.push_back(face.mIndices[1]);
}
uint32_t meshId = addMesh(meshName, vertices, indices);
// Look up the material id from the pre-processed map
uint32_t materialId = processedMaterials[aiMeshPtr->mMaterialIndex];
std::string matName = processedMaterialNames[aiMeshPtr->mMaterialIndex];
model.push_back({ meshName, matName, meshId, materialId });
}
modelMap[name] = model;
LCA_LOGI("AssetManager", "loadModel", "Loaded model '" + name + "' with " + std::to_string(model.size()) + " mesh(es) from " + filePath);
return model;
}
const Model& AssetManager::getModel(const std::string& name) const {
auto it = modelMap.find(name);
LCA_ASSERT(it != modelMap.end(), "AssetManager", "getModel", "Model with name " + name + " not found.");
return it->second;
}
uint32_t AssetManager::addSkeletonMesh(const std::string& name, const std::vector<Vertex::Skeleton>& vertices, const std::vector<uint32_t>& indices){
LCA_ASSERT(vertices.size() > 0, "AssetManager", "addSkeletonMesh", "Vertex list is empty for skeleton mesh " + name + ".");
LCA_ASSERT(indices.size() > 0, "AssetManager", "addSkeletonMesh", "Index list is empty for skeleton mesh " + name + ".");
uint32_t vertexCount = static_cast<uint32_t>(vertices.size());
uint32_t indexCount = static_cast<uint32_t>(indices.size());
uint32_t vertexOffsetVal, indexOffsetVal;
{
std::lock_guard<std::mutex> lock(assetMutex);
LCA_ASSERT(skeletonMeshMap.find(name) == skeletonMeshMap.end(), "AssetManager", "addSkeletonMesh", "Skeleton mesh with name " + name + " already exists.");
vertexOffsetVal = allocateRange(freeSkeletonVertexRanges, currentSkeletonVertexOffset, vertexCount);
indexOffsetVal = allocateRange(freeSkeletonIndexRanges, currentSkeletonIndexOffset, indexCount);
}
VkDeviceSize vertexByteSize = vertexCount * sizeof(Vertex::Skeleton);
BufferInterface stagingVertex = createBufferInterface(vertexCount, sizeof(Vertex::Skeleton), VK_BUFFER_USAGE_TRANSFER_SRC_BIT);
memcpy(stagingVertex.pMemory, vertices.data(), vertexByteSize);
VkDeviceSize indexByteSize = indexCount * sizeof(uint32_t);
BufferInterface stagingIndex = createBufferInterface(indexCount, sizeof(uint32_t), VK_BUFFER_USAGE_TRANSFER_SRC_BIT);
memcpy(stagingIndex.pMemory, indices.data(), indexByteSize);
beginSingleCommand(singleCommand);
VkBufferCopy copyRegion{};
copyRegion.srcOffset = 0;
copyRegion.dstOffset = vertexOffsetVal * sizeof(Vertex::Skeleton);
copyRegion.size = vertexByteSize;
vkCmdCopyBuffer(singleCommand.vkCommandBuffer, stagingVertex.vkBuffer, skeletonVertexBuffer.vkBuffer, 1, ©Region);
VkBufferCopy copyRegionIndex{};
copyRegionIndex.srcOffset = 0;
copyRegionIndex.dstOffset = indexOffsetVal * sizeof(uint32_t);
copyRegionIndex.size = indexByteSize;
vkCmdCopyBuffer(singleCommand.vkCommandBuffer, stagingIndex.vkBuffer, skeletonIndexBuffer.vkBuffer, 1, ©RegionIndex);
endSingleCommand(singleCommand);
submitSingleCommand(singleCommand);
destroyBufferInterface(stagingIndex);
destroyBufferInterface(stagingVertex);
MeshInfo info{};
info.indexCount = indexCount;
info.firstIndex = indexOffsetVal;
info.vertexCount = vertexCount;
info.vertexOffset = static_cast<int32_t>(vertexOffsetVal);
glm::vec3 minPos = vertices[0].position;
glm::vec3 maxPos = vertices[0].position;
for (const auto& v : vertices) {
minPos = glm::min(minPos, v.position);
maxPos = glm::max(maxPos, v.position);
}
glm::vec3 center = (minPos + maxPos) * 0.5f;
float radius = 0.0f;
for (const auto& v : vertices) {
float dist = glm::distance(v.position, center);
if (dist > radius) {
radius = dist;
}
}
info.boundingSphere = glm::vec4(center, radius);
uint32_t id;
{
std::lock_guard<std::mutex> lock(assetMutex);
id = skeletonMeshInfos.add(&info);
skeletonMeshMap[name] = id;
}
return id;
}
void AssetManager::removeSkeletonMesh(const std::string& name){
std::lock_guard<std::mutex> lock(assetMutex);
auto it = skeletonMeshMap.find(name);
if (it != skeletonMeshMap.end()) {
uint32_t id = it->second;
MeshInfo info;
skeletonMeshInfos.remove(id, &info);
freeRange(freeSkeletonVertexRanges, static_cast<uint32_t>(info.vertexOffset), info.vertexCount);
freeRange(freeSkeletonIndexRanges, info.firstIndex, info.indexCount);
skeletonMeshMap.erase(name);
return;
}
LCA_LOGE("AssetManager", "removeSkeletonMesh", "Skeleton mesh with name " + name + " not found.");
}
Model AssetManager::loadSkeletonModel(const std::string& name, const std::string& filePath) {
LCA_ASSERT(skeletonModelMap.find(name) == skeletonModelMap.end(), "AssetManager", "loadSkeletonModel", "Skeleton model with name " + name + " already exists.");
loadSkeleton(name, filePath);
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile(filePath,
aiProcess_Triangulate |
aiProcess_GenNormals |
aiProcess_FlipUVs |
aiProcess_CalcTangentSpace |
aiProcess_JoinIdenticalVertices);
LCA_ASSERT(scene && !(scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE) && scene->mRootNode,
"AssetManager", "loadSkeletonModel", "Failed to load model: " + std::string(importer.GetErrorString()));
std::filesystem::path modelPath(filePath);
std::string directory = modelPath.parent_path().string();
Model model;
// --- Pre-process materials ---
std::unordered_map<uint32_t, uint32_t> processedMaterials;
std::unordered_map<uint32_t, std::string> processedMaterialNames;
for (uint32_t matIdx = 0; matIdx < scene->mNumMaterials; ++matIdx) {
const aiMaterial* aiMat = scene->mMaterials[matIdx];
aiString aiMatName;
std::string materialName = (aiMat->Get(AI_MATKEY_NAME, aiMatName) == AI_SUCCESS && aiMatName.length > 0)
? std::string(aiMatName.C_Str())
: name + "_material_" + std::to_string(matIdx);
Material material{};
material.textureId = -1;
material.roughness = 0.5f;
material.metallic = 0.0f;
if (aiMat->GetTextureCount(aiTextureType_DIFFUSE) > 0) {
aiString texPath;
if (aiMat->GetTexture(aiTextureType_DIFFUSE, 0, &texPath) == AI_SUCCESS) {
std::string textureName = name + "_tex_" + std::to_string(matIdx);
if (textureMap.find(textureName) == textureMap.end()) {
const aiTexture* embeddedTex = scene->GetEmbeddedTexture(texPath.C_Str());
if (embeddedTex) {
if (embeddedTex->mHeight == 0) {
int width, height, nrChannels;
auto* pixels = stbi_load_from_memory(
reinterpret_cast<unsigned char*>(embeddedTex->pcData),
embeddedTex->mWidth, &width, &height, &nrChannels, 4);
Texture tex = createTexture(width, height, pixels);
stbi_image_free(pixels);
addTexture(textureName, tex);
} else {
int width, height, nrChannels;
auto* pixels = stbi_load_from_memory(
reinterpret_cast<unsigned char*>(embeddedTex->pcData),
embeddedTex->mWidth * embeddedTex->mHeight * 4, &width, &height, &nrChannels, 4);
Texture tex = createTexture(width, height, pixels);
stbi_image_free(pixels);
addTexture(textureName, tex);
}
} else {
std::string fullPath = directory + "/" + texPath.C_Str();
loadTexture(textureName, fullPath);
}
}
material.textureId = static_cast<int32_t>(getTextureId(textureName));
}
}
float roughness = 0.5f;
float metallic = 0.0f;
if (aiMat->Get(AI_MATKEY_ROUGHNESS_FACTOR, roughness) == AI_SUCCESS) {
material.roughness = roughness;
}
if (aiMat->Get(AI_MATKEY_METALLIC_FACTOR, metallic) == AI_SUCCESS) {
material.metallic = metallic;
}
uint32_t materialId = addMaterial(materialName, material);
processedMaterials[matIdx] = materialId;
processedMaterialNames[matIdx] = materialName;
}
// --- Build node index map for skeleton ---
std::unordered_map<std::string, int> nodeIndexMap;
std::function<void(aiNode*, int&)> buildNodeMap = [&](aiNode* node, int& nextIndex) {
nodeIndexMap[node->mName.C_Str()] = nextIndex++;
for (uint32_t i = 0; i < node->mNumChildren; ++i) {
buildNodeMap(node->mChildren[i], nextIndex);
}
};
int nextNodeIndex = 0;
buildNodeMap(scene->mRootNode, nextNodeIndex);
// Helper to find the parent node that references a mesh by index
std::function<aiNode*(aiNode*, uint32_t)> findMeshParentNode = [&](aiNode* node, uint32_t meshIndex) -> aiNode* {
for (uint32_t i = 0; i < node->mNumMeshes; ++i) {
if (node->mMeshes[i] == meshIndex) {
return node;
}
}
for (uint32_t i = 0; i < node->mNumChildren; ++i) {
aiNode* found = findMeshParentNode(node->mChildren[i], meshIndex);
if (found != nullptr) {
return found;
}
}
return nullptr;
};
// --- Process each mesh ---
for (uint32_t m = 0; m < scene->mNumMeshes; ++m) {
const aiMesh* aiMeshPtr = scene->mMeshes[m];
std::string meshName = aiMeshPtr->mName.length > 0
? std::string(aiMeshPtr->mName.C_Str())
: name + "_mesh_" + std::to_string(m);
int32_t meshNodeIndex = -1; // -1 for deformed, >= 0 for node-attached
std::vector<Vertex::Skeleton> vertices;
vertices.resize(aiMeshPtr->mNumVertices);
for (uint32_t v = 0; v < aiMeshPtr->mNumVertices; ++v) {
Vertex::Skeleton& vertex = vertices[v];
vertex.position = glm::vec3(
aiMeshPtr->mVertices[v].x,
aiMeshPtr->mVertices[v].y,
aiMeshPtr->mVertices[v].z
);
if (aiMeshPtr->HasNormals()) {
vertex.normal = glm::vec3(
aiMeshPtr->mNormals[v].x,
aiMeshPtr->mNormals[v].y,
aiMeshPtr->mNormals[v].z
);
}
if (aiMeshPtr->HasVertexColors(0)) {
vertex.color = glm::vec4(
aiMeshPtr->mColors[0][v].r,
aiMeshPtr->mColors[0][v].g,
aiMeshPtr->mColors[0][v].b,
aiMeshPtr->mColors[0][v].a
);
} else {
vertex.color = glm::vec4(1.0f);
}
if (aiMeshPtr->HasTextureCoords(0)) {
vertex.texCoord = glm::vec2(
aiMeshPtr->mTextureCoords[0][v].x,
aiMeshPtr->mTextureCoords[0][v].y
);
}
vertex.bones = glm::ivec4(0);
vertex.weights = glm::vec4(0.0f);
vertex.nodeIndex = -1;
}
// --- Extract bone data or set nodeIndex from parent node ---
if (aiMeshPtr->HasBones()) {
for (uint32_t b = 0; b < aiMeshPtr->mNumBones; ++b) {
const aiBone* bone = aiMeshPtr->mBones[b];
std::string boneName(bone->mName.C_Str());
auto boneIt = nodeIndexMap.find(boneName);
LCA_ASSERT(boneIt != nodeIndexMap.end(), "AssetManager", "loadSkeletonModel",
"Bone '" + boneName + "' not found in node index map.");
int boneIndex = boneIt->second;
for (uint32_t w = 0; w < bone->mNumWeights; ++w) {
uint32_t vertexId = bone->mWeights[w].mVertexId;
float weight = bone->mWeights[w].mWeight;
Vertex::Skeleton& vert = vertices[vertexId];
// Find the first empty bone slot (weight == 0)
for (int slot = 0; slot < 4; ++slot) {
if (vert.weights[slot] == 0.0f) {
vert.bones[slot] = boneIndex;
vert.weights[slot] = weight;
vert.nodeIndex = -1;
break;
}
}
}
}
} else {
// No bones — use parent node's global transform via the bone skinning path
aiNode* parentNode = findMeshParentNode(scene->mRootNode, m);
LCA_ASSERT(parentNode != nullptr, "AssetManager", "loadSkeletonModel", "Parent node not found for mesh: " + std::to_string(m));
std::string nodeName(parentNode->mName.C_Str());
LCA_ASSERT(nodeIndexMap.find(nodeName) != nodeIndexMap.end(), "AssetManager", "loadSkeletonModel", "Node not found in node mapping: " + nodeName);
meshNodeIndex = nodeIndexMap[nodeName];
for (uint32_t v = 0; v < aiMeshPtr->mNumVertices; ++v) {
vertices[v].nodeIndex = meshNodeIndex;
vertices[v].bones = glm::ivec4(meshNodeIndex, 0, 0, 0);
vertices[v].weights = glm::vec4(1.0f, 0.0f, 0.0f, 0.0f);
}
}
// --- Extract indices ---
std::vector<uint32_t> indices;
for (uint32_t f = 0; f < aiMeshPtr->mNumFaces; ++f) {
const aiFace& face = aiMeshPtr->mFaces[f];
indices.push_back(face.mIndices[0]);
indices.push_back(face.mIndices[2]);
indices.push_back(face.mIndices[1]);
}
uint32_t meshId = addSkeletonMesh(meshName, vertices, indices);
uint32_t materialId = processedMaterials[aiMeshPtr->mMaterialIndex];
std::string matName = processedMaterialNames[aiMeshPtr->mMaterialIndex];
model.push_back({ meshName, matName, meshId, materialId, meshNodeIndex });
}
skeletonModelMap[name] = model;
LCA_LOGI("AssetManager", "loadSkeletonModel", "Loaded skeleton model '" + name + "' with " + std::to_string(model.size()) + " mesh(es) from " + filePath);
return model;
}