19#include <SDL2/SDL_vulkan.h>
42#include "common/config.h"
43#if defined(EVENGINE_MACOSX) || defined(EVENGINE_IOS)
44#include <vulkan/vulkan_beta.h>
51#include "zeroerr/assert.h"
56#include <assimp/matrix3x3.h>
57#include <assimp/matrix4x4.h>
58#include <assimp/mesh.h>
59#include <assimp/vector3.h>
60#include <glm/gtc/matrix_transform.hpp>
68bool wantVulkanValidation() {
69#if defined(EVENGINE_IOS)
72 const char* vkVal = std::getenv(
"EVENGINE_VULKAN_VALIDATION");
73 return vkVal && vkVal[0] !=
'\0' && vkVal[0] !=
'0';
77void disableImplicitLayersIfSafe() {
78 if (wantVulkanValidation())
return;
79 if (
const char* existing = std::getenv(
"VK_LOADER_LAYERS_DISABLE")) {
80 if (existing[0] !=
'\0')
return;
82 if (
const char* layers = std::getenv(
"VK_INSTANCE_LAYERS")) {
83 if (layers[0] !=
'\0')
return;
86 _putenv_s(
"VK_LOADER_LAYERS_DISABLE",
"~implicit~");
88 setenv(
"VK_LOADER_LAYERS_DISABLE",
"~implicit~", 0);
92bool extensionAvailable(
const std::vector<vk::ExtensionProperties>& props,
const char*
name) {
93 for (
const auto&
p : props) {
94 if (std::strcmp(
p.extensionName,
name) == 0)
return true;
99void addIfAvailable(std::vector<const char*>& exts,
const std::vector<vk::ExtensionProperties>& props,
101 if (extensionAvailable(props,
name)) exts.push_back(
name);
104std::vector<const char*> collectFastInstanceExtensions(
const std::vector<vk::ExtensionProperties>& props,
105 vk::InstanceCreateFlags* flagsOut) {
106 std::vector<const char*> exts;
107 addIfAvailable(exts, props,
"VK_KHR_surface");
109 addIfAvailable(exts, props,
"VK_EXT_swapchain_colorspace");
111 addIfAvailable(exts, props,
"VK_KHR_win32_surface");
112#elif defined(__ANDROID__)
113 addIfAvailable(exts, props,
"VK_KHR_android_surface");
114#elif defined(__APPLE__)
115 addIfAvailable(exts, props,
"VK_EXT_metal_surface");
116 if (extensionAvailable(props,
"VK_KHR_portability_enumeration")) {
117 exts.push_back(
"VK_KHR_portability_enumeration");
118 if (flagsOut) *flagsOut |= vk::InstanceCreateFlagBits::eEnumeratePortabilityKHR;
121 addIfAvailable(exts, props,
"VK_KHR_xcb_surface");
122 addIfAvailable(exts, props,
"VK_KHR_xlib_surface");
123 addIfAvailable(exts, props,
"VK_KHR_wayland_surface");
128void initVulkanDispatcher() {
129#if defined(EVENGINE_MACOSX)
130 if (PFN_vkGetInstanceProcAddr sdlGpa =
131 reinterpret_cast<PFN_vkGetInstanceProcAddr
>(SDL_Vulkan_GetVkGetInstanceProcAddr())) {
132 VULKAN_HPP_DEFAULT_DISPATCHER.init(sdlGpa);
133 vkb::InstanceBuilder::loaded =
true;
137 if (!vkb::InstanceBuilder::loaded) {
138 vkb::InstanceBuilder::loadDefault();
139 vkb::InstanceBuilder::loaded =
true;
143uint32_t negotiatedInstanceApiVersion() {
147 uint32_t loaderVersion = VK_API_VERSION_1_0;
148 if (VULKAN_HPP_DEFAULT_DISPATCHER.vkEnumerateInstanceVersion) {
149 if (VULKAN_HPP_DEFAULT_DISPATCHER.vkEnumerateInstanceVersion(&loaderVersion) != VK_SUCCESS)
150 loaderVersion = VK_API_VERSION_1_0;
152 return std::min(loaderVersion,
static_cast<uint32_t
>(VK_API_VERSION_1_2));
155vkb::Instance createInstanceFast() {
156 initVulkanDispatcher();
157 disableImplicitLayersIfSafe();
158 const uint32_t apiVersion = negotiatedInstanceApiVersion();
162 const auto props = vk::enumerateInstanceExtensionProperties();
163 vk::InstanceCreateFlags
flags{};
164 const auto exts = collectFastInstanceExtensions(props, &
flags);
166 if (wantVulkanValidation()) {
167 vkb::InstanceBuilder builder;
168 builder.require_api_version(VK_API_VERSION_MAJOR(apiVersion), VK_API_VERSION_MINOR(apiVersion));
169 builder.request_validation_layers();
170 builder.use_default_debug_messenger();
171 for (
auto* e : exts) builder.enable_extension(e);
172#if defined(EVENGINE_MACOSX) || defined(EVENGINE_IOS)
173 builder.set_headless(
true);
174 builder.add_flags(
flags);
176 std::printf(
"EVEngine: Vulkan validation layers enabled (EVENGINE_VULKAN_VALIDATION)\n");
177 return builder.build();
180 vk::ApplicationInfo app{};
181 app.pApplicationName =
"EVEngine";
182 app.pEngineName =
"EVEngine";
183 app.apiVersion = apiVersion;
185 vk::InstanceCreateInfo ci{};
187 ci.pApplicationInfo = &app;
188 ci.enabledExtensionCount =
static_cast<uint32_t
>(exts.size());
189 ci.ppEnabledExtensionNames = exts.data();
192 inst.instance = vk::createInstance(ci);
193 VULKAN_HPP_DEFAULT_DISPATCHER.init(inst.instance);
197struct InstanceWarmup {
204InstanceWarmup& instanceWarmup() {
205 static InstanceWarmup
state;
209void startVulkanInstanceWarmupImpl() {
210#if defined(EVENGINE_MACOSX) || defined(EVENGINE_IOS)
214 auto&
w = instanceWarmup();
215 std::lock_guard<std::mutex> lock(
w.mu);
216 if (
w.started)
return;
218 w.future = std::async(std::launch::async, [] {
219 StartupStage stage(
" vulkan: instance (warmup thread)");
220 return createInstanceFast();
225vkb::Instance consumeWarmedInstance() {
226#if defined(EVENGINE_MACOSX) || defined(EVENGINE_IOS)
227 StartupStage stage(
" vulkan: instance");
228 return createInstanceFast();
230 startVulkanInstanceWarmupImpl();
231 std::future<vkb::Instance> fut;
233 auto&
w = instanceWarmup();
234 std::lock_guard<std::mutex> lock(
w.mu);
237 fut = std::move(
w.future);
243 StartupStage stage(
" vulkan: instance (new owner)");
244 return createInstanceFast();
246 StartupStage waitStage(
" vulkan: wait instance warmup");
251void discardWarmedInstance() noexcept {
252#if !defined(EVENGINE_MACOSX) && !defined(EVENGINE_IOS)
253 std::future<vkb::Instance> fut;
255 auto&
w = instanceWarmup();
256 std::lock_guard<std::mutex> lock(
w.mu);
257 if (!
w.started ||
w.consumed)
return;
259 fut = std::move(
w.future);
262 vkb::Instance warmed = fut.get();
263 if (
static_cast<VkInstance
>(warmed.instance) != VK_NULL_HANDLE) warmed.destroy();
264 }
catch (
const std::exception& e) {
265 std::fprintf(stderr,
"[vulkan] instance warmup cleanup failed: %s\n", e.what());
267 std::fprintf(stderr,
"[vulkan] instance warmup cleanup failed with an unknown error\n");
272struct RegisterVulkanWarmup {
274} gRegisterVulkanWarmup;
280#if defined(VKB_ENABLE_VMA)
281VmaAllocatorOwner::~VmaAllocatorOwner() {
282 if (allocator_) vmaDestroyAllocator(allocator_);
285void VmaAllocatorOwner::create(
const vkb::Instance& instance,
const vkb::PhysicalDevice& physicalDevice,
287 VmaAllocatorCreateInfo createInfo{};
288 createInfo.instance =
static_cast<VkInstance
>(instance.instance);
289 createInfo.physicalDevice =
static_cast<VkPhysicalDevice
>(physicalDevice.instance);
290 createInfo.device =
static_cast<VkDevice
>(
device.instance);
291 VmaVulkanFunctions vulkanFunctions{};
295 vulkanFunctions.vkGetInstanceProcAddr = VULKAN_HPP_DEFAULT_DISPATCHER.vkGetInstanceProcAddr;
296 if (!vulkanFunctions.vkGetInstanceProcAddr) {
297 throw Exception(
"VMA could not resolve vkGetInstanceProcAddr from the Vulkan dispatcher");
299 vulkanFunctions.vkGetDeviceProcAddr =
reinterpret_cast<PFN_vkGetDeviceProcAddr
>(
300 vulkanFunctions.vkGetInstanceProcAddr(createInfo.instance,
"vkGetDeviceProcAddr"));
301 if (!vulkanFunctions.vkGetDeviceProcAddr) {
302 throw Exception(
"VMA could not resolve vkGetDeviceProcAddr");
304 createInfo.pVulkanFunctions = &vulkanFunctions;
308 createInfo.vulkanApiVersion = VK_API_VERSION_1_0;
309 const VkResult
result = vmaCreateAllocator(&createInfo, &allocator_);
311 device.attachVmaAllocator(allocator_);
321 caps.backend =
"vulkan";
332 discardWarmedInstance();
333 if (
static_cast<VkInstance
>(inst.instance) != VK_NULL_HANDLE) inst.destroy();
338 if (
auto* rt = eve::cap::query<eve::graphics::IRayTracing>()) rt->detachFromGraphics();
339 destroyPbrResources();
341 if (gpuQueryPool_)
device->destroyQueryPool(gpuQueryPool_);
342 gpuQueryPool_ =
nullptr;
343 gpuTimingReady_ =
false;
345 gpuTimingPrefix_.fill(vk::CommandBuffer{});
346 gpuTimingPrefixSubmitted_.fill(
false);
353 destroyGpuParticleResources();
354 for (
auto&
slots : framePostTargets_)
slots.clear();
357 ownedCanvases.clear();
359 ownedGpuMeshes.clear();
360 ownedTextures.clear();
361 for (
auto&
g : ownedGpuTextures) {
362 if (
g->sampler && !
g->sharedSampler)
device->destroySampler(
g->sampler);
364 ownedGpuTextures.clear();
365 cachedSamplers_.clear();
366 samplerChangesPending_ =
false;
367 texturesByPath.clear();
368 for (
auto&
g : ownedGpuShaders) {
369 if (
g->swapchainPipeline)
device->destroyPipeline(
g->swapchainPipeline);
370 if (
g->offscreenPipeline)
device->destroyPipeline(
g->offscreenPipeline);
371 if (
g->swapchainOpaquePipeline)
device->destroyPipeline(
g->swapchainOpaquePipeline);
372 if (
g->offscreenOpaquePipeline)
device->destroyPipeline(
g->offscreenOpaquePipeline);
373 if (
g->hdrOffscreenPipeline)
device->destroyPipeline(
g->hdrOffscreenPipeline);
374 if (
g->hdrOffscreenOpaquePipeline)
device->destroyPipeline(
g->hdrOffscreenOpaquePipeline);
375 if (
g->mesh3dPipeline)
device->destroyPipeline(
g->mesh3dPipeline);
376 if (
g->mesh3dXrayPipeline)
device->destroyPipeline(
g->mesh3dXrayPipeline);
377 if (
g->mesh3dOffscreenPipeline)
device->destroyPipeline(
g->mesh3dOffscreenPipeline);
378 if (
g->mesh3dHdrOffscreenPipeline)
device->destroyPipeline(
g->mesh3dHdrOffscreenPipeline);
381 ownedGpuShaders.clear();
382 ownedShaders.clear();
383 destroySwapchainResources();
384 if (pipeline)
device->destroyPipeline(pipeline);
385 if (solidAlphaPipeline)
device->destroyPipeline(solidAlphaPipeline);
386 if (additiveSolidPipeline)
device->destroyPipeline(additiveSolidPipeline);
387 if (premultipliedSolidPipeline)
device->destroyPipeline(premultipliedSolidPipeline);
388 if (multiplySolidPipeline)
device->destroyPipeline(multiplySolidPipeline);
389 if (pipelineLayout)
device->destroyPipelineLayout(pipelineLayout);
390 if (texPipeline)
device->destroyPipeline(texPipeline);
391 if (additiveTexPipeline)
device->destroyPipeline(additiveTexPipeline);
392 if (premultipliedTexPipeline)
device->destroyPipeline(premultipliedTexPipeline);
393 if (multiplyTexPipeline)
device->destroyPipeline(multiplyTexPipeline);
394 if (opaqueTexPipeline)
device->destroyPipeline(opaqueTexPipeline);
395 if (particleDistortionPipeline)
device->destroyPipeline(particleDistortionPipeline);
396 if (sceneTonemapPipeline)
device->destroyPipeline(sceneTonemapPipeline);
397 if (texPipelineLayout)
device->destroyPipelineLayout(texPipelineLayout);
398 if (shaderPipelineLayout)
device->destroyPipelineLayout(shaderPipelineLayout);
399 if (mesh3dPipeline)
device->destroyPipeline(mesh3dPipeline);
400 if (mesh3dTransparentPipeline)
device->destroyPipeline(mesh3dTransparentPipeline);
401 for (
auto pipeline : mesh3dSurfacePipelines)
402 if (pipeline)
device->destroyPipeline(pipeline);
403 for (
auto pipeline : primitive3DPipelines)
404 if (pipeline)
device->destroyPipeline(pipeline);
405 destroyOffscreen3DResources();
406 if (mesh3dPipelineLayout)
device->destroyPipelineLayout(mesh3dPipelineLayout);
407 if (mesh3dShaderPipelineLayout)
device->destroyPipelineLayout(mesh3dShaderPipelineLayout);
408 mesh3dSetLayoutUnique.reset();
409 mesh3dFrameSlots.clear();
410 destroyVoxelRectResources();
411 if (mesh3dClusteredPipeline)
device->destroyPipeline(mesh3dClusteredPipeline);
412 if (mesh3dClusteredPipelineLayout)
device->destroyPipelineLayout(mesh3dClusteredPipelineLayout);
413 mesh3dClusteredSetLayoutUnique.reset();
414 mesh3dClusteredFrameSlots.clear();
415 destroyShadowResources();
416 destroyGBufferResources();
417 if (skinPassPipelineLayout)
device->destroyPipelineLayout(skinPassPipelineLayout);
418 skinPassPipelineLayout =
nullptr;
419 skinPassSetLayoutUnique.reset();
420 skinPassSetLayout =
nullptr;
421 destroyDecalResources();
422 destroySceneColorResources();
423 destroyUiColorResources();
424 auto destroyBuf = [&](vkb::GenericBuffer&
b) {
b.release(); };
425 for (
auto& st : clusteredStorages) {
426 destroyBuf(st.lightsBuf);
427 destroyBuf(st.tableBuf);
428 destroyBuf(st.indicesBuf);
430 clusteredStorages.clear();
431 if (lit2dPipeline)
device->destroyPipeline(lit2dPipeline);
432 if (lit2dAdditivePipeline)
device->destroyPipeline(lit2dAdditivePipeline);
433 if (lit2dPremultipliedPipeline)
device->destroyPipeline(lit2dPremultipliedPipeline);
434 if (lit2dMultiplyPipeline)
device->destroyPipeline(lit2dMultiplyPipeline);
435 if (lit2dOpaquePipeline)
device->destroyPipeline(lit2dOpaquePipeline);
436 if (offscreenLitPipeline)
device->destroyPipeline(offscreenLitPipeline);
437 if (offscreenLitAdditivePipeline)
device->destroyPipeline(offscreenLitAdditivePipeline);
438 if (offscreenLitPremultipliedPipeline)
device->destroyPipeline(offscreenLitPremultipliedPipeline);
439 if (offscreenLitMultiplyPipeline)
device->destroyPipeline(offscreenLitMultiplyPipeline);
440 if (offscreenLitOpaquePipeline)
device->destroyPipeline(offscreenLitOpaquePipeline);
441 if (lit2dPipelineLayout)
device->destroyPipelineLayout(lit2dPipelineLayout);
442 lit2dSetLayoutUnique.reset();
443 for (
auto&
m : lit2dSets)
m.clear();
445 offscreenLit2dSets.clear();
446 destroyBuf(offscreenLighting2dUbo);
447 if (offscreenSolidPipeline)
device->destroyPipeline(offscreenSolidPipeline);
448 if (offscreenSolidAlphaPipeline)
device->destroyPipeline(offscreenSolidAlphaPipeline);
449 if (offscreenAdditiveSolidPipeline)
device->destroyPipeline(offscreenAdditiveSolidPipeline);
450 if (offscreenPremultipliedSolidPipeline)
device->destroyPipeline(offscreenPremultipliedSolidPipeline);
451 if (offscreenMultiplySolidPipeline)
device->destroyPipeline(offscreenMultiplySolidPipeline);
452 if (offscreenTexPipeline)
device->destroyPipeline(offscreenTexPipeline);
453 if (offscreenAdditiveTexPipeline)
device->destroyPipeline(offscreenAdditiveTexPipeline);
454 if (offscreenPremultipliedTexPipeline)
device->destroyPipeline(offscreenPremultipliedTexPipeline);
455 if (offscreenMultiplyTexPipeline)
device->destroyPipeline(offscreenMultiplyTexPipeline);
456 if (offscreenOpaqueTexPipeline)
device->destroyPipeline(offscreenOpaqueTexPipeline);
457 if (offscreenRenderPass)
device->destroyRenderPass(offscreenRenderPass);
458 if (hdrOffscreenTexPipeline)
device->destroyPipeline(hdrOffscreenTexPipeline);
459 if (hdrOffscreenOpaqueTexPipeline)
device->destroyPipeline(hdrOffscreenOpaqueTexPipeline);
460 if (hdrOffscreenAdditiveTexPipeline)
device->destroyPipeline(hdrOffscreenAdditiveTexPipeline);
461 if (hdrOffscreenPremultipliedTexPipeline)
device->destroyPipeline(hdrOffscreenPremultipliedTexPipeline);
462 if (hdrOffscreenMultiplyTexPipeline)
device->destroyPipeline(hdrOffscreenMultiplyTexPipeline);
463 if (hdrOffscreenSolidPipeline)
device->destroyPipeline(hdrOffscreenSolidPipeline);
464 if (hdrOffscreenSolidAlphaPipeline)
device->destroyPipeline(hdrOffscreenSolidAlphaPipeline);
465 if (hdrOffscreenAdditiveSolidPipeline)
device->destroyPipeline(hdrOffscreenAdditiveSolidPipeline);
466 if (hdrOffscreenPremultipliedSolidPipeline)
device->destroyPipeline(hdrOffscreenPremultipliedSolidPipeline);
467 if (hdrOffscreenMultiplySolidPipeline)
device->destroyPipeline(hdrOffscreenMultiplySolidPipeline);
468 if (hdrOffscreenLitPipeline)
device->destroyPipeline(hdrOffscreenLitPipeline);
469 if (hdrOffscreenLitAdditivePipeline)
device->destroyPipeline(hdrOffscreenLitAdditivePipeline);
470 if (hdrOffscreenLitPremultipliedPipeline)
device->destroyPipeline(hdrOffscreenLitPremultipliedPipeline);
471 if (hdrOffscreenLitMultiplyPipeline)
device->destroyPipeline(hdrOffscreenLitMultiplyPipeline);
472 if (hdrOffscreenLitOpaquePipeline)
device->destroyPipeline(hdrOffscreenLitOpaquePipeline);
473 if (hdrOffscreenTonemapPipeline)
device->destroyPipeline(hdrOffscreenTonemapPipeline);
474 if (hdrOffscreenParticleDistortionPipeline)
device->destroyPipeline(hdrOffscreenParticleDistortionPipeline);
475 destroyPresentComposeResources();
476 if (hdrOffscreenRenderPass)
device->destroyRenderPass(hdrOffscreenRenderPass);
477 texSetLayoutUnique.reset();
478 if (descriptorPool)
device->destroyDescriptorPool(descriptorPool);
479 if (uploadPool)
device->destroyCommandPool(uploadPool);
480 if (renderpass)
device->destroyRenderPass(renderpass);
481 if (surface) inst.instance.destroySurfaceKHR(surface);
484void Graphics::createInstanceAndDevice(
const std::vector<const char*>& extNames,
void* nativeWindow,
485 vk::SurfaceKHR* surfaceOut) {
487 if (
static_cast<VkInstance
>(inst.instance) == VK_NULL_HANDLE) inst = consumeWarmedInstance();
489 if (nativeWindow !=
nullptr && surfaceOut !=
nullptr) {
491 auto* window =
static_cast<SDL_Window*
>(nativeWindow);
492 VkSurfaceKHR rawSurface = VK_NULL_HANDLE;
493 if (!SDL_Vulkan_CreateSurface(window,
static_cast<VkInstance
>(inst.instance), &rawSurface))
494 throw Exception(
"SDL_Vulkan_CreateSurface failed: %s", SDL_GetError());
495 surface = rawSurface;
496 *surfaceOut = rawSurface;
500 StartupStage stage(
" vulkan: physical device + device");
501 auto selector = inst.selectPhysicalDevice();
502 selector.set_minimum_version(1, 0);
504 selector.set_surface(surface);
510 selector.defer_surface_initialization();
512#if defined(EVENGINE_MACOSX) || defined(EVENGINE_IOS)
513 selector.add_required_extension(
"VK_KHR_portability_subset");
517 selector.add_desired_extension(VK_KHR_ACCELERATION_STRUCTURE_EXTENSION_NAME);
518 selector.add_desired_extension(VK_KHR_RAY_TRACING_PIPELINE_EXTENSION_NAME);
519 selector.add_desired_extension(VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME);
520 selector.add_desired_extension(VK_KHR_BUFFER_DEVICE_ADDRESS_EXTENSION_NAME);
521 selector.add_desired_extension(VK_KHR_SPIRV_1_4_EXTENSION_NAME);
522 selector.add_desired_extension(VK_KHR_SHADER_FLOAT_CONTROLS_EXTENSION_NAME);
523 selector.add_desired_extension(VK_KHR_RAY_QUERY_EXTENSION_NAME);
524 auto phys = selector.select();
528 const auto& pp = phys.properties;
529 const char* vendor =
"unknown";
530 switch (pp.vendorID) {
531 case 0x10DE: vendor =
"NVIDIA";
break;
532 case 0x1002: vendor =
"AMD";
break;
533 case 0x8086: vendor =
"Intel";
break;
534 case 0x13B5: vendor =
"ARM";
break;
535 case 0x5143: vendor =
"Qualcomm";
break;
538 char vendorHex[16], deviceHex[16], driverHex[16];
539 std::snprintf(vendorHex,
sizeof(vendorHex),
"%04X", pp.vendorID);
540 std::snprintf(deviceHex,
sizeof(deviceHex),
"%04X", pp.deviceID);
541 std::snprintf(driverHex,
sizeof(driverHex),
"%08X", pp.driverVersion);
542 const uint32_t maj = VK_API_VERSION_MAJOR(pp.apiVersion);
543 const uint32_t
min = VK_API_VERSION_MINOR(pp.apiVersion);
544 const uint32_t pat = VK_API_VERSION_PATCH(pp.apiVersion);
545 eve::recordLogEvent(
"info", std::string(
"gpu: ") + vendor +
" '" + std::string(pp.deviceName.data()) +
546 "' vendorId=0x" + vendorHex +
" deviceId=0x" + deviceHex +
547 " api=" + std::to_string(maj) +
"." + std::to_string(
min) +
"." +
548 std::to_string(pat) +
" driver=0x" + driverHex +
549 (nativeWindow ?
"" :
" [headless]"));
552 const vk::PhysicalDeviceFeatures supported = phys->getFeatures();
553 if (supported.samplerAnisotropy) {
554 phys.features.samplerAnisotropy = VK_TRUE;
555 maxSamplerAnisotropy = phys.properties.limits.maxSamplerAnisotropy;
556 if (maxSamplerAnisotropy < 1.f) maxSamplerAnisotropy = 1.f;
558 maxSamplerAnisotropy = 1.f;
560 if (supported.independentBlend) phys.features.independentBlend = VK_TRUE;
565 gpuDrivenCaps_ = GpuDrivenCaps{};
566 vk::PhysicalDeviceVulkan12Features vk12{};
567 gpuDrivenCaps_.
api12 = negotiatedInstanceApiVersion() >= VK_API_VERSION_1_2 &&
568 phys.properties.apiVersion >= VK_API_VERSION_1_2;
569 if (gpuDrivenCaps_.
api12) {
570 vk::PhysicalDeviceFeatures2 features2{};
571 vk12.sType = vk::StructureType::ePhysicalDeviceVulkan12Features;
572 features2.sType = vk::StructureType::ePhysicalDeviceFeatures2;
573 features2.pNext = &vk12;
574 phys->getFeatures2(&features2);
579 supported.shaderSampledImageArrayDynamicIndexing == VK_TRUE;
585 phys.features.shaderSampledImageArrayDynamicIndexing = VK_TRUE;
586 phys.features.shaderStorageBufferArrayDynamicIndexing = VK_TRUE;
587 phys.features.multiDrawIndirect = VK_TRUE;
594 rayTracingCaps_ = RayTracingCaps{};
595 vk::PhysicalDeviceAccelerationStructureFeaturesKHR rtAsEnable{};
596 vk::PhysicalDeviceRayTracingPipelineFeaturesKHR rtPipeEnable{};
597 vk::PhysicalDeviceRayQueryFeaturesKHR rtQueryEnable{};
598 bool enableRtFeatures =
false;
600 const auto extProps = phys->enumerateDeviceExtensionProperties();
601 auto hasExt = [&](
const char*
name) {
602 for (
const auto&
p : extProps) {
603 if (std::strcmp(
p.extensionName,
name) == 0)
return true;
607 const bool extsOk = hasExt(VK_KHR_ACCELERATION_STRUCTURE_EXTENSION_NAME) &&
608 hasExt(VK_KHR_RAY_TRACING_PIPELINE_EXTENSION_NAME) &&
609 hasExt(VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME);
610 const bool api12 = phys.properties.apiVersion >= VK_API_VERSION_1_2;
611 const bool bdaExt = hasExt(VK_KHR_BUFFER_DEVICE_ADDRESS_EXTENSION_NAME) || api12;
612 const bool spirv14 = hasExt(VK_KHR_SPIRV_1_4_EXTENSION_NAME) || api12;
614 vk::PhysicalDeviceBufferDeviceAddressFeatures bdaFeat{};
615 bdaFeat.sType = vk::StructureType::ePhysicalDeviceBufferDeviceAddressFeatures;
616 vk::PhysicalDeviceAccelerationStructureFeaturesKHR asFeat{};
617 asFeat.sType = vk::StructureType::ePhysicalDeviceAccelerationStructureFeaturesKHR;
618 asFeat.pNext = &bdaFeat;
619 vk::PhysicalDeviceRayTracingPipelineFeaturesKHR rtFeat{};
620 rtFeat.sType = vk::StructureType::ePhysicalDeviceRayTracingPipelineFeaturesKHR;
621 rtFeat.pNext = &asFeat;
622 vk::PhysicalDeviceFeatures2 features2Rt{};
623 features2Rt.sType = vk::StructureType::ePhysicalDeviceFeatures2;
624 features2Rt.pNext = &rtFeat;
625 phys->getFeatures2(&features2Rt);
627 vk::PhysicalDeviceRayQueryFeaturesKHR rqFeat{};
628 rqFeat.sType = vk::StructureType::ePhysicalDeviceRayQueryFeaturesKHR;
629 if (hasExt(VK_KHR_RAY_QUERY_EXTENSION_NAME)) {
632 vk::PhysicalDeviceFeatures2 features2Rq{};
633 features2Rq.sType = vk::StructureType::ePhysicalDeviceFeatures2;
634 features2Rq.pNext = &rqFeat;
635 phys->getFeatures2(&features2Rq);
638 const bool featuresOk = rtFeat.rayTracingPipeline == VK_TRUE && asFeat.accelerationStructure == VK_TRUE &&
639 bdaFeat.bufferDeviceAddress == VK_TRUE;
641 if (extsOk && bdaExt && spirv14 && featuresOk) {
646 if (hasExt(VK_KHR_RAY_QUERY_EXTENSION_NAME) && rqFeat.rayQuery == VK_TRUE)
649 vk::PhysicalDeviceRayTracingPipelinePropertiesKHR rtProps{};
650 rtProps.sType = vk::StructureType::ePhysicalDeviceRayTracingPipelinePropertiesKHR;
651 vk::PhysicalDeviceProperties2 props2{};
652 props2.sType = vk::StructureType::ePhysicalDeviceProperties2;
653 props2.pNext = &rtProps;
654 phys->getProperties2(&props2);
663 rtAsEnable.sType = vk::StructureType::ePhysicalDeviceAccelerationStructureFeaturesKHR;
664 rtAsEnable.accelerationStructure = VK_TRUE;
665 rtPipeEnable.sType = vk::StructureType::ePhysicalDeviceRayTracingPipelineFeaturesKHR;
666 rtPipeEnable.rayTracingPipeline = VK_TRUE;
668 rtQueryEnable.sType = vk::StructureType::ePhysicalDeviceRayQueryFeaturesKHR;
669 rtQueryEnable.rayQuery = VK_TRUE;
671 enableRtFeatures =
true;
677 vkb::DeviceBuilder deviceBuilder = phys.createDevice();
678#if defined(EVENGINE_MACOSX) || defined(EVENGINE_IOS)
681 VkPhysicalDevicePortabilitySubsetFeaturesKHR portabilitySupported{};
683 constexpr auto portabilityFeatureType =
static_cast<VkStructureType
>(1000163000);
684 portabilitySupported.sType = portabilityFeatureType;
685 vk::PhysicalDeviceFeatures2 portabilityQuery{};
686 portabilityQuery.pNext = &portabilitySupported;
687 phys->getFeatures2(&portabilityQuery);
688 VkPhysicalDevicePortabilitySubsetFeaturesKHR portabilityEnable{};
689 portabilityEnable.sType = portabilityFeatureType;
690 portabilityEnable.mutableComparisonSamplers = portabilitySupported.mutableComparisonSamplers;
691 deviceBuilder.add_pNext(&portabilityEnable);
694 vk::PhysicalDeviceVulkan12Features vk12Enable{};
695 vk12Enable.sType = vk::StructureType::ePhysicalDeviceVulkan12Features;
697 if (enableRtFeatures) {
698 vk12Enable.bufferDeviceAddress = VK_TRUE;
701 deviceBuilder.add_pNext(&rtPipeEnable);
702 deviceBuilder.add_pNext(&rtAsEnable);
703 if (rayTracingCaps_.
rayQuery) deviceBuilder.add_pNext(&rtQueryEnable);
705 if (gpuDrivenCaps_.
api12) deviceBuilder.add_pNext(&vk12Enable);
706 device = deviceBuilder.build();
708 VULKAN_HPP_DEFAULT_DISPATCHER.init(
device.instance);
709#if defined(VKB_ENABLE_VMA)
710 vmaAllocatorOwner_.create(inst, phys, device);
712 maxSamplerAnisotropy =
device.caps.maxSamplerAnisotropy;
714 "gpu: logical device created (gpuDriven=" +
716 ", rayTracing=" +
std::
string(rayTracingCaps_.rayTracingAvailable() ?
"on" :
"off") +
717#if defined(VKB_ENABLE_VMA)
720 ", allocator=native" +
722 ", maxAniso=" +
std::to_string(maxSamplerAnisotropy) +
")");
727 StartupStage initStage(
"graphics: initHeadless (total)");
735 throw Exception(
"Graphics::initHeadless: already initialized with a window");
741 createInstanceAndDevice({},
nullptr,
nullptr);
743 uploadPool =
device.createCommandPool();
748 StartupStage stage(
" vulkan: headless renderpass + pipelines");
751 vkb::RenderPassBuilder rpBuilder{
device};
753 rpBuilder.addPresentAttachment(vk::Format::eB8G8R8A8Unorm, vk::AttachmentLoadOp::eClear)
754 .addDepthAttachment(depthFormat, vk::AttachmentLoadOp::eClear, vk::AttachmentStoreOp::eDontCare)
755 .addSubpass(vkb::SubpassBuilder()
756 .addAttachmentRef(0, vk::ImageLayout::eColorAttachmentOptimal)
757 .setDepthStencilAttachment(1, vk::ImageLayout::eDepthStencilAttachmentOptimal))
759 VK_SUBPASS_EXTERNAL, 0,
760 vk::PipelineStageFlagBits::eColorAttachmentOutput | vk::PipelineStageFlagBits::eEarlyFragmentTests,
761 vk::PipelineStageFlagBits::eColorAttachmentOutput | vk::PipelineStageFlagBits::eEarlyFragmentTests,
763 vk::AccessFlagBits::eColorAttachmentRead | vk::AccessFlagBits::eColorAttachmentWrite |
764 vk::AccessFlagBits::eDepthStencilAttachmentWrite)
766 depthImage = vkb::DepthStencilImage{
device, uint32_t(
width), uint32_t(
height), depthFormat};
767 pipelineLayout = createPipelineLayout(
device);
768 createTexturedPipeline();
769 createMesh3DPipeline();
770 createMesh3DClusteredPipeline();
771 createVoxelRectPipeline();
776 StartupStage stage(
" vulkan: shadow resources (CSM atlas + pipelines)");
777 createShadowResources();
781 const uint8_t whitePixel[4] = {255, 255, 255, 255};
783 const std::vector<uint8_t> cubePx(6 * 4, 255);
784 defaultBindlessCube =
newCubemap(1, cubePx.data());
787 StartupStage stage(
" vulkan: gpu-driven bindless set + pipeline");
788 initGpuDrivenResources();
794 eve::cap::provide<eve::service::IGpuTimer>(
this);
795 StartupStage initStage(
"graphics: initWithWindow (total)");
802 if (sdlWindow == nativeWindow && surface)
return;
803 sdlWindow = nativeWindow;
804 recreateSurfaceForResume();
809 rebuildSwapchainIfNeeded();
812 sdlWindow = nativeWindow;
813 auto* window =
static_cast<SDL_Window*
>(nativeWindow);
814 ASSERT(window !=
nullptr);
815 if (!window)
throw Exception(
"Graphics::initWithWindow: null SDL_Window");
817 unsigned int count = 0;
818 if (!SDL_Vulkan_GetInstanceExtensions(window, &
count,
nullptr))
819 throw Exception(
"SDL_Vulkan_GetInstanceExtensions failed: %s", SDL_GetError());
821 std::vector<const char*> extNames(
count);
822 if (!SDL_Vulkan_GetInstanceExtensions(window, &
count, extNames.data()))
823 throw Exception(
"SDL_Vulkan_GetInstanceExtensions failed: %s", SDL_GetError());
825 createInstanceAndDevice(extNames, nativeWindow, &surface);
827 uploadPool =
device.createCommandPool();
830 SDL_Vulkan_GetDrawableSize(window, &pw, &ph);
832 SDL_GetWindowSize(window, &lw, &lh);
836 StartupStage stage(
" vulkan: swapchain + solid pipelines");
837 createSwapchainAndPipeline();
841 StartupStage stage(
" vulkan: textured/lit2d pipelines");
842 createTexturedPipeline();
846 createMesh3DPipeline();
850 createMesh3DClusteredPipeline();
854 createVoxelRectPipeline();
858 StartupStage stage(
" vulkan: shadow resources (CSM atlas + pipelines)");
859 createShadowResources();
863 const uint8_t whitePixel[4] = {255, 255, 255, 255};
865 const std::vector<uint8_t> cubePx(6 * 4, 255);
866 defaultBindlessCube =
newCubemap(1, cubePx.data());
869 StartupStage stage(
" vulkan: gpu-driven bindless set + pipeline");
870 initGpuDrivenResources();
876 if (!initialized)
return;
877 if (swapchainPassOpen || sceneColorPassOpen) abortOpen3DFrame();
885 destroySwapchainResources();
887 swapchain = vkb::Swapchain{};
889 inst.instance.destroySurfaceKHR(surface);
890 surface = VK_NULL_HANDLE;
893 swapchainDirty =
true;
896void Graphics::destroySwapchainResources() {
897 destroyPbrResources();
898 presentRecording = {};
900 presentModel.destroy();
901 presentModel = vkb::Present{};
902 destroyGpuDrivenCullResources();
903 depthImage = vkb::DepthStencilImage{};
904 destroyReadbackResources();
907 for (
auto& fb : frame2dBuffers) releaseFrame2dBuffers(fb);
908 frame2dBuffers.clear();
909 releaseFrame2dBuffers(offscreenBuffers);
912 for (
auto& ubo : lighting2dUboSlots) ubo.release();
913 lighting2dUboSlots.clear();
919uint32_t Graphics::frameSlotCount()
const {
920 uint32_t
n = presentModel.frames_in_flight;
921 if (
n == 0)
n = swapchain.image_count;
925size_t Graphics::currentFrameSlot()
const {
926 const uint32_t
n = frameSlotCount();
927 size_t slot = presentRecording ? presentRecording.slot().index : swapchain.current_frame;
931vk::CommandBuffer& Graphics::currentPresentCb() {
932 if (offscreen3DPassOpen && offscreen3DCB)
return offscreen3DCB;
933 if (swapchainPass)
return swapchainPass.commandBuffer();
934 return presentRecording.commandBuffer();
937vkb::FrameSlot Graphics::frameToken()
const {
938 if (offscreen3DPassOpen)
return vkb::FrameSlot{0};
939 if (presentRecording)
return presentRecording.slot();
940 return vkb::FrameSlot::gpuIdle();
945 presentModel.waitForAllFrames();
948void Graphics::invalidateTextureBindings() {
951 for (
auto&
m : lit2dSets)
m.
clear();
952 offscreenLit2dSets.clear();
954 voxelRectSets.clear();
957Graphics::Frame2DBuffers& Graphics::currentFrame2DBuffers() {
958 return currentSlot(frame2dBuffers, frameSlotCount(), currentFrameSlot());
961Graphics::Mesh3dFrameSlots& Graphics::currentMesh3dFrameSlots() {
962 return currentSlot(mesh3dFrameSlots, frameSlotCount(), currentFrameSlot());
965Graphics::Mesh3dClusteredFrameSlots& Graphics::currentMesh3dClusteredFrameSlots() {
966 return currentSlot(mesh3dClusteredFrameSlots, frameSlotCount(), currentFrameSlot());
969vkb::GenericBuffer& Graphics::currentLighting2dUbo() {
970 auto& ubo = currentSlot(lighting2dUboSlots, frameSlotCount(), currentFrameSlot());
973 ubo.allocate(frameToken(), device, vk::BufferUsageFlagBits::eUniformBuffer,
sizeof(Lighting2DUBO),
974 vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
978std::unordered_map<Graphics::LitSetKey, vkb::BoundSet, Graphics::LitSetKeyHash>& Graphics::currentLit2dSets() {
979 return currentSlot(lit2dSets, frameSlotCount(), currentFrameSlot());
982Graphics::ClusteredStorage& Graphics::currentClusteredStorage() {
983 return currentSlot(clusteredStorages, frameSlotCount(), currentFrameSlot());
986Graphics::VoxelInstanceFrame& Graphics::currentVoxelInstanceFrame() {
987 return currentSlot(voxelInstanceFrames, frameSlotCount(), currentFrameSlot());
990Graphics::ShadowMapSlot& Graphics::currentShadowMap() {
991 ASSERT(!shadowMaps.empty());
992 return shadowMaps[currentFrameSlot() % shadowMaps.size()];
995vk::ImageView Graphics::currentShadowArrayView() {
996 if (shadowMaps.empty())
return vk::ImageView{};
997 return currentShadowMap().image.arrayView();
1000Graphics::GBufferSlot* Graphics::currentGBufferSlot() {
1001 if (gbufferSlots.empty())
return nullptr;
1002 return &gbufferSlots[currentFrameSlot() % gbufferSlots.size()];
1006 if (
auto*
slot = currentGBufferSlot();
slot && gbufferPending &&
slot->depthColorTex.gpuHandle)
1007 return &
slot->depthColorTex;
1012Graphics::DecalSlot* Graphics::currentDecalSlot() {
1013 if (decalSlots.empty())
return nullptr;
1014 return &decalSlots[currentFrameSlot() % decalSlots.size()];
1017Graphics::SceneColorSlot* Graphics::currentSceneColorSlot() {
1018 if (sceneColorSlots.empty())
return nullptr;
1019 return &sceneColorSlots[currentFrameSlot() % sceneColorSlots.size()];
1023 auto*
slot = currentSceneColorSlot();
1024 if (!
slot || !
slot->colorTex.gpuHandle)
return nullptr;
1025 return &
slot->colorTex;
1028Graphics::UiColorSlot* Graphics::currentUiColorSlot() {
1029 if (uiColorSlots.empty())
return nullptr;
1030 return &uiColorSlots[currentFrameSlot() % uiColorSlots.size()];
1033void Graphics::dropPendingOffscreenPasses() {
1034 shadowPendingMask = 0;
1035 for (
auto&
d : shadowCascadeDraws)
d.
clear();
1036 gbufferPending =
false;
1037 gbufferPassDraws.clear();
1038 gbufferInstancedBatches.clear();
1039 decalPending =
false;
1040 decalPassDraws.clear();
1043bool Graphics::beginSwapchainRenderPass() {
1044 if (!beginPresentCommandBuffer()) {
1045 dropPendingOffscreenPasses();
1048 recordDeferredFrameGraph();
1049 beginSwapchainColorPass();
1053void Graphics::beginSwapchainColorPass() {
1054 std::array<vk::ClearValue, 2> clears{};
1055 clears[0].color = vk::ClearColorValue(std::array<float, 4>{clearColor.r, clearColor.g, clearColor.b, clearColor.a});
1056 clears[1].depthStencil = vk::ClearDepthStencilValue{1.0f, 0};
1057 swapchainPass = presentRecording.beginRenderPass(renderpass, clears.data(), uint32_t(clears.size()));
1060bool Graphics::rebuildSwapchainIfNeeded() {
1061 const bool wantRecreate = surfaceNeedsRecreate.load() || swapchainDirty || presentModel.needs_recreate;
1062 if (!wantRecreate)
return true;
1063 if (!isRenderSurfaceStable())
return false;
1065 if (surfaceNeedsRecreate.exchange(
false)) recreateSurfaceForResume();
1066 if (presentModel.needs_recreate) {
1067 presentModel.needs_recreate =
false;
1076 auto*
window =
static_cast<SDL_Window*
>(sdlWindow);
1078 if (window) SDL_Vulkan_GetDrawableSize(window, &pw, &ph);
1081 const bool sizeMismatch = swapchain.extent.width == 0 || swapchain.extent.height == 0 || pw <= 0 || ph <= 0 ||
1082 uint32_t(pw) != swapchain.extent.width || uint32_t(ph) != swapchain.extent.height;
1083 if (sizeMismatch) swapchainDirty =
true;
1085 if (swapchainDirty) {
1087 createSwapchainAndPipeline();
1092bool Graphics::beginPresentCommandBuffer() {
1094 for (
int attempt = 0; attempt < 3; ++attempt) {
1095 if (!rebuildSwapchainIfNeeded())
return false;
1098 const bool newFrame = !presentRecording;
1099 presentRecording = presentModel.begin();
1101 if (presentRecording && newFrame) {
1103 deferredGraphRecorded_ =
false;
1106 if (presentRecording) {
1113 if (presentModel.needs_recreate) {
1114 presentModel.needs_recreate =
false;
1115 swapchainDirty =
true;
1123bool Graphics::isRenderSurfaceReady()
const {
1124 auto*
window =
static_cast<SDL_Window*
>(sdlWindow);
1125 if (!window)
return false;
1130 SDL_Vulkan_GetDrawableSize(window, &pw, &ph);
1131 return pw > 0 && ph > 0;
1134bool Graphics::isRenderSurfaceStable() {
1135#if defined(EVENGINE_ANDROID) || defined(EVENGINE_IOS)
1136 auto*
window =
static_cast<SDL_Window*
>(sdlWindow);
1137 if (!window)
return false;
1139 SDL_Vulkan_GetDrawableSize(window, &pw, &ph);
1140 if (pw <= 0 || ph <= 0) {
1141 surfaceStableFrames = 0;
1144 if (pw != pendingSurfaceW || ph != pendingSurfaceH) {
1146 pendingSurfaceW = pw;
1147 pendingSurfaceH = ph;
1148 surfaceStableFrames = 1;
1152 if (surfaceStableFrames < 3) {
1153 ++surfaceStableFrames;
1162void Graphics::recreateSurfaceForResume() {
1167 if (!initialized)
return;
1168 auto*
window =
static_cast<SDL_Window*
>(sdlWindow);
1169 if (!window)
return;
1174 destroySwapchainResources();
1175 swapchain.destroy();
1176 swapchain = vkb::Swapchain{};
1178 inst.instance.destroySurfaceKHR(surface);
1179 surface = VK_NULL_HANDLE;
1183 VkSurfaceKHR rawSurface = VK_NULL_HANDLE;
1184 if (!SDL_Vulkan_CreateSurface(window,
static_cast<VkInstance
>(inst.instance), &rawSurface))
1185 throw Exception(
"resume: SDL_Vulkan_CreateSurface failed: %s", SDL_GetError());
1186 surface = rawSurface;
1187 device.surface = surface;
1190 int pw = 0, ph = 0, lw = 0, lh = 0;
1191 SDL_Vulkan_GetDrawableSize(window, &pw, &ph);
1192 SDL_GetWindowSize(window, &lw, &lh);
1195 swapchainDirty =
true;
1200 if (!initialized)
return;
1201 if (headless_)
return;
1204 if (!isRenderSurfaceReady()) {
1207 if (swapchainPassOpen)
1211 hasPendingClear =
false;
1223 if (
const char* setting = std::getenv(
"EVENGINE_GPU_TIMING"); setting && std::strcmp(setting,
"0") == 0)
return;
1224 if (gpuQueryPool_)
return;
1226 timestampPeriod_ =
device.physical_device.properties.limits.timestampPeriod;
1227 vk::QueryPoolCreateInfo ci;
1228 ci.queryType = vk::QueryType::eTimestamp;
1229 ci.queryCount = 2 * kAsyncResourceCopies;
1230 gpuQueryPool_ =
device->createQueryPool(ci);
1231 const auto buffers =
device->allocateCommandBuffers(
1232 vk::CommandBufferAllocateInfo{uploadPool, vk::CommandBufferLevel::ePrimary, kAsyncResourceCopies});
1233 std::copy(buffers.begin(), buffers.end(), gpuTimingPrefix_.begin());
1234 gpuTimingPrefixSubmitted_.fill(
false);
1235 gpuTimingReady_ =
true;
1237 gpuTimingReady_ =
false;
1238 if (gpuQueryPool_)
device->destroyQueryPool(gpuQueryPool_);
1239 gpuQueryPool_ =
nullptr;
1244 if (!gpuTimingReady_ || !presentRecording)
return;
1245 const uint32_t
slot = uint32_t(currentFrameSlot() % kAsyncResourceCopies);
1246 auto cb = gpuTimingPrefix_[
slot];
1248 cb.begin(vk::CommandBufferBeginInfo{});
1249 cb.resetQueryPool(gpuQueryPool_,
slot * 2, 2);
1250 cb.writeTimestamp(vk::PipelineStageFlagBits::eTopOfPipe, gpuQueryPool_,
slot * 2);
1252 gpuTimingPrefixSubmitted_[
slot] =
false;
1255void Graphics::submitGpuTimingPrefix() {
1256 if (!gpuTimingReady_ || !presentRecording)
return;
1257 const uint32_t
slot = uint32_t(currentFrameSlot() % kAsyncResourceCopies);
1258 if (gpuTimingPrefixSubmitted_[
slot])
return;
1260 vk::SubmitInfo
info{};
1261 info.commandBufferCount = 1;
1262 info.pCommandBuffers = &gpuTimingPrefix_[
slot];
1263 const auto result =
device.getQueue(vkb::QueueType::graphics).submit(1, &
info, vk::Fence{});
1264 if (
result != vk::Result::eSuccess)
throw Exception(
"GPU timing prefix submission failed");
1265 gpuTimingPrefixSubmitted_[
slot] =
true;
1269 if (!gpuTimingReady_ || !presentRecording)
return;
1270 vk::CommandBuffer cb = presentRecording.commandBuffer();
1271 const uint32_t
first = uint32_t(currentFrameSlot() % kAsyncResourceCopies) * 2;
1272 cb.writeTimestamp(vk::PipelineStageFlagBits::eBottomOfPipe, gpuQueryPool_,
first + 1);
1277 if (!gpuTimingReady_ || !gpuQueryPool_)
return;
1281 const uint32_t
slot = uint32_t(currentFrameSlot() % kAsyncResourceCopies);
1282 if (!gpuTimingPrefixSubmitted_[
slot]) {
1287 std::array<uint64_t, 4> ts{};
1289 device->getQueryPoolResults(gpuQueryPool_,
first, 2,
sizeof(ts), ts.data(), 2 *
sizeof(uint64_t),
1290 vk::QueryResultFlagBits::e64 | vk::QueryResultFlagBits::eWithAvailability);
1291 if (
result == vk::Result::eSuccess && ts[1] && ts[3] && ts[2] > ts[0])
1292 gpuFrameMs_ = float(
double(ts[2] - ts[0]) *
double(timestampPeriod_) / 1'000'000.0);
Persistent, thread-safe record of engine crash and problem events.
std::future< JobOutput > future
#define EV_PROFILE_MODULE(module, name)
Profile the enclosing scope, tagged with a module for grouping.
LocalPageCacheEntry slots[ShadowConfig::kLocalSlots]
EVENGINE_API_FOUNDATION public API.
void configure(FrameCaptureCapabilities capabilities)
Set backend support at provider initialization.
Screen-space buffers for mid/post effects and Hybrid deferred lighting.
Texture * getDepthTexture() const
Returns the depth texture.
bool isValid() const
True when valid.
std::vector< std::pair< WindowDestroyedCallback, void * > > windowDestroyedCallbacks_
std::unique_ptr< AntiAliasing > pipelineAA_
std::vector< DeferredFileTexture > deferredFileTextures_
void retireResourceLifetime() const
Retire resource lifetime.
Canvas * sharedFramePostTargets_[2]
void clearPresentOverlay()
Drop the present overlay callback (window gone; re-register on UI init).
Canvas * spatialAAResolve_
std::unique_ptr< RenderControl > renderControl_
bool isActive() const
True when active.
std::unique_ptr< GlobalIllumination > pipelineGI_
std::unique_ptr< AmbientOcclusion > pipelineAO_
FrameCaptureStore & frameCaptures()
Graphics-owned frame capture authority. @thread Engine main thread only. @lifetime Borrowed until Gra...
GPU texture created via Graphics::newTexture. Owns GPU resources through an opaque backend handle.
void onNativeWindowDestroyed() override
On native window destroyed.
void draw(eve::graphics::Graphics *gfx, const glm::mat4 &matrix) const override
Draws .
void present() override
Present.
Texture * getSceneColorTexture() override
Returns the scene color texture.
std::string getBackendName() const override
Returns the backend name.
void waitForSharedGpuResources()
Block until all in-flight GPU work (all frames) has completed.
bool isCanvasActive() const override
True when canvas active.
void initWithWindow(void *nativeWindow) override
Initializes with window.
void writeGpuTimestampEnd()
Writes an end timestamp into the current present command buffer.
void setViewportSize(int width, int height, int pixelwidth, int pixelheight) override
Sets the viewport size.
float gpuFrameMs() const override
Gpu frame ms.
Graphics()
Starts asynchronous VkInstance creation (overlaps later window init).
bool gpuTimingAvailable() const override
Gpu timing available.
bool supportsRuntimeGlslCompilation() const override
Supports runtime glsl compilation.
Texture * getSceneLinearDepthTexture() override
Returns the scene linear depth texture.
Texture * newCubemap(int faceSize, const uint8_t *rgbaFaces) override
Creates a cubemap. @ownership Caller deletes unless documented otherwise.
void readGpuFrameTiming()
Reads a completed reusable slot without blocking; call after acquire and before recording.
void initGpuTiming()
Creates the GPU timestamp query pool; call after device init.
Texture * newTexture(int width, int height, const uint8_t *rgba, bool repeatU=false, bool repeatV=false) override
Creates a texture. @ownership Caller deletes unless documented otherwise.
void initHeadless(int width, int height) override
Initializes headless.
~Graphics() override
Graphics.
void clear(std::optional< Color > color, std::optional< int > stencil, std::optional< double > depth) override
Clears .
void writeGpuTimestampBegin()
Records a slot-owned prefix timestamp; submitted before deferred or present GPU work.
EVENGINE_API_FOUNDATION void registerVulkanInstanceWarmup(void(*start)())
Register the graphics-backend function that starts VkInstance creation.
constexpr uint32_t kMaxBindlessTextures
bool glslRuntimeCompilationAvailable()
Whether this build can compile GLSL text to SPIR-V at runtime.
void detachGraphicsArtifactProvider(Graphics *graphics) noexcept
Detach a Graphics instance before its derived backend is destroyed.
WidgetDesc window(std::string title, std::vector< WidgetDesc > children, std::string id)
Top-level window widget with a title bar.
void recordLogEvent(const std::string &level, const std::string &message)
Appends a timestamped event line to the crash/error log.
FrameAttachment
Stable logical render attachments; Depth and Velocity share storage.
Backend support is explicit; candidates need not be produced in every frame.
uint32_t shaderGroupHandleAlignment
bool accelerationStructure
bool available
Full KHR RT pipeline path usable
uint32_t maxRecursionDepth
uint32_t shaderGroupHandleSize
uint32_t shaderGroupBaseAlignment
bool rayQuery
Optional VK_KHR_ray_query
bool gpuDrivenAvailable() const
Gpu driven available.
bool samplerArrayCapacity
bool shaderSampledImageArrayDynamicIndexing