GlistEngine
Loading...
Searching...
No Matches
gVKContext.h
Go to the documentation of this file.
1/*
2 * gVKContext.h
3 *
4 * Shared state of the Vulkan render backend. gVKRenderEngine.h only forward
5 * declares gVKContext, so including that header still never pulls in
6 * <vulkan/vulkan.h>; the layout lives here instead of inside a single .cpp so
7 * every gVK* module of the backend can work against the same contract.
8 */
9
10#pragma once
11
12#ifndef CORE_GVKCONTEXT_H
13#define CORE_GVKCONTEXT_H
14
15// TARGET_OS_IPHONE only exists once TargetConditionals.h has been included, so it
16// has to be pulled in before the guard below is evaluated.
17#if defined(__APPLE__)
18#include <TargetConditionals.h>
19#endif
20
21// Vulkan is an optional dependency of this engine: engine/CMakeLists.txt defines
22// GLIST_HAS_VULKAN only when the development files are actually present, which is
23// not the case on every machine or CI runner. Every gVK* module guards its body
24// with GVK_VULKAN so those translation units stay empty when Vulkan is not
25// available, and the engine still builds.
26#if defined(GLIST_HAS_VULKAN) && !defined(EMSCRIPTEN)
27#define GVK_VULKAN 1
28#endif
29
30#ifdef GVK_VULKAN
31
32#include <vulkan/vulkan.h>
33#include <algorithm>
34#include <cstdint>
35#include <cstring>
36#include <string>
37#include <vector>
38#include <map>
39#include <array>
40
41class gBaseWindow;
42struct gVKContext;
43struct gVKDeferredResources;
44
45// How many frames the CPU may prepare while the GPU is still busy with earlier ones.
46inline constexpr int GVK_MAX_FRAMES_IN_FLIGHT = 2;
47inline constexpr uint32_t GVK_SCENE_UNIFORM_SLOTS = 16;
48
49// Declared here as well so the struct can befriend them.
50bool gvkCreateSwapchain(gVKContext& ctx, gBaseWindow* window);
51void gvkDestroySwapchain(gVKContext& ctx);
52bool gvkRecreateSwapchain(gVKContext& ctx, gBaseWindow* window);
53bool gvkRecreateSurface(gVKContext& ctx, gBaseWindow* window);
54VkFormat gvkFindDepthFormat(gVKContext& ctx);
55bool gvkCreateDepthResources(gVKContext& ctx);
56void gvkDestroyDepthResources(gVKContext& ctx);
57bool gvkCreateMsaaColorResources(gVKContext& ctx);
58void gvkDestroyMsaaColorResources(gVKContext& ctx);
59bool gvkCreateRenderPass(gVKContext& ctx);
60void gvkDestroyRenderPass(gVKContext& ctx);
61bool gvkCreateFramebuffers(gVKContext& ctx);
62void gvkDestroyFramebuffers(gVKContext& ctx);
63bool gvkCreateCommandResources(gVKContext& ctx);
64void gvkDestroyCommandResources(gVKContext& ctx);
65bool gvkCreateFrameSyncObjects(gVKContext& ctx);
66void gvkDestroyFrameSyncObjects(gVKContext& ctx);
67bool gvkCreatePresentSemaphores(gVKContext& ctx, uint32_t imagecount);
68void gvkDestroyPresentSemaphores(gVKContext& ctx);
69bool gvkBeginFrame(gVKContext& ctx, gBaseWindow* window);
70bool gvkEndFrame(gVKContext& ctx, gBaseWindow* window);
71
72// 2D draw path. Declared here so the struct can befriend them; defined in
73// gVKFrame.cpp (render pass) / gVKPipeline.cpp (pipelines) / gVKDraw.cpp (ring).
74bool gvkEnsureRenderPass(gVKContext& ctx);
75// Copies what the last pass resolved into a sampleable texture, so a multisampled
76// frame can be rebuilt after a render target was bound part way through it.
77VkDescriptorSet gvkCaptureResolvedScreen(gVKContext& ctx);
78// Clears the depth buffer of the open pass without ending it, the way
79// glClear(GL_DEPTH_BUFFER_BIT) does part way through a frame. Defined in
80// gVKDraw.cpp. Returns false when no pass is open, in which case the pass's own
81// load op has already done the clearing.
82bool gvkClearDepthNow(gVKContext& ctx);
83bool gvkCreateGraphicsPipelines(gVKContext& ctx);
84bool gvkReloadGraphicsPipelines(gVKContext& ctx);
85void gvkDestroyGraphicsPipelines(gVKContext& ctx);
86bool gvkCreateDeferredGeometryPipeline(gVKContext& ctx, VkRenderPass renderpass);
87void gvkDestroyDeferredGeometryPipeline(gVKContext& ctx);
88bool gvkCreateDeferredLightingPipeline(gVKContext& ctx);
89void gvkDestroyDeferredLightingPipeline(gVKContext& ctx);
90bool gvkCreateDrawResources(gVKContext& ctx);
91bool gvkEnsureMeshArena(gVKContext& ctx, VkDeviceSize capacity);
92void gvkDestroyMeshArena(gVKContext& ctx);
93void gvkDestroyDrawResources(gVKContext& ctx);
94bool gvkCreateShadowResources(gVKContext& ctx, uint32_t width, uint32_t height);
95bool gvkCreateShadowPipeline(gVKContext& ctx);
96void gvkDestroyShadowPipeline(gVKContext& ctx);
97void gvkDestroyShadowResources(gVKContext& ctx);
98bool gvkBeginShadowPass(gVKContext& ctx);
99void gvkEndShadowPass(gVKContext& ctx);
100gVKDeferredResources* gvkCreateDeferredResources(gVKContext& ctx,
101 uint32_t width, uint32_t height);
102void gvkDestroyDeferredResources(gVKContext& ctx, gVKDeferredResources*& resources);
103bool gvkBeginDeferredPass(gVKContext& ctx, gVKDeferredResources& resources);
104void gvkEndDeferredPass(gVKContext& ctx);
105bool gvkRestoreDeferredDepth(gVKContext& ctx, gVKDeferredResources& resources);
106bool gvkCreateUniformResources(gVKContext& ctx);
107void gvkDestroyUniformResources(gVKContext& ctx);
108bool gvkAppendSceneUniformChunk(gVKContext& ctx, int framei);
109
110// Multisampling and the render-pass compatibility problem it creates.
111//
112// A graphics pipeline is baked against a render pass, and the sample count of
113// every attachment is part of render-pass *compatibility*: a pipeline built for a
114// 4x pass cannot be recorded into a 1x one, nor the other way round. This backend
115// has three kinds of pass - the screen pass, one pass per offscreen render target
116// (gFbo), and the shadow pass - and the same 2D/3D pipelines are recorded into the
117// first two. Switching the screen pass to 4x therefore breaks every draw into an
118// FBO unless something is done about it.
119//
120// The two honest ways out are to put every pass on the same sample count, or to
121// key the pipelines by sample count and build the variants that are actually used.
122// This backend does the second, for three reasons:
123//
124// - The shadow pass must stay 1x. Multisampling a depth-only map that is compared
125// against rather than displayed buys nothing and costs bandwidth and memory on
126// exactly the mobile parts this backend targets. So "one count everywhere" is
127// already impossible; the only question is where the seam sits.
128// - An FBO's attachments are gTextures the application samples afterwards. Making
129// those passes multisampled means a transient MSAA image *plus* the resolve
130// target for every render target the app owns, and a depth-only FBO - which
131// gFbo produces for depth prepasses - has no resolve path at all before VK 1.2's
132// separate depth/stencil resolve. A post-processing chain wants the raw 1x
133// buffer regardless.
134// - The cost of the second design is one extra set of VkPipeline objects, and only
135// while MSAA is on. They come out of the same VkPipelineCache and reuse the same
136// modules and layouts, so the second build is a fraction of the first.
137//
138// So: index 0 is the single-sample build, used by every offscreen pass and by the
139// screen pass while MSAA is off; index 1 is the build for the screen pass's sample
140// count and only exists while that is above one. getActivePipelineVariant() is what
141// the pipeline getters index with, and whichever pass opens sets it.
142inline constexpr uint32_t GVK_PIPELINE_SAMPLE_VARIANTS = 2;
143
144// The forms one pipeline family takes at a single sample count. Which of them get
145// built is decided per family by gvkPipelineOptions; the ones that are not stay
146// null and the getters fall back to the plain pipeline. gVKContext holds one array
147// of these per family, indexed by sample-count variant.
148struct gVKPipelineVariants {
149 VkPipeline pipeline = VK_NULL_HANDLE;
150 // The same pipeline with a line topology, for stroking unfilled shapes and for
151 // meshes drawn as wireframe.
152 VkPipeline linepipeline = VK_NULL_HANDLE;
153 // The same pipeline with the opposite blend setting; blending cannot be dynamic
154 // state, so following the renderer's setting means choosing a pipeline.
155 VkPipeline blendvariantpipeline = VK_NULL_HANDLE;
156 // The same pipeline adding instead of compositing, for BLENDMODE_ADDITIVE.
157 VkPipeline additivepipeline = VK_NULL_HANDLE;
158 // The same pipeline with the cutout discard specialised out; see
159 // gvkPipelineOptions::nocutoutvariant in gVKPipeline.cpp.
160 VkPipeline nocutoutpipeline = VK_NULL_HANDLE;
161};
162
163// Validation layers cost performance, so the default follows the same DEBUG
164// condition the OpenGL debug output already uses in this engine. A developer can
165// still override it per context through setValidationEnabled().
166#if defined(DEBUG) || defined(ENGINE_OPENGL_CHECKS)
167inline constexpr bool gvkdefaultvalidation = true;
168#else
169inline constexpr bool gvkdefaultvalidation = false;
170#endif
171
172// Every Vulkan handle lives here so the header stays Vulkan free, right next to
173// the developer facing settings that shape initialisation. Handles start as
174// VK_NULL_HANDLE, which is what makes the "destroy only if non null" teardown
175// correct even when initialisation fails half way through.
176//
177// The public surface is accessor based: settings go in through setters, and both
178// settings and handles come back out through pointer returning getters. Handing
179// back the address of a handle is deliberate - that is exactly the shape most
180// Vulkan entry points want for their out parameters, so the same getter both
181// reads a handle and receives it when the next phase (swapchain, pipeline, ...)
182// is wired up. gVKRenderEngine drives creation, so it is a friend and reaches
183// the raw members directly; every other consumer goes through the accessors.
184struct gVKContext {
185 friend class gVKRenderEngine;
186 // The backend's own modules create and tear down the members below, so they
187 // reach them directly just like gVKRenderEngine does. Everything outside the
188 // backend goes through the accessors.
189 friend bool gvkCreateSwapchain(gVKContext&, gBaseWindow*);
190 friend void gvkDestroySwapchain(gVKContext&);
191 friend bool gvkRecreateSwapchain(gVKContext&, gBaseWindow*);
192 friend bool gvkRecreateSurface(gVKContext&, gBaseWindow*);
193 friend VkFormat gvkFindDepthFormat(gVKContext&);
194 friend bool gvkCreateDepthResources(gVKContext&);
195 friend void gvkDestroyDepthResources(gVKContext&);
196 friend bool gvkCreateMsaaColorResources(gVKContext&);
197 friend void gvkDestroyMsaaColorResources(gVKContext&);
198 friend bool gvkCreateRenderPass(gVKContext&);
199 friend void gvkDestroyRenderPass(gVKContext&);
200 friend bool gvkCreateFramebuffers(gVKContext&);
201 friend void gvkDestroyFramebuffers(gVKContext&);
202 friend bool gvkCreateCommandResources(gVKContext&);
203 friend void gvkDestroyCommandResources(gVKContext&);
204 friend bool gvkCreateFrameSyncObjects(gVKContext&);
205 friend void gvkDestroyFrameSyncObjects(gVKContext&);
206 friend bool gvkCreatePresentSemaphores(gVKContext&, uint32_t);
207 friend void gvkDestroyPresentSemaphores(gVKContext&);
208 friend bool gvkBeginFrame(gVKContext&, gBaseWindow*);
209 friend bool gvkEndFrame(gVKContext&, gBaseWindow*);
210 friend bool gvkEnsureRenderPass(gVKContext&);
211 friend VkDescriptorSet gvkCaptureResolvedScreen(gVKContext&);
212 friend bool gvkClearDepthNow(gVKContext&);
213 friend bool gvkCreateGraphicsPipelines(gVKContext&);
214 friend bool gvkReloadGraphicsPipelines(gVKContext&);
215 friend void gvkDestroyGraphicsPipelines(gVKContext&);
216 friend bool gvkCreateDeferredGeometryPipeline(gVKContext&, VkRenderPass);
217 friend void gvkDestroyDeferredGeometryPipeline(gVKContext&);
218 friend bool gvkCreateDeferredLightingPipeline(gVKContext&);
219 friend void gvkDestroyDeferredLightingPipeline(gVKContext&);
220 friend void gvkDestroyPipelineCache(gVKContext&);
221 friend bool gvkCreateDrawResources(gVKContext&);
222 friend bool gvkEnsureMeshArena(gVKContext&, VkDeviceSize);
223 friend void gvkDestroyMeshArena(gVKContext&);
224 friend void gvkDestroyDrawResources(gVKContext&);
225 friend bool gvkCreateShadowResources(gVKContext&, uint32_t, uint32_t);
226 friend bool gvkCreateShadowPipeline(gVKContext&);
227 friend void gvkDestroyShadowPipeline(gVKContext&);
228 friend void gvkDestroyShadowResources(gVKContext&);
229 friend bool gvkBeginShadowPass(gVKContext&);
230 friend void gvkEndShadowPass(gVKContext&);
231 friend gVKDeferredResources* gvkCreateDeferredResources(gVKContext&, uint32_t, uint32_t);
232 friend void gvkDestroyDeferredResources(gVKContext&, gVKDeferredResources*&);
233 friend bool gvkBeginDeferredPass(gVKContext&, gVKDeferredResources&);
234 friend void gvkEndDeferredPass(gVKContext&);
235 friend bool gvkRestoreDeferredDepth(gVKContext&, gVKDeferredResources&);
236 friend bool gvkCreateUniformResources(gVKContext&);
237 friend bool gvkAppendSceneUniformChunk(gVKContext&, int);
238 friend void gvkDestroyUniformResources(gVKContext&);
239 friend struct gVKSceneUniforms;
240 friend bool gvkWriteSceneUniforms(gVKContext&, const struct gVKSceneUniforms&);
241 // A pipeline built from a shader the application supplied. Reaches the same
242 // render passes, sample state and pipeline cache the built-in builds do, which
243 // is what makes a user shader record into the same passes as the engine's own.
244 // gVKUserShader itself needs none of this and goes through the public getters.
245 friend bool gvkBuildUserPipeline(gVKContext&, const std::vector<uint32_t>&,
246 const std::vector<uint32_t>&, const char*, struct gVKUserPipeline&);
247 friend void gvkDestroyUserPipeline(gVKContext&, struct gVKUserPipeline&);
248
249 /* ---------------- configurable settings ---------------- */
250 // Set these before the backend initialises to influence instance and device
251 // creation. Reading them afterwards simply reports what was used.
252
253 // Identity handed to VkApplicationInfo. Informational to drivers and tools,
254 // but handy for profiling and crash triage.
255 void setAppName(const std::string& name) { appname = name; }
256 void setEngineName(const std::string& name) { enginename = name; }
257 void setAppVersion(uint32_t version) { appversion = version; }
258 void setEngineVersion(uint32_t version) { engineversion = version; }
259
260 // The minimum Vulkan version the engine requires (the floor), e.g.
261 // VK_API_VERSION_1_3. init does NOT target this value: it targets the highest
262 // version the loader offers, so newer Vulkan (1.4 today, 1.5+ later) is picked
263 // up automatically with no code change. This floor only decides when to give
264 // up - if the loader cannot even reach it, init fails instead of limping on.
265 void setMinApiVersion(uint32_t version) { minapiversion = version; }
266
267 // Validation layers are a debugging aid; on by default only in debug builds.
268 void setValidationEnabled(bool enabled) { enablevalidation = enabled; }
269
270 // Extra names appended on top of the mandatory GLFW / portability ones the
271 // engine always requests. The pointed to strings must outlive init, so string
272 // literals (or otherwise long lived storage) are the natural fit.
273 void addInstanceExtension(const char* name) { extrainstanceextensions.push_back(name); }
274 void addDeviceExtension(const char* name) { extradeviceextensions.push_back(name); }
275 void addLayer(const char* name) { extralayers.push_back(name); }
276
277 // Pointer returning getters for the settings, so a caller can both inspect
278 // and, when a Vulkan struct wants an address, forward it without copying.
279 std::string* getAppName() { return &appname; }
280 std::string* getEngineName() { return &enginename; }
281 uint32_t* getAppVersion() { return &appversion; }
282 uint32_t* getEngineVersion() { return &engineversion; }
283 uint32_t* getMinApiVersion() { return &minapiversion; }
284 bool* getValidationEnabled() { return &enablevalidation; }
285 std::vector<const char*>* getInstanceExtensions() { return &extrainstanceextensions; }
286 std::vector<const char*>* getDeviceExtensions() { return &extradeviceextensions; }
287 std::vector<const char*>* getLayers() { return &extralayers; }
288
289 /* ---------------- created Vulkan handles ---------------- */
290 // Filled during init. Each getter returns the address of the handle, matching
291 // the out parameter shape of the Vulkan calls that will consume them.
292
293 VkInstance* getInstance() { return &instance; }
294 VkDebugUtilsMessengerEXT* getDebugMessenger() { return &debugmessenger; }
295 VkSurfaceKHR* getSurface() { return &surface; }
296 VkPhysicalDevice* getPhysicalDevice() { return &physicaldevice; }
297
298 // The full set of GPUs the instance enumerated, and how many. init keeps only
299 // the first device that can both render and present (getPhysicalDevice());
300 // these expose the whole list so code can inspect or pick a different one.
301 uint32_t* getDeviceCount() { return &devicecount; }
302 std::vector<VkPhysicalDevice>* getPhysicalDevices() { return &physicaldevices; }
303
304 // Properties and features for every enumerated GPU (parallel to
305 // getPhysicalDevices()), including the ones init did not pick, so code can
306 // compare and choose a different device without querying each handle itself.
307 std::vector<VkPhysicalDeviceProperties>* getAllDeviceProperties() { return &physicaldeviceproperties; }
308 std::vector<VkPhysicalDeviceFeatures>* getAllDeviceFeatures() { return &physicaldevicefeatures; }
309
310 VkDevice* getDevice() { return &device; }
311 VkQueue* getGraphicsQueue() { return &graphicsqueue; }
312 VkQueue* getPresentQueue() { return &presentqueue; }
313 uint32_t* getGraphicsFamily() { return &graphicsfamily; }
314 uint32_t* getPresentFamily() { return &presentfamily; }
315
316 // Queue families of the selected physical device as the driver reported them:
317 // queue counts and capability flags (graphics/compute/transfer/...). init reads
318 // these to choose the graphics and present indices; kept for later multi-queue
319 // work (e.g. a dedicated transfer or compute queue).
320 std::vector<VkQueueFamilyProperties>* getQueueFamilyProperties() { return &queuefamilyproperties; }
321
322 // Per queue family of the selected device: whether that family can present to
323 // the surface (parallel to getQueueFamilyProperties()). init keeps only the
324 // first presentable family index; this exposes every family's support.
325 std::vector<VkBool32>* getQueueFamilyPresentSupport() { return &queuefamilypresentsupport; }
326
327 // The instance extensions, layers and device extensions actually enabled at
328 // creation: the mandatory GLFW / portability / swapchain / validation names
329 // merged with the developer's additions. getInstanceExtensions() / getLayers()
330 // / getDeviceExtensions() above return only the developer's extra requests;
331 // these return the full effective set that was handed to Vulkan.
332 std::vector<const char*>* getEnabledInstanceExtensions() { return &enabledinstanceextensions; }
333 std::vector<const char*>* getEnabledLayers() { return &enabledlayers; }
334 std::vector<const char*>* getEnabledDeviceExtensions() { return &enableddeviceextensions; }
335
336 // Everything the instance / GPU actually supports (not just what we enabled),
337 // enumerated once at init so a developer can check for a capability without
338 // re-querying: is extension X available on this GPU, is layer Y installed.
339 std::vector<VkExtensionProperties>* getAvailableInstanceExtensions() { return &availableinstanceextensions; }
340 std::vector<VkLayerProperties>* getAvailableLayers() { return &availablelayers; }
341 std::vector<VkExtensionProperties>* getAvailableDeviceExtensions() { return &availabledeviceextensions; }
342
343 // The three core physical-device capability blocks, queried once during init.
344 // Properties: limits and identity. Features: optional capabilities the GPU
345 // supports (samplerAnisotropy, geometryShader, ...). Memory: heaps and memory
346 // types, needed to pick where every buffer and image gets allocated.
347 VkPhysicalDeviceProperties* getDeviceProperties() { return &deviceproperties; }
348
349 // Convenience for the selected GPU's own Vulkan version (same as
350 // getDeviceProperties()->apiVersion). Check against this before using
351 // version-specific core features; getInstanceApiVersion() is the loader side.
352 uint32_t getDeviceApiVersion() const { return deviceproperties.apiVersion; }
353
354 VkPhysicalDeviceFeatures* getDeviceFeatures() { return &devicefeatures; }
355 VkPhysicalDeviceMemoryProperties* getDeviceMemoryProperties() { return &devicememoryproperties; }
356
357 // The surface's capabilities and the formats / present modes it supports on the
358 // selected device - what the swapchain is built from: extent and image-count
359 // bounds, colour formats, and vsync / present modes.
360 VkSurfaceCapabilitiesKHR* getSurfaceCapabilities() { return &surfacecapabilities; }
361 std::vector<VkSurfaceFormatKHR>* getSurfaceFormats() { return &surfaceformats; }
362 std::vector<VkPresentModeKHR>* getSurfacePresentModes() { return &surfacepresentmodes; }
363
364 // The instance-level Vulkan version the loader actually supports (from
365 // vkEnumerateInstanceVersion). This is exactly what init targets - it is the
366 // highest version available; getMinApiVersion() is only the floor init checks
367 // it against.
368 uint32_t* getInstanceApiVersion() { return &instanceapiversion; }
369
370 // Whether validation is actually running, which is not the same as whether it
371 // was requested: setValidationEnabled(true) still yields false here when the
372 // layer or debug-utils extension is missing at runtime. getValidationEnabled()
373 // reports the request; this reports the outcome.
374 bool isValidationActive() const { return validationactive; }
375
376 // True once a logical device exists, i.e. init reached the point where the
377 // context is actually usable for swapchains, pipelines and queues.
378 bool isInitialized() const { return device != VK_NULL_HANDLE; }
379
380 /* ---------------- presentation and frame path ---------------- */
381 // Built after the device, in this order: swapchain, render pass, framebuffers,
382 // command pool and buffers, synchronisation. Same pointer returning shape as
383 // the handles above, for the same reason.
384
385 VkSwapchainKHR* getSwapchain() { return &swapchain; }
386 std::vector<VkImage>* getSwapchainImages() { return &swapchainimages; }
387 std::vector<VkImageView>* getSwapchainImageViews() { return &swapchainimageviews; }
388 VkFormat* getSwapchainFormat() { return &swapchainformat; }
389 VkExtent2D* getSwapchainExtent() { return &swapchainextent; }
390
391 VkRenderPass* getRenderPass() { return &renderpass; }
392 VkRenderPass getShadowRenderPass() const { return shadowrenderpass; }
393 VkDescriptorSet getShadowDescriptorSet() const { return shadowdescriptorset; }
394 bool hasShadowMap() const { return shadowframebuffer != VK_NULL_HANDLE; }
395 VkPipeline getShadowPipeline() const { return shadowpipeline; }
396 VkPipelineLayout getShadowPipelineLayout() const { return shadowpipelinelayout; }
397 // False when the shadow shader does not sample its cutout map, in which case the
398 // reflected layout has no descriptor set to bind into.
399 bool hasShadowDescriptorSetLayout() const { return !shadowsetlayouts.empty(); }
400 uint32_t getShadowPushSize() const { return shadowpushsize; }
401 VkShaderStageFlags getShadowPushStages() const { return shadowpushstages; }
402 bool isShadowPassActive() const { return shadowpassactive; }
403 bool isDeferredPassActive() const { return deferredpassactive; }
404 std::vector<VkFramebuffer>* getFramebuffers() { return &framebuffers; }
405
406 // Depth attachments are private to each frame in flight.
407 VkFormat getDepthFormat() const { return depthformat; }
408 VkImageView getDepthImageView() const {
409 return depthimageviews.empty() ? VK_NULL_HANDLE : depthimageviews[0];
410 }
411
412 VkCommandPool* getCommandPool() { return &commandpool; }
413 std::vector<VkCommandBuffer>* getCommandBuffers() { return &commandbuffers; }
414
415 // Image available semaphores and fences are per frame in flight; the render
416 // finished ones are per swapchain image, because presentation waits on the
417 // semaphore chosen by the acquired image index.
418 std::vector<VkSemaphore>* getImageAvailableSemaphores() { return &imageavailablesemaphores; }
419 std::vector<VkFence>* getInFlightFences() { return &inflightfences; }
420 std::vector<VkSemaphore>* getRenderFinishedSemaphores() { return &renderfinishedsemaphores; }
421
422 // The colour the render pass writes over the whole attachment when a frame
423 // begins; gVKRenderEngine::clearColor() feeds it.
424 VkClearValue* getClearValue() { return &clearvalue; }
425
426 // The window the surface was created from. The frame loop needs it to notice
427 // resizes and rebuild the swapchain.
428 gBaseWindow* getWindow() { return window; }
429
430 // True once the frame path exists too, so a frame can actually be recorded.
431 // isInitialized() only promises a logical device.
432 bool isFramePathReady() const {
433 return swapchain != VK_NULL_HANDLE && renderpass != VK_NULL_HANDLE;
434 }
435
436 /* ---------------- 2D draw path ---------------- */
437 // Pipelines and descriptor infrastructure the Vulkan triangle / rectangle /
438 // image helpers use, plus the per-frame host-visible vertex ring. Built by
439 // gvkCreateGraphicsPipelines and gvkCreateDrawResources, consumed by gVKDraw.
440
441 // Every getter here indexes by getActivePipelineVariant(), which the open pass
442 // set: the screen pass hands out the pipelines built for its sample count, an
443 // offscreen pass the single-sampled ones. See GVK_PIPELINE_SAMPLE_VARIANTS.
444 VkPipeline getColor2DPipeline() { return color2d[activepipelinevariant].pipeline; }
445 // Same pipeline with a line topology, for stroking unfilled shapes.
446 VkPipeline getColor2DLinePipeline() { return color2d[activepipelinevariant].linepipeline; }
447 // Additive copies of the 2D pipelines, for gRenderer::BLENDMODE_ADDITIVE. Blend
448 // factors are baked into a pipeline, so the mode is chosen by binding one or the
449 // other; both fall back to the compositing pipeline if the copy failed to build.
450 VkPipeline getColor2DAdditivePipeline() {
451 const gVKPipelineVariants& v = color2d[activepipelinevariant];
452 return v.additivepipeline != VK_NULL_HANDLE ? v.additivepipeline : v.pipeline;
453 }
454 VkPipelineLayout getColor2DPipelineLayout() { return color2dpipelinelayout; }
455 VkPipeline getImage2DPipeline() { return image2d[activepipelinevariant].pipeline; }
456 VkPipeline getImage2DAdditivePipeline() {
457 const gVKPipelineVariants& v = image2d[activepipelinevariant];
458 return v.additivepipeline != VK_NULL_HANDLE ? v.additivepipeline : v.pipeline;
459 }
460 // The image pipeline with blending switched off, so a draw can replace what is
461 // under it rather than composite onto it. Used to rebuild the screen from a
462 // resolved copy; see gvkEnsureRenderPass.
463 VkPipeline getImage2DOpaquePipeline() {
464 const gVKPipelineVariants& v = image2d[activepipelinevariant];
465 return v.blendvariantpipeline;
466 }
467 VkPipelineLayout getImage2DPipelineLayout() { return image2dpipelinelayout; }
468 // The 3D mesh pipeline, and the same pipeline with a line topology for meshes
469 // drawn as wireframe.
470 VkPipeline getMesh3DPipeline() { return mesh3d[activepipelinevariant].pipeline; }
471 VkPipeline getMesh3DLinePipeline() { return mesh3d[activepipelinevariant].linepipeline; }
472 VkPipeline getSkyboxPipeline() { return skybox[activepipelinevariant].pipeline; }
473 VkPipelineLayout getSkyboxPipelineLayout() { return skyboxpipelinelayout; }
474 uint32_t getSkyboxPushSize() const { return skyboxpushsize; }
475 VkShaderStageFlags getSkyboxPushStages() const { return skyboxpushstages; }
476 // Blending cannot be a dynamic state, so each 3D path keeps a second pipeline
477 // with the opposite setting and the draw picks by the renderer's current one.
478 // The line variant has no blended twin: a wireframe pass is a debugging aid.
479 VkPipeline getMesh3DPipeline(bool blending) {
480 const gVKPipelineVariants& v = mesh3d[activepipelinevariant];
481 return blending && v.blendvariantpipeline != VK_NULL_HANDLE ? v.blendvariantpipeline : v.pipeline;
482 }
483 // cutout false means the caller has established that this draw's diffuse map holds
484 // no texel transparent enough for the shader's cutout test, so it can go through
485 // the copy with the discard compiled out and keep early depth rejection. Only the
486 // opaque form has that copy: a blended draw is sorted and layered rather than
487 // depth rejected, so it gains nothing, and the wireframe one is a debugging aid.
488 VkPipeline getMesh3DPipeline(bool blending, bool cutout) {
489 const gVKPipelineVariants& v = mesh3d[activepipelinevariant];
490 if(!blending && !cutout && v.nocutoutpipeline != VK_NULL_HANDLE) return v.nocutoutpipeline;
491 return getMesh3DPipeline(blending);
492 }
493 VkPipeline getMesh3DPbrPipeline(bool blending) {
494 const gVKPipelineVariants& v = mesh3dpbr[activepipelinevariant];
495 return blending && v.blendvariantpipeline != VK_NULL_HANDLE ? v.blendvariantpipeline : v.pipeline;
496 }
497 VkPipelineLayout getMesh3DPipelineLayout() { return mesh3dpipelinelayout; }
498 uint32_t getMesh3DPushSize() const { return mesh3dpushsize; }
499 VkShaderStageFlags getMesh3DPushStages() const { return mesh3dpushstages; }
500 VkPipeline getDeferredGeometryPipeline(bool lines, bool cutout) {
501 if(lines && deferredgeometry.linepipeline != VK_NULL_HANDLE) return deferredgeometry.linepipeline;
502 if(!cutout && deferredgeometry.nocutoutpipeline != VK_NULL_HANDLE) {
503 return deferredgeometry.nocutoutpipeline;
504 }
505 return deferredgeometry.pipeline;
506 }
507 VkPipelineLayout getDeferredGeometryPipelineLayout() { return deferredgeometrypipelinelayout; }
508 uint32_t getDeferredGeometryPushSize() const { return deferredgeometrypushsize; }
509 VkShaderStageFlags getDeferredGeometryPushStages() const { return deferredgeometrypushstages; }
510 VkPipeline getDeferredLightingPipeline() {
511 return deferredlighting[activepipelinevariant].pipeline;
512 }
513 VkPipelineLayout getDeferredLightingPipelineLayout() { return deferredlightingpipelinelayout; }
514 VkDescriptorSetLayout getDeferredLightingGBufferSetLayout() {
515 return deferredlightingsetlayouts.size() > 1
516 ? deferredlightingsetlayouts[1] : VK_NULL_HANDLE;
517 }
518
519 VkPipeline getMesh3DPbrPipeline() { return mesh3dpbr[activepipelinevariant].pipeline; }
520 VkPipelineLayout getMesh3DPbrPipelineLayout() { return mesh3dpbrpipelinelayout; }
521 uint32_t getMesh3DPbrPushSize() const { return mesh3dpbrpushsize; }
522 VkShaderStageFlags getMesh3DPbrPushStages() const { return mesh3dpbrpushstages; }
523 // Layout of the PBR material set (set 1), which gVKRenderEngine allocates one of
524 // per distinct combination of maps.
525 std::map<std::array<uint32_t, 5>, VkDescriptorSet>* getPbrMaterialSets() { return &pbrmaterialsets; }
526 VkDescriptorSetLayout getMesh3DPbrMaterialSetLayout() {
527 return mesh3dpbrsetlayouts.size() > 1 ? mesh3dpbrsetlayouts[1] : VK_NULL_HANDLE;
528 }
529 // The same arrangement for the classic path's diffuse/specular/normal trio.
530 std::map<std::array<uint32_t, 3>, VkDescriptorSet>* getMaterialSets() { return &materialsets; }
531 VkDescriptorSetLayout getMesh3DMaterialSetLayout() {
532 return mesh3dsetlayouts.size() > 1 ? mesh3dsetlayouts[1] : VK_NULL_HANDLE;
533 }
534
535 // The scene descriptor set of the frame being recorded: camera matrices and
536 // lights. VK_NULL_HANDLE when the 3D path has no uniform block, or when the
537 // slot is beyond every chunk allocated so far.
538 VkDescriptorSet getCurrentSceneDescriptorSet() const {
539 if(currentsceneuniformslot >= sceneuniformsets[currentframe].size()) return VK_NULL_HANDLE;
540 return sceneuniformsets[currentframe][currentsceneuniformslot];
541 }
542 void resetSceneUniformSlots() { currentsceneuniformslot = 0; sceneuniformslotcount = 0; }
543 // Which of the frames in flight is being recorded. Anything the CPU rewrites
544 // while the GPU may still be reading the previous frame needs one copy per
545 // index and has to write the one this returns: the frame loop waits on that
546 // index's fence before recording, which is what makes the copy free again.
547 uint32_t getCurrentFrame() const { return currentframe; }
548
549 // Whether presentation waits for the display. Vulkan expresses this as the
550 // swapchain's present mode rather than a call like glfwSwapInterval, so a
551 // change only takes effect when the swapchain is rebuilt - which is what
552 // gVKRenderEngine::setVsync asks for.
553 void setVsyncEnabled(bool enabled) { vsyncenabled = enabled; }
554 bool isVsyncEnabled() const { return vsyncenabled; }
555
556 /* ---------------- multisampling ---------------- */
557 // What the application asked for, and what it got. The two are not the same
558 // thing: a request is capped at the intersection of the device's
559 // framebufferColorSampleCounts and framebufferDepthSampleCounts, so asking for
560 // 8x on a part that offers 4x colour and 4x depth yields 4x, and asking on a
561 // part that offers neither yields 1x - MSAA simply off. Like vsync, the sample
562 // count is baked into objects (the render pass, its attachments and every
563 // pipeline) rather than set per draw, so a change only lands when those are
564 // rebuilt; gVKRenderEngine::setMultiSampling does that at a frame boundary.
565 void setSampleCount(int samples) {
566 requestedsamples = samples < 1 ? 1 : static_cast<uint32_t>(samples);
567 }
568 int getRequestedSampleCount() const { return static_cast<int>(requestedsamples); }
569 int getActiveSampleCount() const { return static_cast<int>(samplecount); }
570 VkSampleCountFlagBits getSampleCountFlag() const { return samplecount; }
571 bool isMultiSampled() const { return samplecount != VK_SAMPLE_COUNT_1_BIT; }
572
573 // Sample shading runs the fragment shader per sample instead of per pixel, which
574 // is the only thing that antialiases *inside* a triangle - specular sparkle on a
575 // normal-mapped surface, alpha-tested foliage edges. It is off by default and
576 // should stay off on mobile: coverage MSAA costs the resolve and nothing else,
577 // while sample shading multiplies the fragment shader's own cost by
578 // minSampleShading x rasterizationSamples, which on a tiler with a heavy PBR
579 // shader is the difference between free and unshippable. Requires the device's
580 // sampleRateShading feature; the request is ignored when it is missing.
581 void setSampleShadingEnabled(bool enabled) { sampleshadingenabled = enabled; }
582 bool isSampleShadingEnabled() const { return sampleshadingenabled; }
583 void setMinSampleShading(float fraction) { minsampleshading = fraction; }
584 float getMinSampleShading() const { return minsampleshading; }
585
586 // Which sample-count build of the pipelines the pass currently being recorded
587 // needs; every pipeline getter above indexes with it. Whichever pass opens sets
588 // it, so a draw can never reach a pipeline that pass would reject.
589 uint32_t getActivePipelineVariant() const { return activepipelinevariant; }
590 void useScreenPipelines() { activepipelinevariant = isMultiSampled() ? 1 : 0; }
591 void useOffscreenPipelines() { activepipelinevariant = 0; }
592
593 VkDeviceSize getMinUniformBufferOffsetAlignment() const {
594 return deviceproperties.limits.minUniformBufferOffsetAlignment;
595 }
596 // The layout of the image pipeline's descriptor set 0, which is where a
597 // texture's combined image sampler goes.
598 VkDescriptorSetLayout getImageDescriptorSetLayout() {
599 return image2dsetlayouts.empty() ? VK_NULL_HANDLE : image2dsetlayouts[0];
600 }
601 VkDescriptorPool getDescriptorPool() { return descriptorpool; }
602 std::map<uint64_t, std::pair<VkSampler, uint32_t>>& getSamplerCache() { return samplercache; }
603 bool isRenderPassActive() const { return renderpassactive; }
604 bool doesPassFlipY() const { return passflipsy; }
605
606 // Push constant block each 2D pipeline declares, as reported by reflecting its
607 // SPIR-V. gVKDraw pushes exactly this much to exactly these stages, so editing
608 // the push_constant block in a shader needs no matching change in the draw path.
609 uint32_t getColor2DPushSize() const { return color2dpushsize; }
610 VkShaderStageFlags getColor2DPushStages() const { return color2dpushstages; }
611 uint32_t getImage2DPushSize() const { return image2dpushsize; }
612 VkShaderStageFlags getImage2DPushStages() const { return image2dpushstages; }
613
614 // The command buffer of the frame currently being recorded, or VK_NULL_HANDLE
615 // when no frame is active.
616 VkCommandBuffer getCurrentCommandBuffer() {
617 return frameactive ? commandbuffers[currentframe] : VK_NULL_HANDLE;
618 }
619 // Whether a frame is being recorded. Uploads that arrive outside one - a canvas
620 // building its meshes in setup() - cannot use anything the frame loop rewinds.
621 bool isFrameActive() const { return frameactive; }
622
623 // Per-frame vertex ring. resetDynamicVertices() rewinds the current frame's
624 // buffer at frame start; pushDynamicVertices() appends vertex bytes (16-byte
625 // aligned) and returns the byte offset to bind from, or VK_WHOLE_SIZE when the
626 // buffer is full.
627 void resetDynamicVertices() {
628 if(!dynvertexoffsets.empty()) dynvertexoffsets[currentframe] = 0;
629 framesequence++;
630 }
631 // Frames since start-up, unlike currentframe which cycles 0..1. A per-frame ring
632 // of any kind has to compare against this: the cycling index repeats, so a user
633 // of the ring that skips a frame would see the same index twice running and
634 // conclude nothing had changed.
635 uint64_t getFrameSequence() const { return framesequence; }
636 VkBuffer getCurrentDynamicVertexBuffer() {
637 return dynvertexbuffers.empty() ? VK_NULL_HANDLE : dynvertexbuffers[currentframe];
638 }
639 // alignment is the caller's vertex stride wherever the caller means to reach its
640 // slice through firstVertex rather than by binding at the offset: the index is
641 // offset/stride, so the offset has to be a whole number of vertices from the
642 // start of the buffer. Paths that bind at their own offset can leave it at the
643 // default. Getting this wrong shifts a draw by a fraction of a vertex and
644 // scrambles it, so it is a parameter rather than an assumption - the ring is
645 // shared, and one path's stride is not another's.
646 VkDeviceSize pushDynamicVertices(const void* data, VkDeviceSize size, VkDeviceSize alignment = 16) {
647 if(dynvertexmapped.empty()) return VK_WHOLE_SIZE;
648 if(alignment == 0) alignment = 1;
649 VkDeviceSize offset = ((dynvertexoffsets[currentframe] + alignment - 1) / alignment) * alignment;
650 if(offset + size > dynvertexcapacity) return VK_WHOLE_SIZE;
651 std::memcpy(static_cast<char*>(dynvertexmapped[currentframe]) + offset, data, size);
652 dynvertexoffsets[currentframe] = offset + size;
653 return offset;
654 }
655
656 // The same idea again, for 3D meshes whose vertices the CPU rewrites: a per
657 // frame arena that every upload takes its own slice of.
658 //
659 // One slice per upload rather than one buffer per mesh, because a mesh can be
660 // uploaded to several times in a single frame and drawn in between. A game
661 // posing one soldier model once per enemy does exactly that, and a single
662 // buffer per mesh gives every one of them the last pose written - the draws are
663 // recorded now and executed later, so they all read whatever the buffer holds
664 // by the end of the frame. Slices keep each draw pointing at the data it was
665 // recorded with.
666 //
667 // pushMeshData returns the byte offset to bind from, or VK_WHOLE_SIZE when the
668 // arena is full - the caller falls back to its own buffer for that frame, and
669 // the arena grows to the high-water mark at the next frame start.
670 void resetMeshArena() {
671 if(mesharenaoffsets.empty()) return;
672 if(mesharenaoffsets[currentframe] > mesharenahighwater) {
673 mesharenahighwater = mesharenaoffsets[currentframe];
674 }
675 mesharenaoffsets[currentframe] = 0;
676 meshgeneration++;
677 }
678 VkBuffer getCurrentMeshArena() {
679 return mesharenabuffers.empty() ? VK_NULL_HANDLE : mesharenabuffers[currentframe];
680 }
681 VkDeviceSize pushMeshData(const void* data, VkDeviceSize size) {
682 if(mesharenamapped.empty() || mesharenamapped[currentframe] == nullptr) return VK_WHOLE_SIZE;
683 VkDeviceSize offset = (mesharenaoffsets[currentframe] + 63) & ~static_cast<VkDeviceSize>(63);
684 if(offset + size > mesharenacapacity) {
685 // Remember what was actually asked for, so the grow at the next reset is
686 // big enough rather than one slice short of it.
687 mesharenahighwater = std::max(mesharenahighwater, offset + size);
688 return VK_WHOLE_SIZE;
689 }
690 std::memcpy(static_cast<char*>(mesharenamapped[currentframe]) + offset, data, size);
691 mesharenaoffsets[currentframe] = offset + size;
692 return offset;
693 }
694 // Which frame the arena is on. A slice handed out in an earlier frame points
695 // into memory that has since been rewound, so a mesh drawn without a fresh
696 // upload compares this before trusting the slice it kept.
697 uint64_t getMeshGeneration() const { return meshgeneration; }
698
699 // Command-buffer-local state cache. Vulkan state persists between draw calls,
700 // so recording an unchanged bind or dynamic state again only adds CPU/driver
701 // work. The frame and every render-pass begin reset this cache.
702 void resetRecordedDrawState() {
703 recordedpipeline = VK_NULL_HANDLE;
704 recordeddescriptorlayout = VK_NULL_HANDLE;
705 recordeddescriptorcount = 0;
706 recordeddepthvalid = false;
707 recordedtopologyvalid = false;
708 recordedcullvalid = false;
709 recordedvertexcount = 0;
710 recordedindexbuffer = VK_NULL_HANDLE;
711 }
712 bool shouldBindPipeline(VkPipeline pipeline) {
713 if(recordedpipeline == pipeline) return false;
714 recordedpipeline = pipeline;
715 recordeddescriptorlayout = VK_NULL_HANDLE;
716 recordeddescriptorcount = 0;
717 // Binding a pipeline which does not declare one of these dynamic states
718 // invalidates its current value. The next pipeline may declare it again, so
719 // the cache must force all three groups to be emitted after every change.
720 recordeddepthvalid = false;
721 recordedtopologyvalid = false;
722 recordedcullvalid = false;
723 return true;
724 }
725 bool shouldBindDescriptorSets(VkPipelineLayout layout, const VkDescriptorSet* sets, uint32_t count) {
726 if(recordeddescriptorlayout == layout && recordeddescriptorcount == count
727 && std::equal(sets, sets + count, recordeddescriptors.begin())) return false;
728 recordeddescriptorlayout = layout;
729 recordeddescriptorcount = count;
730 std::copy(sets, sets + count, recordeddescriptors.begin());
731 return true;
732 }
733 bool shouldSetDepthState(VkBool32 test, VkBool32 write, VkCompareOp compare) {
734 if(recordeddepthvalid && recordeddepthtest == test && recordeddepthwrite == write
735 && recordeddepthcompare == compare) return false;
736 recordeddepthvalid = true;
737 recordeddepthtest = test;
738 recordeddepthwrite = write;
739 recordeddepthcompare = compare;
740 return true;
741 }
742 bool shouldSetTopology(VkPrimitiveTopology topology) {
743 if(recordedtopologyvalid && recordedtopology == topology) return false;
744 recordedtopologyvalid = true;
745 recordedtopology = topology;
746 return true;
747 }
748 bool shouldSetCullState(VkCullModeFlags mode, VkFrontFace frontface) {
749 if(recordedcullvalid && recordedcullmode == mode && recordedfrontface == frontface) return false;
750 recordedcullvalid = true;
751 recordedcullmode = mode;
752 recordedfrontface = frontface;
753 return true;
754 }
755
756 // VK_EXT_extended_dynamic_state, core since Vulkan 1.3 - which minapiversion
757 // already requires as this backend's floor. Android's NDK import library only
758 // exports these six entry points for API level 33+ regardless of what the
759 // device driver actually supports, so gVKRenderEngine::initVulkan resolves them
760 // itself through vkGetDeviceProcAddr instead of linking them statically, and
761 // every draw call goes through these wrappers rather than the raw vkCmdSetXxx
762 // names.
763 void cmdSetDepthState(VkCommandBuffer cmd, VkBool32 test, VkBool32 write, VkCompareOp compare) {
764 pfncmdsetdepthtestenable(cmd, test);
765 pfncmdsetdepthwriteenable(cmd, write);
766 pfncmdsetdepthcompareop(cmd, compare);
767 }
768 void cmdSetTopology(VkCommandBuffer cmd, VkPrimitiveTopology topology) {
769 pfncmdsetprimitivetopology(cmd, topology);
770 }
771 void cmdSetCullState(VkCommandBuffer cmd, VkCullModeFlags mode, VkFrontFace frontface) {
772 pfncmdsetcullmode(cmd, mode);
773 pfncmdsetfrontface(cmd, frontface);
774 }
775 // Vertex and index bindings are command buffer state in their own right: binding a
776 // pipeline does not disturb them, so a run of draws over one mesh - a crowd posed
777 // from the same model, or the same buffer drawn once per material - can rebind the
778 // same handles hundreds of times per frame for nothing. The contents behind a
779 // handle may change between draws; that does not matter here, because a draw reads
780 // the buffer when the GPU executes it, not when the bind was recorded.
781 //
782 // Every vkCmdBindVertexBuffers / vkCmdBindIndexBuffer in the backend goes through
783 // these. One that did not would leave the cache describing a binding that is no
784 // longer current, and the next draw would skip a bind it actually needed.
785 bool shouldBindVertexBuffers(const VkBuffer* buffers, const VkDeviceSize* offsets, uint32_t count) {
786 if(count > gvkmaxvertexbindings) return true;
787 if(recordedvertexcount == count
788 && std::equal(buffers, buffers + count, recordedvertexbuffers.begin())
789 && std::equal(offsets, offsets + count, recordedvertexoffsets.begin())) {
790 return false;
791 }
792 recordedvertexcount = count;
793 std::copy(buffers, buffers + count, recordedvertexbuffers.begin());
794 std::copy(offsets, offsets + count, recordedvertexoffsets.begin());
795 return true;
796 }
797 bool shouldBindIndexBuffer(VkBuffer buffer, VkDeviceSize offset, VkIndexType type) {
798 if(recordedindexbuffer == buffer && recordedindexoffset == offset
799 && recordedindextype == type) return false;
800 recordedindexbuffer = buffer;
801 recordedindexoffset = offset;
802 recordedindextype = type;
803 return true;
804 }
805
806private:
807 std::string appname = "GlistApp";
808 std::string enginename = "GlistEngine";
809 uint32_t appversion = VK_MAKE_API_VERSION(0, 1, 0, 0);
810 uint32_t engineversion = VK_MAKE_API_VERSION(0, 1, 0, 0);
811 uint32_t minapiversion = VK_API_VERSION_1_3;
812 bool enablevalidation = gvkdefaultvalidation;
813 std::vector<const char*> extrainstanceextensions;
814 std::vector<const char*> extradeviceextensions;
815 std::vector<const char*> extralayers;
816
817 VkInstance instance = VK_NULL_HANDLE;
818 VkDebugUtilsMessengerEXT debugmessenger = VK_NULL_HANDLE;
819 VkSurfaceKHR surface = VK_NULL_HANDLE;
820 VkPhysicalDevice physicaldevice = VK_NULL_HANDLE;
821 VkDevice device = VK_NULL_HANDLE;
822 VkQueue graphicsqueue = VK_NULL_HANDLE;
823 VkQueue presentqueue = VK_NULL_HANDLE;
824 uint32_t graphicsfamily = 0;
825 uint32_t presentfamily = 0;
826 // Resolved via vkGetDeviceProcAddr right after device creation; see
827 // cmdSetDepthState / cmdSetTopology / cmdSetCullState above.
828 PFN_vkCmdSetDepthTestEnable pfncmdsetdepthtestenable = nullptr;
829 PFN_vkCmdSetDepthWriteEnable pfncmdsetdepthwriteenable = nullptr;
830 PFN_vkCmdSetDepthCompareOp pfncmdsetdepthcompareop = nullptr;
831 PFN_vkCmdSetPrimitiveTopology pfncmdsetprimitivetopology = nullptr;
832 PFN_vkCmdSetCullMode pfncmdsetcullmode = nullptr;
833 PFN_vkCmdSetFrontFace pfncmdsetfrontface = nullptr;
834 uint32_t devicecount = 0;
835 std::vector<VkPhysicalDevice> physicaldevices;
836 std::vector<VkPhysicalDeviceProperties> physicaldeviceproperties;
837 std::vector<VkPhysicalDeviceFeatures> physicaldevicefeatures;
838 std::vector<VkQueueFamilyProperties> queuefamilyproperties;
839 std::vector<VkBool32> queuefamilypresentsupport;
840 std::vector<const char*> enabledinstanceextensions;
841 std::vector<const char*> enabledlayers;
842 std::vector<const char*> enableddeviceextensions;
843 std::vector<VkExtensionProperties> availableinstanceextensions;
844 std::vector<VkLayerProperties> availablelayers;
845 std::vector<VkExtensionProperties> availabledeviceextensions;
846 VkPhysicalDeviceProperties deviceproperties{};
847 VkPhysicalDeviceFeatures devicefeatures{};
848 VkPhysicalDeviceMemoryProperties devicememoryproperties{};
849 VkSurfaceCapabilitiesKHR surfacecapabilities{};
850 std::vector<VkSurfaceFormatKHR> surfaceformats;
851 std::vector<VkPresentModeKHR> surfacepresentmodes;
852 uint32_t instanceapiversion = 0;
853 bool validationactive = false;
854
855 gBaseWindow* window = nullptr;
856 bool vsyncenabled = false;
857 bool swapchainrecreaterequested = false;
858 // Set when the surface itself has to be rebuilt rather than just the swapchain:
859 // the native window was replaced, or the driver reported VK_ERROR_SURFACE_LOST_KHR.
860 bool surfacerecreaterequested = false;
861
862 VkSwapchainKHR swapchain = VK_NULL_HANDLE;
863 std::vector<VkImage> swapchainimages;
864 std::vector<VkImageView> swapchainimageviews;
865 VkFormat swapchainformat = VK_FORMAT_UNDEFINED;
866 VkExtent2D swapchainextent = {0, 0};
867
868 // One depth attachment per frame in flight. This avoids overlapping writes
869 // without allocating one for every (often more numerous) swapchain image.
870 std::vector<VkImage> depthimages;
871 std::vector<VkDeviceMemory> depthimagememories;
872 std::vector<VkImageView> depthimageviews;
873 VkFormat depthformat = VK_FORMAT_UNDEFINED;
874
875 // Multisampling. requestedsamples is the application's ask, samplecount is what
876 // the device agreed to and what everything below is built with; see the setters.
877 uint32_t requestedsamples = 1;
878 VkSampleCountFlagBits samplecount = VK_SAMPLE_COUNT_1_BIT;
879 bool sampleshadingenabled = false;
880 float minsampleshading = 0.25f;
881
882 // The multisampled colour attachment the screen pass renders into while MSAA is
883 // on, one per frame in flight for the same reason depth is: private slots avoid
884 // overlapping writes without one per swapchain image. It never leaves tile
885 // memory - the pass clears it, resolves it into the acquired swapchain image and
886 // discards the samples - so it is created TRANSIENT and, where the device offers
887 // it, backed by LAZILY_ALLOCATED memory that a tiler never has to page in.
888 std::vector<VkImage> msaacolorimages;
889 std::vector<VkDeviceMemory> msaacolormemories;
890 std::vector<VkImageView> msaacolorviews;
891
892 // Shadow map: a depth-only target drawn from the light's point of view and
893 // sampled while shading. See gVKShadow.h.
894 VkImage shadowimage = VK_NULL_HANDLE;
895 VkDeviceMemory shadowmemory = VK_NULL_HANDLE;
896 VkImageView shadowview = VK_NULL_HANDLE;
897 VkSampler shadowsampler = VK_NULL_HANDLE;
898 VkRenderPass shadowrenderpass = VK_NULL_HANDLE;
899 VkFramebuffer shadowframebuffer = VK_NULL_HANDLE;
900 VkDescriptorSet shadowdescriptorset = VK_NULL_HANDLE;
901 // Depth-only pipeline that fills the map. Built with the shadow render pass,
902 // so it cannot exist before that pass does.
903 VkPipeline shadowpipeline = VK_NULL_HANDLE;
904 VkPipelineLayout shadowpipelinelayout = VK_NULL_HANDLE;
905 // One set layout, for the cutout diffuse map. Held here rather than left in the
906 // build's scratch struct because it has to outlive the build and be destroyed
907 // with the pipeline; before the cutout sampler existed this list was empty.
908 std::vector<VkDescriptorSetLayout> shadowsetlayouts;
909 uint32_t shadowpushsize = 0;
910 VkShaderStageFlags shadowpushstages = 0;
911 VkFormat shadowformat = VK_FORMAT_UNDEFINED;
912 VkExtent2D shadowextent = {0, 0};
913 // True between gvkBeginShadowPass and gvkEndShadowPass, so the draw path can
914 // tell which of the two passes it is recording into.
915 bool shadowpassactive = false;
916 // True only while the internal G-buffer geometry render pass is open.
917 bool deferredpassactive = false;
918
919 VkRenderPass renderpass = VK_NULL_HANDLE;
920 // The same pass with LOAD in place of CLEAR on colour and depth. A frame opens
921 // the screen pass more than once whenever the application binds a render target
922 // half way through drawing - a gGUIScrollable renders its clipped content into
923 // an FBO, a canvas may run a post effect over the scene it has drawn so far -
924 // and reopening with the clearing pass would erase everything recorded before
925 // the target was bound. Every reopen after the frame's first one uses this.
926 VkRenderPass loadrenderpass = VK_NULL_HANDLE;
927 // Multisampled only. The multisample image is a transient attachment - it may
928 // live entirely on chip and have no memory behind it at all - so its contents
929 // cannot survive between two passes, and the LOAD variant above is useless
930 // there. This one discards the multisample colour and clears depth, and the
931 // picture is put back by redrawing the resolved swapchain image into it.
932 VkRenderPass restorerenderpass = VK_NULL_HANDLE;
933 // The single-sampled copy that redraw samples from, sized to the swapchain and
934 // rebuilt with it. Created on the first reopen and not before: a frame that
935 // never binds a render target half way through never needs it.
936 struct gVKTexture* screenrestoretexture = nullptr;
937 // A 1x colour+depth pass that is never begun. It exists only while the screen
938 // pass is multisampled, as the compatibility template the single-sample
939 // pipelines are built against - a pipeline needs a render pass at build time,
940 // and the passes those pipelines really run in (the per-FBO ones) are created
941 // later, on demand, one per render target. VK_NULL_HANDLE when MSAA is off,
942 // where the screen pass is itself the 1x template.
943 VkRenderPass singlesamplerenderpass = VK_NULL_HANDLE;
944 // One per (frame-in-flight, swapchain image) pair.
945 std::vector<VkFramebuffer> framebuffers;
946
947 VkCommandPool commandpool = VK_NULL_HANDLE;
948 // GVK_MAX_FRAMES_IN_FLIGHT entries, indexed by currentframe.
949 std::vector<VkCommandBuffer> commandbuffers;
950
951 // GVK_MAX_FRAMES_IN_FLIGHT entries, indexed by currentframe.
952 std::vector<VkSemaphore> imageavailablesemaphores;
953 std::vector<VkFence> inflightfences;
954 // One per swapchain image, indexed by currentimageindex.
955 std::vector<VkSemaphore> renderfinishedsemaphores;
956
957 uint32_t currentframe = 0;
958 uint64_t framesequence = 0;
959 uint32_t currentimageindex = 0;
960 bool frameactive = false;
961 // Match gBaseCanvas::clearBackground(), the default used by the OpenGL path.
962 VkClearValue clearvalue = {{{0.0f, 0.0f, 30.0f / 255.0f, 0.0f}}};
963
964 // 2D draw path. Built after the frame path; VK_NULL_HANDLE / empty until then.
965 // renderpassactive tracks the lazily-begun render pass within a frame: geometry
966 // must be recorded inside vkCmdBeginRenderPass..EndRenderPass, but the clear
967 // colour is only final once the canvas has drawn, so the pass is opened on the
968 // first draw (or in endFrame) rather than in beginFrame.
969 // Whether the open pass draws through a negative-height viewport. Only the
970 // screen pass does: it has to hand the presentation engine an image stored top
971 // row first. Offscreen targets are drawn with a positive viewport instead, so
972 // they end up stored bottom row first - the order OpenGL keeps a texture in -
973 // and every consumer written against OpenGL then addresses them correctly,
974 // shaders reading TexCoords included. Mirroring the y axis also reverses the
975 // winding a triangle appears to have, so this is what decides whether the front
976 // face has to be flipped; see gVKCullState.
977 bool passflipsy = true;
978 bool renderpassactive = false;
979 // The render area of whichever pass is open, so a mid-pass clear knows the
980 // rectangle it may touch. Set by every pass begin: the screen pass uses the
981 // swapchain extent, the shadow pass its map size, an offscreen pass the mip
982 // level it renders into.
983 VkExtent2D currentpassextent = {0, 0};
984 // Whether the screen pass has been begun at all this frame. The first begin
985 // clears, every later one loads what the earlier ones left.
986 bool screenpassbegun = false;
987 bool screenshotrequested = false;
988 bool screenshotready = false;
989 std::vector<unsigned char> screenshotpixels;
990 uint32_t screenshotwidth = 0;
991 uint32_t screenshotheight = 0;
992 VkFormat screenshotformat = VK_FORMAT_UNDEFINED;
993 // One entry per sample count in use; index 0 is always the single-sample build.
994 // Layouts and reflected sizes are shared by both, because the variants differ
995 // only in their multisample state and the pass they were built against.
996 VkPipelineLayout color2dpipelinelayout = VK_NULL_HANDLE;
997 gVKPipelineVariants color2d[GVK_PIPELINE_SAMPLE_VARIANTS];
998 VkPipelineLayout image2dpipelinelayout = VK_NULL_HANDLE;
999 gVKPipelineVariants image2d[GVK_PIPELINE_SAMPLE_VARIANTS];
1000 // Which of the two the getters hand out; see useScreenPipelines().
1001 uint32_t activepipelinevariant = 0;
1002 // 3D mesh path. Same shape as the 2D pipelines above, but with depth test and
1003 // depth write on and a vertex layout matching gVertex.
1004 VkPipelineLayout mesh3dpipelinelayout = VK_NULL_HANDLE;
1005 gVKPipelineVariants mesh3d[GVK_PIPELINE_SAMPLE_VARIANTS];
1006 std::vector<VkDescriptorSetLayout> mesh3dsetlayouts;
1007 uint32_t mesh3dpushsize = 0;
1008 VkShaderStageFlags mesh3dpushstages = 0;
1009 // Classic-material MRT pipeline, created only while a G-buffer exists.
1010 VkPipelineLayout deferredgeometrypipelinelayout = VK_NULL_HANDLE;
1011 gVKPipelineVariants deferredgeometry;
1012 std::vector<VkDescriptorSetLayout> deferredgeometrysetlayouts;
1013 uint32_t deferredgeometrypushsize = 0;
1014 VkShaderStageFlags deferredgeometrypushstages = 0;
1015 // Fullscreen G-buffer consumer. It targets the normal screen render pass, so it
1016 // keeps one pipeline per active sample-count variant just like the 2D paths.
1017 VkPipelineLayout deferredlightingpipelinelayout = VK_NULL_HANDLE;
1018 gVKPipelineVariants deferredlighting[GVK_PIPELINE_SAMPLE_VARIANTS];
1019 std::vector<VkDescriptorSetLayout> deferredlightingsetlayouts;
1020
1021 // PBR variant. Its five maps share one descriptor set rather than taking one
1022 // each: Vulkan only guarantees four bound sets, and scene plus five textures
1023 // would need six.
1024 VkPipelineLayout mesh3dpbrpipelinelayout = VK_NULL_HANDLE;
1025 // The skybox: six textured quads around the camera, with a pipeline of its own
1026 // because nothing it draws is lit and it needs none of the mesh push constants.
1027 VkPipelineLayout skyboxpipelinelayout = VK_NULL_HANDLE;
1028 gVKPipelineVariants skybox[GVK_PIPELINE_SAMPLE_VARIANTS];
1029 std::vector<VkDescriptorSetLayout> skyboxsetlayouts;
1030 uint32_t skyboxpushsize = 0;
1031 VkShaderStageFlags skyboxpushstages = 0;
1032 gVKPipelineVariants mesh3dpbr[GVK_PIPELINE_SAMPLE_VARIANTS];
1033 std::vector<VkDescriptorSetLayout> mesh3dpbrsetlayouts;
1034 uint32_t mesh3dpbrpushsize = 0;
1035 VkShaderStageFlags mesh3dpbrpushstages = 0;
1036 // One descriptor set per distinct combination of the five PBR maps, keyed by
1037 // their texture ids. Materials commonly share maps, and a descriptor pool is
1038 // finite, so caching by combination rather than per mesh keeps allocations down.
1039 // An entry is freed and dropped when one of its textures is destroyed or
1040 // replaced, which is what keeps a session of loading and unloading from draining
1041 // the pool; what is left is freed with the pool in gvkDestroyGraphicsPipelines.
1042 std::map<std::array<uint32_t, 5>, VkDescriptorSet> pbrmaterialsets;
1043 // And one per distinct diffuse/specular/normal trio for the classic path.
1044 std::map<std::array<uint32_t, 3>, VkDescriptorSet> materialsets;
1045
1046 // Camera and lights for the 3D path, one set per frame in flight so the CPU can
1047 // write the next frame while the GPU still reads the previous one. Permanently
1048 // mapped; see gVKUniform.h.
1049 // One entry per chunk of GVK_SCENE_UNIFORM_SLOTS slots; a frame that needs more
1050 // scene lighting changes than one chunk holds gets another appended to it
1051 // rather than being capped. sceneuniformsets is flat and indexed by slot
1052 // directly, since a descriptor set is naturally one-per-slot, not one-per-chunk.
1053 std::vector<VkBuffer> sceneuniformbuffers[GVK_MAX_FRAMES_IN_FLIGHT];
1054 std::vector<VkDeviceMemory> sceneuniformmemories[GVK_MAX_FRAMES_IN_FLIGHT];
1055 std::vector<void*> sceneuniformmapped[GVK_MAX_FRAMES_IN_FLIGHT];
1056 std::vector<VkDescriptorSet> sceneuniformsets[GVK_MAX_FRAMES_IN_FLIGHT];
1057 uint32_t currentsceneuniformslot = 0;
1058 uint32_t sceneuniformslotcount = 0;
1059 // Descriptor set layouts of each pipeline, in set order, and the push constant
1060 // block each declares. All of it is reflected out of the compiled SPIR-V rather
1061 // than written out here, so the shaders stay the single source of truth.
1062 std::vector<VkDescriptorSetLayout> color2dsetlayouts;
1063 std::vector<VkDescriptorSetLayout> image2dsetlayouts;
1064 uint32_t color2dpushsize = 0;
1065 VkShaderStageFlags color2dpushstages = 0;
1066 uint32_t image2dpushsize = 0;
1067 VkShaderStageFlags image2dpushstages = 0;
1068 VkDescriptorPool descriptorpool = VK_NULL_HANDLE;
1069 VkPipelineCache pipelinecache = VK_NULL_HANDLE;
1070 // Identical filter/wrap combinations share one immutable sampler object.
1071 std::map<uint64_t, std::pair<VkSampler, uint32_t>> samplercache;
1072 // One host-visible, persistently mapped vertex buffer per frame in flight,
1073 // filled linearly each frame and rewound at the start of the next.
1074 std::vector<VkBuffer> dynvertexbuffers;
1075 std::vector<VkDeviceMemory> dynvertexmemories;
1076 std::vector<void*> dynvertexmapped;
1077 std::vector<VkDeviceSize> dynvertexoffsets;
1078 VkDeviceSize dynvertexcapacity = 0;
1079
1080 // Per-frame arena for mesh vertices the CPU rewrites; see pushMeshData.
1081 std::vector<VkBuffer> mesharenabuffers;
1082 std::vector<VkDeviceMemory> mesharenamemories;
1083 std::vector<void*> mesharenamapped;
1084 std::vector<VkDeviceSize> mesharenaoffsets;
1085 VkDeviceSize mesharenacapacity = 0;
1086 VkDeviceSize mesharenahighwater = 0;
1087 // A capacity the device refused. The frame loop asks for the arena to grow
1088 // whenever the high-water mark is above what it holds, so without remembering
1089 // this it would ask again on the next frame, and the next - each attempt
1090 // draining the device first. Cleared as soon as any growth succeeds.
1091 VkDeviceSize mesharenarefusedcapacity = 0;
1092 uint64_t meshgeneration = 0;
1093
1094 VkPipeline recordedpipeline = VK_NULL_HANDLE;
1095 VkPipelineLayout recordeddescriptorlayout = VK_NULL_HANDLE;
1096 std::array<VkDescriptorSet, 5> recordeddescriptors{};
1097 uint32_t recordeddescriptorcount = 0;
1098 bool recordeddepthvalid = false;
1099 VkBool32 recordeddepthtest = VK_FALSE;
1100 VkBool32 recordeddepthwrite = VK_FALSE;
1101 VkCompareOp recordeddepthcompare = VK_COMPARE_OP_ALWAYS;
1102 bool recordedtopologyvalid = false;
1103 VkPrimitiveTopology recordedtopology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
1104 bool recordedcullvalid = false;
1105 VkCullModeFlags recordedcullmode = VK_CULL_MODE_NONE;
1106 VkFrontFace recordedfrontface = VK_FRONT_FACE_CLOCKWISE;
1107 // Two: a mesh binds its vertices plus the per-instance model matrices, and the
1108 // 2D paths bind one. A larger bind is simply never cached.
1109 static const uint32_t gvkmaxvertexbindings = 2;
1110 std::array<VkBuffer, gvkmaxvertexbindings> recordedvertexbuffers{};
1111 std::array<VkDeviceSize, gvkmaxvertexbindings> recordedvertexoffsets{};
1112 uint32_t recordedvertexcount = 0;
1113 VkBuffer recordedindexbuffer = VK_NULL_HANDLE;
1114 VkDeviceSize recordedindexoffset = 0;
1115 VkIndexType recordedindextype = VK_INDEX_TYPE_UINT32;
1116};
1117
1118#endif /* GVK_VULKAN */
1119
1120#endif /* CORE_GVKCONTEXT_H */
Definition gBaseWindow.h:29