-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathModel.cpp
More file actions
3172 lines (2673 loc) · 137 KB
/
Model.cpp
File metadata and controls
3172 lines (2673 loc) · 137 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
/* SimShip by Edouard Halbert
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License
http://creativecommons.org/licenses/by-nc-nd/4.0/ */
#include "Model.h"
mat4 LightViewProjection;
extern uint32_t g_FramesInFlight;
extern unique_ptr<VulkanTexture>g_TexShadowDepth;
extern VkSampler g_TexShadowDepthSampler;
Model::Model(shared_ptr<VulkanDevice>& vulkanDevice)
{
mVulkanDevice = vulkanDevice;
}
Model::~Model()
{
for (int i = 0; i < g_FramesInFlight; i++)
{
if (mMsMatrixUBO.size() > i) mMsMatrixUBO[i].reset();
if (mMsLightUBO.size() > i) mMsLightUBO[i].reset();
if (mMsViewUBO.size() > i) mMsViewUBO[i].reset();
if (mCxMatrixUBO.size() > i) mCxMatrixUBO[i].reset();
if (mCxLightUBO.size() > i) mCxLightUBO[i].reset();
if (mCxViewUBO.size() > i) mCxViewUBO[i].reset();
if (mShadowMatrixUBO.size() > i) mShadowMatrixUBO[i].reset();
if (mReflMatrixUBO.size() > i) mReflMatrixUBO[i].reset();
if (mReflLightUBO.size() > i) mReflLightUBO[i].reset();
if (mReflViewUBO.size() > i) mReflViewUBO[i].reset();
}
muTextureCache.clear();
for (auto& mesh : mvMeshes)
{
mesh.vertexBuffer.reset();
mesh.indexBuffer.reset();
}
mShadowPipeline.destroy(mVulkanDevice->device);
mReflPipeline.destroy(mVulkanDevice->device);
mBboxPipeline.destroy(mVulkanDevice->device);
mCxPipeline.destroy(mVulkanDevice->device);
mMsPipeline.destroy(mVulkanDevice->device);
vkDestroyDescriptorPool(mVulkanDevice->device, mTexMeshDescPool, nullptr);
vkDestroyDescriptorSetLayout(mVulkanDevice->device, mTexMeshDescSetLayout, nullptr);
}
// Load model
void Model::LoadModel(const char* modelPath, VkFrontFace frontFace, VkCullModeFlags cullMode)
{
mFrontFace = frontFace;
mCullMode = cullMode;
// Assimp : Load model
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile(modelPath, aiProcess_Triangulate | aiProcess_GenSmoothNormals | aiProcess_FlipUVs);
if (!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode)
{
cout << "ERROR::ASSIMP:: " << importer.GetErrorString() << std::endl;
return;
}
// Directory path
string path(modelPath);
mDirectory = path.substr(0, path.find_last_of('/'));
if (mDirectory.length() == 0)
mDirectory = path.substr(0, path.find_last_of('\\'));
// Process hierarchy + meshes
ProcessNode(scene->mRootNode, scene);
// Get bounding box
SetBoundingBox();
#ifdef INFO_INIT // Structures.h
cout << "Model : " << path << " " << mvMeshes.size() << " meshes, " << vTypePaths.size() << " textures" << std::endl;
#endif
// GPU Buffers (vertex/index)
CreateMeshBuffers();
// Shared textures
for (auto& mesh : mvMeshes)
{
mesh.vTextures.resize(mesh.vTypePaths.size());
for (size_t i = 0; i < mesh.vTypePaths.size(); i++)
{
bool bTransparency = false;
mesh.vTextures[i] = LoadTextureShared(mesh.vTypePaths[i].path, bTransparency);
mesh.HasTransparency = bTransparency;
if (!mesh.vTextures[i])
cout << "Failed: " << mesh.vTypePaths[i].path << std::endl;
}
if (mesh.Material.diffuse.a < 0.99f)
mesh.HasTransparency = true;
// Identify the COMP texture among the loaded textures
mesh.pTexComp = nullptr;
for (size_t i = 0; i < mesh.vTypePaths.size(); i++)
{
if (mesh.vTypePaths[i].type == "texture_comp" && mesh.vTextures[i])
{
mesh.pTexComp = mesh.vTextures[i];
break;
}
}
}
mTexDummyWhite.CreateDummyTexture(mVulkanDevice);
mTexDummyBlack.CreateDummyTexture(mVulkanDevice, 0, 0, 0); // R=AO=0(plein), G=Roughness=0, B=Metallic=0
mTexEnvMap.CreateFromFile(mVulkanDevice, "Resources/Textures/citrus_orchard_puresky_2k.hdr");
// Create lists of opaque and transparent meshes
mvTransparentMeshes.clear();
mvOpaqueMeshes.clear();
for (auto& mesh : mvMeshes)
{
if (mesh.HasTransparency)
mvTransparentMeshes.push_back(&mesh);
else
mvOpaqueMeshes.push_back(&mesh);
}
// Gloabal transparency flag
if (mvTransparentMeshes.size() > 0)
HasTransparency = true;
}
void Model::ProcessNode(aiNode* node, const aiScene* scene)
{
for (unsigned int i = 0; i < node->mNumMeshes; i++)
{
aiMesh* mesh = scene->mMeshes[node->mMeshes[i]];
NbVertices += mesh->mNumVertices;
NbFaces += mesh->mNumFaces;
mvMeshes.push_back(ProcessMesh(mesh, scene));
}
for (unsigned int i = 0; i < node->mNumChildren; i++)
ProcessNode(node->mChildren[i], scene);
}
Mesh Model::ProcessMesh(aiMesh* mesh, const aiScene* scene)
{
vector<sVertex> vVertices;
vector<unsigned int> vIndices;
vector<sTypePath> vTypePaths;
// Vertices
for (unsigned int i = 0; i < mesh->mNumVertices; i++)
{
sVertex vertex;
// position
vec3 vector;
vector.x = mesh->mVertices[i].x;
vector.y = mesh->mVertices[i].y;
vector.z = mesh->mVertices[i].z;
vertex.pos = vector;
// normals
if (mesh->HasNormals())
{
vector.x = mesh->mNormals[i].x;
vector.y = mesh->mNormals[i].y;
vector.z = mesh->mNormals[i].z;
vertex.normal = vector;
}
// texture coordinates
if (mesh->mTextureCoords[0])
{
vec2 vec;
vec.x = mesh->mTextureCoords[0][i].x;
vec.y = mesh->mTextureCoords[0][i].y;
vertex.texCoord = vec;
}
else
vertex.texCoord = vec2(0.0f, 0.0f);
vVertices.push_back(vertex);
}
// Indices
for (unsigned int i = 0; i < mesh->mNumFaces; i++)
{
aiFace face = mesh->mFaces[i];
// retrieve all mvIndices of the face and store them in the mvIndices vector
for (unsigned int j = 0; j < face.mNumIndices; j++)
vIndices.push_back(face.mIndices[j]);
}
// Materials
aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex];
sMaterial mat;
// Name
aiString name;
if (AI_SUCCESS == material->Get(AI_MATKEY_NAME, name))
string matName = name.C_Str();
// Ambient
mat.ambient = vec4(0.0f, 0.0f, 0.0f, 1.0f);
aiColor4D ambient(0.0f, 0.0f, 0.0f, 1.0f);
if (AI_SUCCESS == material->Get(AI_MATKEY_COLOR_AMBIENT, ambient))
mat.ambient = vec4(ambient.r, ambient.g, ambient.b, ambient.a);
// Diffuse
mat.diffuse = vec4(0.0f, 0.0f, 0.0f, 1.0f);
aiColor4D diffuse(0.0f, 0.0f, 0.0f, 1.0f);
if (AI_SUCCESS == material->Get(AI_MATKEY_COLOR_DIFFUSE, diffuse))
mat.diffuse = vec4(diffuse.r, diffuse.g, diffuse.b, diffuse.a);
// Specular
mat.specular = vec4(0.0f, 0.0f, 0.0f, 1.0f);
aiColor4D specular(0.0f, 0.0f, 0.0f, 1.0f);
if (AI_SUCCESS == material->Get(AI_MATKEY_COLOR_SPECULAR, specular))
mat.specular = vec4(specular.r, specular.g, specular.b, specular.a);
// Emission
mat.emission = vec4(0.0f, 0.0f, 0.0f, 1.0f);
aiColor4D emission(0.0f, 0.0f, 0.0f, 1.0f);
if (AI_SUCCESS == material->Get(AI_MATKEY_COLOR_EMISSIVE, emission))
mat.emission = vec4(emission.r, emission.g, emission.b, emission.a);
// Shininess
float shininess = 0.0f;
if (AI_SUCCESS == material->Get(AI_MATKEY_SHININESS, shininess))
{
float strength;
if (AI_SUCCESS == material->Get(AI_MATKEY_SHININESS_STRENGTH, strength))
mat.shininess = shininess * strength;
else
mat.shininess = shininess;
}
else
mat.shininess = 0.0f;
// Roughness
float roughness = 1.0f;
if (AI_SUCCESS == material->Get(AI_MATKEY_ROUGHNESS_FACTOR, roughness))
mat.roughness = roughness;
else
mat.roughness = 1.0f;
// Metallic
float metallic = 0.0f;
if (AI_SUCCESS == material->Get(AI_MATKEY_METALLIC_FACTOR, metallic))
mat.metallic = metallic;
else
mat.metallic = 0.0f;
// Textures
// 1. diffuse maps
vector<sTypePath> diffuseMaps = ListTextures(material, aiTextureType_DIFFUSE, "texture_diffuse");
vTypePaths.insert(vTypePaths.end(), diffuseMaps.begin(), diffuseMaps.end());
// 2. specular maps
vector<sTypePath> specularMaps = ListTextures(material, aiTextureType_SPECULAR, "texture_specular");
vTypePaths.insert(vTypePaths.end(), specularMaps.begin(), specularMaps.end());
// 3. normal maps
vector<sTypePath> heightMaps = ListTextures(material, aiTextureType_NORMALS, "texture_normals");
vTypePaths.insert(vTypePaths.end(), heightMaps.begin(), heightMaps.end());
// 4. height maps
vector<sTypePath> normalMaps = ListTextures(material, aiTextureType_HEIGHT, "texture_height");
vTypePaths.insert(vTypePaths.end(), normalMaps.begin(), normalMaps.end());
// 5. COMP map (GLTF metallicRoughness = aiTextureType_UNKNOWN via Assimp)
// Fallback : search in other types for a texture whose name contains "_COMP"
vector<sTypePath> compMaps = ListTextures(material, aiTextureType_UNKNOWN, "texture_comp");
if (compMaps.empty())
{
// Fallback : iterate through all known types, search for "_COMP" in the path
static const aiTextureType allTypes[] = {
aiTextureType_DIFFUSE, aiTextureType_SPECULAR, aiTextureType_AMBIENT,
aiTextureType_EMISSIVE, aiTextureType_HEIGHT, aiTextureType_NORMALS,
aiTextureType_SHININESS, aiTextureType_OPACITY, aiTextureType_DISPLACEMENT,
aiTextureType_LIGHTMAP, aiTextureType_REFLECTION, aiTextureType_UNKNOWN
};
for (auto t : allTypes)
{
for (unsigned int i = 0; i < material->GetTextureCount(t); i++)
{
aiString str;
material->GetTexture(t, i, &str);
string path(str.C_Str());
string pathUpper = path;
transform(pathUpper.begin(), pathUpper.end(), pathUpper.begin(), ::toupper);
if (pathUpper.find("_COMP") != string::npos)
{
compMaps.push_back({ "texture_comp", path });
break;
}
}
if (!compMaps.empty()) break;
}
}
vTypePaths.insert(vTypePaths.end(), compMaps.begin(), compMaps.end());
return Mesh(vVertices, vIndices, mat, vTypePaths);
}
void Model::SetBoundingBox()
{
mBbox.min = { std::numeric_limits<float>::max(), std::numeric_limits<float>::max(), std::numeric_limits<float>::max() };
mBbox.max = { std::numeric_limits<float>::lowest(), std::numeric_limits<float>::lowest(), std::numeric_limits<float>::lowest() };
for (const auto& mesh : mvMeshes)
{
for (const auto& vertex : mesh.vVertices)
{
mBbox.min.x = std::min(mBbox.min.x, vertex.pos.x);
mBbox.min.y = std::min(mBbox.min.y, vertex.pos.y);
mBbox.min.z = std::min(mBbox.min.z, vertex.pos.z);
mBbox.max.x = std::max(mBbox.max.x, vertex.pos.x);
mBbox.max.y = std::max(mBbox.max.y, vertex.pos.y);
mBbox.max.z = std::max(mBbox.max.z, vertex.pos.z);
}
}
mCorners[0] = { mBbox.min.x, mBbox.min.y, mBbox.min.z, 1.0f };
mCorners[1] = { mBbox.max.x, mBbox.min.y, mBbox.min.z, 1.0f };
mCorners[2] = { mBbox.min.x, mBbox.max.y, mBbox.min.z, 1.0f };
mCorners[3] = { mBbox.max.x, mBbox.max.y, mBbox.min.z, 1.0f };
mCorners[4] = { mBbox.min.x, mBbox.min.y, mBbox.max.z, 1.0f };
mCorners[5] = { mBbox.max.x, mBbox.min.y, mBbox.max.z, 1.0f };
mCorners[6] = { mBbox.min.x, mBbox.max.y, mBbox.max.z, 1.0f };
mCorners[7] = { mBbox.max.x, mBbox.max.y, mBbox.max.z, 1.0f };
}
vector<sTypePath> Model::ListTextures(aiMaterial* mat, aiTextureType type, string typeName)
{
// checks all material textures of a given type and loads the textures if they're not loaded yet. The required info is returned as a Texture struct.
vector<sTypePath> vTypePaths;
for (unsigned int i = 0; i < mat->GetTextureCount(type); i++)
{
aiString str;
mat->GetTexture(type, i, &str);
// check if texture was loaded before and if so, continue to next iteration: skip loading a new texture
bool skip = false;
for (unsigned int j = 0; j < vTypePaths.size(); j++)
{
if (strcmp(vTypePaths[j].path.data(), str.C_Str()) == 0)
{
skip = true; // a texture with the same filepath has already been loaded, continue to next one. (optimization)
break;
}
}
if (!skip)
{ // if texture hasn't been loaded already, load it
sTypePath texture{ typeName, str.C_Str() };
vTypePaths.push_back(texture);
}
}
return vTypePaths;
}
VulkanTexture* Model::LoadTextureShared(const string& texturePath, bool& bTransparency)
{
string fullPath = mDirectory + '/' + texturePath;
// Search cache
auto it = muTextureCache.find(fullPath);
if (it != muTextureCache.end()) {
it->second.refCount++;
bTransparency = it->second.hasTransparency;
return &it->second.texture;
}
// Create directly in cache → NO copy!
auto& newEntry = muTextureCache[fullPath];
newEntry.path = fullPath;
if (!newEntry.texture.CreateFromFile(mVulkanDevice, fullPath, true)) {
muTextureCache.erase(fullPath);
return nullptr;
}
newEntry.hasTransparency = newEntry.texture.bTransparency;
newEntry.refCount = 1;
return &newEntry.texture;
}
void Model::CreateMeshBuffers()
{
for (auto& mesh : mvMeshes)
{
// Vertex buffer
VkDeviceSize size = sizeof(sVertex) * mesh.vVertices.size();
VulkanBuffer vertexBuffer = VulkanBuffer(mVulkanDevice, size, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
void* data;
vkMapMemory(mVulkanDevice->device, vertexBuffer.bufferMemory, 0, size, 0, &data);
memcpy(data, mesh.vVertices.data(), (size_t)size);
vkUnmapMemory(mVulkanDevice->device, vertexBuffer.bufferMemory);
mesh.vertexBuffer = make_unique<VulkanBuffer>(mVulkanDevice, size, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
mesh.vertexBuffer->CopyIntoBuffer(vertexBuffer, size);
// Index buffer
size = sizeof(uint32_t) * mesh.vIndices.size();
VulkanBuffer indexBuffer = VulkanBuffer(mVulkanDevice, size, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
vkMapMemory(mVulkanDevice->device, indexBuffer.bufferMemory, 0, size, 0, &data);
memcpy(data, mesh.vIndices.data(), (size_t)size);
vkUnmapMemory(mVulkanDevice->device, indexBuffer.bufferMemory);
mesh.indexBuffer = make_unique<VulkanBuffer>(mVulkanDevice, size, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
mesh.indexBuffer->CopyIntoBuffer(indexBuffer, size);
mesh.indexCount = static_cast<uint32_t>(mesh.vIndices.size());
}
}
bool Model::IsVisibleInFrustum(const mat4& mvp)
{
// Plane i: all corners are on the wrong side → object is outside the frustum
for (int plane = 0; plane < 6; plane++)
{
int cornersOutside = 0;
for (int i = 0; i < 8; i++)
{
vec4 clip = mvp * mCorners[i];
bool outside = false;
switch (plane)
{
case 0: outside = clip.x < -clip.w; break; // left
case 1: outside = clip.x > clip.w; break; // right
case 2: outside = clip.y < -clip.w; break; // bottom
case 3: outside = clip.y > clip.w; break; // top
case 4: outside = clip.z < 0.0f; break; // near (Vulkan: z in [0,1])
case 5: outside = clip.z > clip.w; break; // far
}
if (outside) cornersOutside++;
}
// All corners outside this plane → object is invisible
if (cornersOutside == 8)
{
bIsVisibleInFrustum = false;
return false;
}
}
bIsVisibleInFrustum = true;
return true;
}
void Model::CreateTexMeshDescriptors()
{
array<VkDescriptorSetLayoutBinding, 2> texBindings{};
texBindings[0].binding = 0;
texBindings[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
texBindings[0].descriptorCount = 1;
texBindings[0].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
texBindings[1].binding = 1;
texBindings[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
texBindings[1].descriptorCount = 1;
texBindings[1].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
VkDescriptorSetLayoutCreateInfo layoutInfo{};
layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
layoutInfo.bindingCount = static_cast<uint32_t>(texBindings.size());
layoutInfo.pBindings = texBindings.data();
vkCreateDescriptorSetLayout(mVulkanDevice->device, &layoutInfo, nullptr, &mTexMeshDescSetLayout);
// mTexMeshDescPool : 2 samplers par mesh (diffuse + COMP)
VkDescriptorPoolSize poolSize{};
poolSize.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
poolSize.descriptorCount = static_cast<uint32_t>(mvMeshes.size() * 2); // x2 : diffuse + COMP
VkDescriptorPoolCreateInfo poolInfo{};
poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
poolInfo.poolSizeCount = 1;
poolInfo.pPoolSizes = &poolSize;
poolInfo.maxSets = static_cast<uint32_t>(mvMeshes.size());
vkCreateDescriptorPool(mVulkanDevice->device, &poolInfo, nullptr, &mTexMeshDescPool);
}
void Model::UpdateTexMeshDescriptors()
{
vector<VkDescriptorSetLayout> layouts(mvMeshes.size(), mTexMeshDescSetLayout);
VkDescriptorSetAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
allocInfo.descriptorPool = mTexMeshDescPool;
allocInfo.descriptorSetCount = static_cast<uint32_t>(mvMeshes.size());
allocInfo.pSetLayouts = layouts.data();
vector<VkDescriptorSet> textureSets(mvMeshes.size());
vkAllocateDescriptorSets(mVulkanDevice->device, &allocInfo, textureSets.data());
// Update each set
for (size_t i = 0; i < mvMeshes.size(); i++)
{
auto& mesh = mvMeshes[i];
mesh.DescriptorSet = textureSets[i];
// binding 0 : diffuse (or dummy white if absent)
VulkanTexture* texDiffuse = (!mesh.vTextures.empty() && mesh.vTextures[0]) ? mesh.vTextures[0] : &mTexDummyWhite;
VkDescriptorImageInfo diffuseInfo{};
diffuseInfo.imageLayout = VK_IMAGE_LAYOUT_GENERAL;
diffuseInfo.imageView = texDiffuse->imageView;
diffuseInfo.sampler = texDiffuse->sampler;
VkWriteDescriptorSet writeDiffuse{};
writeDiffuse.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
writeDiffuse.dstSet = mesh.DescriptorSet;
writeDiffuse.dstBinding = 0;
writeDiffuse.descriptorCount = 1;
writeDiffuse.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
writeDiffuse.pImageInfo = &diffuseInfo;
// binding 1 : COMP (R=AO, G=Roughness, B=Metallic) — dummy black if absent
VulkanTexture* texComp = mesh.pTexComp ? mesh.pTexComp : &mTexDummyBlack;
VkDescriptorImageInfo compInfo{};
compInfo.imageLayout = VK_IMAGE_LAYOUT_GENERAL;
compInfo.imageView = texComp->imageView;
compInfo.sampler = texComp->sampler;
VkWriteDescriptorSet writeComp{};
writeComp.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
writeComp.dstSet = mesh.DescriptorSet;
writeComp.dstBinding = 1;
writeComp.descriptorCount = 1;
writeComp.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
writeComp.pImageInfo = &compInfo;
array<VkWriteDescriptorSet, 2> writes = { writeDiffuse, writeComp };
vkUpdateDescriptorSets(mVulkanDevice->device, static_cast<uint32_t>(writes.size()), writes.data(), 0, nullptr);
}
}
// Pipeline of shadow
void Model::CreateShadowPipeline(VkRenderPass renderPass, VkExtent2D shadowExtent)
{
mShadowExtent = shadowExtent;
// Previous cleanup
mShadowPipeline.destroy(mVulkanDevice->device);
// Texture descriptors (Set 1: Per-mesh) - reused from MsPipeline
CreateTexMeshDescriptors();
UpdateTexMeshDescriptors();
// 1. Shaders
// Shader opaque (vertex)
auto vertCode = CompileShaderRuntime("Resources/Shaders/Model/model_shadow.vert");
VkShaderModule vertModule = CreateShaderModule(mVulkanDevice->device, vertCode);
VkPipelineShaderStageCreateInfo opaqueShaderStage = {
VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, nullptr, 0, VK_SHADER_STAGE_VERTEX_BIT, vertModule, "main"
};
// Shaders transparent (vertex + fragment)
auto vertTranspCode = CompileShaderRuntime("Resources/Shaders/Model/model_shadow_transparent.vert");
auto fragTranspCode = CompileShaderRuntime("Resources/Shaders/Model/model_shadow_transparent.frag");
VkShaderModule vertTranspModule = CreateShaderModule(mVulkanDevice->device, vertTranspCode);
VkShaderModule fragTranspModule = CreateShaderModule(mVulkanDevice->device, fragTranspCode);
VkPipelineShaderStageCreateInfo transpShaderStages[] = {
{ VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, nullptr, 0, VK_SHADER_STAGE_VERTEX_BIT, vertTranspModule, "main" },
{ VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, nullptr, 0, VK_SHADER_STAGE_FRAGMENT_BIT, fragTranspModule, "main" }
};
// 2. Vertex input
// opaque (position only)
auto bindingDescription = sVertex::getBindingDescription();
array<VkVertexInputAttributeDescription, 1> opaqueAttributes = { {
{0, 0, VK_FORMAT_R32G32B32_SFLOAT, offsetof(sVertex, pos)}
} };
VkPipelineVertexInputStateCreateInfo opaqueVertexInputInfo{};
opaqueVertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
opaqueVertexInputInfo.vertexBindingDescriptionCount = 1;
opaqueVertexInputInfo.pVertexBindingDescriptions = &bindingDescription;
opaqueVertexInputInfo.vertexAttributeDescriptionCount = 1;
opaqueVertexInputInfo.pVertexAttributeDescriptions = opaqueAttributes.data();
// transparent (position + UV)
array<VkVertexInputAttributeDescription, 2> transpAttributes = { {
{0, 0, VK_FORMAT_R32G32B32_SFLOAT, offsetof(sVertex, pos)},
{1, 0, VK_FORMAT_R32G32_SFLOAT, offsetof(sVertex, texCoord)}
} };
VkPipelineVertexInputStateCreateInfo transpVertexInputInfo{};
transpVertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
transpVertexInputInfo.vertexBindingDescriptionCount = 1;
transpVertexInputInfo.pVertexBindingDescriptions = &bindingDescription;
transpVertexInputInfo.vertexAttributeDescriptionCount = 2;
transpVertexInputInfo.pVertexAttributeDescriptions = transpAttributes.data();
// 3. DescriptorSetLayout Set 0 (UBO shadow)
array<VkDescriptorSetLayoutBinding, 1> bindings = { VkDescriptorSetLayoutBinding{
0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_VERTEX_BIT, nullptr
} };
VkDescriptorSetLayoutCreateInfo layoutInfo{};
layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
layoutInfo.bindingCount = static_cast<uint32_t>(bindings.size());
layoutInfo.pBindings = bindings.data();
vkCreateDescriptorSetLayout(mVulkanDevice->device, &layoutInfo, nullptr, &mShadowPipeline.descSetLayout);
// 4. PipelineLayout : Set 0 (UBO) + Set 1 (textures mesh)
array<VkDescriptorSetLayout, 2> pipelineLayouts = {
mShadowPipeline.descSetLayout, // Set 0 : UBO shadow
mTexMeshDescSetLayout // Set 1 : textures per mesh (reused)
};
VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipelineLayoutInfo.setLayoutCount = 2;
pipelineLayoutInfo.pSetLayouts = pipelineLayouts.data();
vkCreatePipelineLayout(mVulkanDevice->device, &pipelineLayoutInfo, nullptr, &mShadowPipeline.pipelineLayout);
// 5. Input assembly
VkPipelineInputAssemblyStateCreateInfo inputAssembly{};
inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
inputAssembly.primitiveRestartEnable = VK_FALSE;
// 6. Viewport & scissors
VkViewport viewport{ 0.0f, 0.0f, (float)shadowExtent.width, (float)shadowExtent.height, 0.0f, 1.0f };
VkRect2D scissor{ {0, 0}, shadowExtent };
VkPipelineViewportStateCreateInfo viewportState{};
viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
viewportState.viewportCount = 1;
viewportState.pViewports = &viewport;
viewportState.scissorCount = 1;
viewportState.pScissors = &scissor;
// 7. Rasterizer
VkPipelineRasterizationStateCreateInfo rasterizer{};
rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
rasterizer.depthClampEnable = VK_FALSE;
rasterizer.rasterizerDiscardEnable = VK_FALSE;
rasterizer.polygonMode = VK_POLYGON_MODE_FILL;
rasterizer.lineWidth = 1.0f;
rasterizer.cullMode = VK_CULL_MODE_NONE;
rasterizer.frontFace = mFrontFace;
rasterizer.depthBiasEnable = VK_TRUE;
// 8. Multisampling 1x
VkPipelineMultisampleStateCreateInfo multisampling{};
multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
multisampling.sampleShadingEnable = VK_FALSE;
multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
// 9. Depth stencil (write only)
VkPipelineDepthStencilStateCreateInfo depthStencil{};
depthStencil.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
depthStencil.depthTestEnable = VK_TRUE;
depthStencil.depthWriteEnable = VK_TRUE;
depthStencil.depthCompareOp = VK_COMPARE_OP_LESS;
depthStencil.depthBoundsTestEnable = VK_FALSE;
depthStencil.stencilTestEnable = VK_FALSE;
// 10. Dynamic state
VkDynamicState dynamicStates[] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_LINE_WIDTH, VK_DYNAMIC_STATE_DEPTH_BIAS };
VkPipelineDynamicStateCreateInfo dynamicState{};
dynamicState.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
dynamicState.dynamicStateCount = 3;
dynamicState.pDynamicStates = dynamicStates;
// 11. Base pipelineInfo commune
VkGraphicsPipelineCreateInfo pipelineInfo{};
pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
pipelineInfo.pInputAssemblyState = &inputAssembly;
pipelineInfo.pViewportState = &viewportState;
pipelineInfo.pRasterizationState = &rasterizer;
pipelineInfo.pMultisampleState = &multisampling;
pipelineInfo.pDepthStencilState = &depthStencil;
pipelineInfo.pDynamicState = &dynamicState;
pipelineInfo.layout = mShadowPipeline.pipelineLayout;
pipelineInfo.renderPass = renderPass;
pipelineInfo.subpass = 0;
pipelineInfo.basePipelineHandle = VK_NULL_HANDLE;
// 12. Pipeline opaque (vertex only, position only, 0 attachment)
VkPipelineColorBlendStateCreateInfo opaqueColorBlending{};
opaqueColorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
opaqueColorBlending.logicOpEnable = VK_FALSE;
opaqueColorBlending.attachmentCount = 0;
opaqueColorBlending.pAttachments = nullptr;
pipelineInfo.stageCount = 1;
pipelineInfo.pStages = &opaqueShaderStage;
pipelineInfo.pVertexInputState = &opaqueVertexInputInfo;
pipelineInfo.pColorBlendState = &opaqueColorBlending;
vkCreateGraphicsPipelines(mVulkanDevice->device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &mShadowPipeline.pipelineOpaque);
// 13. Pipeline transparent (vertex + frag, position + UV, discard alpha)
VkPipelineColorBlendStateCreateInfo transpColorBlending{};
transpColorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
transpColorBlending.logicOpEnable = VK_FALSE;
transpColorBlending.attachmentCount = 0;
transpColorBlending.pAttachments = nullptr;
pipelineInfo.stageCount = 2;
pipelineInfo.pStages = transpShaderStages;
pipelineInfo.pVertexInputState = &transpVertexInputInfo;
pipelineInfo.pColorBlendState = &transpColorBlending;
vkCreateGraphicsPipelines(mVulkanDevice->device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &mShadowPipeline.pipelineTransparent);
vkDestroyShaderModule(mVulkanDevice->device, vertModule, nullptr);
vkDestroyShaderModule(mVulkanDevice->device, vertTranspModule, nullptr);
vkDestroyShaderModule(mVulkanDevice->device, fragTranspModule, nullptr);
CreateShadowDescriptors();
}
void Model::CreateShadowDescriptors()
{
mShadowMatrixUBO.resize(g_FramesInFlight);
mShadowPipeline.descSet.resize(g_FramesInFlight);
for (size_t i = 0; i < g_FramesInFlight; i++)
mShadowMatrixUBO[i] = make_unique<VulkanUBO>(mVulkanDevice, sizeof(sShadowUBO));
// Pool : UBO only (Set 0), The Set 1 texture is managed by CreateTexMeshDescriptors
array<VkDescriptorPoolSize, 1> poolSizes{};
poolSizes[0].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
poolSizes[0].descriptorCount = static_cast<uint32_t>(g_FramesInFlight);
VkDescriptorPoolCreateInfo poolInfo{};
poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
poolInfo.poolSizeCount = static_cast<uint32_t>(poolSizes.size());
poolInfo.pPoolSizes = poolSizes.data();
poolInfo.maxSets = static_cast<uint32_t>(g_FramesInFlight);
vkCreateDescriptorPool(mVulkanDevice->device, &poolInfo, nullptr, &mShadowPipeline.descPool);
// Allocate 1 descriptor set per frame in flight
vector<VkDescriptorSetLayout> layouts(g_FramesInFlight, mShadowPipeline.descSetLayout);
VkDescriptorSetAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
allocInfo.descriptorPool = mShadowPipeline.descPool;
allocInfo.descriptorSetCount = static_cast<uint32_t>(g_FramesInFlight);
allocInfo.pSetLayouts = layouts.data();
vkAllocateDescriptorSets(mVulkanDevice->device, &allocInfo, mShadowPipeline.descSet.data());
UpdateShadowDescriptors();
}
void Model::UpdateShadowDescriptors()
{
for (size_t i = 0; i < g_FramesInFlight; ++i)
{
VkDescriptorBufferInfo shadowInfo{};
shadowInfo.buffer = mShadowMatrixUBO[i]->buffer;
shadowInfo.offset = 0;
shadowInfo.range = sizeof(sShadowUBO);
VkWriteDescriptorSet write{};
write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
write.dstSet = mShadowPipeline.descSet[i];
write.dstBinding = 0;
write.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
write.descriptorCount = 1;
write.pBufferInfo = &shadowInfo;
vkUpdateDescriptorSets(mVulkanDevice->device, 1, &write, 0, nullptr);
}
mHasShadowPipeline = true;
}
void Model::UpdateShadowUBOs(uint32_t currentImage, Camera& camera, Sky* sky, mat4 model, vec3 Position)
{
vec3 lightDir = glm::normalize(sky->SunPosition);
vec3 lightPos = lightDir * 200.0f;
mat4 lightView = glm::lookAt(Position, -lightPos + Position, vec3(0.0f, 1.0f, 0.0f));
vec3 BBmin = glm::vec3(model * vec4(mBbox.min, 1.0f));
vec3 BBmax = glm::vec3(model * vec4(mBbox.max, 1.0f));
vec3 bboxCorners[8];
bboxCorners[0] = vec3(BBmin.x, BBmin.y, BBmin.z);
bboxCorners[1] = vec3(BBmax.x, BBmin.y, BBmin.z);
bboxCorners[2] = vec3(BBmin.x, BBmax.y, BBmin.z);
bboxCorners[3] = vec3(BBmax.x, BBmax.y, BBmin.z);
bboxCorners[4] = vec3(BBmin.x, BBmin.y, BBmax.z);
bboxCorners[5] = vec3(BBmax.x, BBmin.y, BBmax.z);
bboxCorners[6] = vec3(BBmin.x, BBmax.y, BBmax.z);
bboxCorners[7] = vec3(BBmax.x, BBmax.y, BBmax.z);
vec3 lightSpaceMin(FLT_MAX);
vec3 lightSpaceMax(-FLT_MAX);
for (int i = 0; i < 8; ++i)
{
vec4 lightSpacePos = lightView * vec4(bboxCorners[i], 1.0f);
lightSpaceMin = glm::min(lightSpaceMin, vec3(lightSpacePos));
lightSpaceMax = glm::max(lightSpaceMax, vec3(lightSpacePos));
}
vec3 lightSpaceSize = lightSpaceMax - lightSpaceMin;
float dimOptimized = glm::max(lightSpaceSize.x, lightSpaceSize.y) * 0.5f;
dimOptimized *= 1.0f; // Margin
const float far_plane = 300.0f;
mat4 lightProjection = glm::ortho(-dimOptimized, dimOptimized, -dimOptimized, dimOptimized, -dimOptimized, dimOptimized * 2.0f);
/* Z_openGL ∈ [-1,1] --lightProjection(GLM)--> Z_ndc ∈ [-1,1]
↓
Z_ndc ∈ [-1,1] --depthFix--> Z_vulkan ∈ [0,1] */
mat4 depthFix(1.0f);
depthFix[2][2] = 0.5f;
depthFix[3][2] = 0.5f;
lightProjection = depthFix * lightProjection;
LightViewProjection = lightProjection * lightView;
sShadowUBO* ubo = static_cast<sShadowUBO*>(mShadowMatrixUBO[currentImage]->data);
*ubo = { LightViewProjection, model };
}
void Model::RenderShadow(VkCommandBuffer cmd, int iCurrentFrame)
{
if (!bVisible) return;
RenderShadowOpaque(cmd, iCurrentFrame);
RenderShadowTransparent(cmd, iCurrentFrame);
}
void Model::RenderShadowOpaque(VkCommandBuffer cmd, int iCurrentFrame)
{
if (!bVisible) return;
vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, mShadowPipeline.pipelineOpaque);
vkCmdSetDepthBias(cmd, 1.25f, 0.0f, 0.025f); // Anti-acne
vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, mShadowPipeline.pipelineLayout, 0, 1, &mShadowPipeline.descSet[iCurrentFrame], 0, nullptr);
for (const auto* mesh : mvOpaqueMeshes)
{
// Vertex buffers
VkBuffer vertexBuffers[] = { mesh->vertexBuffer->buffer };
VkDeviceSize offsets[] = { 0 };
vkCmdBindVertexBuffers(cmd, 0, 1, vertexBuffers, offsets);
vkCmdBindIndexBuffer(cmd, mesh->indexBuffer->buffer, 0, VK_INDEX_TYPE_UINT32);
vkCmdDrawIndexed(cmd, mesh->indexCount, 1, 0, 0, 0);
}
}
void Model::RenderShadowTransparent(VkCommandBuffer cmd, int iCurrentFrame)
{
if (!bVisible) return;
vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, mShadowPipeline.pipelineTransparent);
vkCmdSetDepthBias(cmd, 1.25f, 0.0f, 0.025f); // Anti-acne
vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, mShadowPipeline.pipelineLayout, 0, 1, &mShadowPipeline.descSet[iCurrentFrame], 0, nullptr);
for (const auto* mesh : mvTransparentMeshes)
{
vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, mShadowPipeline.pipelineLayout, 1, 1, &mesh->DescriptorSet, 0, nullptr);
// Vertex buffers
VkBuffer vertexBuffers[] = { mesh->vertexBuffer->buffer };
VkDeviceSize offsets[] = { 0 };
vkCmdBindVertexBuffers(cmd, 0, 1, vertexBuffers, offsets);
vkCmdBindIndexBuffer(cmd, mesh->indexBuffer->buffer, 0, VK_INDEX_TYPE_UINT32);
vkCmdDrawIndexed(cmd, mesh->indexCount, 1, 0, 0, 0);
}
}
// Pipeline of reflection
void Model::CreateReflectionPipeline(VkRenderPass renderPass, VkExtent2D swapChainExtent)
{
// Texture descriptors (Set 1: Per-mesh)
CreateTexMeshDescriptors();
UpdateTexMeshDescriptors();
// Previous cleanup
mReflPipeline.destroy(mVulkanDevice->device);
// 1. Shaders
auto vertCode = CompileShaderRuntime("Resources/Shaders/Model/model_reflection.vert");
auto fragCode = CompileShaderRuntime("Resources/Shaders/Model/model_reflection.frag");
VkShaderModule vertModule = CreateShaderModule(mVulkanDevice->device, vertCode);
VkShaderModule fragModule = CreateShaderModule(mVulkanDevice->device, fragCode);
VkPipelineShaderStageCreateInfo shaderStages[] = {
{ VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, nullptr, 0, VK_SHADER_STAGE_VERTEX_BIT, vertModule, "main" },
{ VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, nullptr, 0, VK_SHADER_STAGE_FRAGMENT_BIT, fragModule, "main" }
};
// 2. Vertex input
auto attributeDescriptions = sVertex::getAttributeDescriptions();
auto bindingDescription = sVertex::getBindingDescription();
VkPipelineVertexInputStateCreateInfo vertexInputInfo{};
vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
vertexInputInfo.vertexBindingDescriptionCount = 1;
vertexInputInfo.pVertexBindingDescriptions = &bindingDescription;
vertexInputInfo.vertexAttributeDescriptionCount = static_cast<uint32_t>(attributeDescriptions.size());
vertexInputInfo.pVertexAttributeDescriptions = attributeDescriptions.data();
// 3. DescriptorSetLayout
array<VkDescriptorSetLayoutBinding, 3> bindings = { {
{ 0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_VERTEX_BIT, nullptr }, // Matrix
{ 1, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr }, // Light
{ 2, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr } // CamPos
} };
VkDescriptorSetLayoutCreateInfo layoutInfo{};
layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
layoutInfo.bindingCount = static_cast<uint32_t>(bindings.size());
layoutInfo.pBindings = bindings.data();
vkCreateDescriptorSetLayout(mVulkanDevice->device, &layoutInfo, nullptr, &mReflPipeline.descSetLayout);
// 4. Pipeline Layout
array<VkDescriptorSetLayout, 2> pipelineLayouts = {
mReflPipeline.descSetLayout, // Set 0: MVP + Light + CamPos
mTexMeshDescSetLayout // Set 1: Texture mesh
};
VkPushConstantRange pushRange{};
pushRange.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
pushRange.offset = 0;
pushRange.size = sizeof(sMaterial);
VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipelineLayoutInfo.setLayoutCount = 2;
pipelineLayoutInfo.pSetLayouts = pipelineLayouts.data();
pipelineLayoutInfo.pushConstantRangeCount = 1;
pipelineLayoutInfo.pPushConstantRanges = &pushRange;
vkCreatePipelineLayout(mVulkanDevice->device, &pipelineLayoutInfo, nullptr, &mReflPipeline.pipelineLayout);
// 5. Input assembly
VkPipelineInputAssemblyStateCreateInfo inputAssembly{};
inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
inputAssembly.primitiveRestartEnable = VK_FALSE;
// 4. Viewport & scissors
VkViewport viewport{};
viewport.x = 0.0f;
viewport.y = 0.0f;
viewport.width = (float)swapChainExtent.width;
viewport.height = (float)swapChainExtent.height;
viewport.minDepth = 0.0f;
viewport.maxDepth = 1.0f;
VkRect2D scissor{};
scissor.offset = { 0, 0 };
scissor.extent = swapChainExtent;
VkPipelineViewportStateCreateInfo viewportState{};
viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
viewportState.viewportCount = 1;
viewportState.pViewports = &viewport;
viewportState.scissorCount = 1;
viewportState.pScissors = &scissor;
// 5. Rasterizer
VkPipelineRasterizationStateCreateInfo rasterizer{};
rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
rasterizer.depthClampEnable = VK_FALSE;
rasterizer.rasterizerDiscardEnable = VK_FALSE;
rasterizer.polygonMode = VK_POLYGON_MODE_FILL;
rasterizer.lineWidth = 1.0f;
rasterizer.cullMode = mCullMode;
rasterizer.frontFace = mFrontFace;
rasterizer.depthBiasEnable = VK_FALSE;
// 6. Multisampling 1x
VkPipelineMultisampleStateCreateInfo multisampling{};
multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
multisampling.sampleShadingEnable = VK_FALSE;
multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
// 7. Depth stencil
VkPipelineDepthStencilStateCreateInfo depthStencil{};
depthStencil.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
depthStencil.depthTestEnable = VK_TRUE;
depthStencil.depthWriteEnable = VK_TRUE;
depthStencil.depthCompareOp = VK_COMPARE_OP_LESS;
depthStencil.depthBoundsTestEnable = VK_FALSE;
depthStencil.stencilTestEnable = VK_FALSE;
// 8. Dynamic state
VkDynamicState dynamicStates[] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_LINE_WIDTH };
VkPipelineDynamicStateCreateInfo dynamicState{};
dynamicState.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
dynamicState.dynamicStateCount = 2;
dynamicState.pDynamicStates = dynamicStates;
// CREATION OF TWO PIPELINES
// 12. Pipeline
VkGraphicsPipelineCreateInfo pipelineInfo{};
pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;