| 1 | #define VK_USE_PLATFORM_XCB_KHR |
| 2 | #define VK_USE_PLATFORM_XLIB_KHR |
| 3 | #define VK_USE_PLATFORM_WAYLAND_KHR |
| 4 | #include "vulkan.h" |
| 5 | #include "vk_layer.h" |
| 6 | |
| 7 | #include "primus_vk_dispatch_table.h" |
| 8 | |
| 9 | #include <cassert> |
| 10 | #include <cstring> |
| 11 | |
| 12 | #include <mutex> |
| 13 | #include <condition_variable> |
| 14 | #include <map> |
| 15 | #include <vector> |
| 16 | #include <list> |
| 17 | #include <iostream> |
| 18 | |
| 19 | #include <pthread.h> |
| 20 | |
| 21 | #include <stdexcept> |
| 22 | |
| 23 | #include <dlfcn.h> |
| 24 | |
| 25 | #include <vector> |
| 26 | #include <memory> |
| 27 | #include <thread> |
| 28 | #include <algorithm> |
| 29 | #include <sstream> |
| 30 | #include <string> |
| 31 | #include <chrono> |
| 32 | #include <functional> |
| 33 | |
| 34 | #include <X11/extensions/Xrandr.h> |
| 35 | |
| 36 | #undef VK_LAYER_EXPORT |
| 37 | #if defined(WIN32) |
| 38 | #define VK_LAYER_EXPORT extern "C" __declspec(dllexport) |
| 39 | #else |
| 40 | #define VK_LAYER_EXPORT extern "C" |
| 41 | #endif |
| 42 | |
| 43 | // single global lock, for simplicity |
| 44 | std::mutex global_lock; |
| 45 | typedef std::lock_guard<std::mutex> scoped_lock; |
| 46 | |
| 47 | // use the loader's dispatch table pointer as a key for dispatch map lookups |
| 48 | template<typename DispatchableType> |
| 49 | void *&GetKey(DispatchableType inst) |
| 50 | { |
| 51 | return *(void **)inst; |
| 52 | } |
| 53 | |
| 54 | class CreateOtherDevice; |
| 55 | |
| 56 | // #define TRACE(x) |
| 57 | #define TRACE(x) std::cerr << "PrimusVK: " << x << "\n"; |
| 58 | #define TRACE_PROFILING(x) |
| 59 | // #define TRACE_PROFILING(x) std::cout << "PrimusVK: " << x << "\n"; |
| 60 | #define TRACE_PROFILING_EVENT(x, y) |
| 61 | // #define TRACE_PROFILING_EVENT(idx, evt) std::cout << "PrimusVK-profiling: " << idx << " " << std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now() - primus_start).count() << " " << evt << "\n"; |
| 62 | #define TRACE_FRAME(x) |
| 63 | // #define TRACE_FRAME(x) std::cout << "PrimusVK: " << x << "\n"; |
| 64 | |
| 65 | #define VK_CHECK_RESULT(x) do{ const VkResult r = x; if(r != VK_SUCCESS){printf("PrimusVK: Error %d in line %d.\n", r, __LINE__);}}while(0); |
| 66 | // #define VK_CHECK_RESULT(x) if(x != VK_SUCCESS){printf("Error %d, in %d\n", x, __LINE__);} |
| 67 | |
| 68 | struct InstanceInfo { |
| 69 | public: |
| 70 | VkInstance instance; |
| 71 | PFN_vkLayerCreateDevice layerCreateDevice; |
| 72 | PFN_vkLayerDestroyDevice layerDestroyDevice; |
| 73 | |
| 74 | VkPhysicalDevice render = VK_NULL_HANDLE; |
| 75 | uint32_t renderQueueFamilyIndex = 0; |
| 76 | VkPhysicalDevice display = VK_NULL_HANDLE; |
| 77 | uint32_t displayQueueFamilyIndex = 0; |
| 78 | std::map<void*, std::shared_ptr<CreateOtherDevice>> cod = {}; |
| 79 | |
| 80 | std::shared_ptr<std::mutex> renderQueueMutex = std::make_shared<std::mutex>(); |
| 81 | InstanceInfo() = default; |
| 82 | InstanceInfo(const InstanceInfo &) = delete; |
| 83 | InstanceInfo(InstanceInfo &&) = default; |
| 84 | InstanceInfo(VkInstance instance, |
| 85 | PFN_vkLayerCreateDevice layerCreateDevice, |
| 86 | PFN_vkLayerDestroyDevice layerDestroyDevice) : instance(instance), layerCreateDevice(layerCreateDevice), layerDestroyDevice(layerDestroyDevice) { |
| 87 | } |
| 88 | InstanceInfo &operator=(InstanceInfo &&) = default; |
| 89 | private: |
| 90 | void GetEnvVendorDeviceIDs(std::string env, uint32_t &vendor, uint32_t &device) { |
| 91 | char *envstr = getenv(env.c_str()); |
| 92 | if(envstr != nullptr){ |
| 93 | std::stringstream ss(envstr); |
| 94 | std::string item; |
| 95 | std::vector<uint32_t> hexnums(2); |
| 96 | int i = 0; |
| 97 | while(std::getline(ss, item, ':') && (i < 2)) { |
| 98 | uint32_t num = 0; |
| 99 | std::stringstream _ss; |
| 100 | _ss << std::hex << item; |
| 101 | _ss >> num; |
| 102 | hexnums[i] = num; |
| 103 | ++i; |
| 104 | } |
| 105 | vendor = hexnums[0]; |
| 106 | device = hexnums[1]; |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | bool IsDevice( |
| 111 | VkPhysicalDeviceProperties props, |
| 112 | uint32_t vendor, |
| 113 | uint32_t device, |
| 114 | VkPhysicalDeviceType type = VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU) { |
| 115 | if((vendor == 0) && (props.deviceType == type)){ |
| 116 | if(type == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU){ |
| 117 | TRACE("Got integrated gpu!"); |
| 118 | } else { |
| 119 | TRACE("Got discrete gpu!"); |
| 120 | } |
| 121 | TRACE("Device: " << props.deviceName); |
| 122 | TRACE(" Type: " << props.deviceType); |
| 123 | return true; |
| 124 | } |
| 125 | if((props.vendorID == vendor) && (props.deviceID == device)){ |
| 126 | TRACE("Got device from env!"); |
| 127 | TRACE("Device: " << props.deviceName); |
| 128 | TRACE(" Type: " << props.deviceType); |
| 129 | return true; |
| 130 | } |
| 131 | if(props.vendorID == vendor && device == 0){ |
| 132 | TRACE("Got device from env! (via vendorID)"); |
| 133 | TRACE("Device: " << props.deviceName); |
| 134 | TRACE(" Type: " << props.deviceType); |
| 135 | return true; |
| 136 | } |
| 137 | return false; |
| 138 | } |
| 139 | |
| 140 | public: |
| 141 | VkResult searchDevices(PvkInstanceDispatchTable &dispatchTable){ |
| 142 | uint32_t displayVendorID = 0; |
| 143 | uint32_t displayDeviceID = 0; |
| 144 | uint32_t renderVendorID = 0; |
| 145 | uint32_t renderDeviceID = 0; |
| 146 | GetEnvVendorDeviceIDs("PRIMUS_VK_DISPLAYID", displayVendorID, displayDeviceID); |
| 147 | GetEnvVendorDeviceIDs("PRIMUS_VK_RENDERID", renderVendorID, renderDeviceID); |
| 148 | |
| 149 | std::vector<VkPhysicalDevice> physicalDevices; |
| 150 | { |
| 151 | auto enumerateDevices = dispatchTable.EnumeratePhysicalDevices; |
| 152 | uint32_t gpuCount = 0; |
| 153 | enumerateDevices(instance, &gpuCount, nullptr); |
| 154 | physicalDevices.resize(gpuCount); |
| 155 | enumerateDevices(instance, &gpuCount, physicalDevices.data()); |
| 156 | } |
| 157 | |
| 158 | TRACE("Searching for display GPU:"); |
| 159 | for(auto &dev: physicalDevices){ |
| 160 | VkPhysicalDeviceProperties props; |
| 161 | dispatchTable.GetPhysicalDeviceProperties(dev, &props); |
| 162 | TRACE(dev << ": " << props.vendorID << ";" << props.deviceID); |
| 163 | if(IsDevice(props, displayVendorID, displayDeviceID, VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU)){ |
| 164 | display = dev; |
| 165 | break; |
| 166 | } |
| 167 | } |
| 168 | |
| 169 | TRACE("Searching for render GPU:"); |
| 170 | for(auto &dev: physicalDevices){ |
| 171 | VkPhysicalDeviceProperties props; |
| 172 | dispatchTable.GetPhysicalDeviceProperties(dev, &props); |
| 173 | TRACE(dev << "."); |
| 174 | if(IsDevice(props, renderVendorID, renderDeviceID)){ |
| 175 | render = dev; |
| 176 | break; |
| 177 | } |
| 178 | } |
| 179 | if(display == VK_NULL_HANDLE || render == VK_NULL_HANDLE){ |
| 180 | const auto c_icd_filenames = getenv("VK_ICD_FILENAMES"); |
| 181 | if(display == VK_NULL_HANDLE) { |
| 182 | TRACE("No device for the display GPU found. Are the intel-mesa drivers installed?"); |
| 183 | } |
| 184 | if(render == VK_NULL_HANDLE) { |
| 185 | TRACE("No device for the rendering GPU found. Is the correct driver installed?"); |
| 186 | } |
| 187 | if(c_icd_filenames != nullptr) { |
| 188 | TRACE("VK_ICD_FILENAMES=" << c_icd_filenames); |
| 189 | } else { |
| 190 | TRACE("VK_ICD_FILENAMES not set"); |
| 191 | } |
| 192 | return VK_ERROR_INITIALIZATION_FAILED; |
| 193 | } |
| 194 | auto ret = getQueueFamilyIndex(display, dispatchTable, &displayQueueFamilyIndex); |
| 195 | if(ret != VK_SUCCESS){ |
| 196 | return ret; |
| 197 | } |
| 198 | ret = getQueueFamilyIndex(render, dispatchTable, &renderQueueFamilyIndex); |
| 199 | if(ret != VK_SUCCESS){ |
| 200 | return ret; |
| 201 | } |
| 202 | return VK_SUCCESS; |
| 203 | } |
| 204 | VkResult getQueueFamilyIndex(VkPhysicalDevice device, PvkInstanceDispatchTable &dispatchTable, uint32_t *queueFamilyIndex) { |
| 205 | uint32_t display_queue_count = 0; |
| 206 | dispatchTable.GetPhysicalDeviceQueueFamilyProperties(device, &display_queue_count, nullptr); |
| 207 | auto displayQueueProperties = std::vector<VkQueueFamilyProperties>(display_queue_count); |
| 208 | dispatchTable.GetPhysicalDeviceQueueFamilyProperties(device, &display_queue_count, displayQueueProperties.data()); |
| 209 | VkQueueFlags requiredFlags = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT | VK_QUEUE_TRANSFER_BIT; |
| 210 | bool found = false; |
| 211 | while(*queueFamilyIndex < displayQueueProperties.size()){ |
| 212 | auto &prop = displayQueueProperties[*queueFamilyIndex]; |
| 213 | if((prop.queueFlags & requiredFlags) == requiredFlags){ |
| 214 | found = true; |
| 215 | break; |
| 216 | } |
| 217 | (*queueFamilyIndex)++; |
| 218 | } |
| 219 | if(!found) { |
| 220 | TRACE("No fitting queue found out of: " << display_queue_count); |
| 221 | return VK_ERROR_INITIALIZATION_FAILED; |
| 222 | } |
| 223 | return VK_SUCCESS; |
| 224 | } |
| 225 | }; |
| 226 | |
| 227 | std::map<void *, PvkInstanceDispatchTable> instance_dispatch; |
| 228 | // VkInstance->disp is beeing malloc'ed for every new instance |
| 229 | // so we can assume it to be a good key. |
| 230 | std::map<void *, InstanceInfo> instance_info; |
| 231 | |
| 232 | std::map<void *, InstanceInfo*> device_instance_info; |
| 233 | std::map<void *, PvkDispatchTable> device_dispatch; |
| 234 | |
| 235 | /////////////////////////////////////////////////////////////////////////////////////////// |
| 236 | // Layer init and shutdown |
| 237 | PvkDispatchTable fetchDispatchTable(PFN_vkGetDeviceProcAddr gdpa, VkDevice *pDevice); |
| 238 | VK_LAYER_EXPORT PFN_vkVoidFunction VKAPI_CALL PrimusVK_GetInstanceProcAddr(VkInstance instance, const char *pName); |
| 239 | VkResult VKAPI_CALL PrimusVK_CreateInstance( |
| 240 | const VkInstanceCreateInfo* pCreateInfo, |
| 241 | const VkAllocationCallbacks* pAllocator, |
| 242 | VkInstance* pInstance) |
| 243 | { |
| 244 | VkLayerInstanceCreateInfo *layer_link_info = nullptr; |
| 245 | PFN_vkLayerCreateDevice layerCreateDevice = nullptr; |
| 246 | PFN_vkLayerDestroyDevice layerDestroyDevice = nullptr; |
| 247 | VkLayerInstanceCreateInfo *layerCreateInfo = (VkLayerInstanceCreateInfo *)pCreateInfo->pNext; |
| 248 | |
| 249 | while(layerCreateInfo) { |
| 250 | if ( layerCreateInfo->sType == VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO && layerCreateInfo->function == VK_LAYER_LINK_INFO) { |
| 251 | layer_link_info = layerCreateInfo; |
| 252 | } |
| 253 | if ( layerCreateInfo->sType == VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO && layerCreateInfo->function == VK_LOADER_LAYER_CREATE_DEVICE_CALLBACK) { |
| 254 | layerCreateDevice = layerCreateInfo->u.layerDevice.pfnLayerCreateDevice; |
| 255 | layerDestroyDevice = layerCreateInfo->u.layerDevice.pfnLayerDestroyDevice; |
| 256 | } |
| 257 | layerCreateInfo = (VkLayerInstanceCreateInfo *)layerCreateInfo->pNext; |
| 258 | } |
| 259 | |
| 260 | if(layer_link_info == nullptr) { |
| 261 | return VK_ERROR_INITIALIZATION_FAILED; |
| 262 | } |
| 263 | if(layerCreateDevice == nullptr || layerDestroyDevice == nullptr) { |
| 264 | TRACE("Loader did not supply layer device creation callbacks. Please upgrade to vulkan >= 1.1.108"); |
| 265 | return VK_ERROR_INITIALIZATION_FAILED; |
| 266 | } |
| 267 | |
| 268 | PFN_vkGetInstanceProcAddr gpa = layer_link_info->u.pLayerInfo->pfnNextGetInstanceProcAddr; |
| 269 | layer_link_info->u.pLayerInfo = layer_link_info->u.pLayerInfo->pNext; |
| 270 | |
| 271 | PFN_vkCreateInstance createFunc = (PFN_vkCreateInstance)gpa(VK_NULL_HANDLE, "vkCreateInstance"); |
| 272 | VK_CHECK_RESULT( createFunc(pCreateInfo, pAllocator, pInstance) ); |
| 273 | |
| 274 | // fetch our own dispatch table for the functions we need, into the next layer |
| 275 | PvkInstanceDispatchTable dispatchTable = {pInstance, gpa}; |
| 276 | auto my_instance_info = InstanceInfo{*pInstance, layerCreateDevice, layerDestroyDevice}; |
| 277 | |
| 278 | // store the table by key |
| 279 | { |
| 280 | scoped_lock l(global_lock); |
| 281 | |
| 282 | instance_dispatch.insert({GetKey(*pInstance), dispatchTable}); |
| 283 | instance_info[GetKey(*pInstance)] = std::move(my_instance_info); |
| 284 | } |
| 285 | |
| 286 | return VK_SUCCESS; |
| 287 | } |
| 288 | |
| 289 | void VKAPI_CALL PrimusVK_DestroyInstance(VkInstance instance, const VkAllocationCallbacks* pAllocator) |
| 290 | { |
| 291 | scoped_lock l(global_lock); |
| 292 | |
| 293 | auto instance_key = GetKey(instance); |
| 294 | instance_dispatch[GetKey(instance)].DestroyInstance(instance, pAllocator); |
| 295 | instance_dispatch.erase(instance_key); |
| 296 | instance_info.erase(instance_key); |
| 297 | } |
| 298 | |
| 299 | struct FramebufferImage; |
| 300 | struct MappedMemory{ |
| 301 | VkDevice device; |
| 302 | VkDeviceMemory mem; |
| 303 | char* data; |
| 304 | MappedMemory(VkDevice device, FramebufferImage &img); |
| 305 | ~MappedMemory(); |
| 306 | }; |
| 307 | struct FramebufferImage { |
| 308 | VkImage img; |
| 309 | VkDeviceMemory mem; |
| 310 | |
| 311 | VkDevice device; |
| 312 | |
| 313 | std::shared_ptr<MappedMemory> mapped; |
| 314 | FramebufferImage(FramebufferImage &) = delete; |
| 315 | FramebufferImage(VkDevice device, VkExtent2D size, VkImageTiling tiling, VkImageUsageFlags usage, VkFormat format, std::function<uint32_t(uint32_t memory_type_bits)> memoryTypeIndex): device(device){ |
| 316 | TRACE("Creating image: " << size.width << "x" << size.height); |
| 317 | VkImageCreateInfo imageCreateCI {}; |
| 318 | imageCreateCI.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; |
| 319 | imageCreateCI.imageType = VK_IMAGE_TYPE_2D; |
| 320 | imageCreateCI.format = format; |
| 321 | imageCreateCI.extent.width = size.width; |
| 322 | imageCreateCI.extent.height = size.height; |
| 323 | imageCreateCI.extent.depth = 1; |
| 324 | imageCreateCI.arrayLayers = 1; |
| 325 | imageCreateCI.mipLevels = 1; |
| 326 | imageCreateCI.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; |
| 327 | imageCreateCI.samples = VK_SAMPLE_COUNT_1_BIT; |
| 328 | imageCreateCI.tiling = tiling; |
| 329 | imageCreateCI.usage = usage; |
| 330 | VK_CHECK_RESULT(device_dispatch[GetKey(device)].CreateImage(device, &imageCreateCI, nullptr, &img)); |
| 331 | |
| 332 | VkMemoryRequirements memRequirements {}; |
| 333 | VkMemoryAllocateInfo memAllocInfo {.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; |
| 334 | device_dispatch[GetKey(device)].GetImageMemoryRequirements(device, img, &memRequirements); |
| 335 | memAllocInfo.allocationSize = memRequirements.size; |
| 336 | memAllocInfo.memoryTypeIndex = memoryTypeIndex(memRequirements.memoryTypeBits); |
| 337 | VK_CHECK_RESULT(device_dispatch[GetKey(device)].AllocateMemory(device, &memAllocInfo, nullptr, &mem)); |
| 338 | VK_CHECK_RESULT(device_dispatch[GetKey(device)].BindImageMemory(device, img, mem, 0)); |
| 339 | } |
| 340 | std::shared_ptr<MappedMemory> getMapped(){ |
| 341 | if(!mapped){ |
| 342 | throw std::runtime_error("not mapped"); |
| 343 | } |
| 344 | return mapped; |
| 345 | } |
| 346 | void map(){ |
| 347 | mapped = std::make_shared<MappedMemory>(device, *this); |
| 348 | } |
| 349 | VkSubresourceLayout getLayout(){ |
| 350 | VkImageSubresource subResource { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0 }; |
| 351 | VkSubresourceLayout subResourceLayout; |
| 352 | device_dispatch[GetKey(device)].GetImageSubresourceLayout(device, img, &subResource, &subResourceLayout); |
| 353 | return subResourceLayout; |
| 354 | } |
| 355 | ~FramebufferImage(){ |
| 356 | mapped.reset(); |
| 357 | device_dispatch[GetKey(device)].FreeMemory(device, mem, nullptr); |
| 358 | device_dispatch[GetKey(device)].DestroyImage(device, img, nullptr); |
| 359 | } |
| 360 | }; |
| 361 | MappedMemory::MappedMemory(VkDevice device, FramebufferImage &img): device(device), mem(img.mem){ |
| 362 | device_dispatch[GetKey(device)].MapMemory(device, img.mem, 0, VK_WHOLE_SIZE, 0, (void**)&data); |
| 363 | } |
| 364 | MappedMemory::~MappedMemory(){ |
| 365 | device_dispatch[GetKey(device)].UnmapMemory(device, mem); |
| 366 | } |
| 367 | class CommandBuffer; |
| 368 | class Fence{ |
| 369 | VkDevice device; |
| 370 | public: |
| 371 | VkFence fence; |
| 372 | Fence(VkDevice dev): device(dev){ |
| 373 | // Create fence to ensure that the command buffer has finished executing |
| 374 | VkFenceCreateInfo fenceInfo = {.sType=VK_STRUCTURE_TYPE_FENCE_CREATE_INFO}; |
| 375 | fenceInfo.flags = 0; |
| 376 | VK_CHECK_RESULT(device_dispatch[GetKey(device)].CreateFence(device, &fenceInfo, nullptr, &fence)); |
| 377 | } |
| 378 | void await(){ |
| 379 | // Wait for the fence to signal that command buffer has finished executing |
| 380 | VK_CHECK_RESULT(device_dispatch[GetKey(device)].WaitForFences(device, 1, &fence, VK_TRUE, 10000000000L)); |
| 381 | } |
| 382 | void reset(){ |
| 383 | VK_CHECK_RESULT(device_dispatch[GetKey(device)].ResetFences(device, 1, &fence)); |
| 384 | } |
| 385 | Fence(Fence &&other): device(other.device), fence(other.fence){ |
| 386 | other.fence = VK_NULL_HANDLE; |
| 387 | } |
| 388 | ~Fence(){ |
| 389 | if(fence != VK_NULL_HANDLE){ |
| 390 | device_dispatch[GetKey(device)].DestroyFence(device, fence, nullptr); |
| 391 | } |
| 392 | } |
| 393 | }; |
| 394 | class Semaphore{ |
| 395 | VkDevice device; |
| 396 | public: |
| 397 | VkSemaphore sem; |
| 398 | Semaphore(VkDevice dev): device(dev){ |
| 399 | VkSemaphoreCreateInfo semInfo = {.sType=VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO}; |
| 400 | semInfo.flags = 0; |
| 401 | VK_CHECK_RESULT(device_dispatch[GetKey(device)].CreateSemaphore(device, &semInfo, nullptr, &sem)); |
| 402 | } |
| 403 | Semaphore(Semaphore &&other): device(other.device), sem(other.sem) { |
| 404 | other.sem = VK_NULL_HANDLE; |
| 405 | other.device = VK_NULL_HANDLE; |
| 406 | } |
| 407 | ~Semaphore(){ |
| 408 | if(sem != VK_NULL_HANDLE){ |
| 409 | device_dispatch[GetKey(device)].DestroySemaphore(device, sem, nullptr); |
| 410 | } |
| 411 | } |
| 412 | }; |
| 413 | enum class ImageType : int{ |
| 414 | RENDER_TARGET_IMAGE, |
| 415 | RENDER_COPY_IMAGE, |
| 416 | DISPLAY_IMAGE, |
| 417 | IMAGE_TYPE_COUNT |
| 418 | }; |
| 419 | std::ostream &operator<<( std::ostream &output, const ImageType &type ) { |
| 420 | switch(type){ |
| 421 | case ImageType::RENDER_TARGET_IMAGE: |
| 422 | output << "Render Target Image"; |
| 423 | break; |
| 424 | case ImageType::RENDER_COPY_IMAGE: |
| 425 | output << "Render Copy Image"; |
| 426 | break; |
| 427 | case ImageType::DISPLAY_IMAGE: |
| 428 | output << "Display Image"; |
| 429 | break; |
| 430 | } |
| 431 | return output; |
| 432 | } |
| 433 | struct PrimusSwapchain; |
| 434 | struct ImageWorker { |
| 435 | PrimusSwapchain &swapchain; |
| 436 | |
| 437 | std::shared_ptr<FramebufferImage> render_image; |
| 438 | std::shared_ptr<FramebufferImage> render_copy_image; |
| 439 | std::shared_ptr<FramebufferImage> display_src_image; |
| 440 | Fence render_copy_fence; |
| 441 | Semaphore display_semaphore; |
| 442 | VkImage display_image = VK_NULL_HANDLE; |
| 443 | |
| 444 | std::shared_ptr<CommandBuffer> render_copy_command; |
| 445 | std::shared_ptr<CommandBuffer> display_command; |
| 446 | std::unique_ptr<Fence> display_command_fence; |
| 447 | |
| 448 | ImageWorker(PrimusSwapchain &swapchain, VkImage display_image, const VkSwapchainCreateInfoKHR &createInfo); |
| 449 | ImageWorker(ImageWorker &&other) = default; |
| 450 | ~ImageWorker(); |
| 451 | void initImages( const VkSwapchainCreateInfoKHR &createInfo); |
| 452 | void createCommandBuffers(); |
| 453 | void copyImageData(uint32_t idx, std::vector<VkSemaphore> sems); |
| 454 | }; |
| 455 | struct PrimusSwapchain{ |
| 456 | int max_fps = 0; |
| 457 | InstanceInfo &myInstance; |
| 458 | std::chrono::steady_clock::time_point lastPresent = std::chrono::steady_clock::now(); |
| 459 | VkDevice device; |
| 460 | VkQueue render_queue; |
| 461 | VkDevice display_device; |
| 462 | std::mutex displayQueueMutex; |
| 463 | VkQueue display_queue; |
| 464 | VkSwapchainKHR backend; |
| 465 | std::vector<ImageWorker> images; |
| 466 | VkExtent2D imgSize; |
| 467 | |
| 468 | VkSurfaceCapabilitiesKHR surfaceCapabilities = { }; |
| 469 | |
| 470 | std::vector<std::unique_ptr<std::thread>> threads; |
| 471 | |
| 472 | std::shared_ptr<CreateOtherDevice> cod; |
| 473 | |
| 474 | bool suppress_suboptimal = false; |
| 475 | |
| 476 | PrimusSwapchain(PrimusSwapchain &) = delete; |
| 477 | PrimusSwapchain(InstanceInfo &myInstance, VkDevice device, VkDevice display_device, VkSwapchainKHR backend, const VkSwapchainCreateInfoKHR *pCreateInfo, std::shared_ptr<CreateOtherDevice> &cod): |
| 478 | myInstance(myInstance), device(device), display_device(display_device), backend(backend), cod(cod){ |
| 479 | // TODO automatically find correct queue and not choose 0 forcibly |
| 480 | device_dispatch[GetKey(device)].GetDeviceQueue(device, 0, 0, &render_queue); |
| 481 | device_dispatch[GetKey(display_device)].GetDeviceQueue(display_device, myInstance.displayQueueFamilyIndex, 0, &display_queue); |
| 482 | GetKey(render_queue) = GetKey(device); // TODO, use vkSetDeviceLoaderData instead |
| 483 | GetKey(display_queue) = GetKey(display_device); |
| 484 | |
| 485 | instance_dispatch[GetKey(myInstance.instance)].GetPhysicalDeviceSurfaceCapabilitiesKHR(myInstance.display, pCreateInfo->surface, &surfaceCapabilities); |
| 486 | TRACE("Min Images: " << surfaceCapabilities.minImageCount); |
| 487 | char *max_fps_env = getenv("PRIMUS_VK_MAX_FPS"); |
| 488 | if(max_fps_env != nullptr){ |
| 489 | max_fps = std::stoi(std::string{max_fps_env}); |
| 490 | } |
| 491 | if(getenv("PVK_SUPPRESS_SUBOPTIMAL")){ |
| 492 | suppress_suboptimal = true; |
| 493 | } |
| 494 | |
| 495 | uint32_t image_count; |
| 496 | device_dispatch[GetKey(display_device)].GetSwapchainImagesKHR(display_device, backend, &image_count, nullptr); |
| 497 | TRACE("Image aquiring: " << image_count); |
| 498 | std::vector<VkImage> display_images; |
| 499 | display_images.resize(image_count); |
| 500 | device_dispatch[GetKey(display_device)].GetSwapchainImagesKHR(display_device, backend, &image_count, display_images.data()); |
| 501 | |
| 502 | imgSize = pCreateInfo->imageExtent; |
| 503 | |
| 504 | for(uint32_t i = 0; i < image_count; i++){ |
| 505 | images.emplace_back(*this, display_images[i], *pCreateInfo); |
| 506 | } |
| 507 | |
| 508 | TRACE("Creating a Swapchain thread."); |
| 509 | size_t thread_count = 1; |
| 510 | char *m_env = getenv("PRIMUS_VK_MULTITHREADING"); |
| 511 | if(m_env == nullptr || std::string{m_env} != "1"){ |
| 512 | thread_count = image_count; |
| 513 | } |
| 514 | threads.resize(thread_count); |
| 515 | for(auto &thread: threads){ |
| 516 | thread = std::unique_ptr<std::thread>(new std::thread([this](){this->run();})); |
| 517 | pthread_setname_np(thread->native_handle(), "swapchain-thread"); |
| 518 | } |
| 519 | } |
| 520 | |
| 521 | uint32_t getImageMemory(ImageType type, uint32_t memory_type_bits); |
| 522 | |
| 523 | void storeImage(uint32_t index, VkQueue queue, std::vector<VkSemaphore> wait_on, Fence ¬ify); |
| 524 | |
| 525 | void queue(VkQueue queue, const VkPresentInfoKHR *pPresentInfo); |
| 526 | |
| 527 | std::mutex queueMutex; |
| 528 | std::condition_variable has_work; |
| 529 | bool active = true; |
| 530 | struct QueueItem { |
| 531 | VkQueue queue; |
| 532 | VkPresentInfoKHR pPresentInfo; |
| 533 | uint32_t imgIndex; |
| 534 | }; |
| 535 | std::list<QueueItem> work; |
| 536 | std::list<QueueItem> in_progress; |
| 537 | void present(const QueueItem &workItem); |
| 538 | void run(); |
| 539 | void stop(); |
| 540 | void waitForReady(); |
| 541 | }; |
| 542 | |
| 543 | ImageWorker::ImageWorker(PrimusSwapchain &swapchain, VkImage display_image, const VkSwapchainCreateInfoKHR &createInfo): swapchain(swapchain), render_copy_fence(swapchain.device), display_semaphore(swapchain.display_device), display_image(display_image){ |
| 544 | initImages(createInfo); |
| 545 | createCommandBuffers(); |
| 546 | } |
| 547 | ImageWorker::~ImageWorker(){ |
| 548 | if(display_command_fence){ |
| 549 | display_command_fence->await(); |
| 550 | } |
| 551 | } |
| 552 | |
| 553 | class CreateOtherDevice { |
| 554 | public: |
| 555 | VkPhysicalDevice display_dev; |
| 556 | VkPhysicalDevice render_dev; |
| 557 | VkPhysicalDeviceMemoryProperties display_mem; |
| 558 | VkPhysicalDeviceMemoryProperties render_mem; |
| 559 | VkDevice render_gpu = VK_NULL_HANDLE; |
| 560 | VkDevice display_gpu = VK_NULL_HANDLE; |
| 561 | |
| 562 | CreateOtherDevice(VkPhysicalDevice display_dev, VkPhysicalDevice render_dev): |
| 563 | display_dev(display_dev), render_dev(render_dev){ |
| 564 | } |
| 565 | void setRenderDevice(VkDevice render_gpu){ |
| 566 | this->render_gpu = render_gpu; |
| 567 | } |
| 568 | void finish(std::function<VkResult(VkDeviceCreateInfo &createInfo, VkDevice &dev)> creator){ |
| 569 | auto &minstance_info = instance_info[GetKey(render_dev)]; |
| 570 | auto &minstance_dispatch = instance_dispatch[GetKey(minstance_info.instance)]; |
| 571 | minstance_dispatch.GetPhysicalDeviceMemoryProperties(display_dev, &display_mem); |
| 572 | minstance_dispatch.GetPhysicalDeviceMemoryProperties(render_dev, &render_mem); |
| 573 | |
| 574 | createDisplayDev(minstance_info, creator); |
| 575 | } |
| 576 | void createDisplayDev(InstanceInfo &my_instance, std::function<VkResult(VkDeviceCreateInfo &createInfo, VkDevice &dev)> creator){ |
| 577 | VkDeviceCreateInfo createInfo = {}; |
| 578 | createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; |
| 579 | |
| 580 | VkDeviceQueueCreateInfo queueInfo{}; |
| 581 | queueInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; |
| 582 | queueInfo.queueFamilyIndex = my_instance.displayQueueFamilyIndex; |
| 583 | queueInfo.queueCount = 1; |
| 584 | const float defaultQueuePriority(0.0f); |
| 585 | queueInfo.pQueuePriorities = &defaultQueuePriority; |
| 586 | |
| 587 | createInfo.queueCreateInfoCount = 1; |
| 588 | createInfo.pQueueCreateInfos = &queueInfo; |
| 589 | createInfo.enabledExtensionCount = 1; |
| 590 | const char *swap[] = {VK_KHR_SWAPCHAIN_EXTENSION_NAME}; |
| 591 | createInfo.ppEnabledExtensionNames = swap; |
| 592 | VkResult ret = creator(createInfo, display_gpu); |
| 593 | TRACE("Creating display device finished!: " << ret); |
| 594 | if(ret != VK_SUCCESS){ |
| 595 | throw std::runtime_error("Display device creation failed"); |
| 596 | } |
| 597 | } |
| 598 | }; |
| 599 | |
| 600 | |
| 601 | class CommandBuffer { |
| 602 | VkCommandPool commandPool; |
| 603 | VkDevice device; |
| 604 | public: |
| 605 | VkCommandBuffer cmd; |
| 606 | CommandBuffer(VkDevice device, uint32_t queueFamilyIndex) : device(device) { |
| 607 | VkCommandPoolCreateInfo poolInfo = {.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; |
| 608 | poolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; |
| 609 | poolInfo.queueFamilyIndex = queueFamilyIndex; |
| 610 | VK_CHECK_RESULT(device_dispatch[GetKey(device)].CreateCommandPool(device, &poolInfo, nullptr, &commandPool)); |
| 611 | VkCommandBufferAllocateInfo cmdBufAllocateInfo = {.sType=VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; |
| 612 | cmdBufAllocateInfo.commandPool = commandPool; |
| 613 | cmdBufAllocateInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; |
| 614 | cmdBufAllocateInfo.commandBufferCount = 1; |
| 615 | |
| 616 | VK_CHECK_RESULT(device_dispatch[GetKey(device)].AllocateCommandBuffers(device, &cmdBufAllocateInfo, &cmd)); |
| 617 | GetKey(cmd) = GetKey(device); |
| 618 | |
| 619 | VkCommandBufferBeginInfo cmdBufInfo = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; |
| 620 | VK_CHECK_RESULT(device_dispatch[GetKey(device)].BeginCommandBuffer(cmd, &cmdBufInfo)); |
| 621 | } |
| 622 | ~CommandBuffer(){ |
| 623 | device_dispatch[GetKey(device)].FreeCommandBuffers(device, commandPool, 1, &cmd); |
| 624 | device_dispatch[GetKey(device)].DestroyCommandPool(device, commandPool, nullptr); |
| 625 | } |
| 626 | void insertImageMemoryBarrier( |
| 627 | VkImage image, |
| 628 | VkAccessFlags srcAccessMask, |
| 629 | VkAccessFlags dstAccessMask, |
| 630 | VkImageLayout oldImageLayout, |
| 631 | VkImageLayout newImageLayout, |
| 632 | VkPipelineStageFlags srcStageMask, |
| 633 | VkPipelineStageFlags dstStageMask, |
| 634 | VkImageSubresourceRange subresourceRange) { |
| 635 | VkImageMemoryBarrier imageMemoryBarrier{.sType=VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; |
| 636 | imageMemoryBarrier.srcAccessMask = srcAccessMask; |
| 637 | imageMemoryBarrier.dstAccessMask = dstAccessMask; |
| 638 | imageMemoryBarrier.oldLayout = oldImageLayout; |
| 639 | imageMemoryBarrier.newLayout = newImageLayout; |
| 640 | imageMemoryBarrier.image = image; |
| 641 | imageMemoryBarrier.subresourceRange = subresourceRange; |
| 642 | |
| 643 | device_dispatch[GetKey(device)].CmdPipelineBarrier( |
| 644 | cmd, |
| 645 | srcStageMask, |
| 646 | dstStageMask, |
| 647 | 0, |
| 648 | 0, nullptr, |
| 649 | 0, nullptr, |
| 650 | 1, &imageMemoryBarrier); |
| 651 | } |
| 652 | void copyImage(VkImage src, VkImage dst, VkExtent2D imgSize){ |
| 653 | VkImageCopy imageCopyRegion{}; |
| 654 | imageCopyRegion.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; |
| 655 | imageCopyRegion.srcSubresource.layerCount = 1; |
| 656 | imageCopyRegion.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; |
| 657 | imageCopyRegion.dstSubresource.layerCount = 1; |
| 658 | imageCopyRegion.extent.width = imgSize.width; |
| 659 | imageCopyRegion.extent.height = imgSize.height; |
| 660 | imageCopyRegion.extent.depth = 1; |
| 661 | |
| 662 | // Issue the copy command |
| 663 | device_dispatch[GetKey(device)].CmdCopyImage( |
| 664 | cmd, |
| 665 | src, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, |
| 666 | dst, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, |
| 667 | 1, |
| 668 | &imageCopyRegion); |
| 669 | } |
| 670 | void end(){ |
| 671 | VK_CHECK_RESULT(device_dispatch[GetKey(device)].EndCommandBuffer(cmd)); |
| 672 | } |
| 673 | void submit(VkQueue queue, VkFence fence, std::vector<VkSemaphore> wait = {}, std::vector<VkSemaphore> signal = {}){ |
| 674 | VkSubmitInfo submitInfo = {.sType=VK_STRUCTURE_TYPE_SUBMIT_INFO}; |
| 675 | submitInfo.commandBufferCount = 1; |
| 676 | submitInfo.pCommandBuffers = &cmd; |
| 677 | VkPipelineStageFlags waitStage = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; |
| 678 | submitInfo.pWaitDstStageMask = &waitStage; |
| 679 | submitInfo.waitSemaphoreCount = wait.size(); |
| 680 | submitInfo.pWaitSemaphores = wait.data(); |
| 681 | submitInfo.signalSemaphoreCount = signal.size(); |
| 682 | submitInfo.pSignalSemaphores = signal.data(); |
| 683 | |
| 684 | // Submit to the queue |
| 685 | VK_CHECK_RESULT(device_dispatch[GetKey(device)].QueueSubmit(queue, 1, &submitInfo, fence)); |
| 686 | } |
| 687 | }; |
| 688 | |
| 689 | void ImageWorker::initImages( const VkSwapchainCreateInfoKHR &createInfo){ |
| 690 | auto imgSize = createInfo.imageExtent; |
| 691 | auto format = createInfo.imageFormat; |
| 692 | |
| 693 | auto &renderImage = render_image; |
| 694 | auto &renderCopyImage = render_copy_image; |
| 695 | auto &displaySrcImage = display_src_image; |
| 696 | renderImage = std::make_shared<FramebufferImage>(swapchain.device, imgSize, |
| 697 | VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT, format, |
| 698 | [this](uint32_t memoryTypeBits){ return swapchain.getImageMemory(ImageType::RENDER_TARGET_IMAGE, memoryTypeBits); }); |
| 699 | renderCopyImage = std::make_shared<FramebufferImage>(swapchain.device, imgSize, |
| 700 | VK_IMAGE_TILING_LINEAR, VK_IMAGE_USAGE_TRANSFER_DST_BIT, format, |
| 701 | [this](uint32_t memoryTypeBits){ return swapchain.getImageMemory(ImageType::RENDER_COPY_IMAGE, memoryTypeBits); }); |
| 702 | displaySrcImage = std::make_shared<FramebufferImage>(swapchain.display_device, imgSize, |
| 703 | VK_IMAGE_TILING_LINEAR, VK_IMAGE_USAGE_TRANSFER_SRC_BIT, format, |
| 704 | [this](uint32_t memoryTypeBits){ return swapchain.getImageMemory(ImageType::DISPLAY_IMAGE, memoryTypeBits); }); |
| 705 | |
| 706 | renderCopyImage->map(); |
| 707 | displaySrcImage->map(); |
| 708 | |
| 709 | CommandBuffer cmd{swapchain.display_device, swapchain.myInstance.displayQueueFamilyIndex}; |
| 710 | cmd.insertImageMemoryBarrier( |
| 711 | displaySrcImage->img, |
| 712 | 0, |
| 713 | VK_ACCESS_MEMORY_WRITE_BIT, |
| 714 | VK_IMAGE_LAYOUT_UNDEFINED, |
| 715 | VK_IMAGE_LAYOUT_GENERAL, |
| 716 | VK_PIPELINE_STAGE_TRANSFER_BIT, |
| 717 | VK_PIPELINE_STAGE_TRANSFER_BIT, |
| 718 | VkImageSubresourceRange{ VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }); |
| 719 | cmd.end(); |
| 720 | Fence f{swapchain.display_device}; |
| 721 | cmd.submit(swapchain.display_queue, f.fence); |
| 722 | f.await(); |
| 723 | } |
| 724 | |
| 725 | |
| 726 | |
| 727 | VkResult VKAPI_CALL PrimusVK_CreateDevice( |
| 728 | VkPhysicalDevice physicalDevice, |
| 729 | const VkDeviceCreateInfo* pCreateInfo, |
| 730 | const VkAllocationCallbacks* pAllocator, |
| 731 | VkDevice* pDevice) |
| 732 | { |
| 733 | auto &my_instance_info = instance_info[GetKey(physicalDevice)]; |
| 734 | VkLayerDeviceCreateInfo *layerCreateInfo = (VkLayerDeviceCreateInfo *)pCreateInfo->pNext; |
| 735 | |
| 736 | // step through the chain of pNext until we get to the link info |
| 737 | while(layerCreateInfo && (layerCreateInfo->sType != VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO || |
| 738 | layerCreateInfo->function != VK_LAYER_LINK_INFO)) |
| 739 | { |
| 740 | layerCreateInfo = (VkLayerDeviceCreateInfo *)layerCreateInfo->pNext; |
| 741 | } |
| 742 | |
| 743 | if(layerCreateInfo == NULL) |
| 744 | { |
| 745 | // No loader instance create info |
| 746 | return VK_ERROR_INITIALIZATION_FAILED; |
| 747 | } |
| 748 | |
| 749 | PFN_vkGetInstanceProcAddr gipa = layerCreateInfo->u.pLayerInfo->pfnNextGetInstanceProcAddr; |
| 750 | PFN_vkGetDeviceProcAddr gdpa = layerCreateInfo->u.pLayerInfo->pfnNextGetDeviceProcAddr; |
| 751 | // move chain on for next layer |
| 752 | layerCreateInfo->u.pLayerInfo = layerCreateInfo->u.pLayerInfo->pNext; |
| 753 | |
| 754 | auto display_dev = my_instance_info.display; |
| 755 | std::shared_ptr<CreateOtherDevice> cod = nullptr; |
| 756 | { |
| 757 | scoped_lock l(global_lock); |
| 758 | cod = std::make_shared<CreateOtherDevice>(display_dev, physicalDevice); |
| 759 | } |
| 760 | auto createDevice = my_instance_info.layerCreateDevice; |
| 761 | cod->finish([createDevice,&my_instance_info](VkDeviceCreateInfo &createInfo, VkDevice &dev){ |
| 762 | PFN_vkGetDeviceProcAddr gdpa = nullptr; |
| 763 | auto ret = createDevice(my_instance_info.instance, my_instance_info.display, &createInfo, nullptr, &dev, PrimusVK_GetInstanceProcAddr, &gdpa); |
| 764 | { |
| 765 | scoped_lock l(global_lock); |
| 766 | device_instance_info[GetKey(dev)] = &my_instance_info; |
| 767 | device_dispatch.insert({GetKey(dev),fetchDispatchTable(gdpa, &dev)}); |
| 768 | } |
| 769 | return ret; |
| 770 | }); |
| 771 | PFN_vkCreateDevice createFunc = (PFN_vkCreateDevice)gipa(VK_NULL_HANDLE, "vkCreateDevice"); |
| 772 | VkResult ret = createFunc(physicalDevice, pCreateInfo, pAllocator, pDevice); |
| 773 | cod->setRenderDevice(*pDevice); |
| 774 | my_instance_info.cod[GetKey(*pDevice)] = cod; |
| 775 | if(ret != VK_SUCCESS){ |
| 776 | TRACE("Render Device creation failed: " << ret); |
| 777 | return VK_ERROR_INITIALIZATION_FAILED; |
| 778 | } |
| 779 | // store the table by key |
| 780 | { |
| 781 | scoped_lock l(global_lock); |
| 782 | device_instance_info[GetKey(*pDevice)] = &my_instance_info; |
| 783 | device_dispatch.insert({GetKey(*pDevice), fetchDispatchTable(gdpa, pDevice)}); |
| 784 | } |
| 785 | TRACE("CreateDevice done"); |
| 786 | |
| 787 | return ret; |
| 788 | |
| 789 | } |
| 790 | |
| 791 | PvkDispatchTable fetchDispatchTable(PFN_vkGetDeviceProcAddr gdpa, VkDevice *pDevice){ |
| 792 | TRACE("fetching dispatch for " << GetKey(*pDevice)); |
| 793 | // fetch our own dispatch table for the functions we need, into the next layer |
| 794 | PvkDispatchTable dispatchTable = {pDevice, gdpa}; |
| 795 | return dispatchTable; |
| 796 | } |
| 797 | |
| 798 | void VKAPI_CALL PrimusVK_DestroyDevice(VkDevice device, const VkAllocationCallbacks* pAllocator) |
| 799 | { |
| 800 | scoped_lock l(global_lock); |
| 801 | auto &my_instance = *device_instance_info[GetKey(device)]; |
| 802 | auto &display_device = my_instance.cod[GetKey(device)]->display_gpu; |
| 803 | auto device_key = GetKey(device); |
| 804 | auto display_device_key = GetKey(display_device); |
| 805 | my_instance.layerDestroyDevice(display_device, nullptr, device_dispatch[GetKey(display_device)].DestroyDevice); |
| 806 | device_dispatch[GetKey(device)].DestroyDevice(device, pAllocator); |
| 807 | my_instance.cod.erase(device_key); |
| 808 | device_dispatch.erase(device_key); |
| 809 | device_dispatch.erase(display_device_key); |
| 810 | } |
| 811 | |
| 812 | VkResult VKAPI_CALL PrimusVK_CreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain) { |
| 813 | auto &my_instance = *device_instance_info[GetKey(device)]; |
| 814 | TRACE("Application requested " << pCreateInfo->minImageCount << " images."); |
| 815 | VkDevice render_gpu = device; |
| 816 | VkSwapchainCreateInfoKHR info2 = *pCreateInfo; |
| 817 | info2.minImageCount = std::max(3u, pCreateInfo->minImageCount); |
| 818 | info2.imageUsage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT; |
| 819 | pCreateInfo = &info2; |
| 820 | |
| 821 | VkSwapchainKHR old = pCreateInfo->oldSwapchain; |
| 822 | if(old != VK_NULL_HANDLE){ |
| 823 | PrimusSwapchain *ch = reinterpret_cast<PrimusSwapchain*>(old); |
| 824 | info2.oldSwapchain = ch->backend; |
| 825 | TRACE("Old Swapchain: " << ch->backend); |
| 826 | } |
| 827 | TRACE("Creating Swapchain for size: " << pCreateInfo->imageExtent.width << "x" << pCreateInfo->imageExtent.height); |
| 828 | TRACE("MinImageCount: " << pCreateInfo->minImageCount); |
| 829 | TRACE("fetching device for: " << GetKey(render_gpu)); |
| 830 | VkDevice display_gpu = my_instance.cod[GetKey(device)]->display_gpu; |
| 831 | |
| 832 | TRACE("FamilyIndexCount: " << pCreateInfo->queueFamilyIndexCount); |
| 833 | TRACE("Dev: " << GetKey(display_gpu)); |
| 834 | TRACE("Swapchainfunc: " << (void*) device_dispatch[GetKey(display_gpu)].CreateSwapchainKHR); |
| 835 | |
| 836 | VkSwapchainKHR backend; |
| 837 | VkResult rc = device_dispatch[GetKey(display_gpu)].CreateSwapchainKHR(display_gpu, pCreateInfo, pAllocator, &backend); |
| 838 | TRACE(">> Swapchain create done " << rc << ";" << (void*) backend); |
| 839 | if(rc != VK_SUCCESS){ |
| 840 | return rc; |
| 841 | } |
| 842 | try { |
| 843 | PrimusSwapchain *ch = new PrimusSwapchain(my_instance, render_gpu, display_gpu, backend, pCreateInfo, my_instance.cod[GetKey(device)]); |
| 844 | *pSwapchain = reinterpret_cast<VkSwapchainKHR>(ch); |
| 845 | }catch(const std::exception &e){ |
| 846 | return VK_ERROR_UNKNOWN; |
| 847 | } |
| 848 | |
| 849 | |
| 850 | |
| 851 | return rc; |
| 852 | } |
| 853 | |
| 854 | void VKAPI_CALL PrimusVK_DestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapchain, const VkAllocationCallbacks* pAllocator) { |
| 855 | if(swapchain == VK_NULL_HANDLE) { return;} |
| 856 | PrimusSwapchain *ch = reinterpret_cast<PrimusSwapchain*>(swapchain); |
| 857 | TRACE(">> Destroy swapchain: " << (void*) ch->backend); |
| 858 | ch->stop(); |
| 859 | device_dispatch[GetKey(ch->display_device)].DestroySwapchainKHR(ch->display_device, ch->backend, pAllocator); |
| 860 | delete ch; |
| 861 | } |
| 862 | VkResult VKAPI_CALL PrimusVK_GetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount, VkImage* pSwapchainImages) { |
| 863 | PrimusSwapchain *ch = reinterpret_cast<PrimusSwapchain*>(swapchain); |
| 864 | |
| 865 | *pSwapchainImageCount = ch->images.size(); |
| 866 | VkResult res = VK_SUCCESS; |
| 867 | if(pSwapchainImages != nullptr) { |
| 868 | res = VK_SUCCESS; |
| 869 | for(size_t i = 0; i < *pSwapchainImageCount; i++){ |
| 870 | pSwapchainImages[i] = ch->images[i].render_image->img; |
| 871 | } |
| 872 | TRACE("Count: " << *pSwapchainImageCount); |
| 873 | } |
| 874 | return res; |
| 875 | } |
| 876 | |
| 877 | const auto primus_start = std::chrono::steady_clock::now(); |
| 878 | VkResult VKAPI_CALL PrimusVK_AcquireNextImage2KHR(VkDevice device, const VkAcquireNextImageInfoKHR* pAcquireInfo, uint32_t* pImageIndex) { |
| 879 | TRACE_PROFILING_EVENT(-1, "Acquire starting"); |
| 880 | PrimusSwapchain *ch = reinterpret_cast<PrimusSwapchain*>(pAcquireInfo->swapchain); |
| 881 | |
| 882 | auto timeout = pAcquireInfo->timeout; |
| 883 | VkResult res; |
| 884 | { |
| 885 | Fence myfence{ch->display_device}; |
| 886 | |
| 887 | ch->waitForReady(); |
| 888 | res = device_dispatch[GetKey(ch->display_device)].AcquireNextImageKHR(ch->display_device, ch->backend, timeout, VK_NULL_HANDLE, myfence.fence, pImageIndex); |
| 889 | TRACE_PROFILING_EVENT(*pImageIndex, "got image"); |
| 890 | myfence.await(); |
| 891 | } |
| 892 | VkSubmitInfo qsi{}; |
| 893 | qsi.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; |
| 894 | if(pAcquireInfo->semaphore != VK_NULL_HANDLE){ |
| 895 | qsi.signalSemaphoreCount = 1; |
| 896 | qsi.pSignalSemaphores = &pAcquireInfo->semaphore; |
| 897 | } |
| 898 | scoped_lock lock(*device_instance_info[GetKey(ch->render_queue)]->renderQueueMutex); |
| 899 | device_dispatch[GetKey(ch->render_queue)].QueueSubmit(ch->render_queue, 1, &qsi, pAcquireInfo->fence); |
| 900 | TRACE_PROFILING_EVENT(*pImageIndex, "Acquire done"); |
| 901 | |
| 902 | if(ch->suppress_suboptimal && res == VK_SUBOPTIMAL_KHR){ |
| 903 | res = VK_SUCCESS; |
| 904 | } |
| 905 | |
| 906 | return res; |
| 907 | } |
| 908 | VkResult VKAPI_CALL PrimusVK_AcquireNextImageKHR(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout, VkSemaphore semaphore, VkFence fence, uint32_t* pImageIndex) { |
| 909 | auto acquireInfo = VkAcquireNextImageInfoKHR{}; |
| 910 | |
| 911 | acquireInfo.sType = VK_STRUCTURE_TYPE_ACQUIRE_NEXT_IMAGE_INFO_KHR; |
| 912 | acquireInfo.swapchain = swapchain; |
| 913 | acquireInfo.timeout = timeout; |
| 914 | acquireInfo.semaphore = semaphore; |
| 915 | acquireInfo.fence = fence; |
| 916 | |
| 917 | return PrimusVK_AcquireNextImage2KHR(device, &acquireInfo, pImageIndex); |
| 918 | } |
| 919 | VkResult VKAPI_CALL PrimusVK_GetSwapchainStatusKHR(VkDevice device, VkSwapchainKHR swapchain){ |
| 920 | PrimusSwapchain *ch = reinterpret_cast<PrimusSwapchain*>(swapchain); |
| 921 | return device_dispatch[GetKey(ch->display_device)].GetSwapchainStatusKHR(device, ch->backend); |
| 922 | } |
| 923 | |
| 924 | uint32_t PrimusSwapchain::getImageMemory(ImageType image_type, uint32_t memoryTypeBits){ |
| 925 | const VkPhysicalDeviceMemoryProperties *mem_props = &cod->render_mem; |
| 926 | std::vector<std::pair<VkMemoryPropertyFlags, VkMemoryPropertyFlags>> propertyPreferences; |
| 927 | switch(image_type){ |
| 928 | case ImageType::RENDER_TARGET_IMAGE: |
| 929 | propertyPreferences = { |
| 930 | {VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT}, |
| 931 | {VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 0} |
| 932 | }; |
| 933 | break; |
| 934 | case ImageType::RENDER_COPY_IMAGE: |
| 935 | propertyPreferences = { |
| 936 | {VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_CACHED_BIT, VK_MEMORY_PROPERTY_HOST_COHERENT_BIT}, |
| 937 | {VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_CACHED_BIT, 0}, |
| 938 | {VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, 0} |
| 939 | }; |
| 940 | break; |
| 941 | case ImageType::DISPLAY_IMAGE: |
| 942 | mem_props = &cod->display_mem; |
| 943 | propertyPreferences = { |
| 944 | {VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, 0} |
| 945 | }; |
| 946 | break; |
| 947 | } |
| 948 | for( const auto &requested : propertyPreferences ){ |
| 949 | for(size_t j = 0; j < mem_props->memoryTypeCount; j++){ |
| 950 | if( (memoryTypeBits & (1 << j)) == 0) { |
| 951 | continue; |
| 952 | } |
| 953 | auto flags = mem_props->memoryTypes[j].propertyFlags; |
| 954 | if((flags & requested.first) == requested.first && (flags & requested.second) == 0) { |
| 955 | return j; |
| 956 | } |
| 957 | } |
| 958 | } |
| 959 | TRACE("ERROR, no suitable image memory found for " << image_type); |
| 960 | throw std::runtime_error("No suitable image memory found."); |
| 961 | } |
| 962 | |
| 963 | void ImageWorker::createCommandBuffers(){ |
| 964 | { |
| 965 | auto cpyImage = render_copy_image; |
| 966 | auto srcImage = render_image->img; |
| 967 | render_copy_command = std::make_shared<CommandBuffer>(swapchain.device, swapchain.myInstance.renderQueueFamilyIndex); |
| 968 | CommandBuffer &cmd = *render_copy_command; |
| 969 | cmd.insertImageMemoryBarrier( |
| 970 | cpyImage->img, |
| 971 | VK_ACCESS_HOST_READ_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, |
| 972 | VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, |
| 973 | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, |
| 974 | VkImageSubresourceRange{ VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }); |
| 975 | cmd.insertImageMemoryBarrier( |
| 976 | srcImage, |
| 977 | VK_ACCESS_MEMORY_READ_BIT, VK_ACCESS_TRANSFER_READ_BIT, |
| 978 | VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, |
| 979 | VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, |
| 980 | VkImageSubresourceRange{ VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }); |
| 981 | |
| 982 | cmd.copyImage(srcImage, cpyImage->img, swapchain.imgSize); |
| 983 | |
| 984 | cmd.insertImageMemoryBarrier( |
| 985 | cpyImage->img, |
| 986 | VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT, |
| 987 | VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL, |
| 988 | VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, |
| 989 | VkImageSubresourceRange{ VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }); |
| 990 | cmd.insertImageMemoryBarrier( |
| 991 | srcImage, |
| 992 | VK_ACCESS_TRANSFER_READ_BIT, VK_ACCESS_MEMORY_READ_BIT, |
| 993 | VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, |
| 994 | VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, |
| 995 | VkImageSubresourceRange{ VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }); |
| 996 | |
| 997 | cmd.end(); |
| 998 | } |
| 999 | |
| 1000 | { |
| 1001 | display_command = std::make_shared<CommandBuffer>(swapchain.display_device, swapchain.myInstance.displayQueueFamilyIndex); |
| 1002 | CommandBuffer &cmd = *display_command; |
| 1003 | cmd.insertImageMemoryBarrier( |
| 1004 | display_src_image->img, |
| 1005 | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT, |
| 1006 | VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, |
| 1007 | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, |
| 1008 | VkImageSubresourceRange{ VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }); |
| 1009 | cmd.insertImageMemoryBarrier( |
| 1010 | display_image, |
| 1011 | VK_ACCESS_MEMORY_READ_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, |
| 1012 | VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, |
| 1013 | VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, |
| 1014 | VkImageSubresourceRange{ VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }); |
| 1015 | cmd.copyImage(display_src_image->img, display_image, swapchain.imgSize); |
| 1016 | |
| 1017 | cmd.insertImageMemoryBarrier( |
| 1018 | display_src_image->img, |
| 1019 | VK_ACCESS_TRANSFER_READ_BIT, VK_ACCESS_HOST_WRITE_BIT, |
| 1020 | VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL, |
| 1021 | VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, |
| 1022 | VkImageSubresourceRange{ VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }); |
| 1023 | cmd.insertImageMemoryBarrier( |
| 1024 | display_image, |
| 1025 | VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_MEMORY_READ_BIT, |
| 1026 | VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, |
| 1027 | VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, |
| 1028 | VkImageSubresourceRange{ VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }); |
| 1029 | cmd.end(); |
| 1030 | } |
| 1031 | } |
| 1032 | |
| 1033 | void PrimusSwapchain::storeImage(uint32_t index, VkQueue queue, std::vector<VkSemaphore> wait_on, Fence ¬ify){ |
| 1034 | images[index].render_copy_command->submit(queue, notify.fence, wait_on); |
| 1035 | } |
| 1036 | |
| 1037 | void ImageWorker::copyImageData(uint32_t index, std::vector<VkSemaphore> sems){ |
| 1038 | { |
| 1039 | auto rendered = render_copy_image->getMapped(); |
| 1040 | auto display = display_src_image->getMapped(); |
| 1041 | auto rendered_layout = render_copy_image->getLayout(); |
| 1042 | auto display_layout = display_src_image->getLayout(); |
| 1043 | auto rendered_start = rendered->data + rendered_layout.offset; |
| 1044 | auto display_start = display->data + display_layout.offset; |
| 1045 | if(rendered_layout.size/rendered_layout.rowPitch != display_layout.size/display_layout.rowPitch){ |
| 1046 | TRACE("Layouts don't match at all"); |
| 1047 | throw std::runtime_error("Layouts don't match at all"); |
| 1048 | } |
| 1049 | TRACE_PROFILING_EVENT(index, "memcpy start"); |
| 1050 | VkMappedMemoryRange rendered_range { |
| 1051 | .sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE, |
| 1052 | .pNext = VK_NULL_HANDLE, |
| 1053 | .memory = render_copy_image->mem, |
| 1054 | .offset = 0, |
| 1055 | .size = VK_WHOLE_SIZE |
| 1056 | }; |
| 1057 | VK_CHECK_RESULT(device_dispatch[GetKey(swapchain.device)].InvalidateMappedMemoryRanges(swapchain.device, 1, &rendered_range)); |
| 1058 | |
| 1059 | if(rendered_layout.rowPitch == display_layout.rowPitch){ |
| 1060 | std::memcpy(display_start, rendered_start, rendered_layout.size); |
| 1061 | }else{ |
| 1062 | VkDeviceSize display_offset = 0; |
| 1063 | VkDeviceSize minRowPitch = rendered_layout.rowPitch; |
| 1064 | if(display_layout.rowPitch < minRowPitch){ |
| 1065 | minRowPitch = display_layout.rowPitch; |
| 1066 | } |
| 1067 | for(VkDeviceSize offset = 0; offset < rendered_layout.size; offset += rendered_layout.rowPitch){ |
| 1068 | std::memcpy(display_start + display_offset, rendered_start + offset, minRowPitch); |
| 1069 | display_offset += display_layout.rowPitch; |
| 1070 | } |
| 1071 | } |
| 1072 | TRACE_PROFILING_EVENT(index, "memcpy done"); |
| 1073 | } |
| 1074 | { |
| 1075 | std::unique_lock<std::mutex> lock(swapchain.queueMutex); |
| 1076 | if(display_command_fence){ |
| 1077 | display_command_fence->await(); |
| 1078 | display_command_fence->reset(); |
| 1079 | }else{ |
| 1080 | display_command_fence = std::unique_ptr<Fence>(new Fence(swapchain.display_device)); |
| 1081 | } |
| 1082 | display_command->submit(swapchain.display_queue, display_command_fence->fence, {}, sems); |
| 1083 | } |
| 1084 | } |
| 1085 | |
| 1086 | void PrimusSwapchain::queue(VkQueue queue, const VkPresentInfoKHR* pPresentInfo){ |
| 1087 | std::unique_lock<std::mutex> lock(queueMutex); |
| 1088 | |
| 1089 | auto workItem = QueueItem{queue, *pPresentInfo, pPresentInfo->pImageIndices[0]}; |
| 1090 | storeImage(workItem.imgIndex, render_queue, std::vector<VkSemaphore>{pPresentInfo->pWaitSemaphores, pPresentInfo->pWaitSemaphores + pPresentInfo->waitSemaphoreCount}, images[workItem.imgIndex].render_copy_fence); |
| 1091 | |
| 1092 | work.push_back(std::move(workItem)); |
| 1093 | has_work.notify_all(); |
| 1094 | } |
| 1095 | |
| 1096 | void PrimusSwapchain::waitForReady() { |
| 1097 | std::unique_lock<std::mutex> lock(queueMutex); |
| 1098 | has_work.wait(lock, [this](){return work.size() + in_progress.size() <= images.size() - surfaceCapabilities.minImageCount;}); |
| 1099 | } |
| 1100 | |
| 1101 | void PrimusSwapchain::stop(){ |
| 1102 | { |
| 1103 | std::unique_lock<std::mutex> lock(queueMutex); |
| 1104 | active = false; |
| 1105 | has_work.notify_all(); |
| 1106 | } |
| 1107 | for(auto &thread: threads){ |
| 1108 | thread->join(); |
| 1109 | thread.reset(); |
| 1110 | } |
| 1111 | } |
| 1112 | void PrimusSwapchain::present(const QueueItem &workItem){ |
| 1113 | const auto index = workItem.imgIndex; |
| 1114 | images[index].render_copy_fence.await(); |
| 1115 | images[index].render_copy_fence.reset(); |
| 1116 | images[index].copyImageData(index, {images[index].display_semaphore.sem}); |
| 1117 | |
| 1118 | TRACE_PROFILING_EVENT(index, "copy queued"); |
| 1119 | |
| 1120 | VkPresentInfoKHR p2 = {.sType=VK_STRUCTURE_TYPE_PRESENT_INFO_KHR}; |
| 1121 | p2.pSwapchains = &backend; |
| 1122 | p2.swapchainCount = 1; |
| 1123 | p2.pWaitSemaphores = &images[workItem.imgIndex].display_semaphore.sem; |
| 1124 | p2.waitSemaphoreCount = 1; |
| 1125 | p2.pImageIndices = &index; |
| 1126 | |
| 1127 | { |
| 1128 | std::unique_lock<std::mutex> lock(queueMutex); |
| 1129 | has_work.wait(lock, [this,&workItem](){return &workItem == &in_progress.front();}); |
| 1130 | TRACE_PROFILING_EVENT(index, "submitting"); |
| 1131 | VkResult res = device_dispatch[GetKey(display_device)].QueuePresentKHR(display_queue, &p2); |
| 1132 | if(suppress_suboptimal && res == VK_SUBOPTIMAL_KHR){ |
| 1133 | res = VK_SUCCESS; |
| 1134 | } |
| 1135 | if(res != VK_SUCCESS && res != VK_SUBOPTIMAL_KHR) { |
| 1136 | TRACE("ERROR, Queue Present failed: " << res << "\n"); |
| 1137 | } |
| 1138 | in_progress.pop_front(); |
| 1139 | has_work.notify_all(); |
| 1140 | } |
| 1141 | } |
| 1142 | void PrimusSwapchain::run(){ |
| 1143 | while(true){ |
| 1144 | QueueItem *workItem = nullptr; |
| 1145 | { |
| 1146 | std::unique_lock<std::mutex> lock(queueMutex); |
| 1147 | has_work.wait(lock, [this](){return !active || work.size() > 0;}); |
| 1148 | if(!active) return; |
| 1149 | in_progress.push_back(std::move(work.front())); |
| 1150 | workItem = &in_progress.back(); |
| 1151 | work.pop_front(); |
| 1152 | } |
| 1153 | present(*workItem); |
| 1154 | } |
| 1155 | } |
| 1156 | |
| 1157 | VkResult VKAPI_CALL PrimusVK_QueueSubmit(VkQueue queue, uint32_t submitCount, |
| 1158 | const VkSubmitInfo* pSubmits, |
| 1159 | VkFence fence) { |
| 1160 | scoped_lock lock(*device_instance_info[GetKey(queue)]->renderQueueMutex); |
| 1161 | return device_dispatch[GetKey(queue)].QueueSubmit(queue, submitCount, pSubmits, fence); |
| 1162 | } |
| 1163 | |
| 1164 | VkResult VKAPI_CALL PrimusVK_QueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo) { |
| 1165 | scoped_lock lock(*device_instance_info[GetKey(queue)]->renderQueueMutex); |
| 1166 | auto start = std::chrono::steady_clock::now(); |
| 1167 | if(pPresentInfo->swapchainCount != 1){ |
| 1168 | TRACE("Warning, presenting with multiple swapchains not implemented, ignoring"); |
| 1169 | } |
| 1170 | |
| 1171 | PrimusSwapchain *ch = reinterpret_cast<PrimusSwapchain*>(pPresentInfo->pSwapchains[0]); |
| 1172 | double secs = std::chrono::duration_cast<std::chrono::duration<double>>(start - ch->lastPresent).count(); |
| 1173 | TRACE_PROFILING_EVENT(pPresentInfo->pImageIndices[0], "QueuePresent"); |
| 1174 | TRACE_PROFILING(" === Time between VkQueuePresents: " << secs << " -> " << 1/secs << " FPS"); |
| 1175 | if(ch->max_fps != 0) { |
| 1176 | const auto timeBetweenFrame = std::chrono::milliseconds(1000) / ch->max_fps; |
| 1177 | const auto toSleep = ch->lastPresent + timeBetweenFrame - start; |
| 1178 | if(toSleep > std::chrono::seconds(0)){ |
| 1179 | std::this_thread::sleep_for(toSleep); |
| 1180 | start = std::chrono::steady_clock::now(); |
| 1181 | } |
| 1182 | ch->lastPresent = start; |
| 1183 | } |
| 1184 | |
| 1185 | ch->queue(queue, pPresentInfo); |
| 1186 | |
| 1187 | return VK_SUCCESS; |
| 1188 | } |
| 1189 | |
| 1190 | void VKAPI_CALL PrimusVK_GetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount, VkQueueFamilyProperties* pQueueFamilyProperties) { |
| 1191 | VkPhysicalDevice phy = physicalDevice; |
| 1192 | instance_dispatch[GetKey(phy)].GetPhysicalDeviceQueueFamilyProperties(phy, pQueueFamilyPropertyCount, pQueueFamilyProperties); |
| 1193 | } |
| 1194 | VkResult VKAPI_CALL PrimusVK_GetPhysicalDeviceSurfaceSupportKHR( |
| 1195 | VkPhysicalDevice physicalDevice, |
| 1196 | uint32_t queueFamilyIndex, |
| 1197 | VkSurfaceKHR surface, |
| 1198 | VkBool32* pSupported) { |
| 1199 | auto &instance = instance_info[GetKey(physicalDevice)]; |
| 1200 | VkPhysicalDevice phy = instance.display; |
| 1201 | return instance_dispatch[GetKey(phy)].GetPhysicalDeviceSurfaceSupportKHR(phy, instance.displayQueueFamilyIndex, surface, pSupported); |
| 1202 | } |
| 1203 | #ifdef VK_USE_PLATFORM_XCB_KHR |
| 1204 | VkBool32 VKAPI_CALL PrimusVK_GetPhysicalDeviceXcbPresentationSupportKHR( |
| 1205 | VkPhysicalDevice physicalDevice, |
| 1206 | uint32_t queueFamilyIndex, |
| 1207 | xcb_connection_t* connection, |
| 1208 | xcb_visualid_t visual_id){ |
| 1209 | auto &instance = instance_info[GetKey(physicalDevice)]; |
| 1210 | VkPhysicalDevice phy = instance.display; |
| 1211 | return instance_dispatch[GetKey(phy)].GetPhysicalDeviceXcbPresentationSupportKHR(phy, instance.displayQueueFamilyIndex, connection, visual_id); |
| 1212 | } |
| 1213 | #endif |
| 1214 | #ifdef VK_USE_PLATFORM_XLIB_KHR |
| 1215 | VkBool32 VKAPI_CALL PrimusVK_GetPhysicalDeviceXlibPresentationSupportKHR( |
| 1216 | VkPhysicalDevice physicalDevice, |
| 1217 | uint32_t queueFamilyIndex, |
| 1218 | Display* dpy, |
| 1219 | VisualID visualID){ |
| 1220 | auto &instance = instance_info[GetKey(physicalDevice)]; |
| 1221 | VkPhysicalDevice phy = instance.display; |
| 1222 | return instance_dispatch[GetKey(phy)].GetPhysicalDeviceXlibPresentationSupportKHR(phy, instance.displayQueueFamilyIndex, dpy, visualID); |
| 1223 | } |
| 1224 | #endif |
| 1225 | #ifdef VK_USE_PLATFORM_WAYLAND_KHR |
| 1226 | VkBool32 VKAPI_CALL PrimusVK_GetPhysicalDeviceWaylandPresentationSupportKHR( |
| 1227 | VkPhysicalDevice physicalDevice, |
| 1228 | uint32_t queueFamilyIndex, |
| 1229 | struct wl_display* display){ |
| 1230 | auto &instance = instance_info[GetKey(physicalDevice)]; |
| 1231 | VkPhysicalDevice phy = instance.display; |
| 1232 | return instance_dispatch[GetKey(phy)].GetPhysicalDeviceWaylandPresentationSupportKHR(phy, instance.displayQueueFamilyIndex, display); |
| 1233 | } |
| 1234 | #endif |
| 1235 | |
| 1236 | void VKAPI_CALL PrimusVK_QueueWaitIdle(VkQueue queue){ |
| 1237 | scoped_lock lock(*device_instance_info[GetKey(queue)]->renderQueueMutex); |
| 1238 | device_dispatch[GetKey(queue)].QueueWaitIdle(queue); |
| 1239 | } |
| 1240 | |
| 1241 | void VKAPI_CALL PrimusVK_DeviceWaitIdle(VkDevice device){ |
| 1242 | auto &my_instance = *device_instance_info[GetKey(device)]; |
| 1243 | device_dispatch[GetKey(device)].DeviceWaitIdle(device); |
| 1244 | auto display_gpu = my_instance.cod[GetKey(device)]->display_gpu; |
| 1245 | device_dispatch[GetKey(display_gpu)].DeviceWaitIdle(display_gpu); |
| 1246 | } |
| 1247 | |
| 1248 | #include "primus_vk_forwarding_prototypes.h" |
| 1249 | |
| 1250 | /////////////////////////////////////////////////////////////////////////////////////////// |
| 1251 | // Enumeration function |
| 1252 | |
| 1253 | VkResult VKAPI_CALL PrimusVK_EnumerateInstanceLayerProperties(uint32_t *pPropertyCount, |
| 1254 | VkLayerProperties *pProperties) |
| 1255 | { |
| 1256 | if(pPropertyCount) *pPropertyCount = 1; |
| 1257 | |
| 1258 | if(pProperties) |
| 1259 | { |
| 1260 | strcpy(pProperties->layerName, "VK_LAYER_PRIMUS_PrimusVK"); |
| 1261 | strcpy(pProperties->description, "Primus-vk - https://github.com/felixdoerre/primus_vk"); |
| 1262 | pProperties->implementationVersion = 1; |
| 1263 | pProperties->specVersion = VK_API_VERSION_1_0; |
| 1264 | } |
| 1265 | |
| 1266 | return VK_SUCCESS; |
| 1267 | } |
| 1268 | |
| 1269 | VkResult VKAPI_CALL PrimusVK_EnumerateDeviceLayerProperties( |
| 1270 | VkPhysicalDevice physicalDevice, uint32_t *pPropertyCount, VkLayerProperties *pProperties) |
| 1271 | { |
| 1272 | return PrimusVK_EnumerateInstanceLayerProperties(pPropertyCount, pProperties); |
| 1273 | } |
| 1274 | |
| 1275 | VkResult VKAPI_CALL PrimusVK_EnumerateInstanceExtensionProperties( |
| 1276 | const char *pLayerName, uint32_t *pPropertyCount, VkExtensionProperties *pProperties) |
| 1277 | { |
| 1278 | if(pLayerName == NULL || strcmp(pLayerName, "VK_LAYER_PRIMUS_PrimusVK")) |
| 1279 | return VK_ERROR_LAYER_NOT_PRESENT; |
| 1280 | |
| 1281 | // don't expose any extensions |
| 1282 | if(pPropertyCount) *pPropertyCount = 0; |
| 1283 | return VK_SUCCESS; |
| 1284 | } |
| 1285 | |
| 1286 | VkResult VKAPI_CALL PrimusVK_EnumerateDeviceExtensionProperties( |
| 1287 | VkPhysicalDevice physicalDevice, const char *pLayerName, |
| 1288 | uint32_t *pPropertyCount, VkExtensionProperties *pProperties) |
| 1289 | { |
| 1290 | // pass through any queries that aren't to us |
| 1291 | if(pLayerName == NULL || strcmp(pLayerName, "VK_LAYER_PRIMUS_PrimusVK")) |
| 1292 | { |
| 1293 | if(physicalDevice == VK_NULL_HANDLE) { |
| 1294 | *pPropertyCount = 0; |
| 1295 | return VK_SUCCESS; |
| 1296 | } |
| 1297 | |
| 1298 | scoped_lock l(global_lock); |
| 1299 | return instance_dispatch[GetKey(physicalDevice)].EnumerateDeviceExtensionProperties(physicalDevice, pLayerName, pPropertyCount, pProperties); |
| 1300 | } |
| 1301 | |
| 1302 | // don't expose any extensions |
| 1303 | if(pPropertyCount) *pPropertyCount = 0; |
| 1304 | return VK_SUCCESS; |
| 1305 | } |
| 1306 | |
| 1307 | VkResult VKAPI_CALL PrimusVK_EnumeratePhysicalDevices( |
| 1308 | VkInstance instance, |
| 1309 | uint32_t* pPhysicalDeviceCount, |
| 1310 | VkPhysicalDevice* pPhysicalDevices){ |
| 1311 | const int cnt = 1; |
| 1312 | scoped_lock l(global_lock); |
| 1313 | InstanceInfo &info = instance_info[GetKey(instance)]; |
| 1314 | if(info.render == VK_NULL_HANDLE){ |
| 1315 | auto res = info.searchDevices(instance_dispatch[GetKey(instance)]); |
| 1316 | if(res != VK_SUCCESS) return res; |
| 1317 | } |
| 1318 | if(pPhysicalDevices == nullptr){ |
| 1319 | *pPhysicalDeviceCount = cnt; |
| 1320 | return VK_SUCCESS; |
| 1321 | } |
| 1322 | pPhysicalDevices[0] = info.render; |
| 1323 | *pPhysicalDeviceCount = cnt; |
| 1324 | return VK_SUCCESS; |
| 1325 | } |
| 1326 | VkResult VKAPI_CALL PrimusVK_EnumeratePhysicalDeviceGroups( |
| 1327 | VkInstance instance, |
| 1328 | uint32_t* pPhysicalDeviceGroupCount, |
| 1329 | VkPhysicalDeviceGroupProperties* pPhysicalDeviceGroupProperties) { |
| 1330 | InstanceInfo &info = instance_info[GetKey(instance)]; |
| 1331 | *pPhysicalDeviceGroupCount = 1; |
| 1332 | if(pPhysicalDeviceGroupProperties){ |
| 1333 | pPhysicalDeviceGroupProperties[0].sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_GROUP_PROPERTIES; |
| 1334 | pPhysicalDeviceGroupProperties[0].pNext = nullptr; |
| 1335 | pPhysicalDeviceGroupProperties[0].physicalDeviceCount = 1; |
| 1336 | pPhysicalDeviceGroupProperties[0].physicalDevices[0] = info.render; |
| 1337 | pPhysicalDeviceGroupProperties[0].subsetAllocation = VK_FALSE; |
| 1338 | } |
| 1339 | return VK_SUCCESS; |
| 1340 | } |
| 1341 | VkResult VKAPI_CALL PrimusVK_EnumeratePhysicalDeviceGroupsKHR( |
| 1342 | VkInstance instance, |
| 1343 | uint32_t* pPhysicalDeviceGroupCount, |
| 1344 | VkPhysicalDeviceGroupProperties* pPhysicalDeviceGroupProperties) { |
| 1345 | return PrimusVK_EnumeratePhysicalDeviceGroups(instance, pPhysicalDeviceGroupCount, pPhysicalDeviceGroupProperties); |
| 1346 | } |
| 1347 | |
| 1348 | VkResult VKAPI_CALL PrimusVK_GetRandROutputDisplayEXT( |
| 1349 | VkPhysicalDevice physicalDevice, |
| 1350 | Display* dpy, |
| 1351 | RROutput rrOutput, |
| 1352 | VkDisplayKHR* pDisplay){ |
| 1353 | TRACE("Suppressing GetRandROutputDisplay"); |
| 1354 | *pDisplay = VK_NULL_HANDLE; |
| 1355 | return VK_SUCCESS; |
| 1356 | } |
| 1357 | |
| 1358 | /////////////////////////////////////////////////////////////////////////////////////////// |
| 1359 | // GetProcAddr functions, entry points of the layer |
| 1360 | |
| 1361 | #define GETPROCADDR(func) if(!strcmp(pName, "vk" #func)) return (PFN_vkVoidFunction)&PrimusVK_##func; |
| 1362 | |
| 1363 | VK_LAYER_EXPORT PFN_vkVoidFunction VKAPI_CALL PrimusVK_GetDeviceProcAddr(VkDevice device, const char *pName) |
| 1364 | { |
| 1365 | // device chain functions we intercept |
| 1366 | GETPROCADDR(GetDeviceProcAddr); |
| 1367 | GETPROCADDR(EnumerateDeviceLayerProperties); |
| 1368 | GETPROCADDR(EnumerateDeviceExtensionProperties); |
| 1369 | GETPROCADDR(CreateDevice); |
| 1370 | GETPROCADDR(DestroyDevice); |
| 1371 | |
| 1372 | GETPROCADDR(CreateSwapchainKHR); |
| 1373 | GETPROCADDR(DestroySwapchainKHR); |
| 1374 | GETPROCADDR(GetSwapchainImagesKHR); |
| 1375 | GETPROCADDR(AcquireNextImageKHR); |
| 1376 | GETPROCADDR(AcquireNextImage2KHR); |
| 1377 | GETPROCADDR(GetSwapchainStatusKHR); |
| 1378 | GETPROCADDR(QueuePresentKHR); |
| 1379 | |
| 1380 | GETPROCADDR(QueueSubmit); |
| 1381 | GETPROCADDR(DeviceWaitIdle); |
| 1382 | GETPROCADDR(QueueWaitIdle); |
| 1383 | GETPROCADDR(GetRandROutputDisplayEXT); |
| 1384 | #define FORWARD(func) GETPROCADDR(func) |
| 1385 | FORWARD(GetPhysicalDeviceSurfaceSupportKHR); |
| 1386 | #include "primus_vk_forwarding.h" |
| 1387 | #undef FORWARD |
| 1388 | { |
| 1389 | scoped_lock l(global_lock); |
| 1390 | return device_dispatch[GetKey(device)].GetDeviceProcAddr(device, pName); |
| 1391 | } |
| 1392 | } |
| 1393 | |
| 1394 | VK_LAYER_EXPORT PFN_vkVoidFunction VKAPI_CALL PrimusVK_GetInstanceProcAddr(VkInstance instance, const char *pName) |
| 1395 | { |
| 1396 | // instance chain functions we intercept |
| 1397 | GETPROCADDR(GetInstanceProcAddr); |
| 1398 | GETPROCADDR(EnumeratePhysicalDevices); |
| 1399 | GETPROCADDR(EnumeratePhysicalDeviceGroups); |
| 1400 | GETPROCADDR(EnumeratePhysicalDeviceGroupsKHR); |
| 1401 | GETPROCADDR(EnumerateInstanceLayerProperties); |
| 1402 | GETPROCADDR(EnumerateInstanceExtensionProperties); |
| 1403 | GETPROCADDR(CreateInstance); |
| 1404 | GETPROCADDR(DestroyInstance); |
| 1405 | |
| 1406 | // device chain functions we intercept |
| 1407 | GETPROCADDR(GetDeviceProcAddr); |
| 1408 | GETPROCADDR(EnumerateDeviceLayerProperties); |
| 1409 | GETPROCADDR(EnumerateDeviceExtensionProperties); |
| 1410 | GETPROCADDR(CreateDevice); |
| 1411 | GETPROCADDR(DestroyDevice); |
| 1412 | |
| 1413 | GETPROCADDR(CreateSwapchainKHR); |
| 1414 | GETPROCADDR(DestroySwapchainKHR); |
| 1415 | GETPROCADDR(GetSwapchainImagesKHR); |
| 1416 | GETPROCADDR(AcquireNextImageKHR); |
| 1417 | GETPROCADDR(AcquireNextImage2KHR); |
| 1418 | GETPROCADDR(GetSwapchainStatusKHR); |
| 1419 | GETPROCADDR(QueuePresentKHR); |
| 1420 | |
| 1421 | GETPROCADDR(QueueSubmit); |
| 1422 | GETPROCADDR(DeviceWaitIdle); |
| 1423 | GETPROCADDR(QueueWaitIdle); |
| 1424 | GETPROCADDR(GetRandROutputDisplayEXT); |
| 1425 | GETPROCADDR(GetPhysicalDeviceQueueFamilyProperties); |
| 1426 | #ifdef VK_USE_PLATFORM_XCB_KHR |
| 1427 | GETPROCADDR(GetPhysicalDeviceXcbPresentationSupportKHR); |
| 1428 | #endif |
| 1429 | #ifdef VK_USE_PLATFORM_XLIB_KHR |
| 1430 | GETPROCADDR(GetPhysicalDeviceXlibPresentationSupportKHR); |
| 1431 | #endif |
| 1432 | #ifdef VK_USE_PLATFORM_WAYLAND_KHR |
| 1433 | GETPROCADDR(GetPhysicalDeviceWaylandPresentationSupportKHR); |
| 1434 | #endif |
| 1435 | #define FORWARD(func) GETPROCADDR(func) |
| 1436 | FORWARD(GetPhysicalDeviceSurfaceSupportKHR); |
| 1437 | #include "primus_vk_forwarding.h" |
| 1438 | #undef FORWARD |
| 1439 | { |
| 1440 | scoped_lock l(global_lock); |
| 1441 | return instance_dispatch[GetKey(instance)].GetInstanceProcAddr(instance, pName); |
| 1442 | } |
| 1443 | } |