forked from SaschaWillems/Vulkan
-
-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathindirect.cpp
305 lines (259 loc) · 11.2 KB
/
indirect.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
/*
* Vulkan Example - Instanced mesh rendering, uses a separate vertex buffer for instanced data
*
* This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT)
*/
#include <vulkanExampleBase.h>
#include <shapes.h>
#include <easings.hpp>
#include <glm/gtc/quaternion.hpp>
#define SHAPES_COUNT 5
#define INSTANCES_PER_SHAPE 4000
#define INSTANCE_COUNT (INSTANCES_PER_SHAPE * SHAPES_COUNT)
using namespace vk;
class VulkanExample : public vkx::ExampleBase {
public:
vks::Buffer meshes;
// Per-instance data block
struct InstanceData {
glm::vec3 pos;
glm::vec3 rot;
float scale;
};
struct ShapeVertexData {
size_t baseVertex;
size_t vertices;
};
struct Vertex {
glm::vec3 position;
glm::vec3 normal;
glm::vec3 color;
};
// Contains the instanced data
vks::Buffer instanceBuffer;
// Contains the instanced data
vks::Buffer indirectBuffer;
struct UboVS {
glm::mat4 projection;
glm::mat4 view;
float time = 0.0f;
} uboVS;
struct {
vks::Buffer vsScene;
} uniformData;
struct {
vk::Pipeline solid;
} pipelines;
std::vector<ShapeVertexData> shapes;
vk::PipelineLayout pipelineLayout;
vk::DescriptorSet descriptorSet;
vk::DescriptorSetLayout descriptorSetLayout;
VulkanExample() {
rotationSpeed = 0.25f;
title = "Vulkan Example - Instanced mesh rendering";
srand((unsigned int)time(NULL));
}
~VulkanExample() {
device.destroyPipeline(pipelines.solid);
device.destroyPipelineLayout(pipelineLayout);
device.destroyDescriptorSetLayout(descriptorSetLayout);
instanceBuffer.destroy();
indirectBuffer.destroy();
uniformData.vsScene.destroy();
meshes.destroy();
}
void updateDrawCommandBuffer(const vk::CommandBuffer& cmdBuffer) override {
cmdBuffer.setViewport(0, vks::util::viewport(size));
cmdBuffer.setScissor(0, vks::util::rect2D(size));
cmdBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, pipelineLayout, 0, descriptorSet, nullptr);
cmdBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipelines.solid);
// Binding point 0 : Mesh vertex buffer
cmdBuffer.bindVertexBuffers(0, meshes.buffer, { 0 });
// Binding point 1 : Instance data buffer
cmdBuffer.bindVertexBuffers(1, instanceBuffer.buffer, { 0 });
// Equivlant non-indirect commands:
//for (size_t j = 0; j < SHAPES_COUNT; ++j) {
// auto shape = shapes[j];
// cmdBuffer.draw(shape.vertices, INSTANCES_PER_SHAPE, shape.baseVertex, j * INSTANCES_PER_SHAPE);
//}
cmdBuffer.drawIndirect(indirectBuffer.buffer, 0, SHAPES_COUNT, sizeof(vk::DrawIndirectCommand));
}
template <size_t N>
void appendShape(const geometry::Solid<N>& solid, std::vector<Vertex>& vertices) {
using namespace geometry;
using namespace glm;
using namespace std;
ShapeVertexData shape;
shape.baseVertex = vertices.size();
auto faceCount = solid.faces.size();
// FIXME triangulate the faces
auto faceTriangles = triangulatedFaceTriangleCount<N>();
vertices.reserve(vertices.size() + 3 * faceTriangles);
vec3 color = vec3(rand(), rand(), rand()) / (float)RAND_MAX;
color = vec3(0.3f) + (0.7f * color);
for (size_t f = 0; f < faceCount; ++f) {
const Face<N>& face = solid.faces[f];
vec3 normal = solid.getFaceNormal(f);
for (size_t ft = 0; ft < faceTriangles; ++ft) {
// Create the vertices for the face
vertices.push_back({ vec3(solid.vertices[face[0]]), normal, color });
vertices.push_back({ vec3(solid.vertices[face[2 + ft]]), normal, color });
vertices.push_back({ vec3(solid.vertices[face[1 + ft]]), normal, color });
}
}
shape.vertices = vertices.size() - shape.baseVertex;
shapes.push_back(shape);
}
void loadShapes() {
std::vector<Vertex> vertexData;
size_t vertexCount = 0;
appendShape<>(geometry::tetrahedron(), vertexData);
appendShape<>(geometry::octahedron(), vertexData);
appendShape<>(geometry::cube(), vertexData);
appendShape<>(geometry::dodecahedron(), vertexData);
appendShape<>(geometry::icosahedron(), vertexData);
for (auto& vertex : vertexData) {
vertex.position *= 0.2f;
}
meshes = context.stageToDeviceBuffer(vk::BufferUsageFlagBits::eVertexBuffer, vertexData);
}
void setupDescriptorPool() {
// Example uses one ubo
std::vector<vk::DescriptorPoolSize> poolSizes{
vk::DescriptorPoolSize(vk::DescriptorType::eUniformBuffer, 1),
};
descriptorPool = device.createDescriptorPool({ {}, 1, (uint32_t)poolSizes.size(), poolSizes.data() });
}
void setupDescriptorSetLayout() {
// Binding 0 : Vertex shader uniform buffer
std::vector<vk::DescriptorSetLayoutBinding> setLayoutBindings{
vk::DescriptorSetLayoutBinding{ 0, vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eVertex },
};
descriptorSetLayout = device.createDescriptorSetLayout({ {}, (uint32_t)setLayoutBindings.size(), setLayoutBindings.data() });
pipelineLayout = device.createPipelineLayout({ {}, 1, &descriptorSetLayout });
}
void setupDescriptorSet() {
descriptorSet = device.allocateDescriptorSets({ descriptorPool, 1, &descriptorSetLayout })[0];
// Binding 0 : Vertex shader uniform buffer
vk::WriteDescriptorSet writeDescriptorSet;
writeDescriptorSet.dstSet = descriptorSet;
writeDescriptorSet.descriptorType = vk::DescriptorType::eUniformBuffer;
writeDescriptorSet.dstBinding = 0;
writeDescriptorSet.pBufferInfo = &uniformData.vsScene.descriptor;
writeDescriptorSet.descriptorCount = 1;
device.updateDescriptorSets(writeDescriptorSet, nullptr);
}
void preparePipelines() {
// Instacing pipeline
vks::pipelines::GraphicsPipelineBuilder pipelineBuilder{ device, pipelineLayout, renderPass };
// Load shaders
pipelineBuilder.loadShader(getAssetPath() + "shaders/indirect/indirect.vert.spv", vk::ShaderStageFlagBits::eVertex);
pipelineBuilder.loadShader(getAssetPath() + "shaders/indirect/indirect.frag.spv", vk::ShaderStageFlagBits::eFragment);
auto bindingDescriptions = pipelineBuilder.vertexInputState.bindingDescriptions;
auto attributeDescriptions = pipelineBuilder.vertexInputState.attributeDescriptions;
pipelineBuilder.vertexInputState.bindingDescriptions = {
// Mesh vertex buffer (description) at binding point 0
{ 0, sizeof(Vertex), vk::VertexInputRate::eVertex },
{ 1, sizeof(InstanceData), vk::VertexInputRate::eInstance },
};
// Attribute descriptions
// Describes memory layout and shader positions
pipelineBuilder.vertexInputState.attributeDescriptions = {
// Per-Vertex attributes
{ 0, 0, vk::Format::eR32G32B32Sfloat, offsetof(Vertex, position) },
{ 1, 0, vk::Format::eR32G32B32Sfloat, offsetof(Vertex, color) },
{ 2, 0, vk::Format::eR32G32B32Sfloat, offsetof(Vertex, normal) },
// Instanced attributes
{ 3, 1, vk::Format::eR32G32B32Sfloat, offsetof(InstanceData, pos) },
{ 4, 1, vk::Format::eR32G32B32Sfloat, offsetof(InstanceData, rot) },
{ 5, 1, vk::Format::eR32Sfloat, offsetof(InstanceData, scale) },
};
pipelines.solid = pipelineBuilder.create(context.pipelineCache);
}
void prepareIndirectData() {
std::vector<vk::DrawIndirectCommand> indirectData;
indirectData.resize(SHAPES_COUNT);
for (auto i = 0; i < SHAPES_COUNT; ++i) {
auto& drawIndirectCommand = indirectData[i];
const auto& shapeData = shapes[i];
drawIndirectCommand.firstInstance = i * INSTANCES_PER_SHAPE;
drawIndirectCommand.instanceCount = INSTANCES_PER_SHAPE;
drawIndirectCommand.firstVertex = (uint32_t)shapeData.baseVertex;
drawIndirectCommand.vertexCount = (uint32_t)shapeData.vertices;
}
indirectBuffer = context.stageToDeviceBuffer(vk::BufferUsageFlagBits::eIndirectBuffer, indirectData);
}
void prepareInstanceData() {
std::vector<InstanceData> instanceData;
instanceData.resize(INSTANCE_COUNT);
std::mt19937 rndGenerator((unsigned int)time(nullptr));
std::uniform_real_distribution<float> uniformDist(0.0, 1.0);
std::exponential_distribution<float> expDist(1);
for (auto i = 0; i < INSTANCE_COUNT; i++) {
auto& instance = instanceData[i];
instance.rot = (float)M_PI * glm::vec3(uniformDist(rndGenerator), uniformDist(rndGenerator), uniformDist(rndGenerator));
float theta = 2.0f * (float)M_PI * uniformDist(rndGenerator);
float phi = acos(1 - 2 * uniformDist(rndGenerator));
instance.scale = 0.1f + expDist(rndGenerator) * 3.0f;
instance.pos = glm::normalize(glm::vec3(sin(phi) * cos(theta), sin(theta), cos(phi)));
instance.pos *= instance.scale * (1.0f + expDist(rndGenerator) / 2.0f) * 4.0f;
}
instanceBuffer = context.stageToDeviceBuffer(vk::BufferUsageFlagBits::eVertexBuffer, instanceData);
}
void prepareUniformBuffers() {
uniformData.vsScene = context.createUniformBuffer(uboVS);
updateUniformBuffer(true);
}
void updateUniformBuffer(bool viewChanged) {
if (viewChanged) {
uboVS.projection = getProjection();
uboVS.view = camera.matrices.view;
}
if (!paused) {
uboVS.time += frameTimer * 0.05f;
}
memcpy(uniformData.vsScene.mapped, &uboVS, sizeof(uboVS));
}
void prepare() override {
ExampleBase::prepare();
loadShapes();
prepareInstanceData();
prepareIndirectData();
prepareUniformBuffers();
setupDescriptorSetLayout();
preparePipelines();
setupDescriptorPool();
setupDescriptorSet();
buildCommandBuffers();
prepared = true;
}
const float duration = 4.0f;
const float interval = 6.0f;
float zoomDelta = 135;
float zoomStart;
float accumulator = FLT_MAX;
void update(float delta) override {
ExampleBase::update(delta);
if (!paused) {
accumulator += delta;
if (accumulator < duration) {
camera.position.z = easings::inOutQuint(accumulator, duration, zoomStart, zoomDelta);
camera.setTranslation(camera.position);
updateUniformBuffer(true);
} else {
updateUniformBuffer(false);
}
if (accumulator >= interval) {
accumulator = 0;
zoomStart = camera.position.z;
if (camera.position.z < -2) {
zoomDelta = 135;
} else {
zoomDelta = -135;
}
}
}
}
void viewChanged() override { updateUniformBuffer(true); }
};
RUN_EXAMPLE(VulkanExample)