forked from KhronosGroup/Vulkan-Tutorial
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrenderer_core.cpp
More file actions
731 lines (627 loc) · 28.4 KB
/
renderer_core.cpp
File metadata and controls
731 lines (627 loc) · 28.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
#include "renderer.h"
#include <fstream>
#include <iostream>
#include <set>
#include <map>
#include <cstring>
#include <ranges>
#include <thread>
VULKAN_HPP_DEFAULT_DISPATCH_LOADER_DYNAMIC_STORAGE; // In a .cpp file
#include <vulkan/vulkan_raii.hpp>
#include <vulkan/vk_platform.h>
// Debug callback for vk::raii
static VKAPI_ATTR VkBool32 VKAPI_CALL debugCallbackVkRaii(
vk::DebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
vk::DebugUtilsMessageTypeFlagsEXT messageType,
const vk::DebugUtilsMessengerCallbackDataEXT* pCallbackData,
void* pUserData) {
if (messageSeverity >= vk::DebugUtilsMessageSeverityFlagBitsEXT::eWarning) {
// Print a message to the console
std::cerr << "Validation layer: " << pCallbackData->pMessage << std::endl;
} else {
// Print a message to the console
std::cout << "Validation layer: " << pCallbackData->pMessage << std::endl;
}
return VK_FALSE;
}
// Renderer core implementation for the "Rendering Pipeline" chapter of the tutorial.
Renderer::Renderer(Platform* platform)
: platform(platform) {
// Initialize deviceExtensions with required extensions only
// Optional extensions will be added later after checking device support
deviceExtensions = requiredDeviceExtensions;
}
// Destructor
Renderer::~Renderer() {
Cleanup();
}
// Initialize the renderer
bool Renderer::Initialize(const std::string& appName, bool enableValidationLayers) {
vk::detail::DynamicLoader dl;
auto vkGetInstanceProcAddr = dl.getProcAddress<PFN_vkGetInstanceProcAddr>("vkGetInstanceProcAddr");
VULKAN_HPP_DEFAULT_DISPATCHER.init(vkGetInstanceProcAddr);
// Create a Vulkan instance
if (!createInstance(appName, enableValidationLayers)) {
return false;
}
// Setup debug messenger
if (!setupDebugMessenger(enableValidationLayers)) {
return false;
}
// Create surface
if (!createSurface()) {
return false;
}
// Pick the physical device
if (!pickPhysicalDevice()) {
return false;
}
// Create logical device
if (!createLogicalDevice(enableValidationLayers)) {
return false;
}
// Initialize memory pool for efficient memory management
try {
memoryPool = std::make_unique<MemoryPool>(device, physicalDevice);
if (!memoryPool->initialize()) {
std::cerr << "Failed to initialize memory pool" << std::endl;
return false;
}
// Optionally pre-allocate initial memory blocks for pools
if (!memoryPool->preAllocatePools()) {
std::cerr << "Failed to pre-allocate memory pools" << std::endl;
return false;
}
} catch (const std::exception& e) {
std::cerr << "Failed to create memory pool: " << e.what() << std::endl;
return false;
}
// Create swap chain
if (!createSwapChain()) {
return false;
}
// Create image views
if (!createImageViews()) {
return false;
}
// Setup dynamic rendering
if (!setupDynamicRendering()) {
return false;
}
// Create the descriptor set layout
if (!createDescriptorSetLayout()) {
return false;
}
// Create the graphics pipeline
if (!createGraphicsPipeline()) {
return false;
}
// Create PBR pipeline
if (!createPBRPipeline()) {
return false;
}
// Create the lighting pipeline
if (!createLightingPipeline()) {
std::cerr << "Failed to create lighting pipeline" << std::endl;
return false;
}
// Create compute pipeline
if (!createComputePipeline()) {
std::cerr << "Failed to create compute pipeline" << std::endl;
return false;
}
// Create the command pool
if (!createCommandPool()) {
return false;
}
// Create depth resources
if (!createDepthResources()) {
return false;
}
// Create the descriptor pool
if (!createDescriptorPool()) {
return false;
}
if (!createOrResizeLightStorageBuffers(1)) {
std::cerr << "Failed to create initial light storage buffers" << std::endl;
return false;
}
if (!createOpaqueSceneColorResources()) {
return false;
}
createTransparentDescriptorSets();
// Create default texture resources
if (!createDefaultTextureResources()) {
std::cerr << "Failed to create default texture resources" << std::endl;
return false;
}
// Create fallback transparent descriptor sets (must occur after default textures exist)
createTransparentFallbackDescriptorSets();
// Create shared default PBR textures (to avoid creating hundreds of identical textures)
if (!createSharedDefaultPBRTextures()) {
std::cerr << "Failed to create shared default PBR textures" << std::endl;
return false;
}
// Create command buffers
if (!createCommandBuffers()) {
return false;
}
// Create sync objects
if (!createSyncObjects()) {
return false;
}
// Initialize background thread pool for async tasks (textures, etc.) AFTER all Vulkan resources are ready
try {
// Size the thread pool based on hardware concurrency, clamped to a sensible range
unsigned int hw = std::max(2u, std::min(8u, std::thread::hardware_concurrency() ? std::thread::hardware_concurrency() : 4u));
threadPool = std::make_unique<ThreadPool>(hw);
} catch (const std::exception& e) {
std::cerr << "Failed to create thread pool: " << e.what() << std::endl;
return false;
}
initialized = true;
return true;
}
void Renderer::ensureThreadLocalVulkanInit() const {
// Initialize Vulkan-Hpp dispatcher per-thread; required for multi-threaded RAII usage
static thread_local bool s_tlsInitialized = false;
if (s_tlsInitialized) return;
try {
vk::detail::DynamicLoader dl;
auto vkGetInstanceProcAddr = dl.getProcAddress<PFN_vkGetInstanceProcAddr>("vkGetInstanceProcAddr");
if (vkGetInstanceProcAddr) {
VULKAN_HPP_DEFAULT_DISPATCHER.init(vkGetInstanceProcAddr);
}
if (*instance) {
VULKAN_HPP_DEFAULT_DISPATCHER.init(*instance);
}
if (*device) {
VULKAN_HPP_DEFAULT_DISPATCHER.init(*device);
}
s_tlsInitialized = true;
} catch (...) {
// best-effort
}
}
// Clean up renderer resources
void Renderer::Cleanup() {
// Ensure background workers are stopped before tearing down Vulkan resources
{
std::unique_lock<std::shared_mutex> lock(threadPoolMutex);
if (threadPool) {
threadPool.reset();
}
}
if (initialized) {
std::cout << "Starting renderer cleanup..." << std::endl;
// Wait for the device to be idle before cleaning up
device.waitIdle();
// Clean up swapchain-bound resources (depth, offscreen color, pipelines, views, etc.)
cleanupSwapChain();
// Release per-entity resources and return pooled memory to the MemoryPool
for (auto& resources : entityResources | std::views::values) {
// Descriptor sets are RAII and freed with descriptorPool; just clear holders
resources.basicDescriptorSets.clear();
resources.pbrDescriptorSets.clear();
// Destroy UBO buffers and return pooled allocations
resources.uniformBuffers.clear();
for (auto& alloc : resources.uniformBufferAllocations) {
if (alloc) {
try { memoryPool->deallocate(std::move(alloc)); }
catch (const std::exception& e) {
std::cerr << "Warning: failed to deallocate UBO allocation during Cleanup: " << e.what() << std::endl;
}
}
}
resources.uniformBufferAllocations.clear();
resources.uniformBuffersMapped.clear();
// Destroy instance buffer and return pooled allocation
resources.instanceBuffer = nullptr;
if (resources.instanceBufferAllocation) {
try { memoryPool->deallocate(std::move(resources.instanceBufferAllocation)); }
catch (const std::exception& e) {
std::cerr << "Warning: failed to deallocate instance buffer allocation during Cleanup: " << e.what() << std::endl;
}
}
resources.instanceBufferMapped = nullptr;
}
entityResources.clear();
// Release light storage buffers
for (auto& lsb : lightStorageBuffers) {
lsb.buffer = nullptr;
if (lsb.allocation) {
try { memoryPool->deallocate(std::move(lsb.allocation)); }
catch (const std::exception& e) {
std::cerr << "Warning: failed to deallocate light storage buffer during Cleanup: " << e.what() << std::endl;
}
}
lsb.mapped = nullptr;
lsb.capacity = 0;
lsb.size = 0;
}
lightStorageBuffers.clear();
// Release mesh device-local buffers and return pooled allocations
for (auto& [mesh, mres] : meshResources) {
mres.vertexBuffer = nullptr;
if (mres.vertexBufferAllocation) {
try { memoryPool->deallocate(std::move(mres.vertexBufferAllocation)); }
catch (const std::exception& e) {
std::cerr << "Warning: failed to deallocate vertex buffer allocation during Cleanup: " << e.what() << std::endl;
}
}
mres.indexBuffer = nullptr;
if (mres.indexBufferAllocation) {
try { memoryPool->deallocate(std::move(mres.indexBufferAllocation)); }
catch (const std::exception& e) {
std::cerr << "Warning: failed to deallocate index buffer allocation during Cleanup: " << e.what() << std::endl;
}
}
// Staging buffers are RAII and not pooled
mres.stagingVertexBuffer = nullptr;
mres.stagingVertexBufferMemory = nullptr;
mres.stagingIndexBuffer = nullptr;
mres.stagingIndexBufferMemory = nullptr;
mres.vertexBufferSizeBytes = 0;
mres.indexBufferSizeBytes = 0;
mres.indexCount = 0;
}
meshResources.clear();
// Release textures and return pooled allocations
{
std::unique_lock<std::shared_mutex> texLock(textureResourcesMutex);
for (auto& [key, tres] : textureResources) {
tres.textureSampler = nullptr;
tres.textureImageView = nullptr;
tres.textureImage = nullptr;
if (tres.textureImageAllocation) {
try { memoryPool->deallocate(std::move(tres.textureImageAllocation)); }
catch (const std::exception& e) {
std::cerr << "Warning: failed to deallocate texture image allocation during Cleanup: " << e.what() << std::endl;
}
}
}
textureResources.clear();
textureAliases.clear();
textureToEntities.clear();
}
// Release default texture resources if allocated
defaultTextureResources.textureSampler = nullptr;
defaultTextureResources.textureImageView = nullptr;
defaultTextureResources.textureImage = nullptr;
if (defaultTextureResources.textureImageAllocation) {
try { memoryPool->deallocate(std::move(defaultTextureResources.textureImageAllocation)); }
catch (const std::exception& e) {
std::cerr << "Warning: failed to deallocate default texture image allocation during Cleanup: " << e.what() << std::endl;
}
}
// Also clear global descriptor sets that are allocated from descriptorPool, so they are
// destroyed while the pool is still valid (avoid vkFreeDescriptorSets invalid pool errors)
transparentDescriptorSets.clear();
transparentFallbackDescriptorSets.clear();
computeDescriptorSets.clear();
std::cout << "Renderer cleanup completed." << std::endl;
initialized = false;
}
}
// Create instance
bool Renderer::createInstance(const std::string& appName, bool enableValidationLayers) {
try {
// Create application info
vk::ApplicationInfo appInfo{
.pApplicationName = appName.c_str(),
.applicationVersion = VK_MAKE_VERSION(1, 0, 0),
.pEngineName = "Simple Engine",
.engineVersion = VK_MAKE_VERSION(1, 0, 0),
.apiVersion = VK_API_VERSION_1_3
};
// Get required extensions
std::vector<const char*> extensions;
// Add required extensions for GLFW
#if defined(PLATFORM_DESKTOP)
uint32_t glfwExtensionCount = 0;
const char** glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount);
extensions.insert(extensions.end(), glfwExtensions, glfwExtensions + glfwExtensionCount);
#endif
// Add debug extension if validation layers are enabled
if (enableValidationLayers) {
extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
}
// Create instance info
vk::InstanceCreateInfo createInfo{
.pApplicationInfo = &appInfo,
.enabledExtensionCount = static_cast<uint32_t>(extensions.size()),
.ppEnabledExtensionNames = extensions.data()
};
// Enable validation layers if requested
vk::ValidationFeaturesEXT validationFeatures{};
std::vector<vk::ValidationFeatureEnableEXT> enabledValidationFeatures;
if (enableValidationLayers) {
if (!checkValidationLayerSupport()) {
std::cerr << "Validation layers requested, but not available" << std::endl;
return false;
}
createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
createInfo.ppEnabledLayerNames = validationLayers.data();
// Enable debug printf functionality for shader debugging
enabledValidationFeatures.push_back(vk::ValidationFeatureEnableEXT::eDebugPrintf);
validationFeatures.enabledValidationFeatureCount = static_cast<uint32_t>(enabledValidationFeatures.size());
validationFeatures.pEnabledValidationFeatures = enabledValidationFeatures.data();
createInfo.pNext = &validationFeatures;
}
// Create instance
instance = vk::raii::Instance(context, createInfo);
return true;
} catch (const std::exception& e) {
std::cerr << "Failed to create instance: " << e.what() << std::endl;
return false;
}
}
// Setup debug messenger
bool Renderer::setupDebugMessenger(bool enableValidationLayers) {
if (!enableValidationLayers) {
return true;
}
try {
// Create debug messenger info
vk::DebugUtilsMessengerCreateInfoEXT createInfo{
.messageSeverity = vk::DebugUtilsMessageSeverityFlagBitsEXT::eVerbose |
vk::DebugUtilsMessageSeverityFlagBitsEXT::eInfo |
vk::DebugUtilsMessageSeverityFlagBitsEXT::eWarning |
vk::DebugUtilsMessageSeverityFlagBitsEXT::eError,
.messageType = vk::DebugUtilsMessageTypeFlagBitsEXT::eGeneral |
vk::DebugUtilsMessageTypeFlagBitsEXT::eValidation |
vk::DebugUtilsMessageTypeFlagBitsEXT::ePerformance,
.pfnUserCallback = debugCallbackVkRaii
};
// Create debug messenger
debugMessenger = vk::raii::DebugUtilsMessengerEXT(instance, createInfo);
return true;
} catch (const std::exception& e) {
std::cerr << "Failed to set up debug messenger: " << e.what() << std::endl;
return false;
}
}
// Create surface
bool Renderer::createSurface() {
try {
// Create surface
VkSurfaceKHR _surface;
if (!platform->CreateVulkanSurface(*instance, &_surface)) {
std::cerr << "Failed to create window surface" << std::endl;
return false;
}
surface = vk::raii::SurfaceKHR(instance, _surface);
return true;
} catch (const std::exception& e) {
std::cerr << "Failed to create surface: " << e.what() << std::endl;
return false;
}
}
// Pick a physical device
bool Renderer::pickPhysicalDevice() {
try {
// Get available physical devices
std::vector<vk::raii::PhysicalDevice> devices = instance.enumeratePhysicalDevices();
if (devices.empty()) {
std::cerr << "Failed to find GPUs with Vulkan support" << std::endl;
return false;
}
// Prioritize discrete GPUs (like NVIDIA RTX 2080) over integrated GPUs (like Intel UHD Graphics)
// First, collect all suitable devices with their suitability scores
std::multimap<int, vk::raii::PhysicalDevice> suitableDevices;
for (auto& _device : devices) {
// Print device properties for debugging
vk::PhysicalDeviceProperties deviceProperties = _device.getProperties();
std::cout << "Checking device: " << deviceProperties.deviceName
<< " (Type: " << vk::to_string(deviceProperties.deviceType) << ")" << std::endl;
// Check if the device supports Vulkan 1.3
bool supportsVulkan1_3 = deviceProperties.apiVersion >= VK_API_VERSION_1_3;
if (!supportsVulkan1_3) {
std::cout << " - Does not support Vulkan 1.3" << std::endl;
continue;
}
// Check queue families
QueueFamilyIndices indices = findQueueFamilies(_device);
bool supportsGraphics = indices.isComplete();
if (!supportsGraphics) {
std::cout << " - Missing required queue families" << std::endl;
continue;
}
// Check device extensions
bool supportsAllRequiredExtensions = checkDeviceExtensionSupport(_device);
if (!supportsAllRequiredExtensions) {
std::cout << " - Missing required extensions" << std::endl;
continue;
}
// Check swap chain support
SwapChainSupportDetails swapChainSupport = querySwapChainSupport(_device);
bool swapChainAdequate = !swapChainSupport.formats.empty() && !swapChainSupport.presentModes.empty();
if (!swapChainAdequate) {
std::cout << " - Inadequate swap chain support" << std::endl;
continue;
}
// Check for required features
auto features = _device.getFeatures2<vk::PhysicalDeviceFeatures2, vk::PhysicalDeviceVulkan13Features>();
bool supportsRequiredFeatures = features.get<vk::PhysicalDeviceVulkan13Features>().dynamicRendering;
if (!supportsRequiredFeatures) {
std::cout << " - Does not support required features (dynamicRendering)" << std::endl;
continue;
}
// Calculate suitability score - prioritize discrete GPUs
int score = 0;
// Discrete GPUs get the highest priority (NVIDIA RTX 2080, AMD, etc.)
if (deviceProperties.deviceType == vk::PhysicalDeviceType::eDiscreteGpu) {
score += 1000;
std::cout << " - Discrete GPU: +1000 points" << std::endl;
}
// Integrated GPUs get lower priority (Intel UHD Graphics, etc.)
else if (deviceProperties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu) {
score += 100;
std::cout << " - Integrated GPU: +100 points" << std::endl;
}
// Add points for memory size (more VRAM is better)
vk::PhysicalDeviceMemoryProperties memProperties = _device.getMemoryProperties();
for (uint32_t i = 0; i < memProperties.memoryHeapCount; i++) {
if (memProperties.memoryHeaps[i].flags & vk::MemoryHeapFlagBits::eDeviceLocal) {
// Add 1 point per GB of VRAM
score += static_cast<int>(memProperties.memoryHeaps[i].size / (1024 * 1024 * 1024));
break;
}
}
std::cout << " - Device is suitable with score: " << score << std::endl;
suitableDevices.emplace(score, _device);
}
if (!suitableDevices.empty()) {
// Select the device with the highest score (discrete GPU with most VRAM)
physicalDevice = suitableDevices.rbegin()->second;
vk::PhysicalDeviceProperties deviceProperties = physicalDevice.getProperties();
std::cout << "Selected device: " << deviceProperties.deviceName
<< " (Type: " << vk::to_string(deviceProperties.deviceType)
<< ", Score: " << suitableDevices.rbegin()->first << ")" << std::endl;
// Store queue family indices for the selected device
queueFamilyIndices = findQueueFamilies(physicalDevice);
// Add supported optional extensions
addSupportedOptionalExtensions();
return true;
}
std::cerr << "Failed to find a suitable GPU. Make sure your GPU supports Vulkan and has the required extensions." << std::endl;
return false;
} catch (const std::exception& e) {
std::cerr << "Failed to pick physical device: " << e.what() << std::endl;
return false;
}
}
// Add supported optional extensions
void Renderer::addSupportedOptionalExtensions() {
try {
// Get available extensions
auto availableExtensions = physicalDevice.enumerateDeviceExtensionProperties();
// Build a set of available extension names for quick lookup
std::set<std::string> avail;
for (const auto& e : availableExtensions) { avail.insert(e.extensionName); }
// First, handle dependency: VK_EXT_attachment_feedback_loop_dynamic_state requires VK_EXT_attachment_feedback_loop_layout
const char* dynState = VK_EXT_ATTACHMENT_FEEDBACK_LOOP_DYNAMIC_STATE_EXTENSION_NAME;
const char* layoutReq = "VK_EXT_attachment_feedback_loop_layout";
bool dynSupported = avail.contains(dynState);
bool layoutSupported = avail.contains(layoutReq);
for (const auto& optionalExt : optionalDeviceExtensions) {
if (std::strcmp(optionalExt, dynState) == 0) {
if (dynSupported && layoutSupported) {
deviceExtensions.push_back(dynState);
deviceExtensions.push_back(layoutReq);
std::cout << "Adding optional extension: " << dynState << std::endl;
std::cout << "Adding required-by-optional extension: " << layoutReq << std::endl;
} else if (dynSupported && !layoutSupported) {
std::cout << "Skipping extension due to missing dependency: " << dynState << " requires " << layoutReq << std::endl;
}
continue; // handled
}
if (avail.contains(optionalExt)) {
deviceExtensions.push_back(optionalExt);
std::cout << "Adding optional extension: " << optionalExt << std::endl;
}
}
} catch (const std::exception& e) {
std::cerr << "Warning: Failed to add optional extensions: " << e.what() << std::endl;
}
}
// Create logical device
bool Renderer::createLogicalDevice(bool enableValidationLayers) {
try {
// Create queue create info for each unique queue family
std::vector<vk::DeviceQueueCreateInfo> queueCreateInfos;
std::set uniqueQueueFamilies = {
queueFamilyIndices.graphicsFamily.value(),
queueFamilyIndices.presentFamily.value(),
queueFamilyIndices.computeFamily.value(),
queueFamilyIndices.transferFamily.value()
};
float queuePriority = 1.0f;
for (uint32_t queueFamily : uniqueQueueFamilies) {
vk::DeviceQueueCreateInfo queueCreateInfo{
.queueFamilyIndex = queueFamily,
.queueCount = 1,
.pQueuePriorities = &queuePriority
};
queueCreateInfos.push_back(queueCreateInfo);
}
// Enable required features
auto features = physicalDevice.getFeatures2();
features.features.samplerAnisotropy = vk::True;
features.features.depthBiasClamp = vk::True;
// Explicitly configure device features to prevent validation layer warnings
// These features are required by extensions or other features, so we enable them explicitly
// Timeline semaphore features (required for synchronization2)
vk::PhysicalDeviceTimelineSemaphoreFeatures timelineSemaphoreFeatures;
timelineSemaphoreFeatures.timelineSemaphore = vk::True;
// Vulkan memory model features (required for some shader operations)
vk::PhysicalDeviceVulkanMemoryModelFeatures memoryModelFeatures;
memoryModelFeatures.vulkanMemoryModel = vk::True;
memoryModelFeatures.vulkanMemoryModelDeviceScope = vk::True;
// Buffer device address features (required for some buffer operations)
vk::PhysicalDeviceBufferDeviceAddressFeatures bufferDeviceAddressFeatures;
bufferDeviceAddressFeatures.bufferDeviceAddress = vk::True;
// 8-bit storage features (required for some shader storage operations)
vk::PhysicalDevice8BitStorageFeatures storage8BitFeatures;
storage8BitFeatures.storageBuffer8BitAccess = vk::True;
// Enable Vulkan 1.3 features
vk::PhysicalDeviceVulkan13Features vulkan13Features;
vulkan13Features.dynamicRendering = vk::True;
vulkan13Features.synchronization2 = vk::True;
// Chain the feature structures together
timelineSemaphoreFeatures.pNext = &memoryModelFeatures;
memoryModelFeatures.pNext = &bufferDeviceAddressFeatures;
bufferDeviceAddressFeatures.pNext = &storage8BitFeatures;
storage8BitFeatures.pNext = &vulkan13Features;
features.pNext = &timelineSemaphoreFeatures;
// Create a device. Device layers are deprecated and ignored, so we
// only configure extensions and features here; validation is enabled
// via instance layers.
vk::DeviceCreateInfo createInfo{
.pNext = &features,
.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size()),
.pQueueCreateInfos = queueCreateInfos.data(),
.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size()),
.ppEnabledExtensionNames = deviceExtensions.data(),
.pEnabledFeatures = nullptr // Using pNext for features
};
// Create the logical device
device = vk::raii::Device(physicalDevice, createInfo);
// Get queue handles
graphicsQueue = vk::raii::Queue(device, queueFamilyIndices.graphicsFamily.value(), 0);
presentQueue = vk::raii::Queue(device, queueFamilyIndices.presentFamily.value(), 0);
computeQueue = vk::raii::Queue(device, queueFamilyIndices.computeFamily.value(), 0);
transferQueue = vk::raii::Queue(device, queueFamilyIndices.transferFamily.value(), 0);
// Create global timeline semaphore for uploads early (needed before default texture creation)
vk::SemaphoreTypeCreateInfo typeInfo{
.semaphoreType = vk::SemaphoreType::eTimeline,
.initialValue = 0
};
vk::SemaphoreCreateInfo timelineCreateInfo{ .pNext = &typeInfo };
uploadsTimeline = vk::raii::Semaphore(device, timelineCreateInfo);
uploadTimelineLastSubmitted.store(0, std::memory_order_relaxed);
return true;
} catch (const std::exception& e) {
std::cerr << "Failed to create logical device: " << e.what() << std::endl;
return false;
}
}
// Check validation layer support
bool Renderer::checkValidationLayerSupport() const {
// Get available layers
std::vector<vk::LayerProperties> availableLayers = context.enumerateInstanceLayerProperties();
// Check if all requested layers are available
for (const char* layerName : validationLayers) {
bool layerFound = false;
for (const auto& layerProperties : availableLayers) {
if (strcmp(layerName, layerProperties.layerName) == 0) {
layerFound = true;
break;
}
}
if (!layerFound) {
return false;
}
}
return true;
}