Skip to content

Commit c3cb2fa

Browse files
committed
Update chapter to what's actually used in the tutorial:
- No more render passes - No more framebuffers - Dynamci rendering - Explicit barriers - Some rewording and additions to clarify things - Use vulkan-hpp names
1 parent ca42702 commit c3cb2fa

File tree

1 file changed

+99
-132
lines changed

1 file changed

+99
-132
lines changed

en/07_Depth_buffering.adoc

Lines changed: 99 additions & 132 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,9 +23,9 @@ 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
...
@@ -156,20 +156,20 @@ void createDepthResources() {
156156
Creating a depth image is fairly straightforward.
157157
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.
158158
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_`.
159+
The format must contain a depth component, indicated by `_D??_` in the `vk::Format`.
160160

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

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
165+
* `vk::Format::eD32Sfloat`: 32-bit float for depth
166+
* `vk::Format::eD32SfloatS8Uint`: 32-bit signed float for depth and 8 bit stencil component
167+
* `vk::Format::eD24UnormS8Uint`: 24-bit float for depth and 8 bit stencil component
168168

169169
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.
170170
We'll look at this in a future chapter.
171171

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.
172+
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.
173173
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:
174174

175175
[,c++]
@@ -189,7 +189,7 @@ for (const auto format : candidates) {
189189
}
190190
----
191191

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

194194
* `linearTilingFeatures`: Use cases that are supported with linear tiling
195195
* `optimalTilingFeatures`: Use cases that are supported with optimal tiling
@@ -240,7 +240,7 @@ VkFormat findDepthFormat() {
240240
}
241241
----
242242

243-
Make sure to use the `VK_FORMAT_FEATURE_` flag instead of `VK_IMAGE_USAGE_` in this case.
243+
Make sure to use the `vk::FormatFeatureFlagBits` instead of `vk::ImageUsageFlagBits` in this case.
244244
All of these candidate formats contain a depth component, but the latter two also contain a stencil component.
245245
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.
246246
Add a simple helper function that tells us if the chosen depth format contains a stencil component:
@@ -267,13 +267,15 @@ createImage(swapChainExtent.width, swapChainExtent.height, depthFormat, vk::Imag
267267
depthImageView = createImageView(depthImage, depthFormat, vk::ImageAspectFlagBits::eDepth);
268268
----
269269

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:
270+
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:
271271

272272
[,c++]
273273
----
274274
vk::raii::ImageView createImageView(vk::raii::Image& image, vk::Format format, vk::ImageAspectFlags aspectFlags) {
275275
...
276-
viewInfo.subresourceRange.aspectMask = aspectFlags;
276+
vk::ImageViewCreateInfo viewInfo{
277+
...
278+
.subresourceRange = {aspectFlags, 0, 1, 0, 1}};
277279
...
278280
}
279281
----
@@ -290,169 +292,123 @@ textureImageView = createImageView(textureImage, vk::Format::eR8G8B8A8Srgb, vk::
290292
----
291293

292294
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.
295+
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.
294296

295-
=== Explicitly transitioning the depth image
297+
== Command buffer
296298

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.
299+
=== Clear values
300300

301-
Make a call to `transitionImageLayout` at the end of the `createDepthResources` function like so:
301+
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.
302+
Go to `recordCommandBuffer` and create and add an additional `vk::ClearValue` variable called `clearDepth`:
302303

303304
[,c++]
304305
----
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++]
306+
vk::ClearValue clearColor = vk::ClearColorValue(0.0f, 0.0f, 0.0f, 1.0f);
307+
vk::ClearValue clearDepth = vk::ClearDepthStencilValue(1.0f, 0);
312308
----
313-
if (newLayout == vk::ImageLayout::eDepthStencilAttachmentOptimal) {
314-
barrier.subresourceRange.aspectMask = vk::ImageAspectFlagBits::eDepth;
315309

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-
----
323-
324-
Although we're not using the stencil component, we do need to include it in the layout transitions of the depth image.
325-
326-
Finally, add the correct access masks and pipeline stages:
327-
328-
[,c++]
329-
----
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-
}
351-
----
352-
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.
356-
357-
== Render pass
310+
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.
311+
The initial value at each point in the depth buffer should be the furthest possible depth, which is `1.0`.
358312

359-
We're now going to modify `createRenderPass` to include a depth attachment.
360-
First specify the `VkAttachmentDescription`:
313+
=== Dynamic rendering
361314

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-
----
315+
Now that we have our depth image set up, we need to make use of it in `recordCommandBuffer`.
316+
This will be part of dynamic rendering and is similar to setting up our color output image.
368317

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`.
318+
First specify a new rendering attachment for the depth image:
373319

374320
[,c++]
375321
----
376-
vk::AttachmentReference depthAttachmentRef(1, vk::ImageLayout::eDepthStencilAttachmentOptimal);
322+
vk::RenderingAttachmentInfo depthAttachmentInfo = {
323+
.imageView = depthImageView,
324+
.imageLayout = vk::ImageLayout::eDepthAttachmentOptimal,
325+
.loadOp = vk::AttachmentLoadOp::eClear,
326+
.storeOp = vk::AttachmentStoreOp::eDontCare,
327+
.clearValue = clearDepth};
377328
----
378329

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

381332
[,c++]
382333
----
383-
vk::SubpassDescription subpass({}, vk::PipelineBindPoint::eGraphics, 0, {}, 1, &colorAttachmentRef, {}, &depthAttachmentRef);
334+
vk::RenderingInfo renderingInfo = {
335+
...
336+
.pDepthAttachment = &depthAttachmentInfo};
384337
----
385338

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.
339+
=== Explicitly transitioning the depth image
388340

389-
[,c++]
390-
----
391-
std::array attachments = {colorAttachment, depthAttachment};
392-
vk::RenderPassCreateInfo renderPassInfo({}, attachments, subpass, dependency);
393-
----
341+
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.
342+
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.
394343

395-
Next, update the `VkSubpassDependency` struct to refer to both attachments.
344+
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:
396345

397346
[,c++]
398347
----
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-
);
348+
void transition_image_layout(
349+
...
350+
vk::ImageAspectFlags image_aspect_flags)
351+
{
352+
vk::ImageMemoryBarrier2 barrier = {
353+
...
354+
.subresourceRange = {
355+
.aspectMask = image_aspect_flags,
356+
.baseMipLevel = 0,
357+
.levelCount = 1,
358+
.baseArrayLayer = 0,
359+
.layerCount = 1}};
360+
}
405361
----
406362

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:
363+
Now add new image layout transition at the start of the command buffer in `recordCommandBuffer`:
414364

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

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.
384+
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.
422385

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:
386+
Also make sure you adjust all other calls to the `transition_image_layout` function call to pass the correct image aspect:
424387

425388
[,c++]
426389
----
427-
void initVulkan() {
390+
// Before starting rendering, transition the swapchain image to COLOR_ATTACHMENT_OPTIMAL
391+
transition_image_layout(
428392
...
429-
createDepthResources();
430-
createFramebuffers();
431-
...
432-
}
393+
// Also need to specify this for color images
394+
vk::ImageAspectFlagBits::eColor);
433395
----
434396

435-
== Clear values
397+
== Depth and stencil state
436398

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:
399+
The depth attachment is ready to be used now, but depth testing still needs to be enabled in the graphics pipeline.
400+
It is configured through the `PipelineDepthStencilStateCreateInfo` struct:
439401

440402
[,c++]
441403
----
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);
404+
vk::PipelineDepthStencilStateCreateInfo depthStencil{
405+
.depthTestEnable = vk::True,
406+
.depthWriteEnable = vk::True,
407+
.depthCompareOp = vk::CompareOp::eLess,
408+
.depthBoundsTestEnable = vk::False,
409+
.stencilTestEnable = vk::False};
444410
----
445411

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-
456412
The `depthTestEnable` field specifies if the depth of new fragments should be compared to the depth buffer to see if they should be discarded.
457413
The `depthWriteEnable` field specifies if the new depth of fragments that pass the depth test should actually be written to the depth buffer.
458414

@@ -466,8 +422,19 @@ We won't be using this functionality.
466422
The last three fields configure stencil buffer operations, which we also won't be using in this tutorial.
467423
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.
468424

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.
425+
A depth stencil state must always be specified if the dynamic rendering setup contains a depth stencil attachment:
426+
427+
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:
428+
429+
[,c++]
430+
----
431+
vk::StructureChain<vk::GraphicsPipelineCreateInfo, vk::PipelineRenderingCreateInfo> pipelineCreateInfoChain = {
432+
{.stageCount = 2,
433+
...
434+
.pDepthStencilState = &depthStencil,
435+
...
436+
{.colorAttachmentCount = 1, .pColorAttachmentFormats = &swapChainSurfaceFormat.format, .depthAttachmentFormat = depthFormat}};
437+
----
471438

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

0 commit comments

Comments
 (0)