forked from SaschaWillems/Vulkan
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscenerendering.cpp
884 lines (743 loc) · 29.2 KB
/
scenerendering.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
/*
* Vulkan Example - Scene rendering
*
* Copyright (C) 2016 by Sascha Willems - www.saschawillems.de
*
* This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT)
*
* Summary:
* Renders a scene made of multiple parts with different materials and textures.
*
* The example loads a scene made up of multiple parts into one vertex and index buffer to only
* have one (big) memory allocation. In Vulkan it's advised to keep number of memory allocations
* down and try to allocate large blocks of memory at once instead of having many small allocations.
*
* Every part has a separate material and multiple descriptor sets (set = x layout qualifier in GLSL)
* are used to bind a uniform buffer with global matrices and the part's material's sampler at once.
*
* To demonstrate another way of passing data the example also uses push constants for passing
* material properties.
*
* Note that this example is just one way of rendering a scene made up of multiple parts in Vulkan.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <vector>
#define GLM_FORCE_RADIANS
#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include <assimp/cimport.h>
#include <vulkan/vulkan.h>
#include "vulkanexamplebase.h"
#include "VulkanTexture.hpp"
#include "VulkanDevice.hpp"
#include "VulkanBuffer.hpp"
#define VERTEX_BUFFER_BIND_ID 0
#define ENABLE_VALIDATION false
// Vertex layout used in this example
struct Vertex {
glm::vec3 pos;
glm::vec3 normal;
glm::vec2 uv;
glm::vec3 color;
};
// Scene related structs
// Shader properites for a material
// Will be passed to the shaders using push constant
struct SceneMaterialProperties
{
glm::vec4 ambient;
glm::vec4 diffuse;
glm::vec4 specular;
float opacity;
};
// Stores info on the materials used in the scene
struct SceneMaterial
{
std::string name;
// Material properties
SceneMaterialProperties properties;
// The example only uses a diffuse channel
vks::Texture2D diffuse;
// The material's descriptor contains the material descriptors
VkDescriptorSet descriptorSet;
// Pointer to the pipeline used by this material
VkPipeline *pipeline;
};
// Stores per-mesh Vulkan resources
struct ScenePart
{
// Index of first index in the scene buffer
uint32_t indexBase;
uint32_t indexCount;
// Pointer to the material used by this mesh
SceneMaterial *material;
};
// Class for loading the scene and generating all Vulkan resources
class Scene
{
private:
vks::VulkanDevice *vulkanDevice;
VkQueue queue;
VkDescriptorPool descriptorPool;
// We will be using separate descriptor sets (and bindings)
// for material and scene related uniforms
struct
{
VkDescriptorSetLayout material;
VkDescriptorSetLayout scene;
} descriptorSetLayouts;
// We will be using one single index and vertex buffer
// containing vertices and indices for all meshes in the scene
// This allows us to keep memory allocations down
vks::Buffer vertexBuffer;
vks::Buffer indexBuffer;
VkDescriptorSet descriptorSetScene;
const aiScene* aScene;
// Get materials from the assimp scene and map to our scene structures
void loadMaterials()
{
materials.resize(aScene->mNumMaterials);
for (size_t i = 0; i < materials.size(); i++)
{
materials[i] = {};
aiString name;
aScene->mMaterials[i]->Get(AI_MATKEY_NAME, name);
// Properties
aiColor4D color;
aScene->mMaterials[i]->Get(AI_MATKEY_COLOR_AMBIENT, color);
materials[i].properties.ambient = glm::make_vec4(&color.r) + glm::vec4(0.1f);
aScene->mMaterials[i]->Get(AI_MATKEY_COLOR_DIFFUSE, color);
materials[i].properties.diffuse = glm::make_vec4(&color.r);
aScene->mMaterials[i]->Get(AI_MATKEY_COLOR_SPECULAR, color);
materials[i].properties.specular = glm::make_vec4(&color.r);
aScene->mMaterials[i]->Get(AI_MATKEY_OPACITY, materials[i].properties.opacity);
if ((materials[i].properties.opacity) > 0.0f)
materials[i].properties.specular = glm::vec4(0.0f);
materials[i].name = name.C_Str();
std::cout << "Material \"" << materials[i].name << "\"" << std::endl;
// Textures
std::string texFormatSuffix;
VkFormat texFormat;
// Get supported compressed texture format
if (vulkanDevice->features.textureCompressionBC) {
texFormatSuffix = "_bc3_unorm";
texFormat = VK_FORMAT_BC3_UNORM_BLOCK;
}
else if (vulkanDevice->features.textureCompressionASTC_LDR) {
texFormatSuffix = "_astc_8x8_unorm";
texFormat = VK_FORMAT_ASTC_8x8_UNORM_BLOCK;
}
else if (vulkanDevice->features.textureCompressionETC2) {
texFormatSuffix = "_etc2_unorm";
texFormat = VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK;
}
else {
vks::tools::exitFatal("Device does not support any compressed texture format!", VK_ERROR_FEATURE_NOT_PRESENT);
}
aiString texturefile;
// Diffuse
aScene->mMaterials[i]->GetTexture(aiTextureType_DIFFUSE, 0, &texturefile);
if (aScene->mMaterials[i]->GetTextureCount(aiTextureType_DIFFUSE) > 0)
{
std::cout << " Diffuse: \"" << texturefile.C_Str() << "\"" << std::endl;
std::string fileName = std::string(texturefile.C_Str());
std::replace(fileName.begin(), fileName.end(), '\\', '/');
fileName.insert(fileName.find(".ktx"), texFormatSuffix);
materials[i].diffuse.loadFromFile(assetPath + fileName, texFormat, vulkanDevice, queue);
}
else
{
std::cout << " Material has no diffuse, using dummy texture!" << std::endl;
// todo : separate pipeline and layout
materials[i].diffuse.loadFromFile(assetPath + "dummy_rgba_unorm.ktx", VK_FORMAT_R8G8B8A8_UNORM, vulkanDevice, queue);
}
// For scenes with multiple textures per material we would need to check for additional texture types, e.g.:
// aiTextureType_HEIGHT, aiTextureType_OPACITY, aiTextureType_SPECULAR, etc.
// Assign pipeline
materials[i].pipeline = (materials[i].properties.opacity == 0.0f) ? &pipelines.solid : &pipelines.blending;
}
// Generate descriptor sets for the materials
// Descriptor pool
std::vector<VkDescriptorPoolSize> poolSizes;
poolSizes.push_back(vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, static_cast<uint32_t>(materials.size())));
poolSizes.push_back(vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, static_cast<uint32_t>(materials.size())));
VkDescriptorPoolCreateInfo descriptorPoolInfo =
vks::initializers::descriptorPoolCreateInfo(
static_cast<uint32_t>(poolSizes.size()),
poolSizes.data(),
static_cast<uint32_t>(materials.size()) + 1);
VK_CHECK_RESULT(vkCreateDescriptorPool(vulkanDevice->logicalDevice, &descriptorPoolInfo, nullptr, &descriptorPool));
// Descriptor set and pipeline layouts
std::vector<VkDescriptorSetLayoutBinding> setLayoutBindings;
VkDescriptorSetLayoutCreateInfo descriptorLayout;
// Set 0: Scene matrices
setLayoutBindings.push_back(vks::initializers::descriptorSetLayoutBinding(
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
VK_SHADER_STAGE_VERTEX_BIT,
0));
descriptorLayout = vks::initializers::descriptorSetLayoutCreateInfo(
setLayoutBindings.data(),
static_cast<uint32_t>(setLayoutBindings.size()));
VK_CHECK_RESULT(vkCreateDescriptorSetLayout(vulkanDevice->logicalDevice, &descriptorLayout, nullptr, &descriptorSetLayouts.scene));
// Set 1: Material data
setLayoutBindings.clear();
setLayoutBindings.push_back(vks::initializers::descriptorSetLayoutBinding(
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
VK_SHADER_STAGE_FRAGMENT_BIT,
0));
VK_CHECK_RESULT(vkCreateDescriptorSetLayout(vulkanDevice->logicalDevice, &descriptorLayout, nullptr, &descriptorSetLayouts.material));
// Setup pipeline layout
std::array<VkDescriptorSetLayout, 2> setLayouts = { descriptorSetLayouts.scene, descriptorSetLayouts.material };
VkPipelineLayoutCreateInfo pipelineLayoutCreateInfo = vks::initializers::pipelineLayoutCreateInfo(setLayouts.data(), static_cast<uint32_t>(setLayouts.size()));
// We will be using a push constant block to pass material properties to the fragment shaders
VkPushConstantRange pushConstantRange = vks::initializers::pushConstantRange(
VK_SHADER_STAGE_FRAGMENT_BIT,
sizeof(SceneMaterialProperties),
0);
pipelineLayoutCreateInfo.pushConstantRangeCount = 1;
pipelineLayoutCreateInfo.pPushConstantRanges = &pushConstantRange;
VK_CHECK_RESULT(vkCreatePipelineLayout(vulkanDevice->logicalDevice, &pipelineLayoutCreateInfo, nullptr, &pipelineLayout));
// Material descriptor sets
for (size_t i = 0; i < materials.size(); i++)
{
// Descriptor set
VkDescriptorSetAllocateInfo allocInfo =
vks::initializers::descriptorSetAllocateInfo(
descriptorPool,
&descriptorSetLayouts.material,
1);
VK_CHECK_RESULT(vkAllocateDescriptorSets(vulkanDevice->logicalDevice, &allocInfo, &materials[i].descriptorSet));
std::vector<VkWriteDescriptorSet> writeDescriptorSets;
// todo : only use image sampler descriptor set and use one scene ubo for matrices
// Binding 0: Diffuse texture
writeDescriptorSets.push_back(vks::initializers::writeDescriptorSet(
materials[i].descriptorSet,
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
0,
&materials[i].diffuse.descriptor));
vkUpdateDescriptorSets(vulkanDevice->logicalDevice, static_cast<uint32_t>(writeDescriptorSets.size()), writeDescriptorSets.data(), 0, NULL);
}
// Scene descriptor set
VkDescriptorSetAllocateInfo allocInfo =
vks::initializers::descriptorSetAllocateInfo(
descriptorPool,
&descriptorSetLayouts.scene,
1);
VK_CHECK_RESULT(vkAllocateDescriptorSets(vulkanDevice->logicalDevice, &allocInfo, &descriptorSetScene));
std::vector<VkWriteDescriptorSet> writeDescriptorSets;
// Binding 0 : Vertex shader uniform buffer
writeDescriptorSets.push_back(vks::initializers::writeDescriptorSet(
descriptorSetScene,
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
0,
&uniformBuffer.descriptor));
vkUpdateDescriptorSets(vulkanDevice->logicalDevice, static_cast<uint32_t>(writeDescriptorSets.size()), writeDescriptorSets.data(), 0, NULL);
}
// Load all meshes from the scene and generate the buffers for rendering them
void loadMeshes(VkCommandBuffer copyCmd)
{
std::vector<Vertex> vertices;
std::vector<uint32_t> indices;
uint32_t indexBase = 0;
meshes.resize(aScene->mNumMeshes);
for (uint32_t i = 0; i < meshes.size(); i++)
{
aiMesh *aMesh = aScene->mMeshes[i];
std::cout << "Mesh \"" << aMesh->mName.C_Str() << "\"" << std::endl;
std::cout << " Material: \"" << materials[aMesh->mMaterialIndex].name << "\"" << std::endl;
std::cout << " Faces: " << aMesh->mNumFaces << std::endl;
meshes[i].material = &materials[aMesh->mMaterialIndex];
meshes[i].indexBase = indexBase;
meshes[i].indexCount = aMesh->mNumFaces * 3;
// Vertices
bool hasUV = aMesh->HasTextureCoords(0);
bool hasColor = aMesh->HasVertexColors(0);
bool hasNormals = aMesh->HasNormals();
const uint32_t vertexOffset = static_cast<uint32_t>(vertices.size());
for (uint32_t v = 0; v < aMesh->mNumVertices; v++)
{
Vertex vertex;
vertex.pos = glm::make_vec3(&aMesh->mVertices[v].x);
vertex.pos.y = -vertex.pos.y;
vertex.uv = hasUV ? glm::make_vec2(&aMesh->mTextureCoords[0][v].x) : glm::vec2(0.0f);
vertex.normal = hasNormals ? glm::make_vec3(&aMesh->mNormals[v].x) : glm::vec3(0.0f);
vertex.normal.y = -vertex.normal.y;
vertex.color = hasColor ? glm::make_vec3(&aMesh->mColors[0][v].r) : glm::vec3(1.0f);
vertices.push_back(vertex);
}
// Indices
for (uint32_t f = 0; f < aMesh->mNumFaces; f++)
{
for (uint32_t j = 0; j < 3; j++)
{
indices.push_back(vertexOffset + aMesh->mFaces[f].mIndices[j]);
}
}
indexBase += aMesh->mNumFaces * 3;
}
// Create buffers
// For better performance we only create one index and vertex buffer to keep number of memory allocations down
size_t vertexDataSize = vertices.size() * sizeof(Vertex);
size_t indexDataSize = indices.size() * sizeof(uint32_t);
vks::Buffer vertexStaging, indexStaging;
// Vertex buffer
// Staging buffer
VK_CHECK_RESULT(vulkanDevice->createBuffer(
VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
&vertexStaging,
static_cast<uint32_t>(vertexDataSize),
vertices.data()));
// Target
VK_CHECK_RESULT(vulkanDevice->createBuffer(
VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
&vertexBuffer,
static_cast<uint32_t>(vertexDataSize)));
// Index buffer
VK_CHECK_RESULT(vulkanDevice->createBuffer(
VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
&indexStaging,
static_cast<uint32_t>(indexDataSize),
indices.data()));
// Target
VK_CHECK_RESULT(vulkanDevice->createBuffer(
VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
&indexBuffer,
static_cast<uint32_t>(indexDataSize)));
// Copy
VkCommandBufferBeginInfo cmdBufInfo = vks::initializers::commandBufferBeginInfo();
VK_CHECK_RESULT(vkBeginCommandBuffer(copyCmd, &cmdBufInfo));
VkBufferCopy copyRegion = {};
copyRegion.size = vertexDataSize;
vkCmdCopyBuffer(
copyCmd,
vertexStaging.buffer,
vertexBuffer.buffer,
1,
©Region);
copyRegion.size = indexDataSize;
vkCmdCopyBuffer(
copyCmd,
indexStaging.buffer,
indexBuffer.buffer,
1,
©Region);
VK_CHECK_RESULT(vkEndCommandBuffer(copyCmd));
VkSubmitInfo submitInfo = {};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = ©Cmd;
VK_CHECK_RESULT(vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE));
VK_CHECK_RESULT(vkQueueWaitIdle(queue));
//todo: fence
vertexStaging.destroy();
indexStaging.destroy();
}
public:
#if defined(__ANDROID__)
AAssetManager* assetManager = nullptr;
#endif
std::string assetPath = "";
std::vector<SceneMaterial> materials;
std::vector<ScenePart> meshes;
// Shared ubo containing matrices used by all
// materials and meshes
vks::Buffer uniformBuffer;
struct UniformData {
glm::mat4 projection;
glm::mat4 view;
glm::mat4 model;
glm::vec4 lightPos = glm::vec4(1.25f, 8.35f, 0.0f, 0.0f);
} uniformData;
// Scene uses multiple pipelines
struct {
VkPipeline solid;
VkPipeline blending;
VkPipeline wireframe;
} pipelines;
// Shared pipeline layout
VkPipelineLayout pipelineLayout;
// For displaying only a single part of the scene
bool renderSingleScenePart = false;
int32_t scenePartIndex = 0;
// Default constructor
Scene(vks::VulkanDevice *vulkanDevice, VkQueue queue)
{
this->vulkanDevice = vulkanDevice;
this->queue = queue;
// Prepare uniform buffer for global matrices
VkMemoryRequirements memReqs;
VkMemoryAllocateInfo memAlloc = vks::initializers::memoryAllocateInfo();
VkBufferCreateInfo bufferCreateInfo = vks::initializers::bufferCreateInfo(VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, sizeof(uniformData));
VK_CHECK_RESULT(vkCreateBuffer(vulkanDevice->logicalDevice, &bufferCreateInfo, nullptr, &uniformBuffer.buffer));
vkGetBufferMemoryRequirements(vulkanDevice->logicalDevice, uniformBuffer.buffer, &memReqs);
memAlloc.allocationSize = memReqs.size;
memAlloc.memoryTypeIndex = vulkanDevice->getMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
VK_CHECK_RESULT(vkAllocateMemory(vulkanDevice->logicalDevice, &memAlloc, nullptr, &uniformBuffer.memory));
VK_CHECK_RESULT(vkBindBufferMemory(vulkanDevice->logicalDevice, uniformBuffer.buffer, uniformBuffer.memory, 0));
VK_CHECK_RESULT(vkMapMemory(vulkanDevice->logicalDevice, uniformBuffer.memory, 0, sizeof(uniformData), 0, (void **)&uniformBuffer.mapped));
uniformBuffer.descriptor.offset = 0;
uniformBuffer.descriptor.buffer = uniformBuffer.buffer;
uniformBuffer.descriptor.range = sizeof(uniformData);
uniformBuffer.device = vulkanDevice->logicalDevice;
}
// Default destructor
~Scene()
{
vertexBuffer.destroy();
indexBuffer.destroy();
for (auto material : materials)
{
material.diffuse.destroy();
}
vkDestroyPipelineLayout(vulkanDevice->logicalDevice, pipelineLayout, nullptr);
vkDestroyDescriptorSetLayout(vulkanDevice->logicalDevice, descriptorSetLayouts.material, nullptr);
vkDestroyDescriptorSetLayout(vulkanDevice->logicalDevice, descriptorSetLayouts.scene, nullptr);
vkDestroyDescriptorPool(vulkanDevice->logicalDevice, descriptorPool, nullptr);
vkDestroyPipeline(vulkanDevice->logicalDevice, pipelines.solid, nullptr);
vkDestroyPipeline(vulkanDevice->logicalDevice, pipelines.blending, nullptr);
vkDestroyPipeline(vulkanDevice->logicalDevice, pipelines.wireframe, nullptr);
uniformBuffer.destroy();
}
void load(std::string filename, VkCommandBuffer copyCmd)
{
Assimp::Importer Importer;
int flags = aiProcess_PreTransformVertices | aiProcess_Triangulate | aiProcess_GenNormals;
#if defined(__ANDROID__)
AAsset* asset = AAssetManager_open(assetManager, filename.c_str(), AASSET_MODE_STREAMING);
assert(asset);
size_t size = AAsset_getLength(asset);
assert(size > 0);
void *meshData = malloc(size);
AAsset_read(asset, meshData, size);
AAsset_close(asset);
aScene = Importer.ReadFileFromMemory(meshData, size, flags);
free(meshData);
#else
aScene = Importer.ReadFile(filename.c_str(), flags);
#endif
if (aScene)
{
loadMaterials();
loadMeshes(copyCmd);
}
else
{
printf("Error parsing '%s': '%s'\n", filename.c_str(), Importer.GetErrorString());
#if defined(__ANDROID__)
LOGE("Error parsing '%s': '%s'", filename.c_str(), Importer.GetErrorString());
#endif
}
}
// Renders the scene into an active command buffer
// In a real world application we would do some visibility culling in here
void render(VkCommandBuffer cmdBuffer, bool wireframe)
{
VkDeviceSize offsets[1] = { 0 };
// Bind scene vertex and index buffers
vkCmdBindVertexBuffers(cmdBuffer, 0, 1, &vertexBuffer.buffer, offsets);
vkCmdBindIndexBuffer(cmdBuffer, indexBuffer.buffer, 0, VK_INDEX_TYPE_UINT32);
for (size_t i = 0; i < meshes.size(); i++)
{
if ((renderSingleScenePart) && (i != scenePartIndex))
continue;
// todo : per material pipelines
// vkCmdBindPipeline(cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, *mesh.material->pipeline);
// We will be using multiple descriptor sets for rendering
// In GLSL the selection is done via the set and binding keywords
// VS: layout (set = 0, binding = 0) uniform UBO;
// FS: layout (set = 1, binding = 0) uniform sampler2D samplerColorMap;
std::array<VkDescriptorSet, 2> descriptorSets;
// Set 0: Scene descriptor set containing global matrices
descriptorSets[0] = descriptorSetScene;
// Set 1: Per-Material descriptor set containing bound images
descriptorSets[1] = meshes[i].material->descriptorSet;
vkCmdBindPipeline(cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, wireframe ? pipelines.wireframe : *meshes[i].material->pipeline);
vkCmdBindDescriptorSets(cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, static_cast<uint32_t>(descriptorSets.size()), descriptorSets.data(), 0, NULL);
// Pass material properies via push constants
vkCmdPushConstants(
cmdBuffer,
pipelineLayout,
VK_SHADER_STAGE_FRAGMENT_BIT,
0,
sizeof(SceneMaterialProperties),
&meshes[i].material->properties);
// Render from the global scene vertex buffer using the mesh index offset
vkCmdDrawIndexed(cmdBuffer, meshes[i].indexCount, 1, 0, meshes[i].indexBase, 0);
}
}
};
class VulkanExample : public VulkanExampleBase
{
public:
bool wireframe = false;
bool attachLight = false;
Scene *scene = nullptr;
struct {
VkPipelineVertexInputStateCreateInfo inputState;
std::vector<VkVertexInputBindingDescription> bindingDescriptions;
std::vector<VkVertexInputAttributeDescription> attributeDescriptions;
} vertices;
VulkanExample() : VulkanExampleBase(ENABLE_VALIDATION)
{
title = "Multi-part scene rendering";
camera.type = Camera::CameraType::firstperson;
camera.movementSpeed = 7.5f;
camera.position = { 15.0f, -13.5f, 0.0f };
camera.setRotation(glm::vec3(5.0f, 90.0f, 0.0f));
camera.setRotationSpeed(0.5f);
camera.setPerspective(60.0f, (float)width / (float)height, 0.1f, 256.0f);
settings.overlay = true;
}
~VulkanExample()
{
delete(scene);
}
// Enable physical device features required for this example
virtual void getEnabledFeatures()
{
// Fill mode non solid is required for wireframe display
if (deviceFeatures.fillModeNonSolid) {
enabledFeatures.fillModeNonSolid = VK_TRUE;
};
}
void buildCommandBuffers()
{
VkCommandBufferBeginInfo cmdBufInfo = vks::initializers::commandBufferBeginInfo();
VkClearValue clearValues[2];
clearValues[0].color = defaultClearColor;
clearValues[1].depthStencil = { 1.0f, 0 };
VkRenderPassBeginInfo renderPassBeginInfo = vks::initializers::renderPassBeginInfo();
renderPassBeginInfo.renderPass = renderPass;
renderPassBeginInfo.renderArea.offset.x = 0;
renderPassBeginInfo.renderArea.offset.y = 0;
renderPassBeginInfo.renderArea.extent.width = width;
renderPassBeginInfo.renderArea.extent.height = height;
renderPassBeginInfo.clearValueCount = 2;
renderPassBeginInfo.pClearValues = clearValues;
for (int32_t i = 0; i < drawCmdBuffers.size(); ++i)
{
renderPassBeginInfo.framebuffer = frameBuffers[i];
VK_CHECK_RESULT(vkBeginCommandBuffer(drawCmdBuffers[i], &cmdBufInfo));
vkCmdBeginRenderPass(drawCmdBuffers[i], &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
VkViewport viewport = vks::initializers::viewport((float)width, (float)height, 0.0f, 1.0f);
vkCmdSetViewport(drawCmdBuffers[i], 0, 1, &viewport);
VkRect2D scissor = vks::initializers::rect2D(width, height, 0, 0);
vkCmdSetScissor(drawCmdBuffers[i], 0, 1, &scissor);
scene->render(drawCmdBuffers[i], wireframe);
drawUI(drawCmdBuffers[i]);
vkCmdEndRenderPass(drawCmdBuffers[i]);
VK_CHECK_RESULT(vkEndCommandBuffer(drawCmdBuffers[i]));
}
}
void setupVertexDescriptions()
{
// Binding description
vertices.bindingDescriptions.resize(1);
vertices.bindingDescriptions[0] =
vks::initializers::vertexInputBindingDescription(
VERTEX_BUFFER_BIND_ID,
sizeof(Vertex),
VK_VERTEX_INPUT_RATE_VERTEX);
// Attribute descriptions
// Describes memory layout and shader positions
vertices.attributeDescriptions.resize(4);
// Location 0 : Position
vertices.attributeDescriptions[0] =
vks::initializers::vertexInputAttributeDescription(
VERTEX_BUFFER_BIND_ID,
0,
VK_FORMAT_R32G32B32_SFLOAT,
0);
// Location 1 : Normal
vertices.attributeDescriptions[1] =
vks::initializers::vertexInputAttributeDescription(
VERTEX_BUFFER_BIND_ID,
1,
VK_FORMAT_R32G32B32_SFLOAT,
sizeof(float) * 3);
// Location 2 : Texture coordinates
vertices.attributeDescriptions[2] =
vks::initializers::vertexInputAttributeDescription(
VERTEX_BUFFER_BIND_ID,
2,
VK_FORMAT_R32G32_SFLOAT,
sizeof(float) * 6);
// Location 3 : Color
vertices.attributeDescriptions[3] =
vks::initializers::vertexInputAttributeDescription(
VERTEX_BUFFER_BIND_ID,
3,
VK_FORMAT_R32G32B32_SFLOAT,
sizeof(float) * 8);
vertices.inputState = vks::initializers::pipelineVertexInputStateCreateInfo();
vertices.inputState.vertexBindingDescriptionCount = static_cast<uint32_t>(vertices.bindingDescriptions.size());
vertices.inputState.pVertexBindingDescriptions = vertices.bindingDescriptions.data();
vertices.inputState.vertexAttributeDescriptionCount = static_cast<uint32_t>(vertices.attributeDescriptions.size());
vertices.inputState.pVertexAttributeDescriptions = vertices.attributeDescriptions.data();
}
void preparePipelines()
{
VkPipelineInputAssemblyStateCreateInfo inputAssemblyState =
vks::initializers::pipelineInputAssemblyStateCreateInfo(
VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST,
0,
VK_FALSE);
VkPipelineRasterizationStateCreateInfo rasterizationState =
vks::initializers::pipelineRasterizationStateCreateInfo(
VK_POLYGON_MODE_FILL,
VK_CULL_MODE_BACK_BIT,
VK_FRONT_FACE_COUNTER_CLOCKWISE,
0);
VkPipelineColorBlendAttachmentState blendAttachmentState =
vks::initializers::pipelineColorBlendAttachmentState(
0xf,
VK_FALSE);
VkPipelineColorBlendStateCreateInfo colorBlendState =
vks::initializers::pipelineColorBlendStateCreateInfo(
1,
&blendAttachmentState);
VkPipelineDepthStencilStateCreateInfo depthStencilState =
vks::initializers::pipelineDepthStencilStateCreateInfo(
VK_TRUE,
VK_TRUE,
VK_COMPARE_OP_LESS_OR_EQUAL);
VkPipelineViewportStateCreateInfo viewportState =
vks::initializers::pipelineViewportStateCreateInfo(1, 1, 0);
VkPipelineMultisampleStateCreateInfo multisampleState =
vks::initializers::pipelineMultisampleStateCreateInfo(
VK_SAMPLE_COUNT_1_BIT,
0);
std::vector<VkDynamicState> dynamicStateEnables = {
VK_DYNAMIC_STATE_VIEWPORT,
VK_DYNAMIC_STATE_SCISSOR
};
VkPipelineDynamicStateCreateInfo dynamicState =
vks::initializers::pipelineDynamicStateCreateInfo(
dynamicStateEnables.data(),
static_cast<uint32_t>(dynamicStateEnables.size()),
0);
std::array<VkPipelineShaderStageCreateInfo, 2> shaderStages;
// Solid rendering pipeline
shaderStages[0] = loadShader(getShadersPath() + "scenerendering/scene.vert.spv", VK_SHADER_STAGE_VERTEX_BIT);
shaderStages[1] = loadShader(getShadersPath() + "scenerendering/scene.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT);
VkGraphicsPipelineCreateInfo pipelineCreateInfo =
vks::initializers::pipelineCreateInfo(
scene->pipelineLayout,
renderPass,
0);
pipelineCreateInfo.pVertexInputState = &vertices.inputState;
pipelineCreateInfo.pInputAssemblyState = &inputAssemblyState;
pipelineCreateInfo.pRasterizationState = &rasterizationState;
pipelineCreateInfo.pColorBlendState = &colorBlendState;
pipelineCreateInfo.pMultisampleState = &multisampleState;
pipelineCreateInfo.pViewportState = &viewportState;
pipelineCreateInfo.pDepthStencilState = &depthStencilState;
pipelineCreateInfo.pDynamicState = &dynamicState;
pipelineCreateInfo.stageCount = static_cast<uint32_t>(shaderStages.size());
pipelineCreateInfo.pStages = shaderStages.data();
VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &scene->pipelines.solid));
// Alpha blended pipeline
rasterizationState.cullMode = VK_CULL_MODE_NONE;
blendAttachmentState.blendEnable = VK_TRUE;
blendAttachmentState.colorBlendOp = VK_BLEND_OP_ADD;
blendAttachmentState.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_COLOR;
blendAttachmentState.dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR;
VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &scene->pipelines.blending));
// Wire frame rendering pipeline
if (deviceFeatures.fillModeNonSolid) {
rasterizationState.cullMode = VK_CULL_MODE_BACK_BIT;
blendAttachmentState.blendEnable = VK_FALSE;
rasterizationState.polygonMode = VK_POLYGON_MODE_LINE;
rasterizationState.lineWidth = 1.0f;
VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &scene->pipelines.wireframe));
}
}
void updateUniformBuffers()
{
if (attachLight)
{
scene->uniformData.lightPos = glm::vec4(-camera.position, 1.0f);
}
scene->uniformData.projection = camera.matrices.perspective;
scene->uniformData.view = camera.matrices.view;
scene->uniformData.model = glm::mat4(1.0f);
memcpy(scene->uniformBuffer.mapped, &scene->uniformData, sizeof(scene->uniformData));
}
void draw()
{
VulkanExampleBase::prepareFrame();
// Command buffer to be sumitted to the queue
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &drawCmdBuffers[currentBuffer];
// Submit to queue
VK_CHECK_RESULT(vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE));
VulkanExampleBase::submitFrame();
}
void loadScene()
{
VkCommandBuffer copyCmd = vulkanDevice->createCommandBuffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, false);
scene = new Scene(vulkanDevice, queue);
#if defined(__ANDROID__)
scene->assetManager = androidApp->activity->assetManager;
#endif
scene->assetPath = getAssetPath() + "models/sibenik/";
scene->load(getAssetPath() + "models/sibenik/sibenik.dae", copyCmd);
vkFreeCommandBuffers(device, cmdPool, 1, ©Cmd);
updateUniformBuffers();
}
void prepare()
{
VulkanExampleBase::prepare();
setupVertexDescriptions();
loadScene();
preparePipelines();
buildCommandBuffers();
prepared = true;
}
virtual void render()
{
if (!prepared)
return;
draw();
}
virtual void viewChanged()
{
updateUniformBuffers();
}
virtual void OnUpdateUIOverlay(vks::UIOverlay *overlay)
{
if (overlay->header("Settings")) {
if (deviceFeatures.fillModeNonSolid) {
if (overlay->checkBox("Wireframe", &wireframe)) {
buildCommandBuffers();
}
}
if (scene) {
if (overlay->checkBox("Attach light to camera", &attachLight)) {
updateUniformBuffers();
}
if (overlay->checkBox("Render single part", &scene->renderSingleScenePart)) {
buildCommandBuffers();
}
if (scene->renderSingleScenePart) {
if (overlay->sliderInt("Part to render", &scene->scenePartIndex, 0, static_cast<int32_t>(scene->meshes.size()))) {
buildCommandBuffers();
}
}
}
}
}
};
VULKAN_EXAMPLE_MAIN()