2 * Copyright (c) 2018 Samsung Electronics Co., Ltd.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 #include <dali/graphics/vulkan/vulkan-graphics.h>
20 #include <dali/graphics/vulkan/vulkan-command-pool.h>
21 #include <dali/graphics/vulkan/vulkan-queue.h>
22 #include <dali/graphics/vulkan/vulkan-surface.h>
23 #include <dali/integration-api/graphics/vulkan/vk-surface-factory.h>
24 #include <dali/graphics/vulkan/gpu-memory/vulkan-gpu-memory-manager.h>
26 #include <dali/graphics/vulkan/vulkan-buffer.h>
27 #include <dali/graphics/vulkan/vulkan-image.h>
28 #include <dali/graphics/vulkan/vulkan-pipeline.h>
29 #include <dali/graphics/vulkan/vulkan-shader.h>
30 #include <dali/graphics/vulkan/vulkan-descriptor-set.h>
31 #include <dali/graphics/vulkan/vulkan-framebuffer.h>
32 #include <dali/graphics/vulkan/api/vulkan-api-controller.h>
33 #include <dali/graphics/vulkan/vulkan-pipeline-cache.h>
35 #include <dali/graphics-api/graphics-api-controller.h>
37 #ifndef VK_KHR_XLIB_SURFACE_EXTENSION_NAME
38 #define VK_KHR_XLIB_SURFACE_EXTENSION_NAME "VK_KHR_xlib_surface"
41 #ifndef VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME
42 #define VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME "VK_KHR_wayland_surface"
45 #ifndef VK_KHR_XCB_SURFACE_EXTENSION_NAME
46 #define VK_KHR_XCB_SURFACE_EXTENSION_NAME "VK_KHR_xcb_surface"
53 using VkSurfaceFactory = Dali::Integration::Graphics::Vulkan::VkSurfaceFactory;
57 const auto VALIDATION_LAYERS = std::vector< const char* >{
59 //"VK_LAYER_LUNARG_screenshot", // screenshot
60 //"VK_LAYER_RENDERDOC_Capture",
61 //"VK_LAYER_LUNARG_parameter_validation", // parameter
62 //"VK_LAYER_LUNARG_vktrace", // vktrace ( requires vktrace connection )
63 //"VK_LAYER_LUNARG_monitor", // monitor
64 "VK_LAYER_LUNARG_swapchain", // swapchain
65 "VK_LAYER_GOOGLE_threading", // threading
66 "VK_LAYER_LUNARG_api_dump", // api
67 "VK_LAYER_LUNARG_object_tracker", // objects
68 "VK_LAYER_LUNARG_core_validation", // core
69 "VK_LAYER_GOOGLE_unique_objects", // unique objects
70 "VK_LAYER_GOOGLE_unique_objects", // unique objects
71 "VK_LAYER_LUNARG_standard_validation", // standard
74 Graphics::Graphics() = default;
76 Graphics::~Graphics() = default;
77 #pragma GCC diagnostic push
78 #pragma GCC diagnostic ignored "-Wframe-larger-than="
80 Platform Graphics::GetDefaultPlatform() const
82 #ifdef VK_USE_PLATFORM_WAYLAND_KHR
83 mPlatform = Platform::WAYLAND;
84 #elif VK_USE_PLATFORM_XCB_KHR
85 mPlatform = Platform::XCB;
86 #elif VK_USE_PLATFORM_XLIB_KHR
87 mPlatform = Platform::XLIB;
93 Dali::Graphics::API::Controller& Graphics::GetController()
97 mGfxController = Dali::Graphics::VulkanAPI::Controller::New(*this);
100 return *mGfxController.get();
103 std::vector<const char*> Graphics::PrepareDefaultInstanceExtensions()
105 auto extensions = vk::enumerateInstanceExtensionProperties();
107 std::string extensionName;
109 bool xlibAvailable { false };
110 bool xcbAvailable { false };
111 bool waylandAvailable { false };
113 for( auto&& ext : extensions.value )
115 extensionName = ext.extensionName;
116 if( extensionName == VK_KHR_XCB_SURFACE_EXTENSION_NAME )
120 else if( extensionName == VK_KHR_XLIB_SURFACE_EXTENSION_NAME )
122 xlibAvailable = true;
124 else if( extensionName == VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME )
126 waylandAvailable = true;
130 std::vector<const char*> retval;
132 // depending on the platform validate extensions
133 auto platform = GetDefaultPlatform();
135 if( platform != Platform::UNDEFINED )
137 if (platform == Platform::XCB && xcbAvailable)
139 retval.push_back(VK_KHR_XCB_SURFACE_EXTENSION_NAME);
141 else if (platform == Platform::XLIB && xlibAvailable)
143 retval.push_back(VK_KHR_XLIB_SURFACE_EXTENSION_NAME);
145 else if (platform == Platform::WAYLAND && waylandAvailable)
147 retval.push_back(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME);
150 else // try to determine the platform based on available extensions
154 mPlatform = Platform::XCB;
155 retval.push_back(VK_KHR_XCB_SURFACE_EXTENSION_NAME);
157 else if (xlibAvailable)
159 mPlatform = Platform::XLIB;
160 retval.push_back(VK_KHR_XLIB_SURFACE_EXTENSION_NAME);
162 else if (waylandAvailable)
164 mPlatform = Platform::WAYLAND;
165 retval.push_back(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME);
169 // can't determine the platform!
170 mPlatform = Platform::UNDEFINED;
174 // other essential extensions
175 retval.push_back( VK_KHR_SURFACE_EXTENSION_NAME );
176 retval.push_back( VK_EXT_DEBUG_REPORT_EXTENSION_NAME );
181 void Graphics::Create()
184 auto extensions = PrepareDefaultInstanceExtensions();
186 auto layers = vk::enumerateInstanceLayerProperties();
187 std::vector<const char*> validationLayers;
188 for( auto&& reqLayer : VALIDATION_LAYERS )
190 for( auto&& prop : layers.value )
192 std::cout << prop.layerName << std::endl;
193 if( std::string(prop.layerName) == reqLayer )
195 validationLayers.push_back(reqLayer);
200 CreateInstance(extensions, validationLayers);
201 PreparePhysicalDevice();
204 void Graphics::CreateInstance( const std::vector<const char*>& extensions, const std::vector<const char*>& validationLayers )
206 auto info = vk::InstanceCreateInfo{};
208 info.setEnabledExtensionCount(U32(extensions.size()))
209 .setPpEnabledExtensionNames(extensions.data())
210 .setEnabledLayerCount(U32(validationLayers.size()))
211 .setEnabledLayerCount(0)
212 .setPpEnabledLayerNames(validationLayers.data());
214 mInstance = VkAssert(vk::createInstance(info, *mAllocator));
217 void Graphics::DestroyInstance()
221 mInstance.destroy(*mAllocator);
227 void Graphics::PreparePhysicalDevice()
229 auto devices = VkAssert(mInstance.enumeratePhysicalDevices());
230 assert(devices.size() > 0 && "No Vulkan supported device found!");
232 // if only one, pick first
233 mPhysicalDevice = nullptr;
234 if(devices.size() == 1)
236 mPhysicalDevice = devices[0];
238 else // otherwise look for one which is a graphics device
240 for(auto& device : devices)
242 auto properties =device.getProperties();
243 if(properties.deviceType == vk::PhysicalDeviceType::eDiscreteGpu ||
244 properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu)
246 mPhysicalDevice = device;
252 assert(mPhysicalDevice && "No suitable Physical Device found!");
254 GetPhysicalDeviceProperties();
256 GetQueueFamilyProperties();
258 mDeviceMemoryManager = GpuMemoryManager::New( *this );
260 #pragma GCC diagnostic pop
262 #pragma GCC diagnostic push
263 #pragma GCC diagnostic ignored "-Wframe-larger-than="
264 void Graphics::GetPhysicalDeviceProperties()
266 // store data on heap to keep object smaller
267 mPhysicalDeviceProperties =
268 MakeUnique<vk::PhysicalDeviceProperties>(mPhysicalDevice.getProperties());
269 mPhysicalDeviceMemoryProperties =
270 MakeUnique<vk::PhysicalDeviceMemoryProperties>(mPhysicalDevice.getMemoryProperties());
271 mPhysicalDeviceFeatures =
272 MakeUnique<vk::PhysicalDeviceFeatures>(mPhysicalDevice.getFeatures());
274 #pragma GCC diagnostic pop
276 void Graphics::GetQueueFamilyProperties()
278 mQueueFamilyProperties = mPhysicalDevice.getQueueFamilyProperties();
281 FBID Graphics::CreateSurface(std::unique_ptr< SurfaceFactory > surfaceFactory)
283 // create surface from the factory
284 auto surfaceRef = Surface::New( *this, std::move(surfaceFactory) );
286 if( surfaceRef->Create() )
289 // map surface to FBID
290 auto fbid = ++mBaseFBID;
291 mSurfaceFBIDMap[fbid] = SwapchainSurfacePair{ SwapchainRef{}, surfaceRef };
297 SwapchainRef Graphics::CreateSwapchainForSurface( SurfaceRef surface )
299 auto swapchain = Swapchain::New( *this,
300 GetGraphicsQueue(0u),
303 // store swapchain in the correct pair
304 for( auto&& val : mSurfaceFBIDMap )
306 if( val.second.surface == surface )
308 val.second.swapchain = swapchain;
316 SwapchainRef Graphics::GetSwapchainForSurface( SurfaceRef surface )
318 for( auto&& val : mSurfaceFBIDMap )
320 if( val.second.surface == surface )
326 return SwapchainRef();
329 SwapchainRef Graphics::GetSwapchainForFBID( FBID surfaceId )
333 return mSurfaceFBIDMap.begin()->second.swapchain;
335 return mSurfaceFBIDMap[surfaceId].swapchain;
338 #pragma GCC diagnostic push
339 #pragma GCC diagnostic ignored "-Wframe-larger-than="
340 std::vector< vk::DeviceQueueCreateInfo > Graphics::GetQueueCreateInfos()
342 // surface is needed in order to find a family that supports presentation to this surface
343 // fixme: assuming all surfaces will be compatible with the queue family
344 assert(!mSurfaceFBIDMap.empty() &&
345 "At least one surface has to be created before creating VkDevice!");
347 auto queueInfos = std::vector< vk::DeviceQueueCreateInfo >{};
349 constexpr uint8_t MAX_QUEUE_TYPES = 3;
350 // find suitable family for each type of queue
351 uint32_t familyIndexType[MAX_QUEUE_TYPES];
352 std::fill(&familyIndexType[0], &familyIndexType[MAX_QUEUE_TYPES], -1u);
355 auto& graphicsFamily = familyIndexType[0];
358 auto& transferFamily = familyIndexType[1];
361 auto& presentFamily = familyIndexType[2];
363 auto queueFamilyIndex = 0u;
364 for(auto& prop : mQueueFamilyProperties)
366 if((prop.queueFlags & vk::QueueFlagBits::eGraphics) && graphicsFamily == -1u)
368 graphicsFamily = queueFamilyIndex;
370 if((prop.queueFlags & vk::QueueFlagBits::eTransfer) && transferFamily == -1u)
372 transferFamily = queueFamilyIndex;
374 if(mPhysicalDevice.getSurfaceSupportKHR(queueFamilyIndex, mSurfaceFBIDMap.begin()->second.surface->GetSurfaceKHR())
376 presentFamily == -1u)
378 presentFamily = queueFamilyIndex;
383 assert(graphicsFamily != -1u && "No queue family that supports graphics operations!");
384 assert(transferFamily != -1u && "No queue family that supports transfer operations!");
385 assert(presentFamily != -1u && "No queue family that supports present operations!");
387 // todo: we may require that the family must be same for all types of operations, it makes
388 // easier to handle synchronisation related issues.
391 std::sort(&familyIndexType[0], &familyIndexType[MAX_QUEUE_TYPES]);
393 // allocate all queues from graphics family
394 uint32_t prevQueueFamilyIndex = -1u;
396 for(auto i = 0u; i < MAX_QUEUE_TYPES; ++i)
398 auto& familyIndex = familyIndexType[i];
399 if(prevQueueFamilyIndex == familyIndex)
404 auto& queueCount = mQueueFamilyProperties[familyIndex].queueCount;
406 // fill queue create info for the family.
407 // note the priorities are not being set as local pointer will out of scope, this
408 // will be fixed by the caller function
409 auto info = vk::DeviceQueueCreateInfo{}
410 .setPQueuePriorities(nullptr)
411 .setQueueCount(queueCount)
412 .setQueueFamilyIndex(familyIndex);
413 queueInfos.push_back(info);
414 prevQueueFamilyIndex = familyIndex;
419 #pragma GCC diagnostic pop
421 #pragma GCC diagnostic push
422 #pragma GCC diagnostic ignored "-Wframe-larger-than="
423 void Graphics::CreateDevice()
425 auto queueInfos = GetQueueCreateInfos();
427 auto maxQueueCountPerFamily = 0u;
428 for( auto&& info : queueInfos )
430 maxQueueCountPerFamily = std::max( info.queueCount, maxQueueCountPerFamily );
433 auto priorities = std::vector<float>( maxQueueCountPerFamily );
434 std::fill( priorities.begin(), priorities.end(), 1.0f );
436 for( auto& info : queueInfos )
438 info.setPQueuePriorities( priorities.data() );
441 auto extensions = std::vector< const char* >{VK_KHR_SWAPCHAIN_EXTENSION_NAME};
443 auto info = vk::DeviceCreateInfo{};
444 info.setEnabledExtensionCount(U32(extensions.size()))
445 .setPpEnabledExtensionNames(extensions.data())
446 .setPEnabledFeatures(&(*mPhysicalDeviceFeatures))
447 .setPQueueCreateInfos(queueInfos.data())
448 .setQueueCreateInfoCount(U32(queueInfos.size()));
450 mDevice = VkAssert(mPhysicalDevice.createDevice(info, *mAllocator));
453 // create Queue objects
454 for(auto& queueInfo : queueInfos)
456 for(auto i = 0u; i < queueInfo.queueCount; ++i)
458 auto queue = mDevice.getQueue(queueInfo.queueFamilyIndex, i);
460 // based on family push queue instance into right array
461 auto flags = mQueueFamilyProperties[queueInfo.queueFamilyIndex].queueFlags;
462 if(flags & vk::QueueFlagBits::eGraphics)
464 mGraphicsQueues.emplace_back(
465 MakeUnique<Queue>(*this, queue, queueInfo.queueFamilyIndex, i, flags));
467 if(flags & vk::QueueFlagBits::eTransfer)
469 mTransferQueues.emplace_back(
470 MakeUnique<Queue>(*this, queue, queueInfo.queueFamilyIndex, i, flags));
472 if(flags & vk::QueueFlagBits::eCompute)
474 mComputeQueues.emplace_back(
475 MakeUnique<Queue>(*this, queue, queueInfo.queueFamilyIndex, i, flags));
478 // todo: present queue
482 mPipelineDatabase = std::make_unique<PipelineCache>( *this );
484 #pragma GCC diagnostic pop
486 vk::Device Graphics::GetDevice() const
491 vk::PhysicalDevice Graphics::GetPhysicalDevice() const
493 return mPhysicalDevice;
496 vk::Instance Graphics::GetInstance() const
501 const vk::AllocationCallbacks& Graphics::GetAllocator() const
506 Queue& Graphics::GetGraphicsQueue(uint32_t index) const
508 // todo: at the moment each type of queue may use only one, indices greater than 0 are invalid
509 // this will change in the future
510 assert(index == 0u && "Each type of queue may use only one, indices greater than 0 are invalid!");
512 return *mGraphicsQueues[0].get(); // will be mGraphicsQueues[index]
515 Queue& Graphics::GetTransferQueue(uint32_t index) const
517 // todo: at the moment each type of queue may use only one, indices greater than 0 are invalid
518 // this will change in the future
519 assert(index == 0u && "Each type of queue may use only one, indices greater than 0 are invalid!");
521 return *mTransferQueues[0].get(); // will be mGraphicsQueues[index]
524 Queue& Graphics::GetComputeQueue(uint32_t index) const
526 // todo: at the moment each type of queue may use only one, indices greater than 0 are invalid
527 // this will change in the future
528 assert(index == 0u && "Each type of queue may use only one, indices greater than 0 are invalid!");
530 return *mComputeQueues[0].get(); // will be mGraphicsQueues[index]
533 Queue& Graphics::GetPresentQueue() const
535 // fixme: should be a dedicated presentation queue
536 return GetGraphicsQueue(0);
539 Handle< CommandPool > Graphics::CreateCommandPool(const vk::CommandPoolCreateInfo& info)
541 auto cmdpool = CommandPool::New( *this, vk::CommandPoolCreateInfo{}.
542 setQueueFamilyIndex( 0u ).
543 setFlags( vk::CommandPoolCreateFlagBits::eResetCommandBuffer ) );
547 SurfaceRef Graphics::GetSurface( FBID surfaceId )
549 // TODO: FBID == 0 means default framebuffer, but there should be no
550 // such thing as default framebuffer.
553 return mSurfaceFBIDMap.begin()->second.surface;
555 return mSurfaceFBIDMap[surfaceId].surface;
558 // TODO: all this stuff should go into some vulkan cache
560 void Graphics::AddBuffer( Handle<Buffer> buffer )
562 mBuffersCache.push_back( buffer );
565 void Graphics::AddImage( Handle<Image> image )
567 mImageCache.push_back( image );
570 void Graphics::AddPipeline( Handle<Pipeline> pipeline )
572 mPipelineCache.push_back( pipeline );
575 void Graphics::AddShader( Handle<Shader> shader )
577 mShaderCache.push_back( shader );
580 void Graphics::AddCommandPool( Handle<CommandPool> pool )
582 mCommandPoolCache.push_back( pool );
585 void Graphics::AddDescriptorPool( Handle<DescriptorPool> pool )
587 mDescriptorPoolCache.push_back( pool );
590 void Graphics::AddFramebuffer( Handle<Framebuffer> framebuffer )
592 mFramebufferCache.push_back( framebuffer );
595 void Graphics::RemoveBuffer( Buffer& buffer )
598 for( auto&& iter : mBuffersCache )
600 if( &*iter == &buffer )
603 mBuffersCache.erase( mBuffersCache.begin()+index );
609 void Graphics::RemoveShader( Shader& shader )
612 for( auto&& iter : mShaderCache )
614 if( &*iter == &shader )
617 mShaderCache.erase( mShaderCache.begin()+index );
624 void Graphics::RemoveCommandPool( CommandPool& commandPool )
629 void Graphics::RemoveDescriptorPool( std::unique_ptr<DescriptorPool> pool )
634 ShaderRef Graphics::FindShader( vk::ShaderModule shaderModule )
636 for( auto&& iter : mShaderCache )
638 if( iter->GetVkShaderModule() == shaderModule )
640 return Handle<Shader>(&*iter);
643 return Handle<Shader>();
646 ImageRef Graphics::FindImage( vk::Image image )
648 for( auto&& iter : mImageCache )
650 if( iter->GetVkImage() == image )
652 return ImageRef(&*iter);
660 } // namespace Vulkan
661 } // namespace Graphics