Skip to content

Commit 8070bf3

Browse files
Merge pull request #232 from KhronosGroup/depth_buffering_chapter_rework
Rework depth buffer chapter
2 parents 3adc8ea + d445f04 commit 8070bf3

File tree

1 file changed

+108
-139
lines changed

1 file changed

+108
-139
lines changed

en/07_Depth_buffering.adoc

Lines changed: 108 additions & 139 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ We'll use this third coordinate to place a square over the current square to see
1010

1111
== 3D geometry
1212

13-
Change the `Vertex` struct to use a 3D vector for the position, and update the `format` in the corresponding `VkVertexInputAttributeDescription`:
13+
Change the `Vertex` struct to use a 3D vector for the position, and update the `format` in the corresponding `vk::VertexInputAttributeDescription`:
1414

1515
[,c++]
1616
----
@@ -23,22 +23,24 @@ struct Vertex {
2323
2424
static std::array<vk::VertexInputAttributeDescription, 3> getAttributeDescriptions() {
2525
return {
26-
vk::VertexInputAttributeDescription( 0, 0, vk::Format::eR32G32B32Sfloat, offsetof(Vertex, pos) ),
27-
vk::VertexInputAttributeDescription( 1, 0, vk::Format::eR32G32B32Sfloat, offsetof(Vertex, color) ),
28-
vk::VertexInputAttributeDescription( 2, 0, vk::Format::eR32G32Sfloat, offsetof(Vertex, texCoord) )
26+
vk::VertexInputAttributeDescription(0, 0, vk::Format::eR32G32B32Sfloat, offsetof(Vertex, pos)),
27+
vk::VertexInputAttributeDescription(1, 0, vk::Format::eR32G32B32Sfloat, offsetof(Vertex, color)),
28+
vk::VertexInputAttributeDescription(2, 0, vk::Format::eR32G32Sfloat, offsetof(Vertex, texCoord))
2929
};
3030
3131
...
3232
}
3333
};
3434
----
3535

36-
Next, update the vertex shader to accept and transform 3D coordinates as input.
37-
Remember to recompile it afterward!
36+
Next, update the vertex shader to accept and transform 3D coordinates as input by changing the type for `inPosition` from `float2` to `float3`:
3837

3938
[,glsl]
4039
----
41-
float3 inPosition;
40+
struct VSInput {
41+
float3 inPosition;
42+
...
43+
};
4244
4345
...
4446
@@ -52,6 +54,8 @@ VSOutput vertMain(VSInput input) {
5254
}
5355
----
5456

57+
Remember to recompile the shader afterwards!
58+
5559
Lastly, update the `vertices` container to include Z coordinates:
5660

5761
[,c++]
@@ -156,20 +160,20 @@ void createDepthResources() {
156160
Creating a depth image is fairly straightforward.
157161
It should have the same resolution as the color attachment, defined by the swap chain extent, an image usage appropriate for a depth attachment, optimal tiling and device local memory.
158162
The only question is: what is the right format for a depth image?
159-
The format must contain a depth component, indicated by `_D??_` in the `VK_FORMAT_`.
163+
The format must contain a depth component, indicated by `_D??_` in the `vk::Format`.
160164

161165
Unlike the texture image, we don't necessarily need a specific format, because we won't be directly accessing the texels from the program.
162166
It just needs to have a reasonable accuracy, at least 24 bits is common in real-world applications.
163167
There are several formats that fit this requirement:
164168

165-
* `VK_FORMAT_D32_SFLOAT`: 32-bit float for depth
166-
* `VK_FORMAT_D32_SFLOAT_S8_UINT`: 32-bit signed float for depth and 8 bit stencil component
167-
* `VK_FORMAT_D24_UNORM_S8_UINT`: 24-bit float for depth and 8 bit stencil component
169+
* `vk::Format::eD32Sfloat`: 32-bit float for depth
170+
* `vk::Format::eD32SfloatS8Uint`: 32-bit signed float for depth and 8 bit stencil component
171+
* `vk::Format::eD24UnormS8Uint`: 24-bit float for depth and 8 bit stencil component
168172

169173
The stencil component is used for https://en.wikipedia.org/wiki/Stencil_buffer[stencil tests], which is an additional test that can be combined with depth testing.
170174
We'll look at this in a future chapter.
171175

172-
We could simply go for the `VK_FORMAT_D32_SFLOAT` format, because support for it is extremely common (see the hardware database), but it's nice to add some extra flexibility to our application where possible.
176+
We could simply go for the `vk::Format::eD32Sfloat` format, because support for it is extremely common (see the hardware database), but it's nice to add some extra flexibility to our application where possible.
173177
We're going to write a function `findSupportedFormat` that takes a list of candidate formats in order from most desirable to least desirable, and checks which is the first one that is supported:
174178

175179
[,c++]
@@ -180,7 +184,7 @@ vk::Format findSupportedFormat(const std::vector<vk::Format>& candidates, vk::Im
180184
----
181185

182186
The support of a format depends on the tiling mode and usage, so we must also include these as parameters.
183-
The support of a format can be queried using the `vkGetPhysicalDeviceFormatProperties` function:
187+
The support of a format can be queried using the `physicalDevice.getFormatProperties` function:
184188

185189
[,c++]
186190
----
@@ -189,7 +193,7 @@ for (const auto format : candidates) {
189193
}
190194
----
191195

192-
The `VkFormatProperties` struct contains three fields:
196+
The `vk::FormatProperties` struct contains three fields:
193197

194198
* `linearTilingFeatures`: Use cases that are supported with linear tiling
195199
* `optimalTilingFeatures`: Use cases that are supported with optimal tiling
@@ -240,7 +244,7 @@ VkFormat findDepthFormat() {
240244
}
241245
----
242246

243-
Make sure to use the `VK_FORMAT_FEATURE_` flag instead of `VK_IMAGE_USAGE_` in this case.
247+
Make sure to use the `vk::FormatFeatureFlagBits` instead of `vk::ImageUsageFlagBits` in this case.
244248
All of these candidate formats contain a depth component, but the latter two also contain a stencil component.
245249
We won't be using that yet, but we do need to take that into account when performing layout transitions on images with these formats.
246250
Add a simple helper function that tells us if the chosen depth format contains a stencil component:
@@ -267,13 +271,15 @@ createImage(swapChainExtent.width, swapChainExtent.height, depthFormat, vk::Imag
267271
depthImageView = createImageView(depthImage, depthFormat, vk::ImageAspectFlagBits::eDepth);
268272
----
269273

270-
However, the `createImageView` function currently assumes that the subresource is always the `VK_IMAGE_ASPECT_COLOR_BIT`, so we will need to turn that field into a parameter:
274+
However, the `createImageView` function currently assumes that the subresource is always the `vk::ImageAspectFlagBits::eColor`, so we will need to turn that field into a parameter:
271275

272276
[,c++]
273277
----
274278
vk::raii::ImageView createImageView(vk::raii::Image& image, vk::Format format, vk::ImageAspectFlags aspectFlags) {
275279
...
276-
viewInfo.subresourceRange.aspectMask = aspectFlags;
280+
vk::ImageViewCreateInfo viewInfo{
281+
...
282+
.subresourceRange = {aspectFlags, 0, 1, 0, 1}};
277283
...
278284
}
279285
----
@@ -290,169 +296,123 @@ textureImageView = createImageView(textureImage, vk::Format::eR8G8B8A8Srgb, vk::
290296
----
291297

292298
That's it for creating the depth image.
293-
We don't need to map it or copy another image to it, because we're going to clear it at the start of the render pass like the color attachment.
294-
295-
=== Explicitly transitioning the depth image
296-
297-
We don't need to explicitly transition the layout of the image to a depth attachment because we'll take care of this in the render pass.
298-
However, for completeness, I'll still describe the process in this section.
299-
You may skip it if you like.
300-
301-
Make a call to `transitionImageLayout` at the end of the `createDepthResources` function like so:
302-
303-
[,c++]
304-
----
305-
transitionImageLayout(depthImage, depthFormat, vk::ImageLayout::eUndefined, vk::ImageLayout::eTransferDstOptimal);
306-
----
307-
308-
The undefined layout can be used as initial layout, because there are no existing depth image contents that matter.
309-
We need to update some logic in `transitionImageLayout` to use the right subresource aspect:
310-
311-
[,c++]
312-
----
313-
if (newLayout == vk::ImageLayout::eDepthStencilAttachmentOptimal) {
314-
barrier.subresourceRange.aspectMask = vk::ImageAspectFlagBits::eDepth;
299+
We don't need to map it or copy another image to it, because we're going to clear it at the start of our command buffer like the color attachment.
315300

316-
if (hasStencilComponent(format)) {
317-
barrier.subresourceRange.aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT;
318-
}
319-
} else {
320-
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
321-
}
322-
----
301+
== Command buffer
323302

324-
Although we're not using the stencil component, we do need to include it in the layout transitions of the depth image.
303+
=== Clear values
325304

326-
Finally, add the correct access masks and pipeline stages:
305+
Because we now have multiple attachments that will be cleared to `vk::AttachmentLoadOp::eClear` (color and depth), we also need to specify multiple clear values.
306+
Go to `recordCommandBuffer` and create and add an additional `vk::ClearValue` variable called `clearDepth`:
327307

328308
[,c++]
329309
----
330-
if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && newLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) {
331-
barrier.srcAccessMask = 0;
332-
barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
333-
334-
sourceStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
335-
destinationStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
336-
} else if (oldLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
337-
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
338-
barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
339-
340-
sourceStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
341-
destinationStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
342-
} else if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && newLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) {
343-
barrier.srcAccessMask = 0;
344-
barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
345-
346-
sourceStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
347-
destinationStage = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT;
348-
} else {
349-
throw std::invalid_argument("unsupported layout transition!");
350-
}
310+
vk::ClearValue clearColor = vk::ClearColorValue(0.0f, 0.0f, 0.0f, 1.0f);
311+
vk::ClearValue clearDepth = vk::ClearDepthStencilValue(1.0f, 0);
351312
----
352313

353-
The depth buffer will be read from to perform depth tests to see if a fragment is visible, and will be written to when a new fragment is drawn.
354-
The reading happens in the `VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT` stage and the writing in the `VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT`.
355-
You should pick the earliest pipeline stage that matches the specified operations, so that it is ready for usage as depth attachment when it needs to be.
314+
The range of depths in the depth buffer is `0.0` to `1.0` in Vulkan, where `1.0` lies at the far view plane and `0.0` at the near view plane.
315+
The initial value at each point in the depth buffer should be the furthest possible depth, which is `1.0`.
356316

357-
== Render pass
317+
=== Dynamic rendering
358318

359-
We're now going to modify `createRenderPass` to include a depth attachment.
360-
First specify the `VkAttachmentDescription`:
319+
Now that we have our depth image set up, we need to make use of it in `recordCommandBuffer`.
320+
This will be part of dynamic rendering and is similar to setting up our color output image.
361321

362-
[,c++]
363-
----
364-
vk::AttachmentDescription depthAttachment({}, findDepthFormat(), vk::SampleCountFlagBits::e1, vk::AttachmentLoadOp::eClear,
365-
vk::AttachmentStoreOp::eDontCare, vk::AttachmentLoadOp::eDontCare, vk::AttachmentStoreOp::eDontCare, vk::ImageLayout::eUndefined,
366-
vk::ImageLayout::eDepthStencilAttachmentOptimal);
367-
----
368-
369-
The `format` should be the same as the depth image itself.
370-
This time we don't care about storing the depth data (`storeOp`), because it will not be used after drawing has finished.
371-
This may allow the hardware to perform additional optimizations.
372-
Just like the color buffer, we don't care about the previous depth contents, so we can use `VK_IMAGE_LAYOUT_UNDEFINED` as `initialLayout`.
322+
First specify a new rendering attachment for the depth image:
373323

374324
[,c++]
375325
----
376-
vk::AttachmentReference depthAttachmentRef(1, vk::ImageLayout::eDepthStencilAttachmentOptimal);
326+
vk::RenderingAttachmentInfo depthAttachmentInfo = {
327+
.imageView = depthImageView,
328+
.imageLayout = vk::ImageLayout::eDepthAttachmentOptimal,
329+
.loadOp = vk::AttachmentLoadOp::eClear,
330+
.storeOp = vk::AttachmentStoreOp::eDontCare,
331+
.clearValue = clearDepth};
377332
----
378333

379-
Add a reference to the attachment for the first (and only) subpass:
334+
And add it to the dynamic rendering info structure:
380335

381336
[,c++]
382337
----
383-
vk::SubpassDescription subpass({}, vk::PipelineBindPoint::eGraphics, 0, {}, 1, &colorAttachmentRef, {}, &depthAttachmentRef);
338+
vk::RenderingInfo renderingInfo = {
339+
...
340+
.pDepthAttachment = &depthAttachmentInfo};
384341
----
385342

386-
Unlike color attachments, a subpass can only use a single depth (+stencil) attachment.
387-
It wouldn't really make any sense to do depth tests on multiple buffers.
343+
=== Explicitly transitioning the depth image
388344

389-
[,c++]
390-
----
391-
std::array attachments = {colorAttachment, depthAttachment};
392-
vk::RenderPassCreateInfo renderPassInfo({}, attachments, subpass, dependency);
393-
----
345+
Just like the color attachment, the depth attachment needs to be in the correct layout for the intended use case. For this we need to issue an additional barriers to ensure that the depth image can be used as a depth attachment during rendering.
346+
The depth image is first accessed in the early fragment test pipeline stage and because we have a load operation that _clears_, we should specify the access mask for writes.
394347

395-
Next, update the `VkSubpassDependency` struct to refer to both attachments.
348+
As we now deal with an additional image type (depth), first add a new argument to the `transition_image_layout` function for the image aspect:
396349

397350
[,c++]
398351
----
399-
vk::SubpassDependency dependency(vk::SubpassExternal, {},
400-
vk::PipelineStageFlagBits::eColorAttachmentOutput | vk::PipelineStageFlagBits::eLateFragmentTests,
401-
vk::PipelineStageFlagBits::eEarlyFragmentTests | vk::PipelineStageFlagBits::eColorAttachmentOutput,
402-
vk::AccessFlagBits::eDepthStencilAttachmentWrite,
403-
vk::AccessFlagBits::eDepthStencilAttachmentWrite | vk::AccessFlagBits::eColorAttachmentWrite
404-
);
352+
void transition_image_layout(
353+
...
354+
vk::ImageAspectFlags image_aspect_flags)
355+
{
356+
vk::ImageMemoryBarrier2 barrier = {
357+
...
358+
.subresourceRange = {
359+
.aspectMask = image_aspect_flags,
360+
.baseMipLevel = 0,
361+
.levelCount = 1,
362+
.baseArrayLayer = 0,
363+
.layerCount = 1}};
364+
}
405365
----
406366

407-
Finally, we need to extend our subpass dependencies to make sure that there is no conflict between the transitioning of the depth image and it being cleared as part of its load operation.
408-
The depth image is first accessed in the early fragment test pipeline stage and because we have a load operation that _clears_, we should specify the access mask for writes.
409-
410-
== Framebuffer
411-
412-
The next step is to modify the framebuffer creation to bind the depth image to the depth attachment.
413-
Go to `createFramebuffers` and specify the depth image view as second attachment:
367+
Now add new image layout transition at the start of the command buffer in `recordCommandBuffer`:
414368

415369
[,c++]
416370
----
417-
svk::ImageView attachments[] = { view, *depthImageView };
418-
vk::FramebufferCreateInfo framebufferCreateInfo( {}, *renderPass, attachments, swapChainExtent.width, swapChainExtent.height, 1 );
371+
commandBuffers[currentFrame].begin({});
372+
// Transition for the color attachment
373+
transition_image_layout(
374+
...
375+
vk::ImageAspectFlagBits::eColor);
376+
// New transition for the depth image
377+
transition_image_layout(
378+
*depthImage,
379+
vk::ImageLayout::eUndefined,
380+
vk::ImageLayout::eDepthAttachmentOptimal,
381+
vk::AccessFlagBits2::eDepthStencilAttachmentWrite,
382+
vk::AccessFlagBits2::eDepthStencilAttachmentWrite,
383+
vk::PipelineStageFlagBits2::eEarlyFragmentTests | vk::PipelineStageFlagBits2::eLateFragmentTests,
384+
vk::PipelineStageFlagBits2::eEarlyFragmentTests | vk::PipelineStageFlagBits2::eLateFragmentTests,
385+
vk::ImageAspectFlagBits::eDepth);
419386
----
420387

421-
The color attachment differs for every swap chain image, but the same depth image can be used by all of them because only a single subpass is running at the same time due to our semaphores.
388+
Unlike as with the color image we don't need multiple barriers here. As we don't care for the contents of the depth attachment once the frame is finished, we can always translate from `k::ImageLayout::eUndefined`. What's special about this layout, is the fact that you can always use it as a source without having to care what happens before.
422389

423-
You'll also need to move the call to `createFramebuffers` to make sure that it is called after the depth image view has actually been created:
390+
Also make sure you adjust all other calls to the `transition_image_layout` function call to pass the correct image aspect:
424391

425392
[,c++]
426393
----
427-
void initVulkan() {
428-
...
429-
createDepthResources();
430-
createFramebuffers();
394+
// Before starting rendering, transition the swapchain image to COLOR_ATTACHMENT_OPTIMAL
395+
transition_image_layout(
431396
...
432-
}
397+
// Also need to specify this for color images
398+
vk::ImageAspectFlagBits::eColor);
433399
----
434400

435-
== Clear values
401+
== Depth and stencil state
436402

437-
Because we now have multiple attachments with `VK_ATTACHMENT_LOAD_OP_CLEAR`, we also need to specify multiple clear values.
438-
Go to `recordCommandBuffer` and create an array of `VkClearValue` structs:
403+
The depth attachment is ready to be used now, but depth testing still needs to be enabled in the graphics pipeline.
404+
It is configured through the `PipelineDepthStencilStateCreateInfo` struct:
439405

440406
[,c++]
441407
----
442-
vk::ClearValue clearColor[2] = { vk::ClearColorValue(0.0f, 0.0f, 0.0f, 1.0f), vk::ClearDepthStencilValue(1.0f, 0) };
443-
vk::RenderPassBeginInfo renderPassInfo( *renderPass, swapChainFramebuffers[imageIndex], {{0, 0}, swapChainExtent}, clearColor);
408+
vk::PipelineDepthStencilStateCreateInfo depthStencil{
409+
.depthTestEnable = vk::True,
410+
.depthWriteEnable = vk::True,
411+
.depthCompareOp = vk::CompareOp::eLess,
412+
.depthBoundsTestEnable = vk::False,
413+
.stencilTestEnable = vk::False};
444414
----
445415

446-
The range of depths in the depth buffer is `0.0` to `1.0` in Vulkan, where `1.0` lies at the far view plane and `0.0` at the near view plane.
447-
The initial value at each point in the depth buffer should be the furthest possible depth, which is `1.0`.
448-
449-
Note that the order of `clearValues` should be identical to the order of your attachments.
450-
451-
== Depth and stencil state
452-
453-
The depth attachment is ready to be used now, but depth testing still needs to be enabled in the graphics pipeline.
454-
It is configured through the `VkPipelineDepthStencilStateCreateInfo` struct:
455-
456416
The `depthTestEnable` field specifies if the depth of new fragments should be compared to the depth buffer to see if they should be discarded.
457417
The `depthWriteEnable` field specifies if the new depth of fragments that pass the depth test should actually be written to the depth buffer.
458418

@@ -466,8 +426,19 @@ We won't be using this functionality.
466426
The last three fields configure stencil buffer operations, which we also won't be using in this tutorial.
467427
If you want to use these operations, then you will have to make sure that the format of the depth/stencil image contains a stencil component.
468428

469-
Update the `VkGraphicsPipelineCreateInfo` struct to reference the depth stencil state we just filled in.
470-
A depth stencil state must always be specified if the render pass contains a depth stencil attachment.
429+
A depth stencil state must always be specified if the dynamic rendering setup contains a depth stencil attachment:
430+
431+
Update the `pipelineCreateInfoChain` structure chain to reference the depth stencil state we just filled in and also add a reference to the depth format we're using:
432+
433+
[,c++]
434+
----
435+
vk::StructureChain<vk::GraphicsPipelineCreateInfo, vk::PipelineRenderingCreateInfo> pipelineCreateInfoChain = {
436+
{.stageCount = 2,
437+
...
438+
.pDepthStencilState = &depthStencil,
439+
...
440+
{.colorAttachmentCount = 1, .pColorAttachmentFormats = &swapChainSurfaceFormat.format, .depthAttachmentFormat = depthFormat}};
441+
----
471442

472443
If you run your program now, then you should see that the fragments of the geometry are now correctly ordered:
473444

@@ -487,14 +458,12 @@ void recreateSwapChain() {
487458
glfwWaitEvents();
488459
}
489460
490-
vkDeviceWaitIdle(device);
461+
device.waitIdle(device);
491462
492463
cleanupSwapChain();
493-
494464
createSwapChain();
495465
createImageViews();
496466
createDepthResources();
497-
createFramebuffers();
498467
}
499468
----
500469

0 commit comments

Comments
 (0)