~sircmpwn/xrgears

ref: f162555056b018a3805f96df49158518ec63f94c xrgears/vitamin-k/render/vikOffscreenPass.hpp -rw-r--r-- 12.1 KiB
f1625550 — Lubosz Sarnecki vik: Use struct and array initializers. 2 years ago
                                                                                
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
 /*
 * vitamin-k
 *
 * Copyright 2016 Sascha Willems - www.saschawillems.de
 * Copyright 2017-2018 Collabora Ltd.
 *
 * Authors: Lubosz Sarnecki <lubosz.sarnecki@collabora.com>
 * SPDX-License-Identifier: MIT
 */

#pragma once

#include <vulkan/vulkan.h>

#include <vector>
#include <array>

#include "vikDevice.hpp"

// Offscreen frame buffer properties
#define FB_DIM 2048

namespace vik {
class OffscreenPass {
 private:
  VkDevice device;

  // One sampler for the frame buffer color attachments
  VkSampler colorSampler;

  // Framebuffer for offscreen rendering
  struct FrameBufferAttachment {
    VkImage image;
    VkDeviceMemory mem;
    VkImageView view;
    VkFormat format;
  };

  struct FrameBuffer {
    uint32_t width, height;
    VkFramebuffer frameBuffer;
    FrameBufferAttachment diffuseColor;
    FrameBufferAttachment depth;
    VkRenderPass renderPass;
  } offScreenFrameBuf;

 public:
  explicit OffscreenPass(const VkDevice& d) {
    device = d;
  }

  ~OffscreenPass() {
    vkDestroySampler(device, colorSampler, nullptr);

    // Color attachments
    vkDestroyImageView(device, offScreenFrameBuf.diffuseColor.view, nullptr);
    vkDestroyImage(device, offScreenFrameBuf.diffuseColor.image, nullptr);
    vkFreeMemory(device, offScreenFrameBuf.diffuseColor.mem, nullptr);

    // Depth attachment
    vkDestroyImageView(device, offScreenFrameBuf.depth.view, nullptr);
    vkDestroyImage(device, offScreenFrameBuf.depth.image, nullptr);
    vkFreeMemory(device, offScreenFrameBuf.depth.mem, nullptr);

    vkDestroyFramebuffer(device, offScreenFrameBuf.frameBuffer, nullptr);

    vkDestroyRenderPass(device, offScreenFrameBuf.renderPass, nullptr);
  }

  // Create a frame buffer attachment
  void createAttachment(
      Device *vulkanDevice,
      VkFormat format,
      VkImageUsageFlagBits usage,
      FrameBufferAttachment *attachment) {
    attachment->format = format;

    VkImageCreateInfo image = {
      .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
      .imageType = VK_IMAGE_TYPE_2D,
      .format = format,
      .extent = {
        .width = offScreenFrameBuf.width,
        .height = offScreenFrameBuf.height,
        .depth = 1
      },
      .mipLevels = 1,
      .arrayLayers = 1,
      .samples = VK_SAMPLE_COUNT_1_BIT,
      .tiling = VK_IMAGE_TILING_OPTIMAL
    };

    image.usage = usage | VK_IMAGE_USAGE_SAMPLED_BIT;

    VkMemoryRequirements memReqs;
    vik_log_check(vkCreateImage(device, &image, nullptr, &attachment->image));
    vkGetImageMemoryRequirements(device, attachment->image, &memReqs);

    VkMemoryAllocateInfo memAlloc = {
      .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
      .allocationSize = memReqs.size,
      .memoryTypeIndex =
        vulkanDevice->getMemoryType(memReqs.memoryTypeBits,
                                    VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)
    };

    vik_log_check(vkAllocateMemory(device, &memAlloc, nullptr, &attachment->mem));
    vik_log_check(vkBindImageMemory(device, attachment->image, attachment->mem, 0));

    VkImageAspectFlags aspectMask = 0;
    if (usage & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) {
      aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
    } else if (usage & VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
      aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT;
    }
    assert(aspectMask > 0);

    VkImageViewCreateInfo imageView = {
      .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
      .image = attachment->image,
      .viewType = VK_IMAGE_VIEW_TYPE_2D,
      .format = format,
      .subresourceRange = {
        .aspectMask = aspectMask,
        .baseMipLevel = 0,
        .levelCount = 1,
        .baseArrayLayer = 0,
        .layerCount = 1,
      },
    };

    vik_log_check(vkCreateImageView(device, &imageView, nullptr, &attachment->view));
  }

  // Prepare a new framebuffer and attachments for offscreen rendering (G-Buffer)
  void init_offscreen_framebuffer(Device *vulkanDevice, const VkPhysicalDevice& physicalDevice) {
    offScreenFrameBuf.width = FB_DIM;
    offScreenFrameBuf.height = FB_DIM;

    // Color attachments
    // (World space) Positions
    createAttachment(
          vulkanDevice,
          VK_FORMAT_R16G16B16A16_SFLOAT,
          VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,
          &offScreenFrameBuf.diffuseColor);

    // Depth attachment
    // Find a suitable depth format
    VkFormat attDepthFormat;
    VkBool32 validDepthFormat = tools::getSupportedDepthFormat(physicalDevice, &attDepthFormat);
    assert(validDepthFormat);

    createAttachment(
          vulkanDevice,
          attDepthFormat,
          VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT,
          &offScreenFrameBuf.depth);

    // Set up separate renderpass with references to the color and depth attachments
    std::array<VkAttachmentDescription, 2> attachmentDescs = {};

    // Init attachment properties
    for (uint32_t i = 0; i < 2; ++i) {
      attachmentDescs[i].samples = VK_SAMPLE_COUNT_1_BIT;
      attachmentDescs[i].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
      attachmentDescs[i].storeOp = VK_ATTACHMENT_STORE_OP_STORE;
      attachmentDescs[i].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
      attachmentDescs[i].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
      if (i == 1) {
        attachmentDescs[i].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
        attachmentDescs[i].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
      } else {
        attachmentDescs[i].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
        attachmentDescs[i].finalLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
      }
    }

    // Formats
    attachmentDescs[0].format = offScreenFrameBuf.diffuseColor.format;
    attachmentDescs[1].format = offScreenFrameBuf.depth.format;

    std::vector<VkAttachmentReference> colorReferences;
    colorReferences.push_back({ 0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL });

    VkAttachmentReference depthReference = {
      .attachment = 1,
      .layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL
    };

    VkSubpassDescription subpass = {
      .pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS,
      .colorAttachmentCount = static_cast<uint32_t>(colorReferences.size()),
      .pColorAttachments = colorReferences.data(),
      .pDepthStencilAttachment = &depthReference
    };

    // Use subpass dependencies for attachment layput transitions
    std::array<VkSubpassDependency, 2> dependencies = {
      (VkSubpassDependency) {
        .srcSubpass = VK_SUBPASS_EXTERNAL,
        .dstSubpass = 0,
        .srcStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
        .dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
        .srcAccessMask = VK_ACCESS_MEMORY_READ_BIT,
        .dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT |
                         VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
        .dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT
      },
      (VkSubpassDependency)  {
        .srcSubpass = 0,
        .dstSubpass = VK_SUBPASS_EXTERNAL,
        .srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
        .dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
        .srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT |
                         VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
        .dstAccessMask = VK_ACCESS_MEMORY_READ_BIT,
        .dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT
      }
    };

    VkRenderPassCreateInfo renderPassInfo = {
      .sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO,
      .attachmentCount = static_cast<uint32_t>(attachmentDescs.size()),
      .pAttachments = attachmentDescs.data(),
      .subpassCount = 1,
      .pSubpasses = &subpass,
      .dependencyCount = 2,
      .pDependencies = dependencies.data()
    };

    vik_log_check(vkCreateRenderPass(device, &renderPassInfo,
                                     nullptr, &offScreenFrameBuf.renderPass));

    std::array<VkImageView, 2> attachments;
    attachments[0] = offScreenFrameBuf.diffuseColor.view;
    attachments[1] = offScreenFrameBuf.depth.view;

    VkFramebufferCreateInfo fbufCreateInfo = {
      .sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO,
      .renderPass = offScreenFrameBuf.renderPass,
      .attachmentCount = static_cast<uint32_t>(attachments.size()),
      .pAttachments = attachments.data(),
      .width = offScreenFrameBuf.width,
      .height = offScreenFrameBuf.height,
      .layers = 1
    };

    vik_log_check(vkCreateFramebuffer(device, &fbufCreateInfo,
                                      nullptr, &offScreenFrameBuf.frameBuffer));

    // Create sampler to sample from the color attachments

    VkSamplerCreateInfo sampler = {
      .sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO,
      .magFilter = VK_FILTER_NEAREST,
      .minFilter = VK_FILTER_NEAREST,
      .mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR,
      .addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
      .addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
      .addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
      .mipLodBias = 0.0f,
      .maxAnisotropy = 1.0f,
      .minLod = 0.0f,
      .maxLod = 1.0f,
      .borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE
    };

    vik_log_check(vkCreateSampler(device, &sampler, nullptr, &colorSampler));
  }

  VkDescriptorImageInfo get_descriptor_image_info() {
    // Image descriptors for the offscreen color attachments
    VkDescriptorImageInfo descriptor_info = {
          .sampler = colorSampler,
          .imageView = offScreenFrameBuf.diffuseColor.view,
          .imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL
        };
    return descriptor_info;
  }

  VkWriteDescriptorSet
  get_image_write_descriptor_set(const VkDescriptorSet& descriptorSet,
                                 VkDescriptorImageInfo *texDescriptorPosition,
                                 uint32_t binding) {
    return  (VkWriteDescriptorSet) {
      .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
      .dstSet = descriptorSet,
      .dstBinding = binding,
      .descriptorCount = 1,
      .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
      .pImageInfo = texDescriptorPosition
    };
  }

  void beginRenderPass(const VkCommandBuffer& cmdBuffer) {
    // Clear values for all attachments written in the fragment sahder
    std::array<VkClearValue, 2> clearValues;
    clearValues[0].color = { { 1.0f, 1.0f, 1.0f, 1.0f } };
    clearValues[1].depthStencil = { 1.0f, 0 };

    VkRenderPassBeginInfo renderPassBeginInfo = {
      .sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO,
      .renderPass =  offScreenFrameBuf.renderPass,
      .framebuffer = offScreenFrameBuf.frameBuffer,
      .renderArea = {
        .extent = {
          .width = offScreenFrameBuf.width,
          .height = offScreenFrameBuf.height
        }
      },
      .clearValueCount = static_cast<uint32_t>(clearValues.size()),
      .pClearValues = clearValues.data()
    };

    vkCmdBeginRenderPass(cmdBuffer, &renderPassBeginInfo,
                         VK_SUBPASS_CONTENTS_INLINE);
  }

  void setViewPortAndScissor(const VkCommandBuffer& cmdBuffer) {
    VkViewport viewport = {
      .width = (float)offScreenFrameBuf.width,
      .height = (float)offScreenFrameBuf.height,
      .minDepth = 0.0f,
      .maxDepth = 1.0f
    };
    vkCmdSetViewport(cmdBuffer, 0, 1, &viewport);

    VkRect2D scissor = {
      .offset = { .x = 0, .y = 0 },
      .extent = {
        .width = offScreenFrameBuf.width,
        .height = offScreenFrameBuf.height
      }
    };
    vkCmdSetScissor(cmdBuffer, 0, 1, &scissor);
  }

  void setViewPortAndScissorStereo(const VkCommandBuffer& cmdBuffer) {
    VkViewport viewports[2];

    uint32_t w = offScreenFrameBuf.width, h = offScreenFrameBuf.height;

    // Left
    viewports[0] = { 0, 0, (float) w / 2.0f, (float) h, 0.0, 1.0f };
    // Right
    viewports[1] = { (float) w / 2.0f, 0, (float) w / 2.0f, (float) h, 0.0, 1.0f };

    vkCmdSetViewport(cmdBuffer, 0, 2, viewports);

    VkRect2D scissorRects[2] = {
      {
        .offset = { .x = 0, .y = 0 },
        .extent = { .width = w / 2, .height = h }
      },
      {
        .offset = { .x = (int32_t) w / 2, .y = 0 },
        .extent = { .width = w / 2, .height = h }
      },
    };
    vkCmdSetScissor(cmdBuffer, 0, 2, scissorRects);
  }

  VkRenderPass getRenderPass() {
    return offScreenFrameBuf.renderPass;
  }
};
}  // namespace vik