-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path13-specialization.cpp
More file actions
269 lines (246 loc) · 10.4 KB
/
Copy path13-specialization.cpp
File metadata and controls
269 lines (246 loc) · 10.4 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
#include "../framework/vulkanApp.h"
#include "../framework/utilities.h"
#include "quadric/include/knot.h"
#define CAPTION_STRING(name) TEXT("13 - Specialization constants (" name ")")
// Use Space to toggle between albedo and shading.
// Use 1, 2, 3, 4, 5 to change shading branch.
// Use L button + mouse to rotate knot.
class SpecializationApp : public VulkanApp
{
enum ShadingType : uint32_t
{
Normal = 0, FaceNormal, Diffuse, Specular, CellShade, Albedo,
MaxPermutations
};
struct Constants
{
// If the specialization constant is of type boolean,
// size must be the byte size of VkBool32
VkBool32 colorFill;
int shadingType;
};
struct alignas(16) UniformBlock
{
rapid::matrix worldView;
rapid::matrix worldViewProj;
rapid::matrix normalMatrix;
};
struct DescriptorSetTable
{
magma::descriptor::UniformBuffer transforms = 0;
} setTable;
const std::unordered_map<ShadingType, std::tstring> captions = {
{ShadingType::Normal, CAPTION_STRING("Normals")},
{ShadingType::FaceNormal, CAPTION_STRING("Face normals")},
{ShadingType::Diffuse, CAPTION_STRING("Diffuse")},
{ShadingType::Specular, CAPTION_STRING("Specular")},
{ShadingType::CellShade, CAPTION_STRING("Cell-shading")},
{ShadingType::Albedo, CAPTION_STRING("Albedo")}
};
std::unique_ptr<quadric::Knot> mesh;
std::shared_ptr<magma::ShaderModule> vertexShader;
std::shared_ptr<magma::ShaderModule> fragmentShader;
std::unique_ptr<magma::UniformBuffer<UniformBlock>> uniformBuffer;
std::unique_ptr<magma::DescriptorSet> descriptorSet;
std::shared_ptr<magma::PipelineLayout> sharedLayout;
std::shared_ptr<magma::RenderPass> sharedRenderPass;
std::unique_ptr<magma::GraphicsPipelineBatch> pipelineBatch;
std::vector<std::vector<std::shared_ptr<magma::CommandBuffer>>> commandBuffers;
rapid::matrix view;
rapid::matrix proj;
ShadingType shadingType = ShadingType::Normal;
bool colorFill = true; // Albedo
int pipelineIndex = ShadingType::Albedo;
public:
SpecializationApp(const AppEntry& entry):
VulkanApp(entry, CAPTION_STRING("Albedo"), 512, 512, true)
{
initialize();
setupView();
createMesh();
loadShaders();
createUniformBuffer();
setupDescriptorSet();
buildPipelines();
for (uint32_t pipelineIndex = 0; pipelineIndex < ShadingType::MaxPermutations; ++pipelineIndex)
{
for (uint32_t bufferIndex = 0; bufferIndex < (uint32_t)commandBuffers.size(); ++bufferIndex)
recordCommandBuffer(bufferIndex, pipelineIndex);
}
}
void render(uint32_t bufferIndex) override
{
updatePerspectiveTransform();
const std::unique_ptr<magma::Fence>& frameFence = (PresentationWait::Fence == presentWait) ? waitFences[frameIndex] : nullFence;
graphicsQueue->submit(
commandBuffers[bufferIndex][pipelineIndex],
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
presentFinished[frameIndex], // Wait for swapchain
renderFinished[frameIndex], // Semaphore to be signaled when command buffer completed execution
frameFence);
}
void onKeyDown(char key, int repeat, uint32_t flags) override
{
switch (key)
{
case '1': shadingType = ShadingType::Normal; break;
case '2': shadingType = ShadingType::FaceNormal; break;
case '3': shadingType = ShadingType::Diffuse; break;
case '4': shadingType = ShadingType::Specular; break;
case '5': shadingType = ShadingType::CellShade; break;
case AppKey::Space: colorFill = !colorFill;
break;
}
if (colorFill)
pipelineIndex = ShadingType::Albedo;
else
pipelineIndex = shadingType;
setWindowCaption(captions.at(ShadingType(pipelineIndex)));
VulkanApp::onKeyDown(key, repeat, flags);
}
void onResize(uint32_t width, uint32_t height) override
{
createRenderPass();
VulkanApp::onResize(width, height);
setupView();
buildPipelines();
for (uint32_t pipelineIndex = 0; pipelineIndex < ShadingType::MaxPermutations; ++pipelineIndex)
{
for (uint32_t bufferIndex = 0; bufferIndex < (uint32_t)commandBuffers.size(); ++bufferIndex)
recordCommandBuffer(bufferIndex, pipelineIndex);
}
}
void createCommandBuffers() override
{
VulkanApp::createCommandBuffers();
for (size_t i = 0; i < framebuffers.size(); ++i)
{
std::vector<std::shared_ptr<magma::CommandBuffer>> forEachPermutationCmdBuffers = commandPools[0]->allocateCommandBuffers(VK_COMMAND_BUFFER_LEVEL_PRIMARY, ShadingType::MaxPermutations);
commandBuffers.emplace_back(std::move(forEachPermutationCmdBuffers));
}
}
void setupView()
{
const rapid::vector3 eye(0.f, 0.f, 5.f);
const rapid::vector3 center(0.f, 0.f, 0.f);
const rapid::vector3 up(0.f, 1.f, 0.f);
constexpr float fov = rapid::radians(60.f);
const float aspect = width/(float)height;
constexpr float zn = 1.f, zf = 100.f;
view = rapid::lookAtRH(eye, center, up);
proj = rapid::perspectiveFovRH(fov, aspect, zn, zf);
}
void updatePerspectiveTransform()
{
const rapid::matrix pitch = rapid::rotationX(rapid::radians(spinY/2.f));
const rapid::matrix yaw = rapid::rotationY(rapid::radians(spinX/2.f));
const rapid::matrix world = pitch * yaw;
magma::map(uniformBuffer,
[this, &world](auto *block)
{
block->worldView = world * view;
block->worldViewProj = world * view * proj;
block->normalMatrix = rapid::transpose(rapid::inverse(block->worldView));
});
}
void createMesh()
{
constexpr float radius = 0.25f;
constexpr uint16_t turns = 3;
constexpr uint16_t sides = 16;
constexpr uint16_t rings = 256;
mesh = std::make_unique<quadric::Knot>(radius, turns, sides, rings, false, cmdBufferCopy);
}
void loadShaders()
{
aligned_vector<char> bytecode = utilities::loadBinaryFile("transform.o");
vertexShader = std::make_shared<magma::ShaderModule>(device, (const magma::SpirvWord *)bytecode.data(), bytecode.size());
bytecode = utilities::loadBinaryFile("specialized.o");
fragmentShader = std::make_shared<magma::ShaderModule>(device, (const magma::SpirvWord *)bytecode.data(), bytecode.size());
}
void createUniformBuffer()
{
uniformBuffer = std::make_unique<magma::UniformBuffer<UniformBlock>>(device);
}
void setupDescriptorSet()
{
setTable.transforms = uniformBuffer;
descriptorSet = std::make_unique<magma::DescriptorSet>(descriptorPool,
setTable, VK_SHADER_STAGE_VERTEX_BIT,
nullptr, 0, shaderReflectionFactory, "transform");
sharedLayout = std::make_shared<magma::PipelineLayout>(descriptorSet->getLayout());
}
magma::FragmentShaderStage specializeFragmentStage(ShadingType shadingType, const char *entrypoint) const
{
Constants constants;
constants.colorFill = MAGMA_BOOLEAN(ShadingType::Albedo == shadingType);
constants.shadingType = static_cast<int>(shadingType);
auto specialization = std::make_shared<magma::Specialization>(constants,
std::initializer_list<magma::SpecializationEntry>{
magma::SpecializationEntry(0, &Constants::colorFill),
magma::SpecializationEntry(1, &Constants::shadingType)
});
return magma::FragmentShaderStage(fragmentShader, entrypoint, std::move(specialization));
}
void buildPipelines()
{
const magma::VertexShaderStage vertexStage(vertexShader, "main");
const std::vector<VkDynamicState> dynamicStates{
VK_DYNAMIC_STATE_VIEWPORT,
VK_DYNAMIC_STATE_SCISSOR
};
sharedRenderPass = std::move(renderPass);
pipelineBatch = std::make_unique<magma::GraphicsPipelineBatch>(device);
for (uint32_t i = 0; i < ShadingType::MaxPermutations; ++i)
{
const magma::FragmentShaderStage fragmentStage = specializeFragmentStage((ShadingType)i, "main");
pipelineBatch->batchPipeline(
{vertexStage, fragmentStage},
mesh->getVertexInput(),
magma::renderstate::triangleList,
magma::TesselationState(),
magma::ViewportState(),
negateViewport ? magma::renderstate::fillCullBackCcw
: magma::renderstate::fillCullBackCw,
magma::renderstate::dontMultisample,
magma::renderstate::depthLessOrEqual,
magma::renderstate::dontBlendRgb,
dynamicStates,
sharedLayout,
sharedRenderPass, 0);
}
std::future<void> buildResult = pipelineBatch->buildPipelinesAsync(pipelineCache);
std::future_status status;
do
{
status = buildResult.wait_for(std::chrono::milliseconds(1));
std::cout << "You can do something useful here while waiting for completion of graphics pipeline building" << std::endl;
} while (status != std::future_status::ready);
}
void recordCommandBuffer(uint32_t bufferIndex, uint32_t pipelineIndex)
{
auto& cmdBuffer = commandBuffers[bufferIndex][pipelineIndex];
cmdBuffer->reset();
cmdBuffer->begin();
{
cmdBuffer->beginRenderPass(sharedRenderPass, framebuffers[bufferIndex],
{
magma::clear::gray,
magma::clear::depthOne
});
{
cmdBuffer->setViewport(0, 0, width, negateViewport ? -int32_t(height) : height);
cmdBuffer->setScissor(0, 0, width, height);
cmdBuffer->bindDescriptorSet(pipelineBatch->getPipeline(pipelineIndex), 0, descriptorSet);
cmdBuffer->bindPipeline(pipelineBatch->getPipeline(pipelineIndex));
mesh->draw(cmdBuffer);
}
cmdBuffer->endRenderPass();
}
cmdBuffer->end();
}
};
std::unique_ptr<IApplication> appFactory(const AppEntry& entry)
{
return std::unique_ptr<SpecializationApp>(new SpecializationApp(entry));
}