Introduce raii-compliant handle wrapper classes.

This commit is contained in:
asuessenbach 2021-02-17 10:49:59 +01:00
parent 8dc12ba963
commit 2cb1c19c7f
165 changed files with 32669 additions and 2892 deletions

View File

@ -74,7 +74,9 @@ if (NOT DEFINED VulkanHeaders_INCLUDE_DIR)
endif()
file(TO_NATIVE_PATH ${VulkanHeaders_INCLUDE_DIR}/vulkan/vulkan.hpp vulkan_hpp)
string(REPLACE "\\" "\\\\" vulkan_hpp ${vulkan_hpp})
add_definitions(-DVULKAN_HPP_FILE="${vulkan_hpp}")
file(TO_NATIVE_PATH ${VulkanHeaders_INCLUDE_DIR}/vulkan/vulkan_raii.hpp vulkan_raii_hpp)
string(REPLACE "\\" "\\\\" vulkan_raii_hpp ${vulkan_raii_hpp})
add_definitions(-DVULKAN_HPP_FILE="${vulkan_hpp}" -DVULKAN_RAII_HPP_FILE="${vulkan_raii_hpp}")
include_directories(${VulkanHeaders_INCLUDE_DIR})
set(HEADERS
@ -146,6 +148,7 @@ if (SAMPLES_BUILD)
add_subdirectory(glslang)
# samples
add_subdirectory(samples)
add_subdirectory(RAII_Samples)
endif ()
option (TESTS_BUILD "Build tests" OFF)

View File

@ -0,0 +1,62 @@
// Copyright(c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : 01_InitInstanceRAII
// Create and destroy a vk::UniqueInstance
#include "vulkan/vulkan_raii.hpp"
#include "../utils/utils.hpp"
#include <iostream>
static std::string AppName = "01_InitInstanceRAII";
static std::string EngineName = "Vulkan.hpp";
int main( int /*argc*/, char ** /*argv*/ )
{
/* VULKAN_HPP_KEY_START */
try
{
// the very beginning: instantiate a context
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
// initialize the vk::ApplicationInfo structure
vk::ApplicationInfo applicationInfo( AppName.c_str(), 1, EngineName.c_str(), 1, VK_API_VERSION_1_1 );
// initialize the vk::InstanceCreateInfo
vk::InstanceCreateInfo instanceCreateInfo( {}, &applicationInfo );
// create an Instance
std::unique_ptr<vk::raii::Instance> instance = vk::raii::su::make_unique<vk::raii::Instance>( *context, instanceCreateInfo );
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
/* VULKAN_HPP_KEY_END */
return 0;
}

View File

@ -0,0 +1,39 @@
# Copyright(c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
if(NOT SAMPLES_BUILD_ONLY_DYNAMIC)
project(RAII_01_InitInstance)
set(HEADERS
)
set(SOURCES
01_InitInstance.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_01_InitInstance
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_01_InitInstance PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_01_InitInstance PRIVATE utils)
endif()

View File

@ -0,0 +1,69 @@
// Copyright(c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : 02_EnumerateDevicesRAII
// Enumerate physical devices
#if defined( _MSC_VER )
// no need to ignore any warnings with MSVC
#elif defined( __clang__ )
# pragma clang diagnostic ignored "-Wunused-variable"
#elif defined( __GNUC__ )
# pragma GCC diagnostic ignored "-Wunused-but-set-variable"
#else
// unknow compiler... just ignore the warnings for yourselves ;)
#endif
#include "../utils/utils.hpp"
#include <iostream>
static std::string AppName = "02_EnumerateDevicesRAII";
static std::string EngineName = "Vulkan.hpp";
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
std::unique_ptr<vk::raii::Instance> instance = vk::raii::su::makeUniqueInstance( *context, AppName, EngineName );
#if !defined( NDEBUG )
std::unique_ptr<vk::raii::DebugUtilsMessengerEXT> debugUtilsMessenger =
vk::raii::su::makeUniqueDebugUtilsMessengerEXT( *instance );
#endif
/* VULKAN_HPP_KEY_START */
// enumerate the physicalDevices
vk::raii::PhysicalDevices physicalDevices( *instance );
/* VULKAN_HPP_KEY_END */
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,35 @@
# Copyright(c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_02_EnumerateDevices)
set(HEADERS
)
set(SOURCES
02_EnumerateDevices.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_02_EnumerateDevices
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_02_EnumerateDevices PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_02_EnumerateDevices PRIVATE utils)

View File

@ -0,0 +1,68 @@
// Copyright(c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : 03_InitDeviceRAII
// Create and destroy a device
#include "../utils/utils.hpp"
#include <iostream>
static char const * AppName = "03_InitDeviceRAII";
static char const * EngineName = "Vulkan.hpp";
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
std::unique_ptr<vk::raii::Instance> instance = vk::raii::su::makeUniqueInstance( *context, AppName, EngineName );
#if !defined( NDEBUG )
std::unique_ptr<vk::raii::DebugUtilsMessengerEXT> debugUtilsMessenger =
vk::raii::su::makeUniqueDebugUtilsMessengerEXT( *instance );
#endif
std::unique_ptr<vk::raii::PhysicalDevice> physicalDevice = vk::raii::su::makeUniquePhysicalDevice( *instance );
/* VULKAN_HPP_KEY_START */
// find the index of the first queue family that supports graphics
uint32_t graphicsQueueFamilyIndex =
vk::su::findGraphicsQueueFamilyIndex( physicalDevice->getQueueFamilyProperties() );
// create a Device
float queuePriority = 0.0f;
vk::DeviceQueueCreateInfo deviceQueueCreateInfo( {}, graphicsQueueFamilyIndex, 1, &queuePriority );
vk::DeviceCreateInfo deviceCreateInfo( {}, deviceQueueCreateInfo );
std::unique_ptr<vk::raii::Device> device = vk::raii::su::make_unique<vk::raii::Device>( *physicalDevice, deviceCreateInfo );
/* VULKAN_HPP_KEY_END */
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,35 @@
# Copyright(c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_03_InitDevice)
set(HEADERS
)
set(SOURCES
03_InitDevice.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_03_InitDevice
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_03_InitDevice PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_03_InitDevice PRIVATE utils)

View File

@ -0,0 +1,71 @@
// Copyright(c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : 04_InitCommandBufferRAII
// Create command buffer
#include "../utils/utils.hpp"
#include <iostream>
static char const * AppName = "04_InitCommandBufferRAII";
static char const * EngineName = "Vulkan.hpp";
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
std::unique_ptr<vk::raii::Instance> instance = vk::raii::su::makeUniqueInstance( *context, AppName, EngineName );
#if !defined( NDEBUG )
std::unique_ptr<vk::raii::DebugUtilsMessengerEXT> debugUtilsMessenger =
vk::raii::su::makeUniqueDebugUtilsMessengerEXT( *instance );
#endif
std::unique_ptr<vk::raii::PhysicalDevice> physicalDevice = vk::raii::su::makeUniquePhysicalDevice( *instance );
uint32_t graphicsQueueFamilyIndex =
vk::su::findGraphicsQueueFamilyIndex( physicalDevice->getQueueFamilyProperties() );
std::unique_ptr<vk::raii::Device> device =
vk::raii::su::makeUniqueDevice( *physicalDevice, graphicsQueueFamilyIndex );
/* VULKAN_HPP_KEY_START */
// create a CommandPool to allocate a CommandBuffer from
vk::CommandPoolCreateInfo commandPoolCreateInfo( {}, graphicsQueueFamilyIndex );
std::unique_ptr<vk::raii::CommandPool> commandPool =
vk::raii::su::make_unique<vk::raii::CommandPool>( *device, commandPoolCreateInfo );
// allocate a CommandBuffer from the CommandPool
vk::CommandBufferAllocateInfo commandBufferAllocateInfo( **commandPool, vk::CommandBufferLevel::ePrimary, 1 );
std::unique_ptr<vk::raii::CommandBuffer> commandBuffer = vk::raii::su::make_unique<vk::raii::CommandBuffer>(
std::move( vk::raii::CommandBuffers( *device, commandBufferAllocateInfo ).front() ) );
/* VULKAN_HPP_KEY_END */
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,35 @@
# Copyright(c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_04_InitCommandBuffer)
set(HEADERS
)
set(SOURCES
04_InitCommandBuffer.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_04_InitCommandBuffer
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_04_InitCommandBuffer PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_04_InitCommandBuffer PRIVATE utils)

View File

@ -0,0 +1,192 @@
// Copyright(c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : 05_InitSwapchainRAII
// Initialize a swapchain
#include "../utils/utils.hpp"
#include <iostream>
static char const * AppName = "05_InitSwapchainRAII";
static char const * EngineName = "Vulkan.hpp";
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
std::unique_ptr<vk::raii::Instance> instance =
vk::raii::su::makeUniqueInstance( *context, AppName, EngineName, {}, vk::su::getInstanceExtensions() );
#if !defined( NDEBUG )
std::unique_ptr<vk::raii::DebugUtilsMessengerEXT> debugUtilsMessenger =
vk::raii::su::makeUniqueDebugUtilsMessengerEXT( *instance );
#endif
std::unique_ptr<vk::raii::PhysicalDevice> physicalDevice = vk::raii::su::makeUniquePhysicalDevice( *instance );
std::vector<vk::QueueFamilyProperties> queueFamilyProperties = physicalDevice->getQueueFamilyProperties();
uint32_t graphicsQueueFamilyIndex = vk::su::findGraphicsQueueFamilyIndex( queueFamilyProperties );
/* VULKAN_HPP_KEY_START */
uint32_t width = 64;
uint32_t height = 64;
vk::su::WindowData window = vk::su::createWindow( AppName, { width, height } );
VkSurfaceKHR _surface;
glfwCreateWindowSurface( static_cast<VkInstance>( **instance ), window.handle, nullptr, &_surface );
std::unique_ptr<vk::raii::SurfaceKHR> surface = vk::raii::su::make_unique<vk::raii::SurfaceKHR>( *instance, _surface );
// determine a queueFamilyIndex that suports present
// first check if the graphicsQueueFamiliyIndex is good enough
uint32_t presentQueueFamilyIndex = physicalDevice->getSurfaceSupportKHR( graphicsQueueFamilyIndex, **surface )
? graphicsQueueFamilyIndex
: vk::su::checked_cast<uint32_t>( queueFamilyProperties.size() );
if ( presentQueueFamilyIndex == queueFamilyProperties.size() )
{
// the graphicsQueueFamilyIndex doesn't support present -> look for an other family index that supports both
// graphics and present
for ( size_t i = 0; i < queueFamilyProperties.size(); i++ )
{
if ( ( queueFamilyProperties[i].queueFlags & vk::QueueFlagBits::eGraphics ) &&
physicalDevice->getSurfaceSupportKHR( vk::su::checked_cast<uint32_t>( i ), **surface ) )
{
graphicsQueueFamilyIndex = vk::su::checked_cast<uint32_t>( i );
presentQueueFamilyIndex = graphicsQueueFamilyIndex;
break;
}
}
if ( presentQueueFamilyIndex == queueFamilyProperties.size() )
{
// there's nothing like a single family index that supports both graphics and present -> look for an other
// family index that supports present
for ( size_t i = 0; i < queueFamilyProperties.size(); i++ )
{
if ( physicalDevice->getSurfaceSupportKHR( vk::su::checked_cast<uint32_t>( i ), **surface ) )
{
presentQueueFamilyIndex = vk::su::checked_cast<uint32_t>( i );
break;
}
}
}
}
if ( ( graphicsQueueFamilyIndex == queueFamilyProperties.size() ) ||
( presentQueueFamilyIndex == queueFamilyProperties.size() ) )
{
throw std::runtime_error( "Could not find a queue for graphics or present -> terminating" );
}
// create a device
std::unique_ptr<vk::raii::Device> device =
vk::raii::su::makeUniqueDevice( *physicalDevice, graphicsQueueFamilyIndex, vk::su::getDeviceExtensions() );
// get the supported VkFormats
std::vector<vk::SurfaceFormatKHR> formats = physicalDevice->getSurfaceFormatsKHR( **surface );
assert( !formats.empty() );
vk::Format format =
( formats[0].format == vk::Format::eUndefined ) ? vk::Format::eB8G8R8A8Unorm : formats[0].format;
vk::SurfaceCapabilitiesKHR surfaceCapabilities = physicalDevice->getSurfaceCapabilitiesKHR( **surface );
VkExtent2D swapchainExtent;
if ( surfaceCapabilities.currentExtent.width == std::numeric_limits<uint32_t>::max() )
{
// If the surface size is undefined, the size is set to the size of the images requested.
swapchainExtent.width =
vk::su::clamp( width, surfaceCapabilities.minImageExtent.width, surfaceCapabilities.maxImageExtent.width );
swapchainExtent.height =
vk::su::clamp( height, surfaceCapabilities.minImageExtent.height, surfaceCapabilities.maxImageExtent.height );
}
else
{
// If the surface size is defined, the swap chain size must match
swapchainExtent = surfaceCapabilities.currentExtent;
}
// The FIFO present mode is guaranteed by the spec to be supported
vk::PresentModeKHR swapchainPresentMode = vk::PresentModeKHR::eFifo;
vk::SurfaceTransformFlagBitsKHR preTransform =
( surfaceCapabilities.supportedTransforms & vk::SurfaceTransformFlagBitsKHR::eIdentity )
? vk::SurfaceTransformFlagBitsKHR::eIdentity
: surfaceCapabilities.currentTransform;
vk::CompositeAlphaFlagBitsKHR compositeAlpha =
( surfaceCapabilities.supportedCompositeAlpha & vk::CompositeAlphaFlagBitsKHR::ePreMultiplied )
? vk::CompositeAlphaFlagBitsKHR::ePreMultiplied
: ( surfaceCapabilities.supportedCompositeAlpha & vk::CompositeAlphaFlagBitsKHR::ePostMultiplied )
? vk::CompositeAlphaFlagBitsKHR::ePostMultiplied
: ( surfaceCapabilities.supportedCompositeAlpha & vk::CompositeAlphaFlagBitsKHR::eInherit )
? vk::CompositeAlphaFlagBitsKHR::eInherit
: vk::CompositeAlphaFlagBitsKHR::eOpaque;
vk::SwapchainCreateInfoKHR swapChainCreateInfo( vk::SwapchainCreateFlagsKHR(),
**surface,
surfaceCapabilities.minImageCount,
format,
vk::ColorSpaceKHR::eSrgbNonlinear,
swapchainExtent,
1,
vk::ImageUsageFlagBits::eColorAttachment,
vk::SharingMode::eExclusive,
{},
preTransform,
compositeAlpha,
swapchainPresentMode,
true,
nullptr );
std::array<uint32_t, 2> queueFamilyIndices = { graphicsQueueFamilyIndex, presentQueueFamilyIndex };
if ( graphicsQueueFamilyIndex != presentQueueFamilyIndex )
{
// If the graphics and present queues are from different queue families, we either have to explicitly transfer
// ownership of images between the queues, or we have to create the swapchain with imageSharingMode as
// VK_SHARING_MODE_CONCURRENT
swapChainCreateInfo.imageSharingMode = vk::SharingMode::eConcurrent;
swapChainCreateInfo.queueFamilyIndexCount = vk::su::checked_cast<uint32_t>( queueFamilyIndices.size() );
swapChainCreateInfo.pQueueFamilyIndices = queueFamilyIndices.data();
}
std::unique_ptr<vk::raii::SwapchainKHR> swapChain =
vk::raii::su::make_unique<vk::raii::SwapchainKHR>( *device, swapChainCreateInfo );
std::vector<VkImage> swapChainImages = swapChain->getImages();
std::vector<std::unique_ptr<vk::raii::ImageView>> imageViews;
imageViews.reserve( swapChainImages.size() );
vk::ComponentMapping componentMapping(
vk::ComponentSwizzle::eR, vk::ComponentSwizzle::eG, vk::ComponentSwizzle::eB, vk::ComponentSwizzle::eA );
vk::ImageSubresourceRange subResourceRange( vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1 );
for ( auto image : swapChainImages )
{
vk::ImageViewCreateInfo imageViewCreateInfo(
{}, static_cast<vk::Image>( image ), vk::ImageViewType::e2D, format, componentMapping, subResourceRange );
imageViews.push_back( vk::raii::su::make_unique<vk::raii::ImageView>( *device, imageViewCreateInfo ) );
}
/* VULKAN_HPP_KEY_END */
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,35 @@
# Copyright(c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_05_InitSwapchain)
set(HEADERS
)
set(SOURCES
05_InitSwapchain.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_05_InitSwapchain
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_05_InitSwapchain PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_05_InitSwapchain PRIVATE utils)

View File

@ -0,0 +1,123 @@
// Copyright(c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : 06_InitDepthBufferRAII
// Initialize a depth buffer
#include "../utils/utils.hpp"
#include <iostream>
static char const * AppName = "06_InitDepthBuffer";
static char const * EngineName = "Vulkan.hpp";
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
std::unique_ptr<vk::raii::Instance> instance =
vk::raii::su::makeUniqueInstance( *context, AppName, EngineName, {}, vk::su::getInstanceExtensions() );
#if !defined( NDEBUG )
std::unique_ptr<vk::raii::DebugUtilsMessengerEXT> debugUtilsMessenger =
vk::raii::su::makeUniqueDebugUtilsMessengerEXT( *instance );
#endif
std::unique_ptr<vk::raii::PhysicalDevice> physicalDevice = vk::raii::su::makeUniquePhysicalDevice( *instance );
vk::raii::su::SurfaceData surfaceData( *instance, AppName, vk::Extent2D( 500, 500 ) );
std::pair<uint32_t, uint32_t> graphicsAndPresentQueueFamilyIndex =
vk::raii::su::findGraphicsAndPresentQueueFamilyIndex( *physicalDevice, *surfaceData.surface );
std::unique_ptr<vk::raii::Device> device = vk::raii::su::makeUniqueDevice(
*physicalDevice, graphicsAndPresentQueueFamilyIndex.first, vk::su::getDeviceExtensions() );
/* VULKAN_HPP_KEY_START */
const vk::Format depthFormat = vk::Format::eD16Unorm;
vk::FormatProperties formatProperties = physicalDevice->getFormatProperties( depthFormat );
vk::ImageTiling tiling;
if ( formatProperties.linearTilingFeatures & vk::FormatFeatureFlagBits::eDepthStencilAttachment )
{
tiling = vk::ImageTiling::eLinear;
}
else if ( formatProperties.optimalTilingFeatures & vk::FormatFeatureFlagBits::eDepthStencilAttachment )
{
tiling = vk::ImageTiling::eOptimal;
}
else
{
throw std::runtime_error( "DepthStencilAttachment is not supported for D16Unorm depth format." );
}
vk::ImageCreateInfo imageCreateInfo( {},
vk::ImageType::e2D,
depthFormat,
vk::Extent3D( surfaceData.extent, 1 ),
1,
1,
vk::SampleCountFlagBits::e1,
tiling,
vk::ImageUsageFlagBits::eDepthStencilAttachment );
std::unique_ptr<vk::raii::Image> depthImage = vk::raii::su::make_unique<vk::raii::Image>( *device, imageCreateInfo );
vk::PhysicalDeviceMemoryProperties memoryProperties = physicalDevice->getMemoryProperties();
vk::MemoryRequirements memoryRequirements = depthImage->getMemoryRequirements();
uint32_t typeBits = memoryRequirements.memoryTypeBits;
uint32_t typeIndex = uint32_t( ~0 );
for ( uint32_t i = 0; i < memoryProperties.memoryTypeCount; i++ )
{
if ( ( typeBits & 1 ) &&
( ( memoryProperties.memoryTypes[i].propertyFlags & vk::MemoryPropertyFlagBits::eDeviceLocal ) ==
vk::MemoryPropertyFlagBits::eDeviceLocal ) )
{
typeIndex = i;
break;
}
typeBits >>= 1;
}
assert( typeIndex != uint32_t( ~0 ) );
vk::MemoryAllocateInfo memoryAllocateInfo( memoryRequirements.size, typeIndex );
std::unique_ptr<vk::raii::DeviceMemory> depthMemory =
vk::raii::su::make_unique<vk::raii::DeviceMemory>( *device, memoryAllocateInfo );
depthImage->bindMemory( **depthMemory, 0 );
vk::ComponentMapping componentMapping(
vk::ComponentSwizzle::eR, vk::ComponentSwizzle::eG, vk::ComponentSwizzle::eB, vk::ComponentSwizzle::eA );
vk::ImageSubresourceRange subResourceRange( vk::ImageAspectFlagBits::eDepth, 0, 1, 0, 1 );
vk::ImageViewCreateInfo imageViewCreateInfo(
{}, **depthImage, vk::ImageViewType::e2D, depthFormat, componentMapping, subResourceRange );
std::unique_ptr<vk::raii::ImageView> depthView =
vk::raii::su::make_unique<vk::raii::ImageView>( *device, imageViewCreateInfo );
/* VULKAN_HPP_KEY_END */
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,35 @@
# Copyright(c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_06_InitDepthBuffer)
set(HEADERS
)
set(SOURCES
06_InitDepthBuffer.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_06_InitDepthBuffer
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_06_InitDepthBuffer PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_06_InitDepthBuffer PRIVATE utils)

View File

@ -0,0 +1,106 @@
// Copyright(c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : 07_InitUniformBufferRAII
// Initialize a uniform buffer
#if defined( _MSC_VER )
# pragma warning( disable : 4127 ) // disable warning 4127: conditional expression is constant
# pragma warning( disable : 4201 ) // disable warning C4201: nonstandard extension used: nameless struct/union; needed
// to get glm/detail/type_vec?.hpp without warnings
#elif defined( __GNUC__ )
// don't know how to switch off that warning here
#else
// unknow compiler... just ignore the warnings for yourselves ;)
#endif
#include "../utils/utils.hpp"
#include <iostream>
#define GLM_FORCE_RADIANS
#include <glm/gtc/matrix_transform.hpp>
static char const * AppName = "07_InitUniformBuffer";
static char const * EngineName = "Vulkan.hpp";
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
std::unique_ptr<vk::raii::Instance> instance =
vk::raii::su::makeUniqueInstance( *context, AppName, EngineName, {}, vk::su::getInstanceExtensions() );
#if !defined( NDEBUG )
std::unique_ptr<vk::raii::DebugUtilsMessengerEXT> debugUtilsMessenger =
vk::raii::su::makeUniqueDebugUtilsMessengerEXT( *instance );
#endif
std::unique_ptr<vk::raii::PhysicalDevice> physicalDevice = vk::raii::su::makeUniquePhysicalDevice( *instance );
uint32_t graphicsQueueFamilyIndex =
vk::su::findGraphicsQueueFamilyIndex( physicalDevice->getQueueFamilyProperties() );
std::unique_ptr<vk::raii::Device> device =
vk::raii::su::makeUniqueDevice( *physicalDevice, graphicsQueueFamilyIndex );
/* VULKAN_HPP_KEY_START */
glm::mat4x4 model = glm::mat4x4( 1.0f );
glm::mat4x4 view =
glm::lookAt( glm::vec3( -5.0f, 3.0f, -10.0f ), glm::vec3( 0.0f, 0.0f, 0.0f ), glm::vec3( 0.0f, -1.0f, 0.0f ) );
glm::mat4x4 projection = glm::perspective( glm::radians( 45.0f ), 1.0f, 0.1f, 100.0f );
// clang-format off
glm::mat4x4 clip = glm::mat4x4( 1.0f, 0.0f, 0.0f, 0.0f,
0.0f, -1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.5f, 0.0f,
0.0f, 0.0f, 0.5f, 1.0f ); // vulkan clip space has inverted y and half z !
// clang-format on
glm::mat4x4 mvpc = clip * projection * view * model;
vk::BufferCreateInfo bufferCreateInfo( {}, sizeof( mvpc ), vk::BufferUsageFlagBits::eUniformBuffer );
std::unique_ptr<vk::raii::Buffer> uniformDataBuffer =
vk::raii::su::make_unique<vk::raii::Buffer>( *device, bufferCreateInfo );
vk::MemoryRequirements memoryRequirements = uniformDataBuffer->getMemoryRequirements();
uint32_t typeIndex =
vk::su::findMemoryType( physicalDevice->getMemoryProperties(),
memoryRequirements.memoryTypeBits,
vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent );
vk::MemoryAllocateInfo memoryAllocateInfo( memoryRequirements.size, typeIndex );
std::unique_ptr<vk::raii::DeviceMemory> uniformDataMemory =
vk::raii::su::make_unique<vk::raii::DeviceMemory>( *device, memoryAllocateInfo );
uint8_t * pData = static_cast<uint8_t *>( uniformDataMemory->mapMemory( 0, memoryRequirements.size ) );
memcpy( pData, &mvpc, sizeof( mvpc ) );
uniformDataMemory->unmapMemory();
uniformDataBuffer->bindMemory( **uniformDataMemory, 0 );
/* VULKAN_HPP_KEY_END */
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,35 @@
# Copyright(c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_07_InitUniformBuffer)
set(HEADERS
)
set(SOURCES
07_InitUniformBuffer.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_07_InitUniformBuffer
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_07_InitUniformBuffer PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_07_InitUniformBuffer PRIVATE utils)

View File

@ -0,0 +1,74 @@
// Copyright(c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : 08_InitPipelineLayoutRAII
// Initialize a descriptor and pipeline layout
#include "../utils/utils.hpp"
#include <iostream>
static char const * AppName = "08_InitPipelineLayout";
static char const * EngineName = "Vulkan.hpp";
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
std::unique_ptr<vk::raii::Instance> instance =
vk::raii::su::makeUniqueInstance( *context, AppName, EngineName, {}, vk::su::getInstanceExtensions() );
#if !defined( NDEBUG )
std::unique_ptr<vk::raii::DebugUtilsMessengerEXT> debugUtilsMessenger =
vk::raii::su::makeUniqueDebugUtilsMessengerEXT( *instance );
#endif
std::unique_ptr<vk::raii::PhysicalDevice> physicalDevice = vk::raii::su::makeUniquePhysicalDevice( *instance );
uint32_t graphicsQueueFamilyIndex =
vk::su::findGraphicsQueueFamilyIndex( physicalDevice->getQueueFamilyProperties() );
std::unique_ptr<vk::raii::Device> device =
vk::raii::su::makeUniqueDevice( *physicalDevice, graphicsQueueFamilyIndex );
/* VULKAN_HPP_KEY_START */
// create a DescriptorSetLayout
vk::DescriptorSetLayoutBinding descriptorSetLayoutBinding(
0, vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eVertex );
vk::DescriptorSetLayoutCreateInfo descriptorSetLayoutCreateInfo( {}, descriptorSetLayoutBinding );
std::unique_ptr<vk::raii::DescriptorSetLayout> descriptorSetLayout =
vk::raii::su::make_unique<vk::raii::DescriptorSetLayout>( *device, descriptorSetLayoutCreateInfo );
// create a PipelineLayout using that DescriptorSetLayout
vk::PipelineLayoutCreateInfo pipelineLayoutCreateInfo( {}, **descriptorSetLayout );
std::unique_ptr<vk::raii::PipelineLayout> pipelineLayout =
vk::raii::su::make_unique<vk::raii::PipelineLayout>( *device, pipelineLayoutCreateInfo );
/* VULKAN_HPP_KEY_END */
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,35 @@
# Copyright(c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_08_InitPipelineLayout)
set(HEADERS
)
set(SOURCES
08_InitPipelineLayout.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_08_InitPipelineLayout
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_08_InitPipelineLayout PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_08_InitPipelineLayout PRIVATE utils)

View File

@ -0,0 +1,100 @@
// Copyright(c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : 09_InitDescriptorSet
// Initialize a descriptor set
#if defined( _MSC_VER )
# pragma warning( disable : 4201 ) // disable warning C4201: nonstandard extension used: nameless struct/union; needed
// to get glm/detail/type_vec?.hpp without warnings
#elif defined( __GNUC__ )
// don't know how to switch off that warning here
#else
// unknow compiler... just ignore the warnings for yourselves ;)
#endif
#include "../../samples/utils/math.hpp"
#include "../utils/utils.hpp"
#include <iostream>
#define GLM_FORCE_RADIANS
#include <glm/gtc/matrix_transform.hpp>
static char const * AppName = "09_InitDescriptorSet";
static char const * EngineName = "Vulkan.hpp";
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
std::unique_ptr<vk::raii::Instance> instance =
vk::raii::su::makeUniqueInstance( *context, AppName, EngineName, {}, vk::su::getInstanceExtensions() );
#if !defined( NDEBUG )
std::unique_ptr<vk::raii::DebugUtilsMessengerEXT> debugUtilsMessenger =
vk::raii::su::makeUniqueDebugUtilsMessengerEXT( *instance );
#endif
std::unique_ptr<vk::raii::PhysicalDevice> physicalDevice = vk::raii::su::makeUniquePhysicalDevice( *instance );
uint32_t graphicsQueueFamilyIndex =
vk::su::findGraphicsQueueFamilyIndex( physicalDevice->getQueueFamilyProperties() );
std::unique_ptr<vk::raii::Device> device =
vk::raii::su::makeUniqueDevice( *physicalDevice, graphicsQueueFamilyIndex );
vk::raii::su::BufferData uniformBufferData(
*physicalDevice, *device, sizeof( glm::mat4x4 ), vk::BufferUsageFlagBits::eUniformBuffer );
glm::mat4x4 mvpcMatrix = vk::su::createModelViewProjectionClipMatrix( vk::Extent2D( 0, 0 ) );
vk::raii::su::copyToDevice( *uniformBufferData.deviceMemory, mvpcMatrix );
std::unique_ptr<vk::raii::DescriptorSetLayout> descriptorSetLayout = vk::raii::su::makeUniqueDescriptorSetLayout(
*device, { { vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eVertex } } );
/* VULKAN_HPP_KEY_START */
// create a descriptor pool
vk::DescriptorPoolSize poolSize( vk::DescriptorType::eUniformBuffer, 1 );
vk::DescriptorPoolCreateInfo descriptorPoolCreateInfo(
vk::DescriptorPoolCreateFlagBits::eFreeDescriptorSet, 1, poolSize );
std::unique_ptr<vk::raii::DescriptorPool> descriptorPool =
vk::raii::su::make_unique<vk::raii::DescriptorPool>( *device, descriptorPoolCreateInfo );
// allocate a descriptor set
vk::DescriptorSetAllocateInfo descriptorSetAllocateInfo( **descriptorPool, **descriptorSetLayout );
std::unique_ptr<vk::raii::DescriptorSet> descriptorSet = vk::raii::su::make_unique<vk::raii::DescriptorSet>(
std::move( vk::raii::DescriptorSets( *device, descriptorSetAllocateInfo ).front() ) );
vk::DescriptorBufferInfo descriptorBufferInfo( **uniformBufferData.buffer, 0, sizeof( glm::mat4x4 ) );
vk::WriteDescriptorSet writeDescriptorSet(
**descriptorSet, 0, 0, vk::DescriptorType::eUniformBuffer, {}, descriptorBufferInfo );
device->updateDescriptorSets( writeDescriptorSet, nullptr );
/* VULKAN_HPP_KEY_END */
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,35 @@
# Copyright(c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_09_InitDescriptorSet)
set(HEADERS
)
set(SOURCES
09_InitDescriptorSet.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_09_InitDescriptorSet
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_09_InitDescriptorSet PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_09_InitDescriptorSet PRIVATE utils)

View File

@ -0,0 +1,109 @@
// Copyright(c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : 10_InitRenderPass
// Initialize a render pass
#if defined( _MSC_VER )
# pragma warning( disable : 4201 ) // disable warning C4201: nonstandard extension used: nameless struct/union; needed
// to get glm/detail/type_vec?.hpp without warnings
#elif defined( __GNUC__ )
// don't know how to switch off that warning here
#else
// unknow compiler... just ignore the warnings for yourselves ;)
#endif
#include "../utils/utils.hpp"
#include <iostream>
#define GLM_FORCE_RADIANS
#include <glm/gtc/matrix_transform.hpp>
static char const * AppName = "10_InitRenderPass";
static char const * EngineName = "Vulkan.hpp";
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
std::unique_ptr<vk::raii::Instance> instance =
vk::raii::su::makeUniqueInstance( *context, AppName, EngineName, {}, vk::su::getInstanceExtensions() );
#if !defined( NDEBUG )
std::unique_ptr<vk::raii::DebugUtilsMessengerEXT> debugUtilsMessenger =
vk::raii::su::makeUniqueDebugUtilsMessengerEXT( *instance );
#endif
std::unique_ptr<vk::raii::PhysicalDevice> physicalDevice = vk::raii::su::makeUniquePhysicalDevice( *instance );
vk::raii::su::SurfaceData surfaceData( *instance, AppName, vk::Extent2D( 500, 500 ) );
std::pair<uint32_t, uint32_t> graphicsAndPresentQueueFamilyIndex =
vk::raii::su::findGraphicsAndPresentQueueFamilyIndex( *physicalDevice, *surfaceData.surface );
std::unique_ptr<vk::raii::Device> device = vk::raii::su::makeUniqueDevice(
*physicalDevice, graphicsAndPresentQueueFamilyIndex.first, vk::su::getDeviceExtensions() );
vk::Format colorFormat =
vk::su::pickSurfaceFormat( physicalDevice->getSurfaceFormatsKHR( **surfaceData.surface ) ).format;
vk::Format depthFormat = vk::Format::eD16Unorm;
/* VULKAN_HPP_KEY_START */
std::array<vk::AttachmentDescription, 2> attachmentDescriptions;
attachmentDescriptions[0] = vk::AttachmentDescription( {},
colorFormat,
vk::SampleCountFlagBits::e1,
vk::AttachmentLoadOp::eClear,
vk::AttachmentStoreOp::eStore,
vk::AttachmentLoadOp::eDontCare,
vk::AttachmentStoreOp::eDontCare,
vk::ImageLayout::eUndefined,
vk::ImageLayout::ePresentSrcKHR );
attachmentDescriptions[1] = vk::AttachmentDescription( {},
depthFormat,
vk::SampleCountFlagBits::e1,
vk::AttachmentLoadOp::eClear,
vk::AttachmentStoreOp::eDontCare,
vk::AttachmentLoadOp::eDontCare,
vk::AttachmentStoreOp::eDontCare,
vk::ImageLayout::eUndefined,
vk::ImageLayout::eDepthStencilAttachmentOptimal );
vk::AttachmentReference colorReference( 0, vk::ImageLayout::eColorAttachmentOptimal );
vk::AttachmentReference depthReference( 1, vk::ImageLayout::eDepthStencilAttachmentOptimal );
vk::SubpassDescription subpass( {}, vk::PipelineBindPoint::eGraphics, {}, colorReference, {}, &depthReference );
vk::RenderPassCreateInfo renderPassCreateInfo( {}, attachmentDescriptions, subpass );
std::unique_ptr<vk::raii::RenderPass> renderPass =
vk::raii::su::make_unique<vk::raii::RenderPass>( *device, renderPassCreateInfo );
/* VULKAN_HPP_KEY_END */
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,35 @@
# Copyright(c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_10_InitRenderPass)
set(HEADERS
)
set(SOURCES
10_InitRenderPass.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_10_InitRenderPass
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_10_InitRenderPass PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_10_InitRenderPass PRIVATE utils)

View File

@ -0,0 +1,84 @@
// Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : 11_InitShaders
// Initialize vertex and fragment shaders
#include "../utils/shaders.hpp"
#include "../utils/utils.hpp"
#include "SPIRV/GlslangToSpv.h"
#include <iostream>
static char const * AppName = "11_InitShaders";
static char const * EngineName = "Vulkan.hpp";
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
std::unique_ptr<vk::raii::Instance> instance =
vk::raii::su::makeUniqueInstance( *context, AppName, EngineName, {}, vk::su::getInstanceExtensions() );
#if !defined( NDEBUG )
std::unique_ptr<vk::raii::DebugUtilsMessengerEXT> debugUtilsMessenger =
vk::raii::su::makeUniqueDebugUtilsMessengerEXT( *instance );
#endif
std::unique_ptr<vk::raii::PhysicalDevice> physicalDevice = vk::raii::su::makeUniquePhysicalDevice( *instance );
uint32_t graphicsQueueFamilyIndex =
vk::su::findGraphicsQueueFamilyIndex( physicalDevice->getQueueFamilyProperties() );
std::unique_ptr<vk::raii::Device> device =
vk::raii::su::makeUniqueDevice( *physicalDevice, graphicsQueueFamilyIndex );
/* VULKAN_HPP_KEY_START */
glslang::InitializeProcess();
std::vector<unsigned int> vertexShaderSPV;
bool ok = vk::su::GLSLtoSPV( vk::ShaderStageFlagBits::eVertex, vertexShaderText_PC_C, vertexShaderSPV );
assert( ok );
vk::ShaderModuleCreateInfo vertexShaderModuleCreateInfo( {}, vertexShaderSPV );
std::unique_ptr<vk::raii::ShaderModule> vertexShaderModule =
vk::raii::su::make_unique<vk::raii::ShaderModule>( *device, vertexShaderModuleCreateInfo );
std::vector<unsigned int> fragmentShaderSPV;
ok = vk::su::GLSLtoSPV( vk::ShaderStageFlagBits::eFragment, fragmentShaderText_C_C, fragmentShaderSPV );
assert( ok );
vk::ShaderModuleCreateInfo fragmentShaderModuleCreateInfo( {}, fragmentShaderSPV );
std::unique_ptr<vk::raii::ShaderModule> fragmentShaderModule =
vk::raii::su::make_unique<vk::raii::ShaderModule>( *device, fragmentShaderModuleCreateInfo );
glslang::FinalizeProcess();
/* VULKAN_HPP_KEY_END */
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,35 @@
# Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_11_InitShaders)
set(HEADERS
)
set(SOURCES
11_InitShaders.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_11_InitShaders
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_11_InitShaders PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_11_InitShaders PRIVATE utils)

View File

@ -0,0 +1,94 @@
// Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : 12_InitFrameBuffers
// Initialize framebuffers
#include "../utils/utils.hpp"
#include <iostream>
static char const * AppName = "12_InitFrameBuffers";
static char const * EngineName = "Vulkan.hpp";
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
std::unique_ptr<vk::raii::Instance> instance =
vk::raii::su::makeUniqueInstance( *context, AppName, EngineName, {}, vk::su::getInstanceExtensions() );
#if !defined( NDEBUG )
std::unique_ptr<vk::raii::DebugUtilsMessengerEXT> debugUtilsMessenger =
vk::raii::su::makeUniqueDebugUtilsMessengerEXT( *instance );
#endif
std::unique_ptr<vk::raii::PhysicalDevice> physicalDevice = vk::raii::su::makeUniquePhysicalDevice( *instance );
vk::raii::su::SurfaceData surfaceData( *instance, AppName, vk::Extent2D( 64, 64 ) );
std::pair<uint32_t, uint32_t> graphicsAndPresentQueueFamilyIndex =
vk::raii::su::findGraphicsAndPresentQueueFamilyIndex( *physicalDevice, *surfaceData.surface );
std::unique_ptr<vk::raii::Device> device = vk::raii::su::makeUniqueDevice(
*physicalDevice, graphicsAndPresentQueueFamilyIndex.first, vk::su::getDeviceExtensions() );
vk::raii::su::SwapChainData swapChainData( *physicalDevice,
*device,
*surfaceData.surface,
surfaceData.extent,
vk::ImageUsageFlagBits::eColorAttachment |
vk::ImageUsageFlagBits::eTransferSrc,
{},
graphicsAndPresentQueueFamilyIndex.first,
graphicsAndPresentQueueFamilyIndex.second );
vk::raii::su::DepthBufferData depthBufferData(
*physicalDevice, *device, vk::Format::eD16Unorm, surfaceData.extent );
std::unique_ptr<vk::raii::RenderPass> renderPass =
vk::raii::su::makeUniqueRenderPass( *device, swapChainData.colorFormat, depthBufferData.format );
/* VULKAN_KEY_START */
std::array<vk::ImageView, 2> attachments;
attachments[1] = **depthBufferData.imageView;
std::vector<std::unique_ptr<vk::raii::Framebuffer>> framebuffers;
framebuffers.reserve( swapChainData.imageViews.size() );
for ( auto const & view : swapChainData.imageViews )
{
attachments[0] = *view;
vk::FramebufferCreateInfo framebufferCreateInfo(
{}, **renderPass, attachments, surfaceData.extent.width, surfaceData.extent.height, 1 );
framebuffers.push_back( vk::raii::su::make_unique<vk::raii::Framebuffer>( *device, framebufferCreateInfo ) );
}
/* VULKAN_KEY_END */
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,35 @@
# Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_12_InitFrameBuffers)
set(HEADERS
)
set(SOURCES
12_InitFrameBuffers.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_12_InitFrameBuffers
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_12_InitFrameBuffers PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_12_InitFrameBuffers PRIVATE utils)

View File

@ -0,0 +1,151 @@
// Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : 13_InitVertexBuffer
// Initialize vertex buffer
#if defined( _MSC_VER )
// no need to ignore any warnings with MSVC
#elif defined( __GNUC__ )
# if ( 9 <= __GNUC__ )
# pragma GCC diagnostic ignored "-Winit-list-lifetime"
# endif
#else
// unknow compiler... just ignore the warnings for yourselves ;)
#endif
#include "../../samples/utils/geometries.hpp"
#include "../utils/utils.hpp"
#include <iostream>
static char const * AppName = "13_InitVertexBuffer";
static char const * EngineName = "Vulkan.hpp";
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
std::unique_ptr<vk::raii::Instance> instance =
vk::raii::su::makeUniqueInstance( *context, AppName, EngineName, {}, vk::su::getInstanceExtensions() );
#if !defined( NDEBUG )
std::unique_ptr<vk::raii::DebugUtilsMessengerEXT> debugUtilsMessenger =
vk::raii::su::makeUniqueDebugUtilsMessengerEXT( *instance );
#endif
std::unique_ptr<vk::raii::PhysicalDevice> physicalDevice = vk::raii::su::makeUniquePhysicalDevice( *instance );
vk::raii::su::SurfaceData surfaceData( *instance, AppName, vk::Extent2D( 64, 64 ) );
std::pair<uint32_t, uint32_t> graphicsAndPresentQueueFamilyIndex =
vk::raii::su::findGraphicsAndPresentQueueFamilyIndex( *physicalDevice, *surfaceData.surface );
std::unique_ptr<vk::raii::Device> device = vk::raii::su::makeUniqueDevice(
*physicalDevice, graphicsAndPresentQueueFamilyIndex.first, vk::su::getDeviceExtensions() );
std::unique_ptr<vk::raii::CommandPool> commandPool =
vk::raii::su::makeUniqueCommandPool( *device, graphicsAndPresentQueueFamilyIndex.first );
std::unique_ptr<vk::raii::CommandBuffer> commandBuffer =
vk::raii::su::makeUniqueCommandBuffer( *device, *commandPool );
std::unique_ptr<vk::raii::Queue> graphicsQueue =
vk::raii::su::make_unique<vk::raii::Queue>( *device, graphicsAndPresentQueueFamilyIndex.first, 0 );
vk::raii::su::SwapChainData swapChainData( *physicalDevice,
*device,
*surfaceData.surface,
surfaceData.extent,
vk::ImageUsageFlagBits::eColorAttachment |
vk::ImageUsageFlagBits::eTransferSrc,
{},
graphicsAndPresentQueueFamilyIndex.first,
graphicsAndPresentQueueFamilyIndex.second );
vk::raii::su::DepthBufferData depthBufferData(
*physicalDevice, *device, vk::Format::eD16Unorm, surfaceData.extent );
std::unique_ptr<vk::raii::RenderPass> renderPass =
vk::raii::su::makeUniqueRenderPass( *device, swapChainData.colorFormat, depthBufferData.format );
std::vector<std::unique_ptr<vk::raii::Framebuffer>> framebuffers = vk::raii::su::makeUniqueFramebuffers(
*device, *renderPass, swapChainData.imageViews, depthBufferData.imageView, surfaceData.extent );
/* VULKAN_KEY_START */
// create a vertex buffer for some vertex and color data
vk::BufferCreateInfo bufferCreateInfo( {}, sizeof( coloredCubeData ), vk::BufferUsageFlagBits::eVertexBuffer );
std::unique_ptr<vk::raii::Buffer> vertexBuffer = vk::raii::su::make_unique<vk::raii::Buffer>( *device, bufferCreateInfo );
// allocate device memory for that buffer
vk::MemoryRequirements memoryRequirements = vertexBuffer->getMemoryRequirements();
uint32_t memoryTypeIndex =
vk::su::findMemoryType( physicalDevice->getMemoryProperties(),
memoryRequirements.memoryTypeBits,
vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent );
vk::MemoryAllocateInfo memoryAllocateInfo( memoryRequirements.size, memoryTypeIndex );
std::unique_ptr<vk::raii::DeviceMemory> deviceMemory =
vk::raii::su::make_unique<vk::raii::DeviceMemory>( *device, memoryAllocateInfo );
// copy the vertex and color data into that device memory
uint8_t * pData = static_cast<uint8_t *>( deviceMemory->mapMemory( 0, memoryRequirements.size ) );
memcpy( pData, coloredCubeData, sizeof( coloredCubeData ) );
deviceMemory->unmapMemory();
// and bind the device memory to the vertex buffer
vertexBuffer->bindMemory( **deviceMemory, 0 );
std::unique_ptr<vk::raii::Semaphore> imageAcquiredSemaphore =
vk::raii::su::make_unique<vk::raii::Semaphore>( *device, vk::SemaphoreCreateInfo() );
vk::Result result;
uint32_t imageIndex;
std::tie( result, imageIndex ) =
swapChainData.swapChain->acquireNextImage( vk::su::FenceTimeout, **imageAcquiredSemaphore );
assert( result == vk::Result::eSuccess );
assert( imageIndex < swapChainData.images.size() );
std::array<vk::ClearValue, 2> clearValues;
clearValues[0].color = vk::ClearColorValue( std::array<float, 4>( { { 0.2f, 0.2f, 0.2f, 0.2f } } ) );
clearValues[1].depthStencil = vk::ClearDepthStencilValue( 1.0f, 0 );
commandBuffer->begin( {} );
vk::RenderPassBeginInfo renderPassBeginInfo(
**renderPass, **framebuffers[imageIndex], vk::Rect2D( vk::Offset2D( 0, 0 ), surfaceData.extent ), clearValues );
commandBuffer->beginRenderPass( renderPassBeginInfo, vk::SubpassContents::eInline );
commandBuffer->bindVertexBuffers( 0, { **vertexBuffer }, { 0 } );
commandBuffer->endRenderPass();
commandBuffer->end();
vk::raii::su::submitAndWait( *device, *graphicsQueue, *commandBuffer );
/* VULKAN_KEY_END */
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,35 @@
# Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_13_InitVertexBuffer)
set(HEADERS
)
set(SOURCES
13_InitVertexBuffer.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_13_InitVertexBuffer
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_13_InitVertexBuffer PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_13_InitVertexBuffer PRIVATE utils)

View File

@ -0,0 +1,200 @@
// Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : 14_InitPipeline
// Initialize graphics pipeline
#if defined( _MSC_VER )
// no need to ignore any warnings with MSVC
#elif defined( __clang__ )
# pragma clang diagnostic ignored "-Wmissing-braces"
#elif defined( __GNUC__ )
// no need to ignore any warnings with GCC
#else
// unknow compiler... just ignore the warnings for yourselves ;)
#endif
#include "../../samples/utils/geometries.hpp"
#include "../../samples/utils/math.hpp"
#include "../utils/shaders.hpp"
#include "../utils/utils.hpp"
#include "SPIRV/GlslangToSpv.h"
#include <iostream>
static char const * AppName = "14_InitPipeline";
static char const * EngineName = "Vulkan.hpp";
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
std::unique_ptr<vk::raii::Instance> instance =
vk::raii::su::makeUniqueInstance( *context, AppName, EngineName, {}, vk::su::getInstanceExtensions() );
#if !defined( NDEBUG )
std::unique_ptr<vk::raii::DebugUtilsMessengerEXT> debugUtilsMessenger =
vk::raii::su::makeUniqueDebugUtilsMessengerEXT( *instance );
#endif
std::unique_ptr<vk::raii::PhysicalDevice> physicalDevice = vk::raii::su::makeUniquePhysicalDevice( *instance );
vk::raii::su::SurfaceData surfaceData( *instance, AppName, vk::Extent2D( 500, 500 ) );
std::pair<uint32_t, uint32_t> graphicsAndPresentQueueFamilyIndex =
vk::raii::su::findGraphicsAndPresentQueueFamilyIndex( *physicalDevice, *surfaceData.surface );
std::unique_ptr<vk::raii::Device> device = vk::raii::su::makeUniqueDevice(
*physicalDevice, graphicsAndPresentQueueFamilyIndex.first, vk::su::getDeviceExtensions() );
vk::Format colorFormat =
vk::su::pickSurfaceFormat( physicalDevice->getSurfaceFormatsKHR( **surfaceData.surface ) ).format;
std::unique_ptr<vk::raii::RenderPass> renderPass =
vk::raii::su::makeUniqueRenderPass( *device, colorFormat, vk::Format::eD16Unorm );
std::unique_ptr<vk::raii::DescriptorSetLayout> descriptorSetLayout = vk::raii::su::makeUniqueDescriptorSetLayout(
*device, { { vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eVertex } } );
std::unique_ptr<vk::raii::PipelineLayout> pipelineLayout =
vk::raii::su::makeUniquePipelineLayout( *device, *descriptorSetLayout );
glslang::InitializeProcess();
std::unique_ptr<vk::raii::ShaderModule> vertexShaderModule =
vk::raii::su::makeUniqueShaderModule( *device, vk::ShaderStageFlagBits::eVertex, vertexShaderText_PC_C );
std::unique_ptr<vk::raii::ShaderModule> fragmentShaderModule =
vk::raii::su::makeUniqueShaderModule( *device, vk::ShaderStageFlagBits::eFragment, fragmentShaderText_C_C );
glslang::FinalizeProcess();
/* VULKAN_KEY_START */
std::array<vk::PipelineShaderStageCreateInfo, 2> pipelineShaderStageCreateInfos = {
vk::PipelineShaderStageCreateInfo( {}, vk::ShaderStageFlagBits::eVertex, **vertexShaderModule, "main" ),
vk::PipelineShaderStageCreateInfo( {}, vk::ShaderStageFlagBits::eFragment, **fragmentShaderModule, "main" )
};
vk::VertexInputBindingDescription vertexInputBindingDescription( 0, sizeof( coloredCubeData[0] ) );
std::array<vk::VertexInputAttributeDescription, 2> vertexInputAttributeDescriptions = {
vk::VertexInputAttributeDescription( 0, 0, vk::Format::eR32G32B32A32Sfloat, 0 ),
vk::VertexInputAttributeDescription( 1, 0, vk::Format::eR32G32B32A32Sfloat, 16 )
};
vk::PipelineVertexInputStateCreateInfo pipelineVertexInputStateCreateInfo(
{}, // flags
vertexInputBindingDescription, // vertexBindingDescriptions
vertexInputAttributeDescriptions // vertexAttributeDescriptions
);
vk::PipelineInputAssemblyStateCreateInfo pipelineInputAssemblyStateCreateInfo(
{}, vk::PrimitiveTopology::eTriangleList );
vk::PipelineViewportStateCreateInfo pipelineViewportStateCreateInfo( {}, 1, nullptr, 1, nullptr );
vk::PipelineRasterizationStateCreateInfo pipelineRasterizationStateCreateInfo(
{}, // flags
false, // depthClampEnable
false, // rasterizerDiscardEnable
vk::PolygonMode::eFill, // polygonMode
vk::CullModeFlagBits::eBack, // cullMode
vk::FrontFace::eClockwise, // frontFace
false, // depthBiasEnable
0.0f, // depthBiasConstantFactor
0.0f, // depthBiasClamp
0.0f, // depthBiasSlopeFactor
1.0f // lineWidth
);
vk::PipelineMultisampleStateCreateInfo pipelineMultisampleStateCreateInfo(
{}, // flags
vk::SampleCountFlagBits::e1 // rasterizationSamples
// other values can be default
);
vk::StencilOpState stencilOpState(
vk::StencilOp::eKeep, vk::StencilOp::eKeep, vk::StencilOp::eKeep, vk::CompareOp::eAlways );
vk::PipelineDepthStencilStateCreateInfo pipelineDepthStencilStateCreateInfo(
{}, // flags
true, // depthTestEnable
true, // depthWriteEnable
vk::CompareOp::eLessOrEqual, // depthCompareOp
false, // depthBoundTestEnable
false, // stencilTestEnable
stencilOpState, // front
stencilOpState // back
);
vk::ColorComponentFlags colorComponentFlags( vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG |
vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA );
vk::PipelineColorBlendAttachmentState pipelineColorBlendAttachmentState(
false, // blendEnable
vk::BlendFactor::eZero, // srcColorBlendFactor
vk::BlendFactor::eZero, // dstColorBlendFactor
vk::BlendOp::eAdd, // colorBlendOp
vk::BlendFactor::eZero, // srcAlphaBlendFactor
vk::BlendFactor::eZero, // dstAlphaBlendFactor
vk::BlendOp::eAdd, // alphaBlendOp
colorComponentFlags // colorWriteMask
);
vk::PipelineColorBlendStateCreateInfo pipelineColorBlendStateCreateInfo(
{}, // flags
false, // logicOpEnable
vk::LogicOp::eNoOp, // logicOp
pipelineColorBlendAttachmentState, // attachments
{ { 1.0f, 1.0f, 1.0f, 1.0f } } // blendConstants
);
std::array<vk::DynamicState, 2> dynamicStates = { vk::DynamicState::eViewport, vk::DynamicState::eScissor };
vk::PipelineDynamicStateCreateInfo pipelineDynamicStateCreateInfo( {}, dynamicStates );
vk::GraphicsPipelineCreateInfo graphicsPipelineCreateInfo(
{}, // flags
pipelineShaderStageCreateInfos, // stages
&pipelineVertexInputStateCreateInfo, // pVertexInputState
&pipelineInputAssemblyStateCreateInfo, // pInputAssemblyState
nullptr, // pTessellationState
&pipelineViewportStateCreateInfo, // pViewportState
&pipelineRasterizationStateCreateInfo, // pRasterizationState
&pipelineMultisampleStateCreateInfo, // pMultisampleState
&pipelineDepthStencilStateCreateInfo, // pDepthStencilState
&pipelineColorBlendStateCreateInfo, // pColorBlendState
&pipelineDynamicStateCreateInfo, // pDynamicState
**pipelineLayout, // layout
**renderPass // renderPass
);
std::shared_ptr<vk::raii::Pipeline> pipeline =
vk::raii::su::make_unique<vk::raii::Pipeline>( *device, nullptr, graphicsPipelineCreateInfo );
switch ( pipeline->getConstructorSuccessCode() )
{
case vk::Result::eSuccess: break;
case vk::Result::ePipelineCompileRequiredEXT:
// something meaningfull here
break;
default: assert( false ); // should never happen
}
/* VULKAN_KEY_END */
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,35 @@
# Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_14_InitPipeline)
set(HEADERS
)
set(SOURCES
14_InitPipeline.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_14_InitPipeline
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_14_InitPipeline PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_14_InitPipeline PRIVATE utils)

View File

@ -0,0 +1,216 @@
// Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : 15_DrawCube
// Draw a cube
#if defined( _MSC_VER )
// no need to ignore any warnings with MSVC
#elif defined( __GNUC__ )
# if ( 9 <= __GNUC__ )
# pragma GCC diagnostic ignored "-Winit-list-lifetime"
# endif
#else
// unknow compiler... just ignore the warnings for yourselves ;)
#endif
#include "../../samples/utils/geometries.hpp"
#include "../../samples/utils/math.hpp"
#include "../utils/shaders.hpp"
#include "../utils/utils.hpp"
#include "SPIRV/GlslangToSpv.h"
#include <iostream>
#include <thread>
static char const * AppName = "15_DrawCube";
static char const * EngineName = "Vulkan.hpp";
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
std::unique_ptr<vk::raii::Instance> instance =
vk::raii::su::makeUniqueInstance( *context, AppName, EngineName, {}, vk::su::getInstanceExtensions() );
#if !defined( NDEBUG )
std::unique_ptr<vk::raii::DebugUtilsMessengerEXT> debugUtilsMessenger =
vk::raii::su::makeUniqueDebugUtilsMessengerEXT( *instance );
#endif
std::unique_ptr<vk::raii::PhysicalDevice> physicalDevice = vk::raii::su::makeUniquePhysicalDevice( *instance );
vk::raii::su::SurfaceData surfaceData( *instance, AppName, vk::Extent2D( 500, 500 ) );
std::pair<uint32_t, uint32_t> graphicsAndPresentQueueFamilyIndex =
vk::raii::su::findGraphicsAndPresentQueueFamilyIndex( *physicalDevice, *surfaceData.surface );
std::unique_ptr<vk::raii::Device> device = vk::raii::su::makeUniqueDevice(
*physicalDevice, graphicsAndPresentQueueFamilyIndex.first, vk::su::getDeviceExtensions() );
std::unique_ptr<vk::raii::CommandPool> commandPool =
vk::raii::su::makeUniqueCommandPool( *device, graphicsAndPresentQueueFamilyIndex.first );
std::unique_ptr<vk::raii::CommandBuffer> commandBuffer =
vk::raii::su::makeUniqueCommandBuffer( *device, *commandPool );
std::unique_ptr<vk::raii::Queue> graphicsQueue =
vk::raii::su::make_unique<vk::raii::Queue>( *device, graphicsAndPresentQueueFamilyIndex.first, 0 );
std::unique_ptr<vk::raii::Queue> presentQueue =
vk::raii::su::make_unique<vk::raii::Queue>( *device, graphicsAndPresentQueueFamilyIndex.second, 0 );
vk::raii::su::SwapChainData swapChainData( *physicalDevice,
*device,
*surfaceData.surface,
surfaceData.extent,
vk::ImageUsageFlagBits::eColorAttachment |
vk::ImageUsageFlagBits::eTransferSrc,
{},
graphicsAndPresentQueueFamilyIndex.first,
graphicsAndPresentQueueFamilyIndex.second );
vk::raii::su::DepthBufferData depthBufferData(
*physicalDevice, *device, vk::Format::eD16Unorm, surfaceData.extent );
vk::raii::su::BufferData uniformBufferData(
*physicalDevice, *device, sizeof( glm::mat4x4 ), vk::BufferUsageFlagBits::eUniformBuffer );
glm::mat4x4 mvpcMatrix = vk::su::createModelViewProjectionClipMatrix( surfaceData.extent );
vk::raii::su::copyToDevice( *uniformBufferData.deviceMemory, mvpcMatrix );
std::unique_ptr<vk::raii::DescriptorSetLayout> descriptorSetLayout = vk::raii::su::makeUniqueDescriptorSetLayout(
*device, { { vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eVertex } } );
std::unique_ptr<vk::raii::PipelineLayout> pipelineLayout =
vk::raii::su::makeUniquePipelineLayout( *device, *descriptorSetLayout );
vk::Format colorFormat =
vk::su::pickSurfaceFormat( physicalDevice->getSurfaceFormatsKHR( **surfaceData.surface ) ).format;
std::unique_ptr<vk::raii::RenderPass> renderPass =
vk::raii::su::makeUniqueRenderPass( *device, colorFormat, depthBufferData.format );
glslang::InitializeProcess();
std::unique_ptr<vk::raii::ShaderModule> vertexShaderModule =
vk::raii::su::makeUniqueShaderModule( *device, vk::ShaderStageFlagBits::eVertex, vertexShaderText_PC_C );
std::unique_ptr<vk::raii::ShaderModule> fragmentShaderModule =
vk::raii::su::makeUniqueShaderModule( *device, vk::ShaderStageFlagBits::eFragment, fragmentShaderText_C_C );
glslang::FinalizeProcess();
std::vector<std::unique_ptr<vk::raii::Framebuffer>> framebuffers = vk::raii::su::makeUniqueFramebuffers(
*device, *renderPass, swapChainData.imageViews, depthBufferData.imageView, surfaceData.extent );
vk::raii::su::BufferData vertexBufferData(
*physicalDevice, *device, sizeof( coloredCubeData ), vk::BufferUsageFlagBits::eVertexBuffer );
vk::raii::su::copyToDevice(
*vertexBufferData.deviceMemory, coloredCubeData, sizeof( coloredCubeData ) / sizeof( coloredCubeData[0] ) );
std::unique_ptr<vk::raii::DescriptorPool> descriptorPool =
vk::raii::su::makeUniqueDescriptorPool( *device, { { vk::DescriptorType::eUniformBuffer, 1 } } );
std::unique_ptr<vk::raii::DescriptorSet> descriptorSet =
vk::raii::su::makeUniqueDescriptorSet( *device, *descriptorPool, *descriptorSetLayout );
vk::raii::su::updateDescriptorSets(
*device, *descriptorSet, { { vk::DescriptorType::eUniformBuffer, *uniformBufferData.buffer, nullptr } }, {} );
std::unique_ptr<vk::raii::PipelineCache> pipelineCache =
vk::raii::su::make_unique<vk::raii::PipelineCache>( *device, vk::PipelineCacheCreateInfo() );
std::unique_ptr<vk::raii::Pipeline> graphicsPipeline = vk::raii::su::makeUniqueGraphicsPipeline(
*device,
*pipelineCache,
*vertexShaderModule,
nullptr,
*fragmentShaderModule,
nullptr,
vk::su::checked_cast<uint32_t>( sizeof( coloredCubeData[0] ) ),
{ { vk::Format::eR32G32B32A32Sfloat, 0 }, { vk::Format::eR32G32B32A32Sfloat, 16 } },
vk::FrontFace::eClockwise,
true,
*pipelineLayout,
*renderPass );
/* VULKAN_KEY_START */
// Get the index of the next available swapchain image:
std::unique_ptr<vk::raii::Semaphore> imageAcquiredSemaphore =
vk::raii::su::make_unique<vk::raii::Semaphore>( *device, vk::SemaphoreCreateInfo() );
vk::Result result;
uint32_t imageIndex;
std::tie( result, imageIndex ) =
swapChainData.swapChain->acquireNextImage( vk::su::FenceTimeout, **imageAcquiredSemaphore );
assert( result == vk::Result::eSuccess );
assert( imageIndex < swapChainData.images.size() );
commandBuffer->begin( {} );
std::array<vk::ClearValue, 2> clearValues;
clearValues[0].color = vk::ClearColorValue( std::array<float, 4>( { { 0.2f, 0.2f, 0.2f, 0.2f } } ) );
clearValues[1].depthStencil = vk::ClearDepthStencilValue( 1.0f, 0 );
vk::RenderPassBeginInfo renderPassBeginInfo(
**renderPass, **framebuffers[imageIndex], vk::Rect2D( vk::Offset2D( 0, 0 ), surfaceData.extent ), clearValues );
commandBuffer->beginRenderPass( renderPassBeginInfo, vk::SubpassContents::eInline );
commandBuffer->bindPipeline( vk::PipelineBindPoint::eGraphics, **graphicsPipeline );
commandBuffer->bindDescriptorSets(
vk::PipelineBindPoint::eGraphics, **pipelineLayout, 0, { **descriptorSet }, nullptr );
commandBuffer->bindVertexBuffers( 0, { **vertexBufferData.buffer }, { 0 } );
commandBuffer->setViewport( 0,
vk::Viewport( 0.0f,
0.0f,
static_cast<float>( surfaceData.extent.width ),
static_cast<float>( surfaceData.extent.height ),
0.0f,
1.0f ) );
commandBuffer->setScissor( 0, vk::Rect2D( vk::Offset2D( 0, 0 ), surfaceData.extent ) );
commandBuffer->draw( 12 * 3, 1, 0, 0 );
commandBuffer->endRenderPass();
commandBuffer->end();
std::unique_ptr<vk::raii::Fence> drawFence = vk::raii::su::make_unique<vk::raii::Fence>( *device, vk::FenceCreateInfo() );
vk::PipelineStageFlags waitDestinationStageMask( vk::PipelineStageFlagBits::eColorAttachmentOutput );
vk::SubmitInfo submitInfo( **imageAcquiredSemaphore, waitDestinationStageMask, **commandBuffer );
graphicsQueue->submit( submitInfo, **drawFence );
while ( vk::Result::eTimeout == device->waitForFences( { **drawFence }, VK_TRUE, vk::su::FenceTimeout ) )
;
vk::PresentInfoKHR presentInfoKHR( nullptr, **swapChainData.swapChain, imageIndex );
result = presentQueue->presentKHR( presentInfoKHR );
switch ( result )
{
case vk::Result::eSuccess: break;
case vk::Result::eSuboptimalKHR:
std::cout << "vk::Queue::presentKHR returned vk::Result::eSuboptimalKHR !\n";
break;
default: assert( false ); // an unexpected result is returned !
}
std::this_thread::sleep_for( std::chrono::milliseconds( 1000 ) );
/* VULKAN_KEY_END */
device->waitIdle();
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,35 @@
# Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_15_DrawCube)
set(HEADERS
)
set(SOURCES
15_DrawCube.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_15_DrawCube
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_15_DrawCube PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_15_DrawCube PRIVATE utils)

View File

@ -0,0 +1,122 @@
// Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : 16_Vulkan_1_1
// Determine if the current system can use Vulkan 1.1 API features
#include "../utils/utils.hpp"
static char const * AppName = "16_Vulkan_1_1";
static char const * EngineName = "Vulkan.hpp";
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
/* VULKAN_KEY_START */
// Keep track of the major/minor version we can actually use
uint16_t usingMajorVersion = 1;
uint16_t usingMinorVersion = 0;
std::string usingVersionString = "";
// Set the desired version we want
uint16_t desiredMajorVersion = 1;
uint16_t desiredMinorVersion = 1;
uint32_t desiredVersion = VK_MAKE_VERSION( desiredMajorVersion, desiredMinorVersion, 0 );
std::string desiredVersionString = "";
desiredVersionString += std::to_string( desiredMajorVersion );
desiredVersionString += ".";
desiredVersionString += std::to_string( desiredMinorVersion );
// initialize the vulkan context
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
// Determine what API version is available
uint32_t apiVersion = context->enumerateInstanceVersion();
// Translate the version into major/minor for easier comparison
uint32_t loader_major_version = VK_VERSION_MAJOR( apiVersion );
uint32_t loader_minor_version = VK_VERSION_MINOR( apiVersion );
std::cout << "Loader/Runtime support detected for Vulkan " << loader_major_version << "." << loader_minor_version
<< "\n";
// Check current version against what we want to run
if ( loader_major_version > desiredMajorVersion ||
( loader_major_version == desiredMajorVersion && loader_minor_version >= desiredMinorVersion ) )
{
// Create the instance
std::unique_ptr<vk::raii::Instance> instance =
vk::raii::su::makeUniqueInstance( *context, AppName, EngineName, {}, vk::su::getInstanceExtensions() );
#if !defined( NDEBUG )
std::unique_ptr<vk::raii::DebugUtilsMessengerEXT> debugUtilsMessenger =
vk::raii::su::make_unique<vk::raii::DebugUtilsMessengerEXT>( *instance, vk::su::makeDebugUtilsMessengerCreateInfoEXT() );
#endif
// Get the list of physical devices
vk::raii::PhysicalDevices physicalDevices( *instance );
// Go through the list of physical devices and select only those that are capable of running the API version we
// want.
std::vector<std::unique_ptr<vk::raii::PhysicalDevice>> desiredPhysicalDevices;
for ( auto & pdh : physicalDevices )
{
if ( desiredVersion <= pdh.getProperties().apiVersion )
{
desiredPhysicalDevices.push_back( vk::raii::su::make_unique<vk::raii::PhysicalDevice>( std::move( pdh ) ) );
}
}
// If we have something in the desired version physical device list, we're good
if ( desiredPhysicalDevices.size() > 0 )
{
usingMajorVersion = desiredMajorVersion;
usingMinorVersion = desiredMinorVersion;
}
}
usingVersionString += std::to_string( usingMajorVersion );
usingVersionString += ".";
usingVersionString += std::to_string( usingMinorVersion );
if ( usingMinorVersion < desiredMinorVersion )
{
std::cout << "Determined that this system can only use Vulkan API version " << usingVersionString
<< " instead of desired version " << desiredVersionString << std::endl;
}
else
{
std::cout << "Determined that this system can run desired Vulkan API version " << desiredVersionString
<< std::endl;
}
/* VULKAN_KEY_END */
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,35 @@
# Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_16_Vulkan_1_1)
set(HEADERS
)
set(SOURCES
16_Vulkan_1_1.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_16_Vulkan_1_1
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_16_Vulkan_1_1 PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_16_Vulkan_1_1 PRIVATE utils)

View File

@ -0,0 +1,56 @@
# Copyright(c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(Vulkan-Hpp_RAIISamples)
option (SAMPLES_BUILD_WITH_LOCAL_VULKAN_HPP "Build with local Vulkan headers" ON)
option (SAMPLES_BUILD_ONLY_DYNAMIC "Build only dynamic. Required in case the Vulkan SDK is not available" OFF)
if(NOT (SAMPLES_BUILD_ONLY_DYNAMIC AND SAMPLES_BUILD_WITH_LOCAL_VULKAN_HPP))
find_package(Vulkan REQUIRED)
endif()
if(MSVC)
add_compile_options(/W4 /WX /permissive-)
else(MSVC)
add_compile_options(-Wall -Wextra -pedantic -Werror)
endif(MSVC)
if (CMAKE_SYSTEM_NAME MATCHES "Windows")
add_definitions(-DNOMINMAX -DVK_USE_PLATFORM_WIN32_KHR)
elseif(CMAKE_SYSTEM_NAME MATCHES "Linux")
add_definitions(-DVK_USE_PLATFORM_XCB_KHR)
else()
message(FATAL_ERROR, "Vulkan-Hpp: unhandled platform for samples!")
endif()
FILE (GLOB linkunits ${CMAKE_CURRENT_SOURCE_DIR}/*)
if (SAMPLES_BUILD_WITH_LOCAL_VULKAN_HPP)
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/..")
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/../Vulkan-Headers/include")
else()
include_directories("${Vulkan_INCLUDE_DIRS}")
endif()
FOREACH( linkunit ${linkunits} )
if( IS_DIRECTORY ${linkunit} )
if( EXISTS ${linkunit}/CMakeLists.txt )
string( REGEX REPLACE "^.*/([^/]*)$" "\\1" LINK_NAME ${linkunit} )
add_subdirectory( ${LINK_NAME} )
endif()
endif()
ENDFOREACH( linkunit ${linkunits} )

View File

@ -0,0 +1,35 @@
# Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_CopyBlitImage)
set(HEADERS
)
set(SOURCES
CopyBlitImage.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_CopyBlitImage
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_CopyBlitImage PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_CopyBlitImage PRIVATE utils)

View File

@ -0,0 +1,266 @@
// Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : CopyBlitImage
// Draw a cube
#include "../utils/utils.hpp"
#include <thread>
static char const * AppName = "CopyBlitImage";
static char const * EngineName = "Vulkan.hpp";
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
std::unique_ptr<vk::raii::Instance> instance =
vk::raii::su::makeUniqueInstance( *context, AppName, EngineName, {}, vk::su::getInstanceExtensions() );
#if !defined( NDEBUG )
std::unique_ptr<vk::raii::DebugUtilsMessengerEXT> debugUtilsMessenger =
vk::raii::su::makeUniqueDebugUtilsMessengerEXT( *instance );
#endif
std::unique_ptr<vk::raii::PhysicalDevice> physicalDevice = vk::raii::su::makeUniquePhysicalDevice( *instance );
vk::raii::su::SurfaceData surfaceData( *instance, AppName, vk::Extent2D( 640, 640 ) );
vk::SurfaceCapabilitiesKHR surfaceCapabilities = physicalDevice->getSurfaceCapabilitiesKHR( **surfaceData.surface );
if ( !( surfaceCapabilities.supportedUsageFlags & vk::ImageUsageFlagBits::eTransferDst ) )
{
std::cout << "Surface cannot be destination of blit - abort \n";
exit( -1 );
}
std::pair<uint32_t, uint32_t> graphicsAndPresentQueueFamilyIndex =
vk::raii::su::findGraphicsAndPresentQueueFamilyIndex( *physicalDevice, *surfaceData.surface );
std::unique_ptr<vk::raii::Device> device = vk::raii::su::makeUniqueDevice(
*physicalDevice, graphicsAndPresentQueueFamilyIndex.first, vk::su::getDeviceExtensions() );
std::unique_ptr<vk::raii::CommandPool> commandPool =
vk::raii::su::makeUniqueCommandPool( *device, graphicsAndPresentQueueFamilyIndex.first );
std::unique_ptr<vk::raii::CommandBuffer> commandBuffer =
vk::raii::su::makeUniqueCommandBuffer( *device, *commandPool );
std::unique_ptr<vk::raii::Queue> graphicsQueue =
vk::raii::su::make_unique<vk::raii::Queue>( *device, graphicsAndPresentQueueFamilyIndex.first, 0 );
std::unique_ptr<vk::raii::Queue> presentQueue =
vk::raii::su::make_unique<vk::raii::Queue>( *device, graphicsAndPresentQueueFamilyIndex.second, 0 );
vk::raii::su::SwapChainData swapChainData( *physicalDevice,
*device,
*surfaceData.surface,
surfaceData.extent,
vk::ImageUsageFlagBits::eColorAttachment |
vk::ImageUsageFlagBits::eTransferSrc |
vk::ImageUsageFlagBits::eTransferDst,
{},
graphicsAndPresentQueueFamilyIndex.first,
graphicsAndPresentQueueFamilyIndex.second );
/* VULKAN_KEY_START */
vk::FormatProperties formatProperties = physicalDevice->getFormatProperties( swapChainData.colorFormat );
assert( ( formatProperties.linearTilingFeatures & vk::FormatFeatureFlagBits::eBlitSrc ) &&
"Format cannot be used as transfer source" );
std::unique_ptr<vk::raii::Semaphore> imageAcquiredSemaphore =
vk::raii::su::make_unique<vk::raii::Semaphore>( *device, vk::SemaphoreCreateInfo() );
// Get the index of the next available swapchain image:
vk::Result result;
uint32_t imageIndex;
std::tie( result, imageIndex ) =
swapChainData.swapChain->acquireNextImage( vk::su::FenceTimeout, **imageAcquiredSemaphore );
assert( result == vk::Result::eSuccess );
assert( imageIndex < swapChainData.images.size() );
commandBuffer->begin( vk::CommandBufferBeginInfo() );
vk::raii::su::setImageLayout( *commandBuffer,
static_cast<vk::Image>( swapChainData.images[imageIndex] ),
swapChainData.colorFormat,
vk::ImageLayout::eUndefined,
vk::ImageLayout::eTransferDstOptimal );
// Create an image, map it, and write some values to the image
vk::ImageCreateInfo imageCreateInfo( {},
vk::ImageType::e2D,
swapChainData.colorFormat,
vk::Extent3D( surfaceData.extent, 1 ),
1,
1,
vk::SampleCountFlagBits::e1,
vk::ImageTiling::eLinear,
vk::ImageUsageFlagBits::eTransferSrc );
std::unique_ptr<vk::raii::Image> blitSourceImage = vk::raii::su::make_unique<vk::raii::Image>( *device, imageCreateInfo );
vk::PhysicalDeviceMemoryProperties memoryProperties = physicalDevice->getMemoryProperties();
vk::MemoryRequirements memoryRequirements = blitSourceImage->getMemoryRequirements();
uint32_t memoryTypeIndex = vk::su::findMemoryType(
memoryProperties, memoryRequirements.memoryTypeBits, vk::MemoryPropertyFlagBits::eHostVisible );
vk::MemoryAllocateInfo memoryAllocateInfo( memoryRequirements.size, memoryTypeIndex );
std::unique_ptr<vk::raii::DeviceMemory> deviceMemory =
vk::raii::su::make_unique<vk::raii::DeviceMemory>( *device, memoryAllocateInfo );
blitSourceImage->bindMemory( **deviceMemory, 0 );
vk::raii::su::setImageLayout( *commandBuffer,
**blitSourceImage,
swapChainData.colorFormat,
vk::ImageLayout::eUndefined,
vk::ImageLayout::eGeneral );
commandBuffer->end();
/* Queue the command buffer for execution */
std::unique_ptr<vk::raii::Fence> commandFence = vk::raii::su::make_unique<vk::raii::Fence>( *device, vk::FenceCreateInfo() );
vk::PipelineStageFlags waitDestinationStageMask( vk::PipelineStageFlagBits::eColorAttachmentOutput );
vk::SubmitInfo submitInfo( **imageAcquiredSemaphore, waitDestinationStageMask, **commandBuffer );
graphicsQueue->submit( submitInfo, **commandFence );
/* Make sure command buffer is finished before mapping */
while ( device->waitForFences( { **commandFence }, true, vk::su::FenceTimeout ) == vk::Result::eTimeout )
;
unsigned char * pImageMemory =
static_cast<unsigned char *>( deviceMemory->mapMemory( 0, memoryRequirements.size ) );
// Checkerboard of 8x8 pixel squares
for ( uint32_t row = 0; row < surfaceData.extent.height; row++ )
{
for ( uint32_t col = 0; col < surfaceData.extent.width; col++ )
{
unsigned char rgb = ( ( ( row & 0x8 ) == 0 ) ^ ( ( col & 0x8 ) == 0 ) ) * 255;
pImageMemory[0] = rgb;
pImageMemory[1] = rgb;
pImageMemory[2] = rgb;
pImageMemory[3] = 255;
pImageMemory += 4;
}
}
// Flush the mapped memory and then unmap it. Assume it isn't coherent since we didn't really confirm
vk::MappedMemoryRange mappedMemoryRange( **deviceMemory, 0, memoryRequirements.size );
device->flushMappedMemoryRanges( mappedMemoryRange );
deviceMemory->unmapMemory();
commandBuffer->reset( {} );
commandBuffer->begin( vk::CommandBufferBeginInfo() );
// Intend to blit from this image, set the layout accordingly
vk::raii::su::setImageLayout( *commandBuffer,
**blitSourceImage,
swapChainData.colorFormat,
vk::ImageLayout::eGeneral,
vk::ImageLayout::eTransferSrcOptimal );
vk::Image blitDestinationImage = static_cast<vk::Image>( swapChainData.images[imageIndex] );
// Do a 32x32 blit to all of the dst image - should get big squares
vk::ImageSubresourceLayers imageSubresourceLayers( vk::ImageAspectFlagBits::eColor, 0, 0, 1 );
vk::ImageBlit imageBlit(
imageSubresourceLayers,
{ { vk::Offset3D( 0, 0, 0 ), vk::Offset3D( 32, 32, 1 ) } },
imageSubresourceLayers,
{ { vk::Offset3D( 0, 0, 0 ), vk::Offset3D( surfaceData.extent.width, surfaceData.extent.height, 1 ) } } );
commandBuffer->blitImage( **blitSourceImage,
vk::ImageLayout::eTransferSrcOptimal,
blitDestinationImage,
vk::ImageLayout::eTransferDstOptimal,
imageBlit,
vk::Filter::eLinear );
// Use a barrier to make sure the blit is finished before the copy starts
vk::ImageMemoryBarrier memoryBarrier( vk::AccessFlagBits::eTransferWrite,
vk::AccessFlagBits::eMemoryRead,
vk::ImageLayout::eTransferDstOptimal,
vk::ImageLayout::eTransferDstOptimal,
VK_QUEUE_FAMILY_IGNORED,
VK_QUEUE_FAMILY_IGNORED,
blitDestinationImage,
vk::ImageSubresourceRange( vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1 ) );
commandBuffer->pipelineBarrier(
vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eTransfer, {}, nullptr, nullptr, memoryBarrier );
// Do a image copy to part of the dst image - checks should stay small
vk::ImageCopy imageCopy( imageSubresourceLayers,
vk::Offset3D(),
imageSubresourceLayers,
vk::Offset3D( 256, 256, 0 ),
vk::Extent3D( 128, 128, 1 ) );
commandBuffer->copyImage( **blitSourceImage,
vk::ImageLayout::eTransferSrcOptimal,
blitDestinationImage,
vk::ImageLayout::eTransferDstOptimal,
imageCopy );
vk::ImageMemoryBarrier prePresentBarrier(
vk::AccessFlagBits::eTransferWrite,
vk::AccessFlagBits::eMemoryRead,
vk::ImageLayout::eTransferDstOptimal,
vk::ImageLayout::ePresentSrcKHR,
VK_QUEUE_FAMILY_IGNORED,
VK_QUEUE_FAMILY_IGNORED,
blitDestinationImage,
vk::ImageSubresourceRange( vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1 ) );
commandBuffer->pipelineBarrier( vk::PipelineStageFlagBits::eTransfer,
vk::PipelineStageFlagBits::eTopOfPipe,
{},
nullptr,
nullptr,
prePresentBarrier );
commandBuffer->end();
std::unique_ptr<vk::raii::Fence> drawFence = vk::raii::su::make_unique<vk::raii::Fence>( *device, vk::FenceCreateInfo() );
submitInfo = vk::SubmitInfo( {}, {}, **commandBuffer );
graphicsQueue->submit( submitInfo, **drawFence );
graphicsQueue->waitIdle();
/* Make sure command buffer is finished before presenting */
while ( device->waitForFences( { **drawFence }, true, vk::su::FenceTimeout ) == vk::Result::eTimeout )
;
/* Now present the image in the window */
vk::PresentInfoKHR presentInfoKHR( nullptr, **swapChainData.swapChain, imageIndex );
result = presentQueue->presentKHR( presentInfoKHR );
switch ( result )
{
case vk::Result::eSuccess: break;
case vk::Result::eSuboptimalKHR:
std::cout << "vk::Queue::presentKHR returned vk::Result::eSuboptimalKHR !\n";
break;
default: assert( false ); // an unexpected result is returned !
}
std::this_thread::sleep_for( std::chrono::milliseconds( 1000 ) );
/* VULKAN_KEY_END */
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,35 @@
# Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_CreateDebugUtilsMessenger)
set(HEADERS
)
set(SOURCES
CreateDebugUtilsMessenger.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_CreateDebugUtilsMessenger
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_CreateDebugUtilsMessenger PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_CreateDebugUtilsMessenger PRIVATE utils)

View File

@ -0,0 +1,144 @@
// Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : CreateDebugReportMessenger
// Draw a cube
#include "../utils/utils.hpp"
#include <iostream>
#include <sstream>
static char const * AppName = "CreateDebugReportMessenger";
static char const * EngineName = "Vulkan.hpp";
VKAPI_ATTR VkBool32 VKAPI_CALL debugMessageFunc( VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
VkDebugUtilsMessageTypeFlagsEXT messageTypes,
VkDebugUtilsMessengerCallbackDataEXT const * pCallbackData,
void * /*pUserData*/ )
{
std::ostringstream message;
message << vk::to_string( static_cast<vk::DebugUtilsMessageSeverityFlagBitsEXT>( messageSeverity ) ) << ": "
<< vk::to_string( static_cast<vk::DebugUtilsMessageTypeFlagsEXT>( messageTypes ) ) << ":\n";
message << "\t"
<< "messageIDName = <" << pCallbackData->pMessageIdName << ">\n";
message << "\t"
<< "messageIdNumber = " << pCallbackData->messageIdNumber << "\n";
message << "\t"
<< "message = <" << pCallbackData->pMessage << ">\n";
if ( 0 < pCallbackData->queueLabelCount )
{
message << "\t"
<< "Queue Labels:\n";
for ( uint8_t i = 0; i < pCallbackData->queueLabelCount; i++ )
{
message << "\t\t"
<< "labelName = <" << pCallbackData->pQueueLabels[i].pLabelName << ">\n";
}
}
if ( 0 < pCallbackData->cmdBufLabelCount )
{
message << "\t"
<< "CommandBuffer Labels:\n";
for ( uint8_t i = 0; i < pCallbackData->cmdBufLabelCount; i++ )
{
message << "\t\t"
<< "labelName = <" << pCallbackData->pCmdBufLabels[i].pLabelName << ">\n";
}
}
if ( 0 < pCallbackData->objectCount )
{
message << "\t"
<< "Objects:\n";
for ( uint8_t i = 0; i < pCallbackData->objectCount; i++ )
{
message << "\t\t"
<< "Object " << i << "\n";
message << "\t\t\t"
<< "objectType = "
<< vk::to_string( static_cast<vk::ObjectType>( pCallbackData->pObjects[i].objectType ) ) << "\n";
message << "\t\t\t"
<< "objectHandle = " << pCallbackData->pObjects[i].objectHandle << "\n";
if ( pCallbackData->pObjects[i].pObjectName )
{
message << "\t\t\t"
<< "objectName = <" << pCallbackData->pObjects[i].pObjectName << ">\n";
}
}
}
#ifdef _WIN32
MessageBox( NULL, message.str().c_str(), "Alert", MB_OK );
#else
std::cout << message.str() << std::endl;
#endif
return false;
}
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
/* VULKAN_KEY_START */
std::vector<vk::ExtensionProperties> props = context->enumerateInstanceExtensionProperties();
auto propsIterator = std::find_if( props.begin(), props.end(), []( vk::ExtensionProperties const & ep ) {
return strcmp( ep.extensionName, VK_EXT_DEBUG_UTILS_EXTENSION_NAME ) == 0;
} );
if ( propsIterator == props.end() )
{
std::cout << "Something went very wrong, cannot find " << VK_EXT_DEBUG_UTILS_EXTENSION_NAME << " extension"
<< std::endl;
exit( 1 );
}
vk::ApplicationInfo applicationInfo( AppName, 1, EngineName, 1, VK_API_VERSION_1_1 );
const char * extensionName = VK_EXT_DEBUG_UTILS_EXTENSION_NAME;
vk::InstanceCreateInfo instanceCreateInfo( {}, &applicationInfo, {}, extensionName );
std::unique_ptr<vk::raii::Instance> instance = vk::raii::su::make_unique<vk::raii::Instance>( *context, instanceCreateInfo );
vk::DebugUtilsMessageSeverityFlagsEXT severityFlags( vk::DebugUtilsMessageSeverityFlagBitsEXT::eWarning |
vk::DebugUtilsMessageSeverityFlagBitsEXT::eError );
vk::DebugUtilsMessageTypeFlagsEXT messageTypeFlags( vk::DebugUtilsMessageTypeFlagBitsEXT::eGeneral |
vk::DebugUtilsMessageTypeFlagBitsEXT::ePerformance |
vk::DebugUtilsMessageTypeFlagBitsEXT::eValidation );
vk::DebugUtilsMessengerCreateInfoEXT debugUtilsMessengerCreateInfoEXT(
{}, severityFlags, messageTypeFlags, &debugMessageFunc );
std::unique_ptr<vk::raii::DebugUtilsMessengerEXT> debugUtilsMessenger =
vk::raii::su::make_unique<vk::raii::DebugUtilsMessengerEXT>( *instance, debugUtilsMessengerCreateInfoEXT );
/* VULKAN_KEY_END */
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,35 @@
# Copyright(c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_DebugUtilsObjectName)
set(HEADERS
)
set(SOURCES
DebugUtilsObjectName.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_DebugUtilsObjectName
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_DebugUtilsObjectName PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_DebugUtilsObjectName PRIVATE utils)

View File

@ -0,0 +1,75 @@
// Copyright(c) 2020, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : DebugUtilsObjectName
// Demonstrate usage of DebugUtilsObjectName
#include "../utils/utils.hpp"
static char const * AppName = "DebugUtilsObjectName";
static char const * EngineName = "Vulkan.hpp";
#if defined( _MSC_VER ) && !defined( _WIN64 )
# define NON_DISPATCHABLE_HANDLE_TO_UINT64_CAST( type, x ) static_cast<type>( x )
#else
# define NON_DISPATCHABLE_HANDLE_TO_UINT64_CAST( type, x ) reinterpret_cast<uint64_t>( static_cast<type>( x ) )
#endif
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
std::unique_ptr<vk::raii::Instance> instance =
vk::raii::su::makeUniqueInstance( *context, AppName, EngineName, {}, vk::su::getInstanceExtensions() );
#if !defined( NDEBUG )
std::unique_ptr<vk::raii::DebugUtilsMessengerEXT> debugUtilsMessenger =
vk::raii::su::makeUniqueDebugUtilsMessengerEXT( *instance );
#endif
vk::raii::PhysicalDevices physicalDevices( *instance );
assert( !physicalDevices.empty() );
uint32_t graphicsQueueFamilyIndex =
vk::su::findGraphicsQueueFamilyIndex( physicalDevices[0].getQueueFamilyProperties() );
std::unique_ptr<vk::raii::Device> device =
vk::raii::su::makeUniqueDevice( physicalDevices[0], graphicsQueueFamilyIndex );
// create an image
std::unique_ptr<vk::raii::Image> image = vk::raii::su::makeUniqueImage( *device );
/* VULKAN_KEY_START */
vk::DebugUtilsObjectNameInfoEXT debugUtilsObjectNameInfo(
vk::ObjectType::eImage, NON_DISPATCHABLE_HANDLE_TO_UINT64_CAST( VkImage, **image ), "Image name" );
device->setDebugUtilsObjectNameEXT( debugUtilsObjectNameInfo );
/* VULKAN_KEY_END */
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,35 @@
# Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_DrawTexturedCube)
set(HEADERS
)
set(SOURCES
DrawTexturedCube.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_DrawTexturedCube
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_DrawTexturedCube PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_DrawTexturedCube PRIVATE utils)

View File

@ -0,0 +1,214 @@
// Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : DrawTexturedCube
// Draw a textured cube
#include "../../samples/utils/geometries.hpp"
#include "../../samples/utils/math.hpp"
#include "../utils/shaders.hpp"
#include "../utils/utils.hpp"
#include "SPIRV/GlslangToSpv.h"
#include "vulkan/vulkan_raii.hpp"
#include <iostream>
#include <thread>
static char const * AppName = "DrawTexturedCube";
static char const * EngineName = "Vulkan.hpp";
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
std::unique_ptr<vk::raii::Instance> instance =
vk::raii::su::makeUniqueInstance( *context, AppName, EngineName, {}, vk::su::getInstanceExtensions() );
#if !defined( NDEBUG )
std::unique_ptr<vk::raii::DebugUtilsMessengerEXT> debugUtilsMessenger =
vk::raii::su::makeUniqueDebugUtilsMessengerEXT( *instance );
#endif
std::unique_ptr<vk::raii::PhysicalDevice> physicalDevice = vk::raii::su::makeUniquePhysicalDevice( *instance );
vk::raii::su::SurfaceData surfaceData( *instance, AppName, vk::Extent2D( 500, 500 ) );
std::pair<uint32_t, uint32_t> graphicsAndPresentQueueFamilyIndex =
vk::raii::su::findGraphicsAndPresentQueueFamilyIndex( *physicalDevice, *surfaceData.surface );
std::unique_ptr<vk::raii::Device> device = vk::raii::su::makeUniqueDevice(
*physicalDevice, graphicsAndPresentQueueFamilyIndex.first, vk::su::getDeviceExtensions() );
std::unique_ptr<vk::raii::CommandPool> commandPool =
vk::raii::su::makeUniqueCommandPool( *device, graphicsAndPresentQueueFamilyIndex.first );
std::unique_ptr<vk::raii::CommandBuffer> commandBuffer =
vk::raii::su::makeUniqueCommandBuffer( *device, *commandPool );
std::unique_ptr<vk::raii::Queue> graphicsQueue =
vk::raii::su::make_unique<vk::raii::Queue>( *device, graphicsAndPresentQueueFamilyIndex.first, 0 );
std::unique_ptr<vk::raii::Queue> presentQueue =
vk::raii::su::make_unique<vk::raii::Queue>( *device, graphicsAndPresentQueueFamilyIndex.second, 0 );
vk::raii::su::SwapChainData swapChainData( *physicalDevice,
*device,
*surfaceData.surface,
surfaceData.extent,
vk::ImageUsageFlagBits::eColorAttachment |
vk::ImageUsageFlagBits::eTransferSrc,
{},
graphicsAndPresentQueueFamilyIndex.first,
graphicsAndPresentQueueFamilyIndex.second );
vk::raii::su::DepthBufferData depthBufferData(
*physicalDevice, *device, vk::Format::eD16Unorm, surfaceData.extent );
vk::raii::su::TextureData textureData( *physicalDevice, *device );
commandBuffer->begin( vk::CommandBufferBeginInfo() );
textureData.setImage( *commandBuffer, vk::su::CheckerboardImageGenerator() );
vk::raii::su::BufferData uniformBufferData(
*physicalDevice, *device, sizeof( glm::mat4x4 ), vk::BufferUsageFlagBits::eUniformBuffer );
glm::mat4x4 mvpcMatrix = vk::su::createModelViewProjectionClipMatrix( surfaceData.extent );
vk::raii::su::copyToDevice( *uniformBufferData.deviceMemory, mvpcMatrix );
std::unique_ptr<vk::raii::DescriptorSetLayout> descriptorSetLayout = vk::raii::su::makeUniqueDescriptorSetLayout(
*device,
{ { vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eVertex },
{ vk::DescriptorType::eCombinedImageSampler, 1, vk::ShaderStageFlagBits::eFragment } } );
std::unique_ptr<vk::raii::PipelineLayout> pipelineLayout =
vk::raii::su::makeUniquePipelineLayout( *device, *descriptorSetLayout );
vk::Format colorFormat =
vk::su::pickSurfaceFormat( physicalDevice->getSurfaceFormatsKHR( **surfaceData.surface ) ).format;
std::unique_ptr<vk::raii::RenderPass> renderPass =
vk::raii::su::makeUniqueRenderPass( *device, colorFormat, depthBufferData.format );
glslang::InitializeProcess();
std::unique_ptr<vk::raii::ShaderModule> vertexShaderModule =
vk::raii::su::makeUniqueShaderModule( *device, vk::ShaderStageFlagBits::eVertex, vertexShaderText_PT_T );
std::unique_ptr<vk::raii::ShaderModule> fragmentShaderModule =
vk::raii::su::makeUniqueShaderModule( *device, vk::ShaderStageFlagBits::eFragment, fragmentShaderText_T_C );
glslang::FinalizeProcess();
std::vector<std::unique_ptr<vk::raii::Framebuffer>> framebuffers = vk::raii::su::makeUniqueFramebuffers(
*device, *renderPass, swapChainData.imageViews, depthBufferData.imageView, surfaceData.extent );
vk::raii::su::BufferData vertexBufferData(
*physicalDevice, *device, sizeof( texturedCubeData ), vk::BufferUsageFlagBits::eVertexBuffer );
vk::raii::su::copyToDevice(
*vertexBufferData.deviceMemory, texturedCubeData, sizeof( texturedCubeData ) / sizeof( texturedCubeData[0] ) );
std::unique_ptr<vk::raii::DescriptorPool> descriptorPool = vk::raii::su::makeUniqueDescriptorPool(
*device, { { vk::DescriptorType::eUniformBuffer, 1 }, { vk::DescriptorType::eCombinedImageSampler, 1 } } );
std::unique_ptr<vk::raii::DescriptorSet> descriptorSet =
vk::raii::su::makeUniqueDescriptorSet( *device, *descriptorPool, *descriptorSetLayout );
vk::raii::su::updateDescriptorSets( *device,
*descriptorSet,
{ { vk::DescriptorType::eUniformBuffer, *uniformBufferData.buffer, nullptr } },
{ textureData } );
std::unique_ptr<vk::raii::PipelineCache> pipelineCache =
vk::raii::su::make_unique<vk::raii::PipelineCache>( *device, vk::PipelineCacheCreateInfo() );
std::unique_ptr<vk::raii::Pipeline> graphicsPipeline = vk::raii::su::makeUniqueGraphicsPipeline(
*device,
*pipelineCache,
*vertexShaderModule,
nullptr,
*fragmentShaderModule,
nullptr,
sizeof( texturedCubeData[0] ),
{ { vk::Format::eR32G32B32A32Sfloat, 0 }, { vk::Format::eR32G32Sfloat, 16 } },
vk::FrontFace::eClockwise,
true,
*pipelineLayout,
*renderPass );
/* VULKAN_KEY_START */
// Get the index of the next available swapchain image:
std::unique_ptr<vk::raii::Semaphore> imageAcquiredSemaphore =
vk::raii::su::make_unique<vk::raii::Semaphore>( *device, vk::SemaphoreCreateInfo() );
vk::Result result;
uint32_t imageIndex;
std::tie( result, imageIndex ) =
swapChainData.swapChain->acquireNextImage( vk::su::FenceTimeout, **imageAcquiredSemaphore );
assert( result == vk::Result::eSuccess );
assert( imageIndex < swapChainData.images.size() );
// commandBuffer->begin() has already been called above!
std::array<vk::ClearValue, 2> clearValues;
clearValues[0].color = vk::ClearColorValue( std::array<float, 4>( { { 0.2f, 0.2f, 0.2f, 0.2f } } ) );
clearValues[1].depthStencil = vk::ClearDepthStencilValue( 1.0f, 0 );
vk::RenderPassBeginInfo renderPassBeginInfo(
**renderPass, **framebuffers[imageIndex], vk::Rect2D( vk::Offset2D( 0, 0 ), surfaceData.extent ), clearValues );
commandBuffer->beginRenderPass( renderPassBeginInfo, vk::SubpassContents::eInline );
commandBuffer->bindPipeline( vk::PipelineBindPoint::eGraphics, **graphicsPipeline );
commandBuffer->bindDescriptorSets(
vk::PipelineBindPoint::eGraphics, **pipelineLayout, 0, { **descriptorSet }, nullptr );
commandBuffer->bindVertexBuffers( 0, { **vertexBufferData.buffer }, { 0 } );
commandBuffer->setViewport( 0,
vk::Viewport( 0.0f,
0.0f,
static_cast<float>( surfaceData.extent.width ),
static_cast<float>( surfaceData.extent.height ),
0.0f,
1.0f ) );
commandBuffer->setScissor( 0, vk::Rect2D( vk::Offset2D( 0, 0 ), surfaceData.extent ) );
commandBuffer->draw( 12 * 3, 1, 0, 0 );
commandBuffer->endRenderPass();
commandBuffer->end();
std::unique_ptr<vk::raii::Fence> drawFence = vk::raii::su::make_unique<vk::raii::Fence>( *device, vk::FenceCreateInfo() );
vk::PipelineStageFlags waitDestinationStageMask( vk::PipelineStageFlagBits::eColorAttachmentOutput );
vk::SubmitInfo submitInfo( **imageAcquiredSemaphore, waitDestinationStageMask, **commandBuffer );
graphicsQueue->submit( submitInfo, **drawFence );
while ( vk::Result::eTimeout == device->waitForFences( { **drawFence }, VK_TRUE, vk::su::FenceTimeout ) )
;
vk::PresentInfoKHR presentInfoKHR( nullptr, **swapChainData.swapChain, imageIndex );
result = presentQueue->presentKHR( presentInfoKHR );
switch ( result )
{
case vk::Result::eSuccess: break;
case vk::Result::eSuboptimalKHR:
std::cout << "vk::Queue::presentKHR returned vk::Result::eSuboptimalKHR !\n";
break;
default: assert( false ); // an unexpected result is returned !
}
std::this_thread::sleep_for( std::chrono::milliseconds( 1000 ) );
/* VULKAN_KEY_END */
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,35 @@
# Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_DynamicUniform)
set(HEADERS
)
set(SOURCES
DynamicUniform.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_DynamicUniform
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_DynamicUniform PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_DynamicUniform PRIVATE utils)

View File

@ -0,0 +1,254 @@
// Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : DynamicUniform
// Draw 2 Cubes using dynamic uniform buffer
#if defined( _MSC_VER )
# pragma warning( disable : 4127 ) // conditional expression is constant
#endif
#include "../../samples/utils/geometries.hpp"
#include "../../samples/utils/math.hpp"
#include "../utils/shaders.hpp"
#include "../utils/utils.hpp"
#include "SPIRV/GlslangToSpv.h"
#include "vulkan/vulkan_raii.hpp"
#include <iostream>
#include <thread>
static char const * AppName = "DynamicUniform";
static char const * EngineName = "Vulkan.hpp";
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
std::unique_ptr<vk::raii::Instance> instance =
vk::raii::su::makeUniqueInstance( *context, AppName, EngineName, {}, vk::su::getInstanceExtensions() );
#if !defined( NDEBUG )
std::unique_ptr<vk::raii::DebugUtilsMessengerEXT> debugUtilsMessenger =
vk::raii::su::makeUniqueDebugUtilsMessengerEXT( *instance );
#endif
std::unique_ptr<vk::raii::PhysicalDevice> physicalDevice = vk::raii::su::makeUniquePhysicalDevice( *instance );
vk::raii::su::SurfaceData surfaceData( *instance, AppName, vk::Extent2D( 500, 500 ) );
std::pair<uint32_t, uint32_t> graphicsAndPresentQueueFamilyIndex =
vk::raii::su::findGraphicsAndPresentQueueFamilyIndex( *physicalDevice, *surfaceData.surface );
std::unique_ptr<vk::raii::Device> device = vk::raii::su::makeUniqueDevice(
*physicalDevice, graphicsAndPresentQueueFamilyIndex.first, vk::su::getDeviceExtensions() );
std::unique_ptr<vk::raii::CommandPool> commandPool =
vk::raii::su::makeUniqueCommandPool( *device, graphicsAndPresentQueueFamilyIndex.first );
std::unique_ptr<vk::raii::CommandBuffer> commandBuffer =
vk::raii::su::makeUniqueCommandBuffer( *device, *commandPool );
std::unique_ptr<vk::raii::Queue> graphicsQueue =
vk::raii::su::make_unique<vk::raii::Queue>( *device, graphicsAndPresentQueueFamilyIndex.first, 0 );
std::unique_ptr<vk::raii::Queue> presentQueue =
vk::raii::su::make_unique<vk::raii::Queue>( *device, graphicsAndPresentQueueFamilyIndex.second, 0 );
vk::raii::su::SwapChainData swapChainData( *physicalDevice,
*device,
*surfaceData.surface,
surfaceData.extent,
vk::ImageUsageFlagBits::eColorAttachment |
vk::ImageUsageFlagBits::eTransferSrc,
{},
graphicsAndPresentQueueFamilyIndex.first,
graphicsAndPresentQueueFamilyIndex.second );
vk::raii::su::DepthBufferData depthBufferData(
*physicalDevice, *device, vk::Format::eD16Unorm, surfaceData.extent );
vk::Format colorFormat =
vk::su::pickSurfaceFormat( physicalDevice->getSurfaceFormatsKHR( **surfaceData.surface ) ).format;
std::unique_ptr<vk::raii::RenderPass> renderPass =
vk::raii::su::makeUniqueRenderPass( *device, colorFormat, depthBufferData.format );
glslang::InitializeProcess();
std::unique_ptr<vk::raii::ShaderModule> vertexShaderModule =
vk::raii::su::makeUniqueShaderModule( *device, vk::ShaderStageFlagBits::eVertex, vertexShaderText_PC_C );
std::unique_ptr<vk::raii::ShaderModule> fragmentShaderModule =
vk::raii::su::makeUniqueShaderModule( *device, vk::ShaderStageFlagBits::eFragment, fragmentShaderText_C_C );
glslang::FinalizeProcess();
std::vector<std::unique_ptr<vk::raii::Framebuffer>> framebuffers = vk::raii::su::makeUniqueFramebuffers(
*device, *renderPass, swapChainData.imageViews, depthBufferData.imageView, surfaceData.extent );
vk::raii::su::BufferData vertexBufferData(
*physicalDevice, *device, sizeof( coloredCubeData ), vk::BufferUsageFlagBits::eVertexBuffer );
vk::raii::su::copyToDevice(
*vertexBufferData.deviceMemory, coloredCubeData, sizeof( coloredCubeData ) / sizeof( coloredCubeData[0] ) );
/* VULKAN_KEY_START */
vk::PhysicalDeviceLimits limits = physicalDevice->getProperties().limits;
if ( limits.maxDescriptorSetUniformBuffersDynamic < 1 )
{
std::cout << "No dynamic uniform buffers supported\n";
exit( -1 );
}
/* Set up uniform buffer with 2 transform matrices in it */
glm::mat4x4 mvpcs[2];
glm::mat4x4 model = glm::mat4x4( 1.0f );
glm::mat4x4 view =
glm::lookAt( glm::vec3( 0.0f, 3.0f, -10.0f ), glm::vec3( 0.0f, 0.0f, 0.0f ), glm::vec3( 0.0f, -1.0f, 0.0f ) );
glm::mat4x4 projection = glm::perspective( glm::radians( 45.0f ), 1.0f, 0.1f, 100.0f );
// clang-format off
glm::mat4x4 clip = glm::mat4x4( 1.0f, 0.0f, 0.0f, 0.0f,
0.0f, -1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.5f, 0.0f,
0.0f, 0.0f, 0.5f, 1.0f ); // vulkan clip space has inverted y and half z !
// clang-format on
mvpcs[0] = clip * projection * view * model;
model = glm::translate( model, glm::vec3( -1.5f, 1.5f, -1.5f ) );
mvpcs[1] = clip * projection * view * model;
vk::DeviceSize bufferSize = sizeof( glm::mat4x4 );
if ( limits.minUniformBufferOffsetAlignment )
{
bufferSize =
( bufferSize + limits.minUniformBufferOffsetAlignment - 1 ) & ~( limits.minUniformBufferOffsetAlignment - 1 );
}
vk::raii::su::BufferData uniformBufferData(
*physicalDevice, *device, 2 * bufferSize, vk::BufferUsageFlagBits::eUniformBuffer );
vk::raii::su::copyToDevice( *uniformBufferData.deviceMemory, mvpcs, 2, bufferSize );
// create a DescriptorSetLayout with vk::DescriptorType::eUniformBufferDynamic
std::unique_ptr<vk::raii::DescriptorSetLayout> descriptorSetLayout = vk::raii::su::makeUniqueDescriptorSetLayout(
*device, { { vk::DescriptorType::eUniformBufferDynamic, 1, vk::ShaderStageFlagBits::eVertex } } );
std::unique_ptr<vk::raii::PipelineLayout> pipelineLayout =
vk::raii::su::makeUniquePipelineLayout( *device, *descriptorSetLayout );
// create a DescriptorPool with vk::DescriptorType::eUniformBufferDynamic
std::unique_ptr<vk::raii::DescriptorPool> descriptorPool =
vk::raii::su::makeUniqueDescriptorPool( *device, { { vk::DescriptorType::eUniformBufferDynamic, 1 } } );
std::unique_ptr<vk::raii::DescriptorSet> descriptorSet =
vk::raii::su::makeUniqueDescriptorSet( *device, *descriptorPool, *descriptorSetLayout );
vk::raii::su::updateDescriptorSets(
*device,
*descriptorSet,
{ { vk::DescriptorType::eUniformBufferDynamic, *uniformBufferData.buffer, nullptr } },
{} );
std::unique_ptr<vk::raii::PipelineCache> pipelineCache =
vk::raii::su::make_unique<vk::raii::PipelineCache>( *device, vk::PipelineCacheCreateInfo() );
std::unique_ptr<vk::raii::Pipeline> graphicsPipeline = vk::raii::su::makeUniqueGraphicsPipeline(
*device,
*pipelineCache,
*vertexShaderModule,
nullptr,
*fragmentShaderModule,
nullptr,
sizeof( coloredCubeData[0] ),
{ { vk::Format::eR32G32B32A32Sfloat, 0 }, { vk::Format::eR32G32Sfloat, 16 } },
vk::FrontFace::eClockwise,
true,
*pipelineLayout,
*renderPass );
// Get the index of the next available swapchain image:
std::unique_ptr<vk::raii::Semaphore> imageAcquiredSemaphore =
vk::raii::su::make_unique<vk::raii::Semaphore>( *device, vk::SemaphoreCreateInfo() );
vk::Result result;
uint32_t imageIndex;
std::tie( result, imageIndex ) =
swapChainData.swapChain->acquireNextImage( vk::su::FenceTimeout, **imageAcquiredSemaphore );
assert( result == vk::Result::eSuccess );
assert( imageIndex < swapChainData.images.size() );
commandBuffer->begin( {} );
std::array<vk::ClearValue, 2> clearValues;
clearValues[0].color = vk::ClearColorValue( std::array<float, 4>( { { 0.2f, 0.2f, 0.2f, 0.2f } } ) );
clearValues[1].depthStencil = vk::ClearDepthStencilValue( 1.0f, 0 );
vk::RenderPassBeginInfo renderPassBeginInfo(
**renderPass, **framebuffers[imageIndex], vk::Rect2D( vk::Offset2D( 0, 0 ), surfaceData.extent ), clearValues );
commandBuffer->beginRenderPass( renderPassBeginInfo, vk::SubpassContents::eInline );
commandBuffer->bindPipeline( vk::PipelineBindPoint::eGraphics, **graphicsPipeline );
commandBuffer->setViewport( 0,
vk::Viewport( 0.0f,
0.0f,
static_cast<float>( surfaceData.extent.width ),
static_cast<float>( surfaceData.extent.height ),
0.0f,
1.0f ) );
commandBuffer->setScissor( 0, vk::Rect2D( vk::Offset2D( 0, 0 ), surfaceData.extent ) );
/* The first draw should use the first matrix in the buffer */
uint32_t dynamicOffset = 0;
commandBuffer->bindDescriptorSets(
vk::PipelineBindPoint::eGraphics, **pipelineLayout, 0, { **descriptorSet }, dynamicOffset );
commandBuffer->bindVertexBuffers( 0, { **vertexBufferData.buffer }, { 0 } );
commandBuffer->draw( 12 * 3, 1, 0, 0 );
// the second draw should use the second matrix in the buffer;
dynamicOffset = (uint32_t)bufferSize;
commandBuffer->bindDescriptorSets(
vk::PipelineBindPoint::eGraphics, **pipelineLayout, 0, { **descriptorSet }, dynamicOffset );
commandBuffer->draw( 12 * 3, 1, 0, 0 );
commandBuffer->endRenderPass();
commandBuffer->end();
std::unique_ptr<vk::raii::Fence> drawFence = vk::raii::su::make_unique<vk::raii::Fence>( *device, vk::FenceCreateInfo() );
vk::PipelineStageFlags waitDestinationStageMask( vk::PipelineStageFlagBits::eColorAttachmentOutput );
vk::SubmitInfo submitInfo( **imageAcquiredSemaphore, waitDestinationStageMask, **commandBuffer );
graphicsQueue->submit( submitInfo, **drawFence );
while ( vk::Result::eTimeout == device->waitForFences( { **drawFence }, VK_TRUE, vk::su::FenceTimeout ) )
;
vk::PresentInfoKHR presentInfoKHR( nullptr, **swapChainData.swapChain, imageIndex );
result = presentQueue->presentKHR( presentInfoKHR );
switch ( result )
{
case vk::Result::eSuccess: break;
case vk::Result::eSuboptimalKHR:
std::cout << "vk::Queue::presentKHR returned vk::Result::eSuboptimalKHR !\n";
break;
default: assert( false ); // an unexpected result is returned !
}
std::this_thread::sleep_for( std::chrono::milliseconds( 1000 ) );
/* VULKAN_KEY_END */
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,35 @@
# Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_EnableValidationWithCallback)
set(HEADERS
)
set(SOURCES
EnableValidationWithCallback.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_EnableValidationWithCallback
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_EnableValidationWithCallback PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_EnableValidationWithCallback PRIVATE utils)

View File

@ -0,0 +1,211 @@
// Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : EnableValidationWithCallback
// Show how to enable validation layers and provide callback
#if defined( _MSC_VER )
// no need to ignore any warnings with MSVC
#elif defined( __clang__ )
# pragma clang diagnostic ignored "-Wunused-variable"
#elif defined( __GNUC__ )
# pragma GCC diagnostic ignored "-Wunused-but-set-variable"
#else
// unknow compiler... just ignore the warnings for yourselves ;)
#endif
#include "../utils/utils.hpp"
#include "vulkan/vulkan_raii.hpp"
#include <algorithm>
#include <iostream>
#include <sstream>
static char const * AppName = "EnableValidationWithCallback";
static char const * EngineName = "Vulkan.hpp";
PFN_vkCreateDebugUtilsMessengerEXT pfnVkCreateDebugUtilsMessengerEXT;
PFN_vkDestroyDebugUtilsMessengerEXT pfnVkDestroyDebugUtilsMessengerEXT;
VKAPI_ATTR VkResult VKAPI_CALL vkCreateDebugUtilsMessengerEXT( VkInstance instance,
const VkDebugUtilsMessengerCreateInfoEXT * pCreateInfo,
const VkAllocationCallbacks * pAllocator,
VkDebugUtilsMessengerEXT * pMessenger )
{
return pfnVkCreateDebugUtilsMessengerEXT( instance, pCreateInfo, pAllocator, pMessenger );
}
VKAPI_ATTR void VKAPI_CALL vkDestroyDebugUtilsMessengerEXT( VkInstance instance,
VkDebugUtilsMessengerEXT messenger,
VkAllocationCallbacks const * pAllocator )
{
return pfnVkDestroyDebugUtilsMessengerEXT( instance, messenger, pAllocator );
}
VKAPI_ATTR VkBool32 VKAPI_CALL debugMessageFunc( VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
VkDebugUtilsMessageTypeFlagsEXT messageTypes,
VkDebugUtilsMessengerCallbackDataEXT const * pCallbackData,
void * /*pUserData*/ )
{
std::string message;
message += vk::to_string( static_cast<vk::DebugUtilsMessageSeverityFlagBitsEXT>( messageSeverity ) ) + ": " +
vk::to_string( static_cast<vk::DebugUtilsMessageTypeFlagsEXT>( messageTypes ) ) + ":\n";
message += std::string( "\t" ) + "messageIDName = <" + pCallbackData->pMessageIdName + ">\n";
message += std::string( "\t" ) + "messageIdNumber = " + std::to_string( pCallbackData->messageIdNumber ) + "\n";
message += std::string( "\t" ) + "message = <" + pCallbackData->pMessage + ">\n";
if ( 0 < pCallbackData->queueLabelCount )
{
message += std::string( "\t" ) + "Queue Labels:\n";
for ( uint8_t i = 0; i < pCallbackData->queueLabelCount; i++ )
{
message += std::string( "\t\t" ) + "labelName = <" + pCallbackData->pQueueLabels[i].pLabelName + ">\n";
}
}
if ( 0 < pCallbackData->cmdBufLabelCount )
{
message += std::string( "\t" ) + "CommandBuffer Labels:\n";
for ( uint8_t i = 0; i < pCallbackData->cmdBufLabelCount; i++ )
{
message += std::string( "\t\t" ) + "labelName = <" + pCallbackData->pCmdBufLabels[i].pLabelName + ">\n";
}
}
if ( 0 < pCallbackData->objectCount )
{
for ( uint8_t i = 0; i < pCallbackData->objectCount; i++ )
{
message += std::string( "\t" ) + "Object " + std::to_string( i ) + "\n";
message += std::string( "\t\t" ) + "objectType = " +
vk::to_string( static_cast<vk::ObjectType>( pCallbackData->pObjects[i].objectType ) ) + "\n";
message +=
std::string( "\t\t" ) + "objectHandle = " + std::to_string( pCallbackData->pObjects[i].objectHandle ) + "\n";
if ( pCallbackData->pObjects[i].pObjectName )
{
message += std::string( "\t\t" ) + "objectName = <" + pCallbackData->pObjects[i].pObjectName + ">\n";
}
}
}
#ifdef _WIN32
MessageBox( NULL, message.c_str(), "Alert", MB_OK );
#else
std::cout << message << std::endl;
#endif
return false;
}
bool checkLayers( std::vector<char const *> const & layers, std::vector<vk::LayerProperties> const & properties )
{
// return true if all layers are listed in the properties
return std::all_of( layers.begin(), layers.end(), [&properties]( char const * name ) {
return std::find_if( properties.begin(), properties.end(), [&name]( vk::LayerProperties const & property ) {
return strcmp( property.layerName, name ) == 0;
} ) != properties.end();
} );
}
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
std::vector<vk::LayerProperties> instanceLayerProperties = context->enumerateInstanceLayerProperties();
/* VULKAN_KEY_START */
// Use standard_validation meta layer that enables all recommended validation layers
std::vector<char const *> instanceLayerNames;
instanceLayerNames.push_back( "VK_LAYER_KHRONOS_validation" );
if ( !checkLayers( instanceLayerNames, instanceLayerProperties ) )
{
std::cout << "Set the environment variable VK_LAYER_PATH to point to the location of your layers" << std::endl;
exit( 1 );
}
/* Enable debug callback extension */
std::vector<char const *> instanceExtensionNames;
instanceExtensionNames.push_back( VK_EXT_DEBUG_UTILS_EXTENSION_NAME );
vk::ApplicationInfo applicationInfo( AppName, 1, EngineName, 1, VK_API_VERSION_1_1 );
vk::InstanceCreateInfo instanceCreateInfo( {}, &applicationInfo, instanceLayerNames, instanceExtensionNames );
std::unique_ptr<vk::raii::Instance> instance = vk::raii::su::make_unique<vk::raii::Instance>( *context, instanceCreateInfo );
pfnVkCreateDebugUtilsMessengerEXT =
reinterpret_cast<PFN_vkCreateDebugUtilsMessengerEXT>( instance->getProcAddr( "vkCreateDebugUtilsMessengerEXT" ) );
if ( !pfnVkCreateDebugUtilsMessengerEXT )
{
std::cout << "GetInstanceProcAddr: Unable to find pfnVkCreateDebugUtilsMessengerEXT function." << std::endl;
exit( 1 );
}
pfnVkDestroyDebugUtilsMessengerEXT = reinterpret_cast<PFN_vkDestroyDebugUtilsMessengerEXT>(
instance->getProcAddr( "vkDestroyDebugUtilsMessengerEXT" ) );
if ( !pfnVkDestroyDebugUtilsMessengerEXT )
{
std::cout << "GetInstanceProcAddr: Unable to find pfnVkDestroyDebugUtilsMessengerEXT function." << std::endl;
exit( 1 );
}
vk::DebugUtilsMessageSeverityFlagsEXT severityFlags( vk::DebugUtilsMessageSeverityFlagBitsEXT::eWarning |
vk::DebugUtilsMessageSeverityFlagBitsEXT::eError );
vk::DebugUtilsMessageTypeFlagsEXT messageTypeFlags( vk::DebugUtilsMessageTypeFlagBitsEXT::eGeneral |
vk::DebugUtilsMessageTypeFlagBitsEXT::ePerformance |
vk::DebugUtilsMessageTypeFlagBitsEXT::eValidation );
vk::DebugUtilsMessengerCreateInfoEXT debugUtilsMessengerCreateInfoEXT(
{}, severityFlags, messageTypeFlags, &debugMessageFunc );
std::unique_ptr<vk::raii::DebugUtilsMessengerEXT> debugUtilsMessenger =
vk::raii::su::make_unique<vk::raii::DebugUtilsMessengerEXT>( *instance, debugUtilsMessengerCreateInfoEXT );
std::unique_ptr<vk::raii::PhysicalDevice> physicalDevice = vk::raii::su::makeUniquePhysicalDevice( *instance );
// get the index of the first queue family that supports graphics
uint32_t graphicsQueueFamilyIndex =
vk::su::findGraphicsQueueFamilyIndex( physicalDevice->getQueueFamilyProperties() );
float queuePriority = 0.0f;
vk::DeviceQueueCreateInfo deviceQueueCreateInfo( {}, graphicsQueueFamilyIndex, 1, &queuePriority );
vk::DeviceCreateInfo deviceCreateInfo( {}, deviceQueueCreateInfo );
std::unique_ptr<vk::raii::Device> device = vk::raii::su::make_unique<vk::raii::Device>( *physicalDevice, deviceCreateInfo );
// Create a vk::CommandPool (not a vk::raii::CommandPool, for testing purposes!)
vk::CommandPoolCreateInfo commandPoolCreateInfo( {}, graphicsQueueFamilyIndex );
vk::CommandPool commandPool =
( **device ).createCommandPool( commandPoolCreateInfo, nullptr, *device->getDispatcher() );
// The commandPool is not destroyed automatically (as it's not a UniqueCommandPool.
// That is, the device is destroyed before the commmand pool and will trigger a validation error.
std::cout << "*** INTENTIONALLY destroying the Device before destroying a CommandPool ***\n";
std::cout << "*** The following error message is EXPECTED ***\n";
/* VULKAN_KEY_END */
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,35 @@
# Copyright(c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_EnumerateDevicesAdvanced)
set(HEADERS
)
set(SOURCES
EnumerateDevicesAdvanced.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_EnumerateDevicesAdvanced
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_EnumerateDevicesAdvanced PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_EnumerateDevicesAdvanced PRIVATE utils)

View File

@ -0,0 +1,86 @@
// Copyright(c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : EnumerateDevicesAdvanced
// Enumerate physical devices
#include "../utils/utils.hpp"
#include "vulkan/vulkan_raii.hpp"
#include <iomanip>
#include <iostream>
static char const * AppName = "EnumerateDevicesAdvanced";
static char const * EngineName = "Vulkan.hpp";
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
std::unique_ptr<vk::raii::Instance> instance =
vk::raii::su::makeUniqueInstance( *context, AppName, EngineName, {}, vk::su::getInstanceExtensions() );
#if !defined( NDEBUG )
std::unique_ptr<vk::raii::DebugUtilsMessengerEXT> debugUtilsMessenger =
vk::raii::su::makeUniqueDebugUtilsMessengerEXT( *instance );
#endif
/* VULKAN_HPP_KEY_START */
// enumerate the physicalDevices
vk::raii::PhysicalDevices physicalDevices( *instance );
for ( auto const & pdh : physicalDevices )
{
vk::PhysicalDeviceProperties properties = pdh.getProperties();
std::cout << "apiVersion: ";
std::cout << ( ( properties.apiVersion >> 22 ) & 0xfff ) << '.'; // Major.
std::cout << ( ( properties.apiVersion >> 12 ) & 0x3ff ) << '.'; // Minor.
std::cout << ( properties.apiVersion & 0xfff ); // Patch.
std::cout << '\n';
std::cout << "driverVersion: " << properties.driverVersion << '\n';
std::cout << std::showbase << std::internal << std::setfill( '0' ) << std::hex;
std::cout << "vendorId: " << std::setw( 6 ) << properties.vendorID << '\n';
std::cout << "deviceId: " << std::setw( 6 ) << properties.deviceID << '\n';
std::cout << std::noshowbase << std::right << std::setfill( ' ' ) << std::dec;
std::cout << "deviceType: " << vk::to_string( properties.deviceType ) << "\n";
std::cout << "deviceName: " << properties.deviceName << '\n';
std::cout << "pipelineCacheUUID: " << vk::su::UUID( properties.pipelineCacheUUID ) << "\n\n";
}
/* VULKAN_HPP_KEY_END */
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,35 @@
# Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_Events)
set(HEADERS
)
set(SOURCES
Events.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_Events
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_Events PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_Events PRIVATE utils)

View File

@ -0,0 +1,162 @@
// Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : Events
// Use basic events
#include "../utils/utils.hpp"
#include "vulkan/vulkan_raii.hpp"
#include <iostream>
static char const * AppName = "Events";
static char const * EngineName = "Vulkan.hpp";
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
std::unique_ptr<vk::raii::Instance> instance =
vk::raii::su::makeUniqueInstance( *context, AppName, EngineName, {}, vk::su::getInstanceExtensions() );
#if !defined( NDEBUG )
std::unique_ptr<vk::raii::DebugUtilsMessengerEXT> debugUtilsMessenger =
vk::raii::su::makeUniqueDebugUtilsMessengerEXT( *instance );
#endif
std::unique_ptr<vk::raii::PhysicalDevice> physicalDevice = vk::raii::su::makeUniquePhysicalDevice( *instance );
uint32_t graphicsQueueFamilyIndex =
vk::su::findGraphicsQueueFamilyIndex( physicalDevice->getQueueFamilyProperties() );
std::unique_ptr<vk::raii::Device> device =
vk::raii::su::makeUniqueDevice( *physicalDevice, graphicsQueueFamilyIndex, vk::su::getDeviceExtensions() );
std::unique_ptr<vk::raii::CommandPool> commandPool =
vk::raii::su::makeUniqueCommandPool( *device, graphicsQueueFamilyIndex );
std::unique_ptr<vk::raii::CommandBuffer> commandBuffer =
vk::raii::su::makeUniqueCommandBuffer( *device, *commandPool );
std::unique_ptr<vk::raii::Queue> graphicsQueue =
vk::raii::su::make_unique<vk::raii::Queue>( *device, graphicsQueueFamilyIndex, 0 );
/* VULKAN_KEY_START */
// Start with a trivial command buffer and make sure fence wait doesn't time out
commandBuffer->begin( {} );
commandBuffer->setViewport( 0, vk::Viewport( 0.0f, 0.0f, 10.0f, 10.0f, 0.0f, 1.0f ) );
commandBuffer->end();
std::unique_ptr<vk::raii::Fence> fence = vk::raii::su::make_unique<vk::raii::Fence>( *device, vk::FenceCreateInfo() );
vk::SubmitInfo submitInfo( {}, {}, **commandBuffer );
graphicsQueue->submit( submitInfo, **fence );
// Make sure timeout is long enough for a simple command buffer without waiting for an event
vk::Result result;
int timeouts = -1;
do
{
result = device->waitForFences( { **fence }, true, vk::su::FenceTimeout );
timeouts++;
} while ( result == vk::Result::eTimeout );
assert( result == vk::Result::eSuccess );
if ( timeouts != 0 )
{
std::cout << "Unsuitable timeout value, exiting\n";
exit( -1 );
}
// Now create an event and wait for it on the GPU
std::unique_ptr<vk::raii::Event> event = vk::raii::su::make_unique<vk::raii::Event>( *device, vk::EventCreateInfo() );
commandBuffer->reset( vk::CommandBufferResetFlags() );
commandBuffer->begin( vk::CommandBufferBeginInfo() );
commandBuffer->waitEvents( { **event },
vk::PipelineStageFlagBits::eHost,
vk::PipelineStageFlagBits::eBottomOfPipe,
nullptr,
nullptr,
nullptr );
commandBuffer->end();
device->resetFences( { **fence } );
// Note that stepping through this code in the debugger is a bad idea because the GPU can TDR waiting for the event.
// Execute the code from vk::Queue::submit() through vk::Device::setEvent() without breakpoints
graphicsQueue->submit( submitInfo, **fence );
// We should timeout waiting for the fence because the GPU should be waiting on the event
result = device->waitForFences( { **fence }, true, vk::su::FenceTimeout );
if ( result != vk::Result::eTimeout )
{
std::cout << "Didn't get expected timeout in vk::Device::waitForFences, exiting\n";
exit( -1 );
}
// Set the event from the CPU and wait for the fence.
// This should succeed since we set the event
event->set();
do
{
result = device->waitForFences( { **fence }, true, vk::su::FenceTimeout );
} while ( result == vk::Result::eTimeout );
assert( result == vk::Result::eSuccess );
commandBuffer->reset( {} );
device->resetFences( { **fence } );
event->reset();
// Now set the event from the GPU and wait on the CPU
commandBuffer->begin( vk::CommandBufferBeginInfo() );
commandBuffer->setEvent( **event, vk::PipelineStageFlagBits::eBottomOfPipe );
commandBuffer->end();
// Look for the event on the CPU. It should be vk::Result::eEventReset since we haven't sent the command buffer yet.
result = event->getStatus();
assert( result == vk::Result::eEventReset );
// Send the command buffer and loop waiting for the event
graphicsQueue->submit( submitInfo, **fence );
int polls = 0;
do
{
result = event->getStatus();
polls++;
} while ( result != vk::Result::eEventSet );
printf( "%d polls to find the event set\n", polls );
do
{
result = device->waitForFences( { **fence }, true, vk::su::FenceTimeout );
} while ( result == vk::Result::eTimeout );
assert( result == vk::Result::eSuccess );
/* VULKAN_KEY_END */
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,35 @@
# Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_ImmutableSampler)
set(HEADERS
)
set(SOURCES
ImmutableSampler.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_ImmutableSampler
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_ImmutableSampler PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_ImmutableSampler PRIVATE utils)

View File

@ -0,0 +1,238 @@
// Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : ImmutableSampler
// Use an immutable sampler to texture a cube.
#if defined( _MSC_VER )
// no need to ignore any warnings with MSVC
#elif defined( __clang__ )
# pragma clang diagnostic ignored "-Wmissing-braces"
#elif defined( __GNUC__ )
# if ( 9 <= __GNUC__ )
# pragma GCC diagnostic ignored "-Winit-list-lifetime"
# endif
#else
// unknow compiler... just ignore the warnings for yourselves ;)
#endif
#include "../../samples/utils/geometries.hpp"
#include "../../samples/utils/math.hpp"
#include "../utils/shaders.hpp"
#include "../utils/utils.hpp"
#include "SPIRV/GlslangToSpv.h"
#include "vulkan/vulkan_raii.hpp"
#include <iostream>
#include <thread>
static char const * AppName = "ImmutableSampler";
static char const * EngineName = "Vulkan.hpp";
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
std::unique_ptr<vk::raii::Instance> instance =
vk::raii::su::makeUniqueInstance( *context, AppName, EngineName, {}, vk::su::getInstanceExtensions() );
#if !defined( NDEBUG )
std::unique_ptr<vk::raii::DebugUtilsMessengerEXT> debugUtilsMessenger =
vk::raii::su::makeUniqueDebugUtilsMessengerEXT( *instance );
#endif
std::unique_ptr<vk::raii::PhysicalDevice> physicalDevice = vk::raii::su::makeUniquePhysicalDevice( *instance );
vk::raii::su::SurfaceData surfaceData( *instance, AppName, vk::Extent2D( 500, 500 ) );
std::pair<uint32_t, uint32_t> graphicsAndPresentQueueFamilyIndex =
vk::raii::su::findGraphicsAndPresentQueueFamilyIndex( *physicalDevice, *surfaceData.surface );
std::unique_ptr<vk::raii::Device> device = vk::raii::su::makeUniqueDevice(
*physicalDevice, graphicsAndPresentQueueFamilyIndex.first, vk::su::getDeviceExtensions() );
std::unique_ptr<vk::raii::CommandPool> commandPool =
vk::raii::su::makeUniqueCommandPool( *device, graphicsAndPresentQueueFamilyIndex.first );
std::unique_ptr<vk::raii::CommandBuffer> commandBuffer =
vk::raii::su::makeUniqueCommandBuffer( *device, *commandPool );
std::unique_ptr<vk::raii::Queue> graphicsQueue =
vk::raii::su::make_unique<vk::raii::Queue>( *device, graphicsAndPresentQueueFamilyIndex.first, 0 );
std::unique_ptr<vk::raii::Queue> presentQueue =
vk::raii::su::make_unique<vk::raii::Queue>( *device, graphicsAndPresentQueueFamilyIndex.second, 0 );
vk::raii::su::SwapChainData swapChainData( *physicalDevice,
*device,
*surfaceData.surface,
surfaceData.extent,
vk::ImageUsageFlagBits::eColorAttachment |
vk::ImageUsageFlagBits::eTransferSrc,
{},
graphicsAndPresentQueueFamilyIndex.first,
graphicsAndPresentQueueFamilyIndex.second );
vk::raii::su::DepthBufferData depthBufferData(
*physicalDevice, *device, vk::Format::eD16Unorm, surfaceData.extent );
vk::raii::su::BufferData uniformBufferData(
*physicalDevice, *device, sizeof( glm::mat4x4 ), vk::BufferUsageFlagBits::eUniformBuffer );
glm::mat4x4 mvpcMatrix = vk::su::createModelViewProjectionClipMatrix( surfaceData.extent );
vk::raii::su::copyToDevice( *uniformBufferData.deviceMemory, mvpcMatrix );
vk::Format colorFormat =
vk::su::pickSurfaceFormat( physicalDevice->getSurfaceFormatsKHR( **surfaceData.surface ) ).format;
std::unique_ptr<vk::raii::RenderPass> renderPass =
vk::raii::su::makeUniqueRenderPass( *device, colorFormat, depthBufferData.format );
glslang::InitializeProcess();
std::unique_ptr<vk::raii::ShaderModule> vertexShaderModule =
vk::raii::su::makeUniqueShaderModule( *device, vk::ShaderStageFlagBits::eVertex, vertexShaderText_PT_T );
std::unique_ptr<vk::raii::ShaderModule> fragmentShaderModule =
vk::raii::su::makeUniqueShaderModule( *device, vk::ShaderStageFlagBits::eFragment, fragmentShaderText_T_C );
glslang::FinalizeProcess();
std::vector<std::unique_ptr<vk::raii::Framebuffer>> framebuffers = vk::raii::su::makeUniqueFramebuffers(
*device, *renderPass, swapChainData.imageViews, depthBufferData.imageView, surfaceData.extent );
vk::raii::su::BufferData vertexBufferData(
*physicalDevice, *device, sizeof( texturedCubeData ), vk::BufferUsageFlagBits::eVertexBuffer );
vk::raii::su::copyToDevice(
*vertexBufferData.deviceMemory, texturedCubeData, sizeof( texturedCubeData ) / sizeof( texturedCubeData[0] ) );
/* VULKAN_KEY_START */
vk::raii::su::TextureData textureData( *physicalDevice, *device );
commandBuffer->begin( vk::CommandBufferBeginInfo() );
textureData.setImage( *commandBuffer, vk::su::CheckerboardImageGenerator() );
std::array<vk::DescriptorSetLayoutBinding, 2> bindings = {
vk::DescriptorSetLayoutBinding( 0, vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eVertex ),
vk::DescriptorSetLayoutBinding(
1, vk::DescriptorType::eCombinedImageSampler, vk::ShaderStageFlagBits::eFragment, **textureData.sampler )
};
vk::DescriptorSetLayoutCreateInfo descriptorSetLayoutCreateInfo( {}, bindings );
std::unique_ptr<vk::raii::DescriptorSetLayout> descriptorSetLayout =
vk::raii::su::make_unique<vk::raii::DescriptorSetLayout>( *device, descriptorSetLayoutCreateInfo );
// Create pipeline layout
vk::PipelineLayoutCreateInfo pipelineLayoutCreateInfo( {}, **descriptorSetLayout );
std::unique_ptr<vk::raii::PipelineLayout> pipelineLayout =
vk::raii::su::make_unique<vk::raii::PipelineLayout>( *device, pipelineLayoutCreateInfo );
// Create a single pool to contain data for our descriptor set
std::array<vk::DescriptorPoolSize, 2> poolSizes = { vk::DescriptorPoolSize( vk::DescriptorType::eUniformBuffer, 1 ),
vk::DescriptorPoolSize(
vk::DescriptorType::eCombinedImageSampler, 1 ) };
vk::DescriptorPoolCreateInfo descriptorPoolCreateInfo(
vk::DescriptorPoolCreateFlagBits::eFreeDescriptorSet, 1, poolSizes );
std::unique_ptr<vk::raii::DescriptorPool> descriptorPool =
vk::raii::su::make_unique<vk::raii::DescriptorPool>( *device, descriptorPoolCreateInfo );
// Populate descriptor sets
vk::DescriptorSetAllocateInfo descriptorSetAllocateInfo( **descriptorPool, **descriptorSetLayout );
std::unique_ptr<vk::raii::DescriptorSet> descriptorSet = vk::raii::su::make_unique<vk::raii::DescriptorSet>(
std::move( vk::raii::DescriptorSets( *device, descriptorSetAllocateInfo ).front() ) );
vk::DescriptorBufferInfo bufferInfo( **uniformBufferData.buffer, 0, sizeof( glm::mat4x4 ) );
vk::DescriptorImageInfo imageInfo(
**textureData.sampler, **textureData.imageData->imageView, vk::ImageLayout::eShaderReadOnlyOptimal );
std::array<vk::WriteDescriptorSet, 2> writeDescriptorSets = {
vk::WriteDescriptorSet( **descriptorSet, 0, 0, vk::DescriptorType::eUniformBuffer, {}, bufferInfo ),
vk::WriteDescriptorSet( **descriptorSet, 1, 0, vk::DescriptorType::eCombinedImageSampler, imageInfo )
};
device->updateDescriptorSets( writeDescriptorSets, nullptr );
/* VULKAN_KEY_END */
std::unique_ptr<vk::raii::PipelineCache> pipelineCache =
vk::raii::su::make_unique<vk::raii::PipelineCache>( *device, vk::PipelineCacheCreateInfo() );
std::unique_ptr<vk::raii::Pipeline> graphicsPipeline = vk::raii::su::makeUniqueGraphicsPipeline(
*device,
*pipelineCache,
*vertexShaderModule,
nullptr,
*fragmentShaderModule,
nullptr,
sizeof( texturedCubeData[0] ),
{ { vk::Format::eR32G32B32A32Sfloat, 0 }, { vk::Format::eR32G32Sfloat, 16 } },
vk::FrontFace::eClockwise,
true,
*pipelineLayout,
*renderPass );
std::unique_ptr<vk::raii::Semaphore> imageAcquiredSemaphore =
vk::raii::su::make_unique<vk::raii::Semaphore>( *device, vk::SemaphoreCreateInfo() );
vk::Result result;
uint32_t imageIndex;
std::tie( result, imageIndex ) =
swapChainData.swapChain->acquireNextImage( vk::su::FenceTimeout, **imageAcquiredSemaphore );
assert( result == vk::Result::eSuccess );
assert( imageIndex < swapChainData.images.size() );
std::array<vk::ClearValue, 2> clearValues;
clearValues[0].color = vk::ClearColorValue( std::array<float, 4>( { { 0.2f, 0.2f, 0.2f, 0.2f } } ) );
clearValues[1].depthStencil = vk::ClearDepthStencilValue( 1.0f, 0 );
vk::RenderPassBeginInfo renderPassBeginInfo(
**renderPass, **framebuffers[imageIndex], vk::Rect2D( vk::Offset2D( 0, 0 ), surfaceData.extent ), clearValues );
commandBuffer->beginRenderPass( renderPassBeginInfo, vk::SubpassContents::eInline );
commandBuffer->bindPipeline( vk::PipelineBindPoint::eGraphics, **graphicsPipeline );
commandBuffer->bindDescriptorSets(
vk::PipelineBindPoint::eGraphics, **pipelineLayout, 0, { **descriptorSet }, nullptr );
commandBuffer->bindVertexBuffers( 0, { **vertexBufferData.buffer }, { 0 } );
commandBuffer->setViewport( 0,
vk::Viewport( 0.0f,
0.0f,
static_cast<float>( surfaceData.extent.width ),
static_cast<float>( surfaceData.extent.height ),
0.0f,
1.0f ) );
commandBuffer->setScissor( 0, vk::Rect2D( vk::Offset2D( 0, 0 ), surfaceData.extent ) );
commandBuffer->draw( 12 * 3, 1, 0, 0 );
commandBuffer->endRenderPass();
commandBuffer->end();
vk::raii::su::submitAndWait( *device, *graphicsQueue, *commandBuffer );
vk::PresentInfoKHR presentInfoKHR( nullptr, **swapChainData.swapChain, imageIndex );
result = presentQueue->presentKHR( presentInfoKHR );
switch ( result )
{
case vk::Result::eSuccess: break;
case vk::Result::eSuboptimalKHR:
std::cout << "vk::Queue::presentKHR returned vk::Result::eSuboptimalKHR !\n";
break;
default: assert( false ); // an unexpected result is returned !
}
std::this_thread::sleep_for( std::chrono::milliseconds( 1000 ) );
device->waitIdle();
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,35 @@
# Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_InitTexture)
set(HEADERS
)
set(SOURCES
InitTexture.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_InitTexture
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_InitTexture PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_InitTexture PRIVATE utils)

View File

@ -0,0 +1,230 @@
// Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : InitTexture
// Initialize texture
#if defined( _MSC_VER )
// no need to ignore any warnings with MSVC
#elif defined( __clang__ )
# pragma clang diagnostic ignored "-Wunused-variable"
#elif defined( __GNUC__ )
# pragma GCC diagnostic ignored "-Wunused-but-set-variable"
#else
// unknow compiler... just ignore the warnings for yourselves ;)
#endif
#include "../samples/utils/geometries.hpp"
#include "../samples/utils/math.hpp"
#include "../utils/shaders.hpp"
#include "../utils/utils.hpp"
#include "SPIRV/GlslangToSpv.h"
#include "vulkan/vulkan_raii.hpp"
#include <iostream>
static char const * AppName = "InitTexture";
static char const * EngineName = "Vulkan.hpp";
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
std::unique_ptr<vk::raii::Instance> instance =
vk::raii::su::makeUniqueInstance( *context, AppName, EngineName, {}, vk::su::getInstanceExtensions() );
#if !defined( NDEBUG )
std::unique_ptr<vk::raii::DebugUtilsMessengerEXT> debugUtilsMessenger =
vk::raii::su::makeUniqueDebugUtilsMessengerEXT( *instance );
#endif
std::unique_ptr<vk::raii::PhysicalDevice> physicalDevice = vk::raii::su::makeUniquePhysicalDevice( *instance );
vk::raii::su::SurfaceData surfaceData( *instance, AppName, vk::Extent2D( 50, 50 ) );
std::pair<uint32_t, uint32_t> graphicsAndPresentQueueFamilyIndex =
vk::raii::su::findGraphicsAndPresentQueueFamilyIndex( *physicalDevice, *surfaceData.surface );
std::unique_ptr<vk::raii::Device> device = vk::raii::su::makeUniqueDevice(
*physicalDevice, graphicsAndPresentQueueFamilyIndex.first, vk::su::getDeviceExtensions() );
std::unique_ptr<vk::raii::CommandPool> commandPool =
vk::raii::su::makeUniqueCommandPool( *device, graphicsAndPresentQueueFamilyIndex.first );
std::unique_ptr<vk::raii::CommandBuffer> commandBuffer =
vk::raii::su::makeUniqueCommandBuffer( *device, *commandPool );
std::unique_ptr<vk::raii::Queue> graphicsQueue =
vk::raii::su::make_unique<vk::raii::Queue>( *device, graphicsAndPresentQueueFamilyIndex.first, 0 );
std::unique_ptr<vk::raii::Queue> presentQueue =
vk::raii::su::make_unique<vk::raii::Queue>( *device, graphicsAndPresentQueueFamilyIndex.second, 0 );
/* VULKAN_KEY_START */
vk::Format format = vk::Format::eR8G8B8A8Unorm;
vk::FormatProperties formatProperties = physicalDevice->getFormatProperties( format );
// See if we can use a linear tiled image for a texture, if not, we will need a staging buffer for the texture data
bool needsStaging = !( formatProperties.linearTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage );
vk::ImageCreateInfo imageCreateInfo(
{},
vk::ImageType::e2D,
format,
vk::Extent3D( surfaceData.extent, 1 ),
1,
1,
vk::SampleCountFlagBits::e1,
needsStaging ? vk::ImageTiling::eOptimal : vk::ImageTiling::eLinear,
vk::ImageUsageFlagBits::eSampled |
( needsStaging ? vk::ImageUsageFlagBits::eTransferDst : vk::ImageUsageFlagBits() ),
vk::SharingMode::eExclusive,
{},
needsStaging ? vk::ImageLayout::eUndefined : vk::ImageLayout::ePreinitialized );
std::unique_ptr<vk::raii::Image> image = vk::raii::su::make_unique<vk::raii::Image>( *device, imageCreateInfo );
vk::MemoryRequirements memoryRequirements = image->getMemoryRequirements();
uint32_t memoryTypeIndex = vk::su::findMemoryType(
physicalDevice->getMemoryProperties(),
memoryRequirements.memoryTypeBits,
needsStaging ? vk::MemoryPropertyFlags()
: ( vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent ) );
// allocate memory
vk::MemoryAllocateInfo memoryAllocateInfo( memoryRequirements.size, memoryTypeIndex );
std::unique_ptr<vk::raii::DeviceMemory> imageMemory =
vk::raii::su::make_unique<vk::raii::DeviceMemory>( *device, memoryAllocateInfo );
// bind memory
image->bindMemory( **imageMemory, 0 );
std::unique_ptr<vk::raii::Buffer> textureBuffer;
std::unique_ptr<vk::raii::DeviceMemory> textureBufferMemory;
if ( needsStaging )
{
// Need a staging buffer to map and copy texture into
vk::BufferCreateInfo bufferCreateInfo(
{}, surfaceData.extent.width * surfaceData.extent.height * 4, vk::BufferUsageFlagBits::eTransferSrc );
textureBuffer = vk::raii::su::make_unique<vk::raii::Buffer>( *device, bufferCreateInfo );
memoryRequirements = textureBuffer->getMemoryRequirements();
memoryTypeIndex =
vk::su::findMemoryType( physicalDevice->getMemoryProperties(),
memoryRequirements.memoryTypeBits,
vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent );
// allocate memory
memoryAllocateInfo = vk::MemoryAllocateInfo( memoryRequirements.size, memoryTypeIndex );
textureBufferMemory = vk::raii::su::make_unique<vk::raii::DeviceMemory>( *device, memoryAllocateInfo );
// bind memory
textureBuffer->bindMemory( **textureBufferMemory, 0 );
}
else
{
vk::SubresourceLayout subresourceLayout =
image->getSubresourceLayout( vk::ImageSubresource( vk::ImageAspectFlagBits::eColor ) );
}
void * data = needsStaging ? textureBufferMemory->mapMemory( 0, memoryRequirements.size, vk::MemoryMapFlags() )
: imageMemory->mapMemory( 0, memoryRequirements.size, vk::MemoryMapFlags() );
// Checkerboard of 16x16 pixel squares
unsigned char * pImageMemory = static_cast<unsigned char *>( data );
for ( uint32_t row = 0; row < surfaceData.extent.height; row++ )
{
for ( uint32_t col = 0; col < surfaceData.extent.width; col++ )
{
unsigned char rgb = ( ( ( row & 0x10 ) == 0 ) ^ ( ( col & 0x10 ) == 0 ) ) * 255;
pImageMemory[0] = rgb;
pImageMemory[1] = rgb;
pImageMemory[2] = rgb;
pImageMemory[3] = 255;
pImageMemory += 4;
}
}
needsStaging ? textureBufferMemory->unmapMemory() : imageMemory->unmapMemory();
commandBuffer->begin( vk::CommandBufferBeginInfo() );
if ( needsStaging )
{
// Since we're going to blit to the texture image, set its layout to eTransferDstOptimal
vk::raii::su::setImageLayout(
*commandBuffer, **image, format, vk::ImageLayout::eUndefined, vk::ImageLayout::eTransferDstOptimal );
vk::BufferImageCopy copyRegion( 0,
surfaceData.extent.width,
surfaceData.extent.height,
vk::ImageSubresourceLayers( vk::ImageAspectFlagBits::eColor, 0, 0, 1 ),
vk::Offset3D( 0, 0, 0 ),
vk::Extent3D( surfaceData.extent, 1 ) );
commandBuffer->copyBufferToImage( **textureBuffer, **image, vk::ImageLayout::eTransferDstOptimal, copyRegion );
// Set the layout for the texture image from eTransferDstOptimal to SHADER_READ_ONLY
vk::raii::su::setImageLayout( *commandBuffer,
**image,
format,
vk::ImageLayout::eTransferDstOptimal,
vk::ImageLayout::eShaderReadOnlyOptimal );
}
else
{
// If we can use the linear tiled image as a texture, just do it
vk::raii::su::setImageLayout(
*commandBuffer, **image, format, vk::ImageLayout::ePreinitialized, vk::ImageLayout::eShaderReadOnlyOptimal );
}
commandBuffer->end();
vk::raii::su::submitAndWait( *device, *graphicsQueue, *commandBuffer );
vk::SamplerCreateInfo samplerCreateInfo( {},
vk::Filter::eNearest,
vk::Filter::eNearest,
vk::SamplerMipmapMode::eNearest,
vk::SamplerAddressMode::eClampToEdge,
vk::SamplerAddressMode::eClampToEdge,
vk::SamplerAddressMode::eClampToEdge,
0.0f,
false,
1.0f,
false,
vk::CompareOp::eNever,
0.0f,
0.0f,
vk::BorderColor::eFloatOpaqueWhite );
std::unique_ptr<vk::raii::Sampler> sampler = vk::raii::su::make_unique<vk::raii::Sampler>( *device, samplerCreateInfo );
vk::ComponentMapping componentMapping(
vk::ComponentSwizzle::eR, vk::ComponentSwizzle::eG, vk::ComponentSwizzle::eB, vk::ComponentSwizzle::eA );
vk::ImageSubresourceRange imageSubresourceRange( vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1 );
vk::ImageViewCreateInfo imageViewCreateInfo(
{}, **image, vk::ImageViewType::e2D, format, componentMapping, imageSubresourceRange );
std::unique_ptr<vk::raii::ImageView> imageView =
vk::raii::su::make_unique<vk::raii::ImageView>( *device, imageViewCreateInfo );
/* VULKAN_KEY_END */
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,35 @@
# Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_InputAttachment)
set(HEADERS
)
set(SOURCES
InputAttachment.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_InputAttachment
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_InputAttachment PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_InputAttachment PRIVATE utils)

View File

@ -0,0 +1,319 @@
// Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : InputAttachment
// Use an input attachment to draw a yellow triangle
#if defined( _MSC_VER )
// no need to ignore any warnings with MSVC
#elif defined( __clang__ )
# pragma clang diagnostic ignored "-Wmissing-braces"
#elif defined( __GNUC__ )
// no need to ignore any warnings with GCC
#else
// unknow compiler... just ignore the warnings for yourselves ;)
#endif
#include "../../samples/utils/geometries.hpp"
#include "../../samples/utils/math.hpp"
#include "../utils/shaders.hpp"
#include "../utils/utils.hpp"
#include "SPIRV/GlslangToSpv.h"
#include "vulkan/vulkan_raii.hpp"
#include <iostream>
#include <thread>
static char const * AppName = "InputAttachment";
static char const * EngineName = "Vulkan.hpp";
static std::string vertexShaderText = R"(
#version 450
vec2 vertices[3];
void main()
{
vertices[0] = vec2(-1.0f, -1.0f);
vertices[1] = vec2( 1.0f, -1.0f);
vertices[2] = vec2( 0.0f, 1.0f);
gl_Position = vec4(vertices[gl_VertexIndex % 3], 0.0f, 1.0f);
}
)";
// Use subpassLoad to read from input attachment
static const char * fragmentShaderText = R"(
#version 450
layout (input_attachment_index = 0, set = 0, binding = 0) uniform subpassInput inputAttachment;
layout (location = 0) out vec4 outColor;
void main()
{
outColor = subpassLoad(inputAttachment);
}
)";
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
std::unique_ptr<vk::raii::Instance> instance =
vk::raii::su::makeUniqueInstance( *context, AppName, EngineName, {}, vk::su::getInstanceExtensions() );
#if !defined( NDEBUG )
std::unique_ptr<vk::raii::DebugUtilsMessengerEXT> debugUtilsMessenger =
vk::raii::su::makeUniqueDebugUtilsMessengerEXT( *instance );
#endif
std::unique_ptr<vk::raii::PhysicalDevice> physicalDevice = vk::raii::su::makeUniquePhysicalDevice( *instance );
vk::FormatProperties formatProperties = physicalDevice->getFormatProperties( vk::Format::eR8G8B8A8Unorm );
if ( !( formatProperties.optimalTilingFeatures & vk::FormatFeatureFlagBits::eColorAttachment ) )
{
std::cout << "vk::Format::eR8G8B8A8Unorm format unsupported for input attachment\n";
exit( -1 );
}
vk::raii::su::SurfaceData surfaceData( *instance, AppName, vk::Extent2D( 500, 500 ) );
std::pair<uint32_t, uint32_t> graphicsAndPresentQueueFamilyIndex =
vk::raii::su::findGraphicsAndPresentQueueFamilyIndex( *physicalDevice, *surfaceData.surface );
std::unique_ptr<vk::raii::Device> device = vk::raii::su::makeUniqueDevice(
*physicalDevice, graphicsAndPresentQueueFamilyIndex.first, vk::su::getDeviceExtensions() );
std::unique_ptr<vk::raii::CommandPool> commandPool =
vk::raii::su::makeUniqueCommandPool( *device, graphicsAndPresentQueueFamilyIndex.first );
std::unique_ptr<vk::raii::CommandBuffer> commandBuffer =
vk::raii::su::makeUniqueCommandBuffer( *device, *commandPool );
std::unique_ptr<vk::raii::Queue> graphicsQueue =
vk::raii::su::make_unique<vk::raii::Queue>( *device, graphicsAndPresentQueueFamilyIndex.first, 0 );
std::unique_ptr<vk::raii::Queue> presentQueue =
vk::raii::su::make_unique<vk::raii::Queue>( *device, graphicsAndPresentQueueFamilyIndex.second, 0 );
vk::raii::su::SwapChainData swapChainData( *physicalDevice,
*device,
*surfaceData.surface,
surfaceData.extent,
vk::ImageUsageFlagBits::eColorAttachment |
vk::ImageUsageFlagBits::eTransferSrc,
{},
graphicsAndPresentQueueFamilyIndex.first,
graphicsAndPresentQueueFamilyIndex.second );
/* VULKAN_KEY_START */
// Create a framebuffer with 2 attachments, one the color attachment the shaders render into, and the other an input
// attachment which will be cleared to yellow, and then used by the shaders to color the drawn triangle. Final
// result should be a yellow triangle
// Create the image that will be used as the input attachment
// The image for the color attachment is the presentable image already created as part of the SwapChainData
vk::ImageCreateInfo imageCreateInfo( {},
vk::ImageType::e2D,
swapChainData.colorFormat,
vk::Extent3D( surfaceData.extent, 1 ),
1,
1,
vk::SampleCountFlagBits::e1,
vk::ImageTiling::eOptimal,
vk::ImageUsageFlagBits::eInputAttachment |
vk::ImageUsageFlagBits::eTransferDst );
std::unique_ptr<vk::raii::Image> inputImage = vk::raii::su::make_unique<vk::raii::Image>( *device, imageCreateInfo );
vk::MemoryRequirements memoryRequirements = inputImage->getMemoryRequirements();
uint32_t memoryTypeIndex =
vk::su::findMemoryType( physicalDevice->getMemoryProperties(), memoryRequirements.memoryTypeBits, {} );
vk::MemoryAllocateInfo memoryAllocateInfo( memoryRequirements.size, memoryTypeIndex );
std::unique_ptr<vk::raii::DeviceMemory> inputMemory =
vk::raii::su::make_unique<vk::raii::DeviceMemory>( *device, memoryAllocateInfo );
inputImage->bindMemory( **inputMemory, 0 );
// Set the image layout to TRANSFER_DST_OPTIMAL to be ready for clear
commandBuffer->begin( vk::CommandBufferBeginInfo() );
vk::raii::su::setImageLayout( *commandBuffer,
**inputImage,
swapChainData.colorFormat,
vk::ImageLayout::eUndefined,
vk::ImageLayout::eTransferDstOptimal );
vk::ClearColorValue clearColorValue( std::array<float, 4>( { { 1.0f, 1.0f, 0.0f, 0.0f } } ) );
vk::ImageSubresourceRange imageSubresourceRange(
vk::ImageAspectFlagBits::eColor, 0, VK_REMAINING_MIP_LEVELS, 0, VK_REMAINING_ARRAY_LAYERS );
commandBuffer->clearColorImage(
**inputImage, vk::ImageLayout::eTransferDstOptimal, clearColorValue, imageSubresourceRange );
// Set the image layout to SHADER_READONLY_OPTIMAL for use by the shaders
vk::raii::su::setImageLayout( *commandBuffer,
**inputImage,
swapChainData.colorFormat,
vk::ImageLayout::eTransferDstOptimal,
vk::ImageLayout::eShaderReadOnlyOptimal );
vk::ComponentMapping componentMapping(
vk::ComponentSwizzle::eR, vk::ComponentSwizzle::eG, vk::ComponentSwizzle::eB, vk::ComponentSwizzle::eA );
imageSubresourceRange = vk::ImageSubresourceRange( vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1 );
vk::ImageViewCreateInfo imageViewCreateInfo(
{}, **inputImage, vk::ImageViewType::e2D, swapChainData.colorFormat, componentMapping, imageSubresourceRange );
std::unique_ptr<vk::raii::ImageView> inputAttachmentView =
vk::raii::su::make_unique<vk::raii::ImageView>( *device, imageViewCreateInfo );
vk::DescriptorSetLayoutBinding layoutBinding(
0, vk::DescriptorType::eInputAttachment, 1, vk::ShaderStageFlagBits::eFragment );
vk::DescriptorSetLayoutCreateInfo descriptorSetLayoutCreateInfo( {}, layoutBinding );
std::unique_ptr<vk::raii::DescriptorSetLayout> descriptorSetLayout =
vk::raii::su::make_unique<vk::raii::DescriptorSetLayout>( *device, descriptorSetLayoutCreateInfo );
vk::PipelineLayoutCreateInfo pipelineLayoutCreateInfo( {}, **descriptorSetLayout );
std::unique_ptr<vk::raii::PipelineLayout> pipelineLayout =
vk::raii::su::make_unique<vk::raii::PipelineLayout>( *device, pipelineLayoutCreateInfo );
std::array<vk::AttachmentDescription, 2> attachments = {
// First attachment is the color attachment - clear at the beginning of the renderpass and transition layout to
// PRESENT_SRC_KHR at the end of renderpass
vk::AttachmentDescription( {},
swapChainData.colorFormat,
vk::SampleCountFlagBits::e1,
vk::AttachmentLoadOp::eClear,
vk::AttachmentStoreOp::eStore,
vk::AttachmentLoadOp::eDontCare,
vk::AttachmentStoreOp::eDontCare,
vk::ImageLayout::eUndefined,
vk::ImageLayout::ePresentSrcKHR ),
// Second attachment is input attachment. Once cleared it should have width*height yellow pixels.
// Doing a subpassLoad in the fragment shader should give the shader the color at the fragments x,y location from
// the input attachment
vk::AttachmentDescription( {},
swapChainData.colorFormat,
vk::SampleCountFlagBits::e1,
vk::AttachmentLoadOp::eLoad,
vk::AttachmentStoreOp::eDontCare,
vk::AttachmentLoadOp::eDontCare,
vk::AttachmentStoreOp::eDontCare,
vk::ImageLayout::eShaderReadOnlyOptimal,
vk::ImageLayout::eShaderReadOnlyOptimal )
};
vk::AttachmentReference colorReference( 0, vk::ImageLayout::eColorAttachmentOptimal );
vk::AttachmentReference inputReference( 1, vk::ImageLayout::eShaderReadOnlyOptimal );
vk::SubpassDescription subPass( {}, vk::PipelineBindPoint::eGraphics, inputReference, colorReference );
vk::RenderPassCreateInfo renderPassCreateInfo( {}, attachments, subPass );
std::unique_ptr<vk::raii::RenderPass> renderPass =
vk::raii::su::make_unique<vk::raii::RenderPass>( *device, renderPassCreateInfo );
glslang::InitializeProcess();
std::unique_ptr<vk::raii::ShaderModule> vertexShaderModule =
vk::raii::su::makeUniqueShaderModule( *device, vk::ShaderStageFlagBits::eVertex, vertexShaderText );
std::unique_ptr<vk::raii::ShaderModule> fragmentShaderModule =
vk::raii::su::makeUniqueShaderModule( *device, vk::ShaderStageFlagBits::eFragment, fragmentShaderText );
glslang::FinalizeProcess();
std::vector<std::unique_ptr<vk::raii::Framebuffer>> framebuffers = vk::raii::su::makeUniqueFramebuffers(
*device, *renderPass, swapChainData.imageViews, inputAttachmentView, surfaceData.extent );
vk::DescriptorPoolSize poolSize( vk::DescriptorType::eInputAttachment, 1 );
vk::DescriptorPoolCreateInfo descriptorPoolCreateInfo(
vk::DescriptorPoolCreateFlagBits::eFreeDescriptorSet, 1, poolSize );
std::unique_ptr<vk::raii::DescriptorPool> descriptorPool =
vk::raii::su::make_unique<vk::raii::DescriptorPool>( *device, descriptorPoolCreateInfo );
vk::DescriptorSetAllocateInfo descriptorSetAllocateInfo( **descriptorPool, **descriptorSetLayout );
std::unique_ptr<vk::raii::DescriptorSet> descriptorSet = vk::raii::su::make_unique<vk::raii::DescriptorSet>(
std::move( vk::raii::DescriptorSets( *device, descriptorSetAllocateInfo ).front() ) );
vk::DescriptorImageInfo inputImageInfo( nullptr, **inputAttachmentView, vk::ImageLayout::eShaderReadOnlyOptimal );
vk::WriteDescriptorSet writeDescriptorSet(
**descriptorSet, 0, 0, vk::DescriptorType::eInputAttachment, inputImageInfo );
device->updateDescriptorSets( writeDescriptorSet, nullptr );
std::unique_ptr<vk::raii::PipelineCache> pipelineCache =
vk::raii::su::make_unique<vk::raii::PipelineCache>( *device, vk::PipelineCacheCreateInfo() );
std::unique_ptr<vk::raii::Pipeline> graphicsPipeline =
vk::raii::su::makeUniqueGraphicsPipeline( *device,
*pipelineCache,
*vertexShaderModule,
nullptr,
*fragmentShaderModule,
nullptr,
0,
{},
vk::FrontFace::eClockwise,
false,
*pipelineLayout,
*renderPass );
std::unique_ptr<vk::raii::Semaphore> imageAcquiredSemaphore =
vk::raii::su::make_unique<vk::raii::Semaphore>( *device, vk::SemaphoreCreateInfo() );
vk::Result result;
uint32_t imageIndex;
std::tie( result, imageIndex ) =
swapChainData.swapChain->acquireNextImage( vk::su::FenceTimeout, **imageAcquiredSemaphore );
assert( result == vk::Result::eSuccess );
assert( imageIndex < swapChainData.images.size() );
vk::ClearValue clearValue;
clearValue.color = vk::ClearColorValue( std::array<float, 4>( { { 0.2f, 0.2f, 0.2f, 0.2f } } ) );
vk::RenderPassBeginInfo renderPassBeginInfo(
**renderPass, **framebuffers[imageIndex], vk::Rect2D( vk::Offset2D( 0, 0 ), surfaceData.extent ), clearValue );
commandBuffer->beginRenderPass( renderPassBeginInfo, vk::SubpassContents::eInline );
commandBuffer->bindPipeline( vk::PipelineBindPoint::eGraphics, **graphicsPipeline );
commandBuffer->bindDescriptorSets(
vk::PipelineBindPoint::eGraphics, **pipelineLayout, 0, { **descriptorSet }, nullptr );
commandBuffer->setViewport( 0,
vk::Viewport( 0.0f,
0.0f,
static_cast<float>( surfaceData.extent.width ),
static_cast<float>( surfaceData.extent.height ),
0.0f,
1.0f ) );
commandBuffer->setScissor( 0, vk::Rect2D( vk::Offset2D( 0, 0 ), surfaceData.extent ) );
commandBuffer->draw( 3, 1, 0, 0 );
commandBuffer->endRenderPass();
commandBuffer->end();
/* VULKAN_KEY_END */
vk::raii::su::submitAndWait( *device, *graphicsQueue, *commandBuffer );
vk::PresentInfoKHR presentInfoKHR( nullptr, **swapChainData.swapChain, imageIndex );
result = presentQueue->presentKHR( presentInfoKHR );
switch ( result )
{
case vk::Result::eSuccess: break;
case vk::Result::eSuboptimalKHR:
std::cout << "vk::Queue::presentKHR returned vk::Result::eSuboptimalKHR !\n";
break;
default: assert( false ); // an unexpected result is returned !
}
std::this_thread::sleep_for( std::chrono::milliseconds( 1000 ) );
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,35 @@
# Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_InstanceExtensionProperties)
set(HEADERS
)
set(SOURCES
InstanceExtensionProperties.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_InstanceExtensionProperties
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_InstanceExtensionProperties PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_InstanceExtensionProperties PRIVATE utils)

View File

@ -0,0 +1,68 @@
// Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : InstanceExtensionProperties
// Get global extension properties to know what extension are available to enable at CreateInstance
// time.
#include "../utils/utils.hpp"
#include <iostream>
#include <sstream>
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
/* VULKAN_KEY_START */
std::vector<vk::ExtensionProperties> extensionProperties = context->enumerateInstanceExtensionProperties();
// sort the extensions alphabetically
std::sort( extensionProperties.begin(),
extensionProperties.end(),
[]( vk::ExtensionProperties const & a, vk::ExtensionProperties const & b ) {
return strcmp( a.extensionName, b.extensionName ) < 0;
} );
std::cout << "Instance Extensions:" << std::endl;
for ( auto const & ep : extensionProperties )
{
std::cout << ep.extensionName << ":" << std::endl;
std::cout << "\tVersion: " << ep.specVersion << std::endl;
std::cout << std::endl;
}
/* VULKAN_KEY_END */
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,35 @@
# Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_InstanceLayerExtensionProperties)
set(HEADERS
)
set(SOURCES
InstanceLayerExtensionProperties.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_InstanceLayerExtensionProperties
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_InstanceLayerExtensionProperties PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_InstanceLayerExtensionProperties PRIVATE utils)

View File

@ -0,0 +1,103 @@
// Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : InstanceLayerExtensionProperties
// Get list of global layers and their associated extensions, if any.
#include "../utils/utils.hpp"
#include <iostream>
#include <sstream>
#include <vector>
struct PropertyData
{
PropertyData( vk::LayerProperties const & layerProperties_,
std::vector<vk::ExtensionProperties> const & extensionProperties_ )
: layerProperties( layerProperties_ ), extensionProperties( extensionProperties_ )
{}
vk::LayerProperties layerProperties;
std::vector<vk::ExtensionProperties> extensionProperties;
};
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
std::vector<vk::LayerProperties> layerProperties = context->enumerateInstanceLayerProperties();
/* VULKAN_KEY_START */
std::vector<PropertyData> propertyData;
propertyData.reserve( layerProperties.size() );
for ( auto const & layerProperty : layerProperties )
{
std::vector<vk::ExtensionProperties> extensionProperties =
context->enumerateInstanceExtensionProperties( vk::Optional<const std::string>( layerProperty.layerName ) );
propertyData.emplace_back( layerProperty, extensionProperties );
}
/* VULKAN_KEY_END */
std::cout << "Instance Layers:" << std::endl;
if ( propertyData.empty() )
{
std::cout << "Set the environment variable VK_LAYER_PATH to point to the location of your layers" << std::endl;
}
else
{
for ( auto const & pd : propertyData )
{
std::cout << pd.layerProperties.layerName << std::endl;
std::cout << "Layer Extensions: ";
if ( pd.extensionProperties.empty() )
{
std::cout << "None";
}
else
{
for ( auto it = pd.extensionProperties.begin(); it != pd.extensionProperties.end(); ++it )
{
if ( it != pd.extensionProperties.begin() )
{
std::cout << ", ";
}
std::cout << it->extensionName << " Version " << it->specVersion;
}
}
std::cout << std::endl << std::endl;
}
}
std::cout << std::endl;
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,35 @@
# Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_InstanceLayerProperties)
set(HEADERS
)
set(SOURCES
InstanceLayerProperties.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_InstanceLayerProperties
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_InstanceLayerProperties PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_InstanceLayerProperties PRIVATE utils)

View File

@ -0,0 +1,67 @@
// Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : InstanceLayerProperties
// Get global layer properties to know what layers are available to enable at CreateInstance time.
#include "../utils/utils.hpp"
#include <iostream>
#include <sstream>
#include <vector>
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
/* VULKAN_KEY_START */
std::vector<vk::LayerProperties> layerProperties = context->enumerateInstanceLayerProperties();
std::cout << "Instance Layers:" << std::endl;
if ( layerProperties.empty() )
{
std::cout << "Set the environment variable VK_LAYER_PATH to point to the location of your layers" << std::endl;
}
for ( auto const & lp : layerProperties )
{
std::cout << lp.layerName << ":" << std::endl;
std::cout << "\tVersion: " << lp.implementationVersion << std::endl;
std::cout << "\tAPI Version: (" << ( lp.specVersion >> 22 ) << "." << ( ( lp.specVersion >> 12 ) & 0x03FF ) << "."
<< ( lp.specVersion & 0xFFF ) << ")" << std::endl;
std::cout << "\tDescription: " << lp.description << std::endl;
std::cout << std::endl;
}
/* VULKAN_KEY_END */
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::runtexceptionime_error: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,35 @@
# Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_InstanceVersion)
set(HEADERS
)
set(SOURCES
InstanceVersion.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_InstanceVersion
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_InstanceVersion PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_InstanceVersion PRIVATE utils)

View File

@ -0,0 +1,58 @@
// Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : InstanceVersion
// Get the version of instance-level functionality supported by the implementation.
#include "../utils/utils.hpp"
#include <iostream>
#include <sstream>
std::string decodeAPIVersion( uint32_t apiVersion )
{
return std::to_string( VK_VERSION_MAJOR( apiVersion ) ) + "." + std::to_string( VK_VERSION_MINOR( apiVersion ) ) +
"." + std::to_string( VK_VERSION_PATCH( apiVersion ) );
}
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
/* VULKAN_KEY_START */
uint32_t apiVersion = context->enumerateInstanceVersion();
std::cout << "APIVersion = " << decodeAPIVersion( apiVersion ) << std::endl;
/* VULKAN_KEY_END */
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,35 @@
# Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_MultipleSets)
set(HEADERS
)
set(SOURCES
MultipleSets.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_MultipleSets
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_MultipleSets PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_MultipleSets PRIVATE utils)

View File

@ -0,0 +1,304 @@
// Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : MultipleSets
// Use multiple descriptor sets to draw a textured cube.
#if defined( _MSC_VER )
// no need to ignore any warnings with MSVC
#elif defined( __clang__ )
# pragma clang diagnostic ignored "-Wmissing-braces"
#elif defined( __GNUC__ )
# if ( 9 <= __GNUC__ )
# pragma GCC diagnostic ignored "-Winit-list-lifetime"
# endif
#else
// unknow compiler... just ignore the warnings for yourselves ;)
#endif
#include "../../samples/utils/geometries.hpp"
#include "../../samples/utils/math.hpp"
#include "../utils/shaders.hpp"
#include "../utils/utils.hpp"
#include "SPIRV/GlslangToSpv.h"
#include "vulkan/vulkan_raii.hpp"
#include <iostream>
#include <thread>
static char const * AppName = "MultipleSets";
static char const * EngineName = "Vulkan.hpp";
const std::string vertexShaderText = R"(
#version 400
#extension GL_ARB_separate_shader_objects : enable
#extension GL_ARB_shading_language_420pack : enable
layout (std140, set = 0, binding = 0) uniform buffer
{
mat4 mvp;
} uniformBuffer;
layout (set = 1, binding = 0) uniform sampler2D surface;
layout (location = 0) in vec4 pos;
layout (location = 1) in vec2 inTexCoord;
layout (location = 0) out vec4 outColor;
layout (location = 1) out vec2 outTexCoord;
void main()
{
outColor = texture(surface, vec2(0.0f));
outTexCoord = inTexCoord;
gl_Position = uniformBuffer.mvp * pos;
}
)";
const std::string fragmentShaderText = R"(
#version 400
#extension GL_ARB_separate_shader_objects : enable
#extension GL_ARB_shading_language_420pack : enable
layout (location = 0) in vec4 inColor;
layout (location = 1) in vec2 inTexCoord;
layout (location = 0) out vec4 outColor;
void main()
{
outColor = inColor;
// create a border to see the cube more easily
if ((inTexCoord.x < 0.01f) || (0.99f < inTexCoord.x) || (inTexCoord.y < 0.01f) || (0.99f < inTexCoord.y))
{
outColor *= vec4(0.1f, 0.1f, 0.1f, 1.0f);
}
}
)";
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
std::unique_ptr<vk::raii::Instance> instance =
vk::raii::su::makeUniqueInstance( *context, AppName, EngineName, {}, vk::su::getInstanceExtensions() );
#if !defined( NDEBUG )
std::unique_ptr<vk::raii::DebugUtilsMessengerEXT> debugUtilsMessenger =
vk::raii::su::makeUniqueDebugUtilsMessengerEXT( *instance );
#endif
std::unique_ptr<vk::raii::PhysicalDevice> physicalDevice = vk::raii::su::makeUniquePhysicalDevice( *instance );
vk::raii::su::SurfaceData surfaceData( *instance, AppName, vk::Extent2D( 500, 500 ) );
std::pair<uint32_t, uint32_t> graphicsAndPresentQueueFamilyIndex =
vk::raii::su::findGraphicsAndPresentQueueFamilyIndex( *physicalDevice, *surfaceData.surface );
std::unique_ptr<vk::raii::Device> device = vk::raii::su::makeUniqueDevice(
*physicalDevice, graphicsAndPresentQueueFamilyIndex.first, vk::su::getDeviceExtensions() );
std::unique_ptr<vk::raii::CommandPool> commandPool =
vk::raii::su::makeUniqueCommandPool( *device, graphicsAndPresentQueueFamilyIndex.first );
std::unique_ptr<vk::raii::CommandBuffer> commandBuffer =
vk::raii::su::makeUniqueCommandBuffer( *device, *commandPool );
std::unique_ptr<vk::raii::Queue> graphicsQueue =
vk::raii::su::make_unique<vk::raii::Queue>( *device, graphicsAndPresentQueueFamilyIndex.first, 0 );
std::unique_ptr<vk::raii::Queue> presentQueue =
vk::raii::su::make_unique<vk::raii::Queue>( *device, graphicsAndPresentQueueFamilyIndex.second, 0 );
vk::raii::su::SwapChainData swapChainData( *physicalDevice,
*device,
*surfaceData.surface,
surfaceData.extent,
vk::ImageUsageFlagBits::eColorAttachment |
vk::ImageUsageFlagBits::eTransferSrc,
{},
graphicsAndPresentQueueFamilyIndex.first,
graphicsAndPresentQueueFamilyIndex.second );
vk::raii::su::DepthBufferData depthBufferData(
*physicalDevice, *device, vk::Format::eD16Unorm, surfaceData.extent );
vk::raii::su::TextureData textureData( *physicalDevice, *device );
commandBuffer->begin( vk::CommandBufferBeginInfo() );
textureData.setImage( *commandBuffer, vk::su::MonochromeImageGenerator( { 118, 185, 0 } ) );
vk::raii::su::BufferData uniformBufferData(
*physicalDevice, *device, sizeof( glm::mat4x4 ), vk::BufferUsageFlagBits::eUniformBuffer );
glm::mat4x4 mvpcMatrix = vk::su::createModelViewProjectionClipMatrix( surfaceData.extent );
vk::raii::su::copyToDevice( *uniformBufferData.deviceMemory, mvpcMatrix );
vk::Format colorFormat =
vk::su::pickSurfaceFormat( physicalDevice->getSurfaceFormatsKHR( **surfaceData.surface ) ).format;
std::unique_ptr<vk::raii::RenderPass> renderPass =
vk::raii::su::makeUniqueRenderPass( *device, colorFormat, depthBufferData.format );
glslang::InitializeProcess();
std::unique_ptr<vk::raii::ShaderModule> vertexShaderModule =
vk::raii::su::makeUniqueShaderModule( *device, vk::ShaderStageFlagBits::eVertex, vertexShaderText );
std::unique_ptr<vk::raii::ShaderModule> fragmentShaderModule =
vk::raii::su::makeUniqueShaderModule( *device, vk::ShaderStageFlagBits::eFragment, fragmentShaderText );
glslang::FinalizeProcess();
std::vector<std::unique_ptr<vk::raii::Framebuffer>> framebuffers = vk::raii::su::makeUniqueFramebuffers(
*device, *renderPass, swapChainData.imageViews, depthBufferData.imageView, surfaceData.extent );
vk::raii::su::BufferData vertexBufferData(
*physicalDevice, *device, sizeof( texturedCubeData ), vk::BufferUsageFlagBits::eVertexBuffer );
vk::raii::su::copyToDevice(
*vertexBufferData.deviceMemory, texturedCubeData, sizeof( texturedCubeData ) / sizeof( texturedCubeData[0] ) );
/* VULKAN_KEY_START */
// Create first layout to contain uniform buffer data
vk::DescriptorSetLayoutBinding uniformBinding(
0, vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eVertex );
vk::DescriptorSetLayoutCreateInfo descriptorSetLayoutCreateInfo( {}, uniformBinding );
std::unique_ptr<vk::raii::DescriptorSetLayout> uniformLayout =
vk::raii::su::make_unique<vk::raii::DescriptorSetLayout>( *device, descriptorSetLayoutCreateInfo );
// Create second layout containing combined sampler/image data
vk::DescriptorSetLayoutBinding sampler2DBinding(
0, vk::DescriptorType::eCombinedImageSampler, 1, vk::ShaderStageFlagBits::eVertex );
descriptorSetLayoutCreateInfo.pBindings = &sampler2DBinding;
std::unique_ptr<vk::raii::DescriptorSetLayout> samplerLayout =
vk::raii::su::make_unique<vk::raii::DescriptorSetLayout>( *device, descriptorSetLayoutCreateInfo );
// Create pipeline layout with multiple descriptor sets
std::array<vk::DescriptorSetLayout, 2> descriptorSetLayouts = { **uniformLayout, **samplerLayout };
vk::PipelineLayoutCreateInfo pipelineLayoutCreateInfo( {}, descriptorSetLayouts );
std::unique_ptr<vk::raii::PipelineLayout> pipelineLayout =
vk::raii::su::make_unique<vk::raii::PipelineLayout>( *device, pipelineLayoutCreateInfo );
// Create a single pool to contain data for our two descriptor sets
std::array<vk::DescriptorPoolSize, 2> poolSizes = { vk::DescriptorPoolSize( vk::DescriptorType::eUniformBuffer, 1 ),
vk::DescriptorPoolSize(
vk::DescriptorType::eCombinedImageSampler, 1 ) };
vk::DescriptorPoolCreateInfo descriptorPoolCreateInfo(
vk::DescriptorPoolCreateFlagBits::eFreeDescriptorSet, 2, poolSizes );
std::unique_ptr<vk::raii::DescriptorPool> descriptorPool =
vk::raii::su::make_unique<vk::raii::DescriptorPool>( *device, descriptorPoolCreateInfo );
// Populate descriptor sets
vk::DescriptorSetAllocateInfo descriptorSetAllocateInfo( **descriptorPool, descriptorSetLayouts );
vk::raii::DescriptorSets descriptorSets( *device, descriptorSetAllocateInfo );
// Populate with info about our uniform buffer
vk::DescriptorBufferInfo uniformBufferInfo( **uniformBufferData.buffer, 0, sizeof( glm::mat4x4 ) );
vk::DescriptorImageInfo textureImageInfo(
**textureData.sampler, **textureData.imageData->imageView, vk::ImageLayout::eShaderReadOnlyOptimal );
std::array<vk::WriteDescriptorSet, 2> writeDescriptorSets = {
{ vk::WriteDescriptorSet( *descriptorSets[0], 0, 0, vk::DescriptorType::eUniformBuffer, {}, uniformBufferInfo ),
vk::WriteDescriptorSet(
*descriptorSets[1], 0, 0, vk::DescriptorType::eCombinedImageSampler, textureImageInfo ) }
};
device->updateDescriptorSets( writeDescriptorSets, nullptr );
/* VULKAN_KEY_END */
std::unique_ptr<vk::raii::PipelineCache> pipelineCache =
vk::raii::su::make_unique<vk::raii::PipelineCache>( *device, vk::PipelineCacheCreateInfo() );
std::unique_ptr<vk::raii::Pipeline> graphicsPipeline = vk::raii::su::makeUniqueGraphicsPipeline(
*device,
*pipelineCache,
*vertexShaderModule,
nullptr,
*fragmentShaderModule,
nullptr,
sizeof( texturedCubeData[0] ),
{ { vk::Format::eR32G32B32A32Sfloat, 0 }, { vk::Format::eR32G32Sfloat, 16 } },
vk::FrontFace::eClockwise,
true,
*pipelineLayout,
*renderPass );
// Get the index of the next available swapchain image:
std::unique_ptr<vk::raii::Semaphore> imageAcquiredSemaphore =
vk::raii::su::make_unique<vk::raii::Semaphore>( *device, vk::SemaphoreCreateInfo() );
vk::Result result;
uint32_t imageIndex;
std::tie( result, imageIndex ) =
swapChainData.swapChain->acquireNextImage( vk::su::FenceTimeout, **imageAcquiredSemaphore );
assert( result == vk::Result::eSuccess );
assert( imageIndex < swapChainData.images.size() );
std::array<vk::ClearValue, 2> clearValues;
clearValues[0].color = vk::ClearColorValue( std::array<float, 4>( { { 0.2f, 0.2f, 0.2f, 0.2f } } ) );
clearValues[1].depthStencil = vk::ClearDepthStencilValue( 1.0f, 0 );
vk::RenderPassBeginInfo renderPassBeginInfo(
**renderPass, **framebuffers[imageIndex], vk::Rect2D( vk::Offset2D( 0, 0 ), surfaceData.extent ), clearValues );
commandBuffer->beginRenderPass( renderPassBeginInfo, vk::SubpassContents::eInline );
commandBuffer->bindPipeline( vk::PipelineBindPoint::eGraphics, **graphicsPipeline );
commandBuffer->bindDescriptorSets(
vk::PipelineBindPoint::eGraphics, **pipelineLayout, 0, { *descriptorSets[0], *descriptorSets[1] }, nullptr );
vk::Buffer buffer = **vertexBufferData.buffer;
commandBuffer->bindVertexBuffers( 0, buffer, { 0 } );
commandBuffer->setViewport( 0,
vk::Viewport( 0.0f,
0.0f,
static_cast<float>( surfaceData.extent.width ),
static_cast<float>( surfaceData.extent.height ),
0.0f,
1.0f ) );
commandBuffer->setScissor( 0, vk::Rect2D( vk::Offset2D( 0, 0 ), surfaceData.extent ) );
commandBuffer->draw( 12 * 3, 1, 0, 0 );
commandBuffer->endRenderPass();
commandBuffer->end();
std::unique_ptr<vk::raii::Fence> drawFence = vk::raii::su::make_unique<vk::raii::Fence>( *device, vk::FenceCreateInfo() );
vk::PipelineStageFlags waitDestinationStageMask( vk::PipelineStageFlagBits::eColorAttachmentOutput );
vk::SubmitInfo submitInfo( **imageAcquiredSemaphore, waitDestinationStageMask, **commandBuffer );
graphicsQueue->submit( submitInfo, **drawFence );
while ( vk::Result::eTimeout == device->waitForFences( { **drawFence }, VK_TRUE, vk::su::FenceTimeout ) )
;
vk::PresentInfoKHR presentInfoKHR( nullptr, **swapChainData.swapChain, imageIndex );
result = presentQueue->presentKHR( presentInfoKHR );
switch ( result )
{
case vk::Result::eSuccess: break;
case vk::Result::eSuboptimalKHR:
std::cout << "vk::Queue::presentKHR returned vk::Result::eSuboptimalKHR !\n";
break;
default: assert( false ); // an unexpected result is returned !
}
std::this_thread::sleep_for( std::chrono::milliseconds( 1000 ) );
device->waitIdle();
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,35 @@
# Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_OcclusionQuery)
set(HEADERS
)
set(SOURCES
OcclusionQuery.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_OcclusionQuery
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_OcclusionQuery PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_OcclusionQuery PRIVATE utils)

View File

@ -0,0 +1,270 @@
// Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : OcclusionQuery
// Use occlusion query to determine if drawing renders any samples.
#include "../../samples/utils/geometries.hpp"
#include "../../samples/utils/math.hpp"
#include "../utils/shaders.hpp"
#include "../utils/utils.hpp"
#include "SPIRV/GlslangToSpv.h"
#include "vulkan/vulkan_raii.hpp"
#include <iostream>
#include <thread>
static char const * AppName = "OcclusionQuery";
static char const * EngineName = "Vulkan.hpp";
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
std::unique_ptr<vk::raii::Instance> instance =
vk::raii::su::makeUniqueInstance( *context, AppName, EngineName, {}, vk::su::getInstanceExtensions() );
#if !defined( NDEBUG )
std::unique_ptr<vk::raii::DebugUtilsMessengerEXT> debugUtilsMessenger =
vk::raii::su::makeUniqueDebugUtilsMessengerEXT( *instance );
#endif
std::unique_ptr<vk::raii::PhysicalDevice> physicalDevice = vk::raii::su::makeUniquePhysicalDevice( *instance );
vk::raii::su::SurfaceData surfaceData( *instance, AppName, vk::Extent2D( 500, 500 ) );
std::pair<uint32_t, uint32_t> graphicsAndPresentQueueFamilyIndex =
vk::raii::su::findGraphicsAndPresentQueueFamilyIndex( *physicalDevice, *surfaceData.surface );
std::unique_ptr<vk::raii::Device> device = vk::raii::su::makeUniqueDevice(
*physicalDevice, graphicsAndPresentQueueFamilyIndex.first, vk::su::getDeviceExtensions() );
std::unique_ptr<vk::raii::CommandPool> commandPool =
vk::raii::su::makeUniqueCommandPool( *device, graphicsAndPresentQueueFamilyIndex.first );
std::unique_ptr<vk::raii::CommandBuffer> commandBuffer =
vk::raii::su::makeUniqueCommandBuffer( *device, *commandPool );
std::unique_ptr<vk::raii::Queue> graphicsQueue =
vk::raii::su::make_unique<vk::raii::Queue>( *device, graphicsAndPresentQueueFamilyIndex.first, 0 );
std::unique_ptr<vk::raii::Queue> presentQueue =
vk::raii::su::make_unique<vk::raii::Queue>( *device, graphicsAndPresentQueueFamilyIndex.second, 0 );
vk::raii::su::SwapChainData swapChainData( *physicalDevice,
*device,
*surfaceData.surface,
surfaceData.extent,
vk::ImageUsageFlagBits::eColorAttachment |
vk::ImageUsageFlagBits::eTransferSrc,
{},
graphicsAndPresentQueueFamilyIndex.first,
graphicsAndPresentQueueFamilyIndex.second );
vk::raii::su::DepthBufferData depthBufferData(
*physicalDevice, *device, vk::Format::eD16Unorm, surfaceData.extent );
vk::raii::su::BufferData uniformBufferData(
*physicalDevice, *device, sizeof( glm::mat4x4 ), vk::BufferUsageFlagBits::eUniformBuffer );
glm::mat4x4 mvpcMatrix = vk::su::createModelViewProjectionClipMatrix( surfaceData.extent );
vk::raii::su::copyToDevice( *uniformBufferData.deviceMemory, mvpcMatrix );
std::unique_ptr<vk::raii::DescriptorSetLayout> descriptorSetLayout = vk::raii::su::makeUniqueDescriptorSetLayout(
*device, { { vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eVertex } } );
std::unique_ptr<vk::raii::PipelineLayout> pipelineLayout =
vk::raii::su::makeUniquePipelineLayout( *device, *descriptorSetLayout );
vk::Format colorFormat =
vk::su::pickSurfaceFormat( physicalDevice->getSurfaceFormatsKHR( **surfaceData.surface ) ).format;
std::unique_ptr<vk::raii::RenderPass> renderPass =
vk::raii::su::makeUniqueRenderPass( *device, colorFormat, depthBufferData.format );
glslang::InitializeProcess();
std::unique_ptr<vk::raii::ShaderModule> vertexShaderModule =
vk::raii::su::makeUniqueShaderModule( *device, vk::ShaderStageFlagBits::eVertex, vertexShaderText_PC_C );
std::unique_ptr<vk::raii::ShaderModule> fragmentShaderModule =
vk::raii::su::makeUniqueShaderModule( *device, vk::ShaderStageFlagBits::eFragment, fragmentShaderText_C_C );
glslang::FinalizeProcess();
std::vector<std::unique_ptr<vk::raii::Framebuffer>> framebuffers = vk::raii::su::makeUniqueFramebuffers(
*device, *renderPass, swapChainData.imageViews, depthBufferData.imageView, surfaceData.extent );
vk::raii::su::BufferData vertexBufferData(
*physicalDevice, *device, sizeof( coloredCubeData ), vk::BufferUsageFlagBits::eVertexBuffer );
vk::raii::su::copyToDevice(
*vertexBufferData.deviceMemory, coloredCubeData, sizeof( coloredCubeData ) / sizeof( coloredCubeData[0] ) );
std::unique_ptr<vk::raii::DescriptorPool> descriptorPool =
vk::raii::su::makeUniqueDescriptorPool( *device, { { vk::DescriptorType::eUniformBuffer, 1 } } );
std::unique_ptr<vk::raii::DescriptorSet> descriptorSet =
vk::raii::su::makeUniqueDescriptorSet( *device, *descriptorPool, *descriptorSetLayout );
vk::raii::su::updateDescriptorSets(
*device, *descriptorSet, { { vk::DescriptorType::eUniformBuffer, *uniformBufferData.buffer, nullptr } }, {} );
std::unique_ptr<vk::raii::PipelineCache> pipelineCache =
vk::raii::su::make_unique<vk::raii::PipelineCache>( *device, vk::PipelineCacheCreateInfo() );
std::unique_ptr<vk::raii::Pipeline> graphicsPipeline = vk::raii::su::makeUniqueGraphicsPipeline(
*device,
*pipelineCache,
*vertexShaderModule,
nullptr,
*fragmentShaderModule,
nullptr,
sizeof( coloredCubeData[0] ),
{ { vk::Format::eR32G32B32A32Sfloat, 0 }, { vk::Format::eR32G32Sfloat, 16 } },
vk::FrontFace::eClockwise,
true,
*pipelineLayout,
*renderPass );
/* VULKAN_KEY_START */
std::unique_ptr<vk::raii::Semaphore> imageAcquiredSemaphore =
vk::raii::su::make_unique<vk::raii::Semaphore>( *device, vk::SemaphoreCreateInfo() );
// Get the index of the next available swapchain image:
vk::Result result;
uint32_t imageIndex;
std::tie( result, imageIndex ) =
swapChainData.swapChain->acquireNextImage( vk::su::FenceTimeout, **imageAcquiredSemaphore );
assert( result == vk::Result::eSuccess );
assert( imageIndex < swapChainData.images.size() );
/* Allocate a uniform buffer that will take query results. */
vk::BufferCreateInfo bufferCreateInfo(
{}, 4 * sizeof( uint64_t ), vk::BufferUsageFlagBits::eUniformBuffer | vk::BufferUsageFlagBits::eTransferDst );
std::unique_ptr<vk::raii::Buffer> queryResultBuffer =
vk::raii::su::make_unique<vk::raii::Buffer>( *device, bufferCreateInfo );
vk::MemoryRequirements memoryRequirements = queryResultBuffer->getMemoryRequirements();
uint32_t memoryTypeIndex =
vk::su::findMemoryType( physicalDevice->getMemoryProperties(),
memoryRequirements.memoryTypeBits,
vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent );
vk::MemoryAllocateInfo memoryAllocateInfo( memoryRequirements.size, memoryTypeIndex );
std::unique_ptr<vk::raii::DeviceMemory> queryResultMemory =
vk::raii::su::make_unique<vk::raii::DeviceMemory>( *device, memoryAllocateInfo );
queryResultBuffer->bindMemory( **queryResultMemory, 0 );
vk::QueryPoolCreateInfo queryPoolCreateInfo( {}, vk::QueryType::eOcclusion, 2, {} );
std::unique_ptr<vk::raii::QueryPool> queryPool =
vk::raii::su::make_unique<vk::raii::QueryPool>( *device, queryPoolCreateInfo );
commandBuffer->begin( {} );
commandBuffer->resetQueryPool( **queryPool, 0, 2 );
std::array<vk::ClearValue, 2> clearValues;
clearValues[0].color = vk::ClearColorValue( std::array<float, 4>( { { 0.2f, 0.2f, 0.2f, 0.2f } } ) );
clearValues[1].depthStencil = vk::ClearDepthStencilValue( 1.0f, 0 );
commandBuffer->beginRenderPass(
vk::RenderPassBeginInfo(
**renderPass, **framebuffers[imageIndex], vk::Rect2D( vk::Offset2D(), surfaceData.extent ), clearValues ),
vk::SubpassContents::eInline );
commandBuffer->bindPipeline( vk::PipelineBindPoint::eGraphics, **graphicsPipeline );
commandBuffer->bindDescriptorSets( vk::PipelineBindPoint::eGraphics, **pipelineLayout, 0, { **descriptorSet }, {} );
commandBuffer->bindVertexBuffers( 0, { **vertexBufferData.buffer }, { 0 } );
commandBuffer->setViewport( 0,
vk::Viewport( 0.0f,
0.0f,
static_cast<float>( surfaceData.extent.width ),
static_cast<float>( surfaceData.extent.height ),
0.0f,
1.0f ) );
commandBuffer->setScissor( 0, vk::Rect2D( vk::Offset2D( 0, 0 ), surfaceData.extent ) );
commandBuffer->beginQuery( **queryPool, 0, vk::QueryControlFlags() );
commandBuffer->endQuery( **queryPool, 0 );
commandBuffer->beginQuery( **queryPool, 1, vk::QueryControlFlags() );
commandBuffer->draw( 12 * 3, 1, 0, 0 );
commandBuffer->endRenderPass();
commandBuffer->endQuery( **queryPool, 1 );
commandBuffer->copyQueryPoolResults( **queryPool,
0,
2,
**queryResultBuffer,
0,
sizeof( uint64_t ),
vk::QueryResultFlagBits::e64 | vk::QueryResultFlagBits::eWait );
commandBuffer->end();
std::unique_ptr<vk::raii::Fence> drawFence = vk::raii::su::make_unique<vk::raii::Fence>( *device, vk::FenceCreateInfo() );
vk::PipelineStageFlags waitDestinationStageMask( vk::PipelineStageFlagBits::eColorAttachmentOutput );
vk::SubmitInfo submitInfo( **imageAcquiredSemaphore, waitDestinationStageMask, **commandBuffer );
graphicsQueue->submit( submitInfo, **drawFence );
graphicsQueue->waitIdle();
std::vector<uint64_t> poolResults;
std::tie( result, poolResults ) = queryPool->getResults<uint64_t>(
0, 2, 2 * sizeof( uint64_t ), sizeof( uint64_t ), vk::QueryResultFlagBits::e64 | vk::QueryResultFlagBits::eWait );
switch ( result )
{
case vk::Result::eSuccess: break;
case vk::Result::eNotReady:
std::cout << "vk::Device::getQueryPoolResults returned vk::Result::eNotReady !\n";
break;
default: assert( false ); // an unexpected result is returned !
}
std::cout << "vkGetQueryPoolResults data\n";
std::cout << "samples_passed[0] = " << poolResults[0] << "\n";
std::cout << "samples_passed[1] = " << poolResults[1] << "\n";
/* Read back query result from buffer */
uint64_t * samplesPassedPtr =
static_cast<uint64_t *>( queryResultMemory->mapMemory( 0, memoryRequirements.size, vk::MemoryMapFlags() ) );
std::cout << "vkCmdCopyQueryPoolResults data\n";
std::cout << "samples_passed[0] = " << samplesPassedPtr[0] << "\n";
std::cout << "samples_passed[1] = " << samplesPassedPtr[1] << "\n";
queryResultMemory->unmapMemory();
while ( vk::Result::eTimeout == device->waitForFences( { **drawFence }, VK_TRUE, vk::su::FenceTimeout ) )
;
vk::PresentInfoKHR presentInfoKHR( nullptr, **swapChainData.swapChain, imageIndex );
result = presentQueue->presentKHR( presentInfoKHR );
switch ( result )
{
case vk::Result::eSuccess: break;
case vk::Result::eSuboptimalKHR:
std::cout << "vk::Queue::presentKHR returned vk::Result::eSuboptimalKHR !\n";
break;
default: assert( false ); // an unexpected result is returned !
}
std::this_thread::sleep_for( std::chrono::milliseconds( 1000 ) );
/* VULKAN_KEY_END */
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,35 @@
# Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_PhysicalDeviceExtensions)
set(HEADERS
)
set(SOURCES
PhysicalDeviceExtensions.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_PhysicalDeviceExtensions
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_PhysicalDeviceExtensions PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_PhysicalDeviceExtensions PRIVATE utils)

View File

@ -0,0 +1,80 @@
// Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : DeviceExtensionProperties
// Get extension properties per physical device.
#include "../utils/utils.hpp"
#include "vulkan/vulkan.hpp"
#include <vector>
static char const * AppName = "DeviceExtensionProperties";
static char const * EngineName = "Vulkan.hpp";
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
std::unique_ptr<vk::raii::Instance> instance = vk::raii::su::makeUniqueInstance( *context, AppName, EngineName );
#if !defined( NDEBUG )
std::unique_ptr<vk::raii::DebugUtilsMessengerEXT> debugUtilsMessenger =
vk::raii::su::makeUniqueDebugUtilsMessengerEXT( *instance );
#endif
// enumerate the physicalDevices
vk::raii::PhysicalDevices physicalDevices( *instance );
/* VULKAN_KEY_START */
for ( size_t i = 0; i < physicalDevices.size(); i++ )
{
std::vector<vk::ExtensionProperties> extensionProperties =
physicalDevices[i].enumerateDeviceExtensionProperties();
std::cout << "PhysicalDevice " << i << " : " << extensionProperties.size() << " extensions:\n";
// sort the extensions alphabetically
std::sort( extensionProperties.begin(),
extensionProperties.end(),
[]( vk::ExtensionProperties const & a, vk::ExtensionProperties const & b ) {
return strcmp( a.extensionName, b.extensionName ) < 0;
} );
for ( auto const & ep : extensionProperties )
{
std::cout << "\t" << ep.extensionName << ":" << std::endl;
std::cout << "\t\tVersion: " << ep.specVersion << std::endl;
std::cout << std::endl;
}
}
/* VULKAN_KEY_END */
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,35 @@
# Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_PhysicalDeviceFeatures)
set(HEADERS
)
set(SOURCES
PhysicalDeviceFeatures.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_PhysicalDeviceFeatures
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_PhysicalDeviceFeatures PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_PhysicalDeviceFeatures PRIVATE utils)

View File

@ -0,0 +1,746 @@
// Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : PhysicalDeviceFeatures
// Get the fine-grained features of the physical devices that can be supported by an implementation.
// ignore warning 4503: decorated name length exceeded, name was truncated
#if defined( _MSC_VER )
# pragma warning( disable : 4503 )
#elif defined( __GNUC__ )
// don't know how to switch off that warning here
#else
// unknow compiler... just ignore the warnings for yourselves ;)
#endif
#include "../utils/utils.hpp"
#include "vulkan/vulkan.hpp"
#include <vector>
static char const * AppName = "PhysicalDeviceFeatures";
static char const * EngineName = "Vulkan.hpp";
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
std::unique_ptr<vk::raii::Instance> instance =
vk::raii::su::makeUniqueInstance( *context, AppName, EngineName, {}, {}, VK_API_VERSION_1_1 );
#if !defined( NDEBUG )
std::unique_ptr<vk::raii::DebugUtilsMessengerEXT> debugUtilsMessenger =
vk::raii::su::makeUniqueDebugUtilsMessengerEXT( *instance );
#endif
// enumerate the physicalDevices
vk::raii::PhysicalDevices physicalDevices( *instance );
/* VULKAN_KEY_START */
std::cout << std::boolalpha;
for ( size_t i = 0; i < physicalDevices.size(); i++ )
{
// some features are only valid, if a corresponding extension is available!
std::vector<vk::ExtensionProperties> extensionProperties =
physicalDevices[i].enumerateDeviceExtensionProperties();
std::cout << "PhysicalDevice " << i << " :\n";
auto features2 = physicalDevices[i]
.getFeatures2<vk::PhysicalDeviceFeatures2,
vk::PhysicalDevice16BitStorageFeatures,
vk::PhysicalDevice8BitStorageFeaturesKHR,
vk::PhysicalDeviceASTCDecodeFeaturesEXT,
vk::PhysicalDeviceBlendOperationAdvancedFeaturesEXT,
vk::PhysicalDeviceBufferDeviceAddressFeaturesEXT,
vk::PhysicalDeviceCoherentMemoryFeaturesAMD,
vk::PhysicalDeviceComputeShaderDerivativesFeaturesNV,
vk::PhysicalDeviceConditionalRenderingFeaturesEXT,
vk::PhysicalDeviceCooperativeMatrixFeaturesNV,
vk::PhysicalDeviceCornerSampledImageFeaturesNV,
vk::PhysicalDeviceCoverageReductionModeFeaturesNV,
vk::PhysicalDeviceDedicatedAllocationImageAliasingFeaturesNV,
vk::PhysicalDeviceDepthClipEnableFeaturesEXT,
vk::PhysicalDeviceDescriptorIndexingFeaturesEXT,
vk::PhysicalDeviceExclusiveScissorFeaturesNV,
vk::PhysicalDeviceFragmentDensityMapFeaturesEXT,
vk::PhysicalDeviceFragmentShaderBarycentricFeaturesNV,
vk::PhysicalDeviceFragmentShaderInterlockFeaturesEXT,
vk::PhysicalDeviceHostQueryResetFeaturesEXT,
vk::PhysicalDeviceImagelessFramebufferFeaturesKHR,
vk::PhysicalDeviceIndexTypeUint8FeaturesEXT,
vk::PhysicalDeviceInlineUniformBlockFeaturesEXT,
vk::PhysicalDeviceLineRasterizationFeaturesEXT,
vk::PhysicalDeviceMemoryPriorityFeaturesEXT,
vk::PhysicalDeviceMeshShaderFeaturesNV,
vk::PhysicalDeviceMultiviewFeatures,
vk::PhysicalDevicePipelineExecutablePropertiesFeaturesKHR,
vk::PhysicalDeviceProtectedMemoryFeatures,
vk::PhysicalDeviceRepresentativeFragmentTestFeaturesNV,
vk::PhysicalDeviceSamplerYcbcrConversionFeatures,
vk::PhysicalDeviceScalarBlockLayoutFeaturesEXT,
vk::PhysicalDeviceShaderAtomicInt64FeaturesKHR,
vk::PhysicalDeviceShaderDemoteToHelperInvocationFeaturesEXT,
vk::PhysicalDeviceShaderDrawParametersFeatures,
vk::PhysicalDeviceShaderFloat16Int8FeaturesKHR,
vk::PhysicalDeviceShaderImageFootprintFeaturesNV,
vk::PhysicalDeviceShaderIntegerFunctions2FeaturesINTEL,
vk::PhysicalDeviceShaderSMBuiltinsFeaturesNV,
vk::PhysicalDeviceShaderSubgroupExtendedTypesFeaturesKHR,
vk::PhysicalDeviceShadingRateImageFeaturesNV,
vk::PhysicalDeviceSubgroupSizeControlFeaturesEXT,
vk::PhysicalDeviceTexelBufferAlignmentFeaturesEXT,
vk::PhysicalDeviceTextureCompressionASTCHDRFeaturesEXT,
vk::PhysicalDeviceTimelineSemaphoreFeaturesKHR,
vk::PhysicalDeviceTransformFeedbackFeaturesEXT,
vk::PhysicalDeviceUniformBufferStandardLayoutFeaturesKHR,
vk::PhysicalDeviceVariablePointersFeatures,
vk::PhysicalDeviceVertexAttributeDivisorFeaturesEXT,
vk::PhysicalDeviceVulkanMemoryModelFeaturesKHR,
vk::PhysicalDeviceYcbcrImageArraysFeaturesEXT>();
vk::PhysicalDeviceFeatures const & features = features2.get<vk::PhysicalDeviceFeatures2>().features;
std::cout << "\tFeatures:\n";
std::cout << "\t\talphaToOne : " << !!features.alphaToOne << "\n";
std::cout << "\t\tdepthBiasClamp : " << !!features.depthBiasClamp << "\n";
std::cout << "\t\tdepthBounds : " << !!features.depthBounds << "\n";
std::cout << "\t\tdepthClamp : " << !!features.depthClamp << "\n";
std::cout << "\t\tdrawIndirectFirstInstance : " << !!features.drawIndirectFirstInstance << "\n";
std::cout << "\t\tdualSrcBlend : " << !!features.dualSrcBlend << "\n";
std::cout << "\t\tfillModeNonSolid : " << !!features.fillModeNonSolid << "\n";
std::cout << "\t\tfragmentStoresAndAtomics : " << !!features.fragmentStoresAndAtomics << "\n";
std::cout << "\t\tfullDrawIndexUint32 : " << !!features.fullDrawIndexUint32 << "\n";
std::cout << "\t\tgeometryShader : " << !!features.geometryShader << "\n";
std::cout << "\t\timageCubeArray : " << !!features.imageCubeArray << "\n";
std::cout << "\t\tindependentBlend : " << !!features.independentBlend << "\n";
std::cout << "\t\tinheritedQueries : " << !!features.inheritedQueries << "\n";
std::cout << "\t\tlargePoints : " << !!features.largePoints << "\n";
std::cout << "\t\tlogicOp : " << !!features.logicOp << "\n";
std::cout << "\t\tmultiDrawIndirect : " << !!features.multiDrawIndirect << "\n";
std::cout << "\t\tmultiViewport : " << !!features.multiViewport << "\n";
std::cout << "\t\tocclusionQueryPrecise : " << !!features.occlusionQueryPrecise << "\n";
std::cout << "\t\tpipelineStatisticsQuery : " << !!features.pipelineStatisticsQuery << "\n";
std::cout << "\t\trobustBufferAccess : " << !!features.robustBufferAccess << "\n";
std::cout << "\t\tsamplerAnisotropy : " << !!features.samplerAnisotropy << "\n";
std::cout << "\t\tsampleRateShading : " << !!features.sampleRateShading << "\n";
std::cout << "\t\tshaderClipDistance : " << !!features.shaderClipDistance << "\n";
std::cout << "\t\tshaderCullDistance : " << !!features.shaderCullDistance << "\n";
std::cout << "\t\tshaderFloat64 : " << !!features.shaderFloat64 << "\n";
std::cout << "\t\tshaderImageGatherExtended : " << !!features.shaderImageGatherExtended << "\n";
std::cout << "\t\tshaderInt16 : " << !!features.shaderInt16 << "\n";
std::cout << "\t\tshaderInt64 : " << !!features.shaderInt64 << "\n";
std::cout << "\t\tshaderResourceMinLod : " << !!features.shaderResourceMinLod << "\n";
std::cout << "\t\tshaderResourceResidency : " << !!features.shaderResourceResidency << "\n";
std::cout << "\t\tshaderSampledImageArrayDynamicIndexing : " << !!features.shaderSampledImageArrayDynamicIndexing
<< "\n";
std::cout << "\t\tshaderStorageBufferArrayDynamicIndexing : "
<< !!features.shaderStorageBufferArrayDynamicIndexing << "\n";
std::cout << "\t\tshaderStorageImageArrayDynamicIndexing : " << !!features.shaderStorageImageArrayDynamicIndexing
<< "\n";
std::cout << "\t\tshaderStorageImageExtendedFormats : " << !!features.shaderStorageImageExtendedFormats
<< "\n";
std::cout << "\t\tshaderStorageImageMultisample : " << !!features.shaderStorageImageMultisample << "\n";
std::cout << "\t\tshaderStorageImageReadWithoutFormat : " << !!features.shaderStorageImageReadWithoutFormat
<< "\n";
std::cout << "\t\tshaderStorageImageWriteWithoutFormat : " << !!features.shaderStorageImageWriteWithoutFormat
<< "\n";
std::cout << "\t\tshaderTessellationAndGeometryPointSize : " << !!features.shaderTessellationAndGeometryPointSize
<< "\n";
std::cout << "\t\tshaderUniformBufferArrayDynamicIndexing : "
<< !!features.shaderUniformBufferArrayDynamicIndexing << "\n";
std::cout << "\t\tsparseBinding : " << !!features.sparseBinding << "\n";
std::cout << "\t\tsparseResidency16Samples : " << !!features.sparseResidency16Samples << "\n";
std::cout << "\t\tsparseResidency2Samples : " << !!features.sparseResidency2Samples << "\n";
std::cout << "\t\tsparseResidency4Samples : " << !!features.sparseResidency4Samples << "\n";
std::cout << "\t\tsparseResidency8Samples : " << !!features.sparseResidency8Samples << "\n";
std::cout << "\t\tsparseResidencyAliased : " << !!features.sparseResidencyAliased << "\n";
std::cout << "\t\tsparseResidencyBuffer : " << !!features.sparseResidencyBuffer << "\n";
std::cout << "\t\tsparseResidencyImage2D : " << !!features.sparseResidencyImage2D << "\n";
std::cout << "\t\tsparseResidencyImage3D : " << !!features.sparseResidencyImage3D << "\n";
std::cout << "\t\ttessellationShader : " << !!features.tessellationShader << "\n";
std::cout << "\t\ttextureCompressionASTC_LDR : " << !!features.textureCompressionASTC_LDR << "\n";
std::cout << "\t\ttextureCompressionBC : " << !!features.textureCompressionBC << "\n";
std::cout << "\t\ttextureCompressionETC2 : " << !!features.textureCompressionETC2 << "\n";
std::cout << "\t\tvariableMultisampleRate : " << !!features.variableMultisampleRate << "\n";
std::cout << "\t\tvertexPipelineStoresAndAtomics : " << !!features.vertexPipelineStoresAndAtomics
<< "\n";
std::cout << "\t\twideLines : " << !!features.wideLines << "\n";
std::cout << "\n";
vk::PhysicalDevice16BitStorageFeatures const & sixteenBitStorageFeatures =
features2.get<vk::PhysicalDevice16BitStorageFeatures>();
std::cout << "\t16BitStorageFeatures:\n";
std::cout << "\t\tstorageBuffer16BitAccess : " << !!sixteenBitStorageFeatures.storageBuffer16BitAccess
<< "\n";
std::cout << "\t\tstorageInputOutput16 : " << !!sixteenBitStorageFeatures.storageInputOutput16
<< "\n";
std::cout << "\t\tstoragePushConstant16 : " << !!sixteenBitStorageFeatures.storagePushConstant16
<< "\n";
std::cout << "\t\tuniformAndStorageBuffer16BitAccess : "
<< !!sixteenBitStorageFeatures.uniformAndStorageBuffer16BitAccess << "\n";
std::cout << "\n";
if ( vk::su::contains( extensionProperties, "VK_KHR_8bit_storage" ) )
{
vk::PhysicalDevice8BitStorageFeaturesKHR const & eightBitStorageFeatures =
features2.get<vk::PhysicalDevice8BitStorageFeaturesKHR>();
std::cout << "\t8BitStorageFeatures:\n";
std::cout << "\t\tstorageBuffer8BitAccess : " << !!eightBitStorageFeatures.storageBuffer8BitAccess
<< "\n";
std::cout << "\t\tstoragePushConstant8 : " << !!eightBitStorageFeatures.storagePushConstant8
<< "\n";
std::cout << "\t\tuniformAndStorageBuffer8BitAccess : "
<< !!eightBitStorageFeatures.uniformAndStorageBuffer8BitAccess << "\n";
std::cout << "\n";
}
if ( vk::su::contains( extensionProperties, "VK_EXT_astc_decode_mode" ) )
{
vk::PhysicalDeviceASTCDecodeFeaturesEXT const & astcDecodeFeatures =
features2.get<vk::PhysicalDeviceASTCDecodeFeaturesEXT>();
std::cout << "\tASTCDecodeFeature:\n";
std::cout << "\t\tdecodeModeSharedExponent : " << !!astcDecodeFeatures.decodeModeSharedExponent << "\n";
std::cout << "\n";
}
if ( vk::su::contains( extensionProperties, "VK_EXT_blend_operation_advanced" ) )
{
vk::PhysicalDeviceBlendOperationAdvancedFeaturesEXT const & blendOperationAdvancedFeatures =
features2.get<vk::PhysicalDeviceBlendOperationAdvancedFeaturesEXT>();
std::cout << "\tBlendOperationAdvancedFeatures:\n";
std::cout << "\t\tadvancedBlendCoherentOperations : "
<< !!blendOperationAdvancedFeatures.advancedBlendCoherentOperations << "\n";
std::cout << "\n";
}
if ( vk::su::contains( extensionProperties, "VK_EXT_buffer_device_address" ) )
{
vk::PhysicalDeviceBufferDeviceAddressFeaturesEXT const & bufferDeviceAddressFeatures =
features2.get<vk::PhysicalDeviceBufferDeviceAddressFeaturesEXT>();
std::cout << "\tBufferDeviceAddressFeatures:\n";
std::cout << "\t\tbufferDeviceAddress : " << !!bufferDeviceAddressFeatures.bufferDeviceAddress
<< "\n";
std::cout << "\t\tbufferDeviceAddressCaptureReplay : "
<< !!bufferDeviceAddressFeatures.bufferDeviceAddressCaptureReplay << "\n";
std::cout << "\t\tbufferDeviceAddressMultiDevice : "
<< !!bufferDeviceAddressFeatures.bufferDeviceAddressMultiDevice << "\n";
std::cout << "\n";
}
if ( vk::su::contains( extensionProperties, "VK_AMD_device_coherent_memory" ) )
{
vk::PhysicalDeviceCoherentMemoryFeaturesAMD const & coherentMemoryFeatures =
features2.get<vk::PhysicalDeviceCoherentMemoryFeaturesAMD>();
std::cout << "\tCoherentMemoryFeatures:\n";
std::cout << "\t\tdeviceCoherentMemory : " << !!coherentMemoryFeatures.deviceCoherentMemory << "\n";
std::cout << "\n";
}
if ( vk::su::contains( extensionProperties, "VK_NV_compute_shader_derivatives" ) )
{
vk::PhysicalDeviceComputeShaderDerivativesFeaturesNV const & computeShaderDerivativesFeatures =
features2.get<vk::PhysicalDeviceComputeShaderDerivativesFeaturesNV>();
std::cout << "\tComputeShaderDerivativeFeatures:\n";
std::cout << "\t\tcomputeDerivativeGroupLinear : "
<< !!computeShaderDerivativesFeatures.computeDerivativeGroupLinear << "\n";
std::cout << "\t\tcomputeDerivativeGroupQuads : "
<< !!computeShaderDerivativesFeatures.computeDerivativeGroupQuads << "\n";
std::cout << "\n";
}
if ( vk::su::contains( extensionProperties, "VK_EXT_conditional_rendering" ) )
{
vk::PhysicalDeviceConditionalRenderingFeaturesEXT const & conditionalRenderingFeatures =
features2.get<vk::PhysicalDeviceConditionalRenderingFeaturesEXT>();
std::cout << "\tConditionalRenderingFeatures:\n";
std::cout << "\t\tconditionalRendering : " << !!conditionalRenderingFeatures.conditionalRendering
<< "\n";
std::cout << "\t\tinheritedConditionalRendering : "
<< !!conditionalRenderingFeatures.inheritedConditionalRendering << "\n";
std::cout << "\n";
}
if ( vk::su::contains( extensionProperties, "VK_NV_cooperative_matrix" ) )
{
vk::PhysicalDeviceCooperativeMatrixFeaturesNV const & cooperativeMatrixFeatures =
features2.get<vk::PhysicalDeviceCooperativeMatrixFeaturesNV>();
std::cout << "\tCooperativeMatrixFeatures:\n";
std::cout << "\t\tcooperativeMatrix : " << !!cooperativeMatrixFeatures.cooperativeMatrix
<< "\n";
std::cout << "\t\tcooperativeMatrixRobustBufferAccess : "
<< !!cooperativeMatrixFeatures.cooperativeMatrixRobustBufferAccess << "\n";
std::cout << "\n";
}
if ( vk::su::contains( extensionProperties, "VK_NV_corner_sampled_image" ) )
{
vk::PhysicalDeviceCornerSampledImageFeaturesNV const & cornerSampledImageFeatures =
features2.get<vk::PhysicalDeviceCornerSampledImageFeaturesNV>();
std::cout << "\tCornerSampledImageFeatures:\n";
std::cout << "\t\tcornerSampledImage : " << !!cornerSampledImageFeatures.cornerSampledImage << "\n";
std::cout << "\n";
}
if ( vk::su::contains( extensionProperties, "VK_NV_coverage_reduction_mode" ) )
{
vk::PhysicalDeviceCoverageReductionModeFeaturesNV const & coverageReductionModeFeatures =
features2.get<vk::PhysicalDeviceCoverageReductionModeFeaturesNV>();
std::cout << "\tCoverageReductionModeFeatures:\n";
std::cout << "\t\tcoverageReductionMode : " << !!coverageReductionModeFeatures.coverageReductionMode << "\n";
std::cout << "\n";
}
if ( vk::su::contains( extensionProperties, "VK_NV_dedicated_allocation_image_aliasing" ) )
{
vk::PhysicalDeviceDedicatedAllocationImageAliasingFeaturesNV const & dedicatedAllocationImageAliasingFeatures =
features2.get<vk::PhysicalDeviceDedicatedAllocationImageAliasingFeaturesNV>();
std::cout << "\tDedicatedAllocationAliasingFeatures:\n";
std::cout << "\t\tdedicatedAllocationImageAliasing : "
<< !!dedicatedAllocationImageAliasingFeatures.dedicatedAllocationImageAliasing << "\n";
std::cout << "\n";
}
if ( vk::su::contains( extensionProperties, "VK_EXT_depth_clip_enable" ) )
{
vk::PhysicalDeviceDepthClipEnableFeaturesEXT const & depthClipEnabledFeatures =
features2.get<vk::PhysicalDeviceDepthClipEnableFeaturesEXT>();
std::cout << "\tDepthClipEnabledFeatures:\n";
std::cout << "\t\tdepthClipEnable : " << !!depthClipEnabledFeatures.depthClipEnable << "\n";
std::cout << "\n";
}
if ( vk::su::contains( extensionProperties, "VK_EXT_descriptor_indexing" ) )
{
vk::PhysicalDeviceDescriptorIndexingFeaturesEXT const & descriptorIndexingFeatures =
features2.get<vk::PhysicalDeviceDescriptorIndexingFeaturesEXT>();
std::cout << "\tDescriptorIndexingFeatures:\n";
std::cout << "\t\tdescriptorBindingPartiallyBound : "
<< !!descriptorIndexingFeatures.descriptorBindingPartiallyBound << "\n";
std::cout << "\t\tdescriptorBindingSampledImageUpdateAfterBind : "
<< !!descriptorIndexingFeatures.descriptorBindingSampledImageUpdateAfterBind << "\n";
std::cout << "\t\tdescriptorBindingStorageBufferUpdateAfterBind : "
<< !!descriptorIndexingFeatures.descriptorBindingStorageBufferUpdateAfterBind << "\n";
std::cout << "\t\tdescriptorBindingStorageImageUpdateAfterBind : "
<< !!descriptorIndexingFeatures.descriptorBindingStorageImageUpdateAfterBind << "\n";
std::cout << "\t\tdescriptorBindingStorageTexelBufferUpdateAfterBind : "
<< !!descriptorIndexingFeatures.descriptorBindingStorageTexelBufferUpdateAfterBind << "\n";
std::cout << "\t\tdescriptorBindingUniformBufferUpdateAfterBind : "
<< !!descriptorIndexingFeatures.descriptorBindingUniformBufferUpdateAfterBind << "\n";
std::cout << "\t\tdescriptorBindingUniformTexelBufferUpdateAfterBind : "
<< !!descriptorIndexingFeatures.descriptorBindingUniformTexelBufferUpdateAfterBind << "\n";
std::cout << "\t\tdescriptorBindingUpdateUnusedWhilePending : "
<< !!descriptorIndexingFeatures.descriptorBindingUpdateUnusedWhilePending << "\n";
std::cout << "\t\tdescriptorBindingVariableDescriptorCount : "
<< !!descriptorIndexingFeatures.descriptorBindingVariableDescriptorCount << "\n";
std::cout << "\t\truntimeDescriptorArray : "
<< !!descriptorIndexingFeatures.runtimeDescriptorArray << "\n";
std::cout << "\t\tshaderInputAttachmentArrayDynamicIndexing : "
<< !!descriptorIndexingFeatures.shaderInputAttachmentArrayDynamicIndexing << "\n";
std::cout << "\t\tshaderInputAttachmentArrayNonUniformIndexing : "
<< !!descriptorIndexingFeatures.shaderInputAttachmentArrayNonUniformIndexing << "\n";
std::cout << "\t\tshaderSampledImageArrayNonUniformIndexing : "
<< !!descriptorIndexingFeatures.shaderSampledImageArrayNonUniformIndexing << "\n";
std::cout << "\t\tshaderStorageBufferArrayNonUniformIndexing : "
<< !!descriptorIndexingFeatures.shaderStorageBufferArrayNonUniformIndexing << "\n";
std::cout << "\t\tshaderStorageImageArrayNonUniformIndexing : "
<< !!descriptorIndexingFeatures.shaderStorageImageArrayNonUniformIndexing << "\n";
std::cout << "\t\tshaderStorageTexelBufferArrayDynamicIndexing : "
<< !!descriptorIndexingFeatures.shaderStorageTexelBufferArrayDynamicIndexing << "\n";
std::cout << "\t\tshaderStorageTexelBufferArrayNonUniformIndexing : "
<< !!descriptorIndexingFeatures.shaderStorageTexelBufferArrayNonUniformIndexing << "\n";
std::cout << "\t\tshaderUniformBufferArrayNonUniformIndexing : "
<< !!descriptorIndexingFeatures.shaderUniformBufferArrayNonUniformIndexing << "\n";
std::cout << "\t\tshaderUniformTexelBufferArrayDynamicIndexing : "
<< !!descriptorIndexingFeatures.shaderUniformTexelBufferArrayDynamicIndexing << "\n";
std::cout << "\t\tshaderUniformTexelBufferArrayNonUniformIndexing : "
<< !!descriptorIndexingFeatures.shaderUniformTexelBufferArrayNonUniformIndexing << "\n";
std::cout << "\n";
}
if ( vk::su::contains( extensionProperties, "VK_NV_scissor_exclusive" ) )
{
vk::PhysicalDeviceExclusiveScissorFeaturesNV const & exclusiveScissorFeatures =
features2.get<vk::PhysicalDeviceExclusiveScissorFeaturesNV>();
std::cout << "\tExclusiveScissorFeatures:\n";
std::cout << "\t\texclusiveScissor : " << !!exclusiveScissorFeatures.exclusiveScissor << "\n";
std::cout << "\n";
}
if ( vk::su::contains( extensionProperties, "VK_EXT_fragment_density_map" ) )
{
vk::PhysicalDeviceFragmentDensityMapFeaturesEXT const & fragmentDensityMapFeatures =
features2.get<vk::PhysicalDeviceFragmentDensityMapFeaturesEXT>();
std::cout << "\tFragmentDensityMapFeatures:\n";
std::cout << "\t\tfragmentDensityMap : " << !!fragmentDensityMapFeatures.fragmentDensityMap
<< "\n";
std::cout << "\t\tfragmentDensityMapDynamic : "
<< !!fragmentDensityMapFeatures.fragmentDensityMapDynamic << "\n";
std::cout << "\t\tfragmentDensityMapNonSubsampledImages : "
<< !!fragmentDensityMapFeatures.fragmentDensityMapNonSubsampledImages << "\n";
std::cout << "\n";
}
if ( vk::su::contains( extensionProperties, "VK_NV_fragment_shader_barycentric" ) )
{
vk::PhysicalDeviceFragmentShaderBarycentricFeaturesNV const & fragmentShaderBarycentricFeatures =
features2.get<vk::PhysicalDeviceFragmentShaderBarycentricFeaturesNV>();
std::cout << "\tFragmentShaderBarycentricFeatures:\n";
std::cout << "\t\tfragmentShaderBarycentric : " << !!fragmentShaderBarycentricFeatures.fragmentShaderBarycentric
<< "\n";
std::cout << "\n";
}
if ( vk::su::contains( extensionProperties, "VK_EXT_fragment_shader_interlock" ) )
{
vk::PhysicalDeviceFragmentShaderInterlockFeaturesEXT const & fragmentShaderInterlockFeatures =
features2.get<vk::PhysicalDeviceFragmentShaderInterlockFeaturesEXT>();
std::cout << "\tFragmentShaderInterlockFeatures:\n";
std::cout << "\t\tfragmentShaderPixelInterlock : "
<< !!fragmentShaderInterlockFeatures.fragmentShaderPixelInterlock << "\n";
std::cout << "\t\tfragmentShaderSampleInterlock : "
<< !!fragmentShaderInterlockFeatures.fragmentShaderSampleInterlock << "\n";
std::cout << "\t\tfragmentShaderShadingRateInterlock : "
<< !!fragmentShaderInterlockFeatures.fragmentShaderShadingRateInterlock << "\n";
std::cout << "\n";
}
if ( vk::su::contains( extensionProperties, "VK_EXT_host_query_reset" ) )
{
vk::PhysicalDeviceHostQueryResetFeaturesEXT const & hostQueryResetFeatures =
features2.get<vk::PhysicalDeviceHostQueryResetFeaturesEXT>();
std::cout << "\tHostQueryResetFeatures:\n";
std::cout << "\t\thostQueryReset : " << !!hostQueryResetFeatures.hostQueryReset << "\n";
std::cout << "\n";
}
if ( vk::su::contains( extensionProperties, "VK_KHR_imageless_framebuffer" ) )
{
vk::PhysicalDeviceImagelessFramebufferFeaturesKHR const & imagelessFramebufferFeatures =
features2.get<vk::PhysicalDeviceImagelessFramebufferFeaturesKHR>();
std::cout << "\tImagelessFramebufferFeatures:\n";
std::cout << "\t\timagelessFramebuffer : " << !!imagelessFramebufferFeatures.imagelessFramebuffer << "\n";
std::cout << "\n";
}
if ( vk::su::contains( extensionProperties, "VK_EXT_index_type_uint8" ) )
{
vk::PhysicalDeviceIndexTypeUint8FeaturesEXT const & indexTypeUint8Features =
features2.get<vk::PhysicalDeviceIndexTypeUint8FeaturesEXT>();
std::cout << "\tIndexTypeUint8Features:\n";
std::cout << "\t\tindexTypeUint8 : " << !!indexTypeUint8Features.indexTypeUint8 << "\n";
std::cout << "\n";
}
if ( vk::su::contains( extensionProperties, "VK_EXT_inline_uniform_block" ) )
{
vk::PhysicalDeviceInlineUniformBlockFeaturesEXT const & inlineUniformBlockFeatures =
features2.get<vk::PhysicalDeviceInlineUniformBlockFeaturesEXT>();
std::cout << "\tInlineUniformBlockFeatures:\n";
std::cout << "\t\tdescriptorBindingInlineUniformBlockUpdateAfterBind : "
<< !!inlineUniformBlockFeatures.descriptorBindingInlineUniformBlockUpdateAfterBind << "\n";
std::cout << "\t\tinlineUniformBlock : "
<< !!inlineUniformBlockFeatures.inlineUniformBlock << "\n";
std::cout << "\n";
}
if ( vk::su::contains( extensionProperties, "VK_EXT_line_rasterization" ) )
{
vk::PhysicalDeviceLineRasterizationFeaturesEXT const & lineRasterizationFeatures =
features2.get<vk::PhysicalDeviceLineRasterizationFeaturesEXT>();
std::cout << "\tLineRasterizationFeatures:\n";
std::cout << "\t\tbresenhamLines : " << !!lineRasterizationFeatures.bresenhamLines << "\n";
std::cout << "\t\trectangularLines : " << !!lineRasterizationFeatures.rectangularLines << "\n";
std::cout << "\t\tsmoothLines : " << !!lineRasterizationFeatures.smoothLines << "\n";
std::cout << "\t\tstippledBresenhamLines : " << !!lineRasterizationFeatures.stippledBresenhamLines << "\n";
std::cout << "\t\tstippledRectangularLines : " << !!lineRasterizationFeatures.stippledRectangularLines << "\n";
std::cout << "\t\tstippledSmoothLines : " << !!lineRasterizationFeatures.stippledSmoothLines << "\n";
std::cout << "\n";
}
if ( vk::su::contains( extensionProperties, "VK_EXT_memory_priority" ) )
{
vk::PhysicalDeviceMemoryPriorityFeaturesEXT const & memoryPriorityFeatures =
features2.get<vk::PhysicalDeviceMemoryPriorityFeaturesEXT>();
std::cout << "\tMemoryPriorityFeatures:\n";
std::cout << "\t\tmemoryPriority : " << !!memoryPriorityFeatures.memoryPriority << "\n";
std::cout << "\n";
}
if ( vk::su::contains( extensionProperties, "VK_NV_mesh_shader" ) )
{
vk::PhysicalDeviceMeshShaderFeaturesNV const & meshShaderFeatures =
features2.get<vk::PhysicalDeviceMeshShaderFeaturesNV>();
std::cout << "\tMeshShaderFeatures:\n";
std::cout << "\t\tmeshShader : " << !!meshShaderFeatures.meshShader << "\n";
std::cout << "\t\ttaskShader : " << !!meshShaderFeatures.taskShader << "\n";
std::cout << "\n";
}
vk::PhysicalDeviceMultiviewFeatures const & multiviewFeatures =
features2.get<vk::PhysicalDeviceMultiviewFeatures>();
std::cout << "\tMultiviewFeatures:\n";
std::cout << "\t\tmultiview : " << !!multiviewFeatures.multiview << "\n";
std::cout << "\t\tmultiviewGeometryShader : " << !!multiviewFeatures.multiviewGeometryShader << "\n";
std::cout << "\t\tmultiviewTessellationShader : " << !!multiviewFeatures.multiviewTessellationShader << "\n";
std::cout << "\n";
if ( vk::su::contains( extensionProperties, "VK_KHR_pipeline_executable_properties" ) )
{
vk::PhysicalDevicePipelineExecutablePropertiesFeaturesKHR const & pipelineExecutablePropertiesFeatures =
features2.get<vk::PhysicalDevicePipelineExecutablePropertiesFeaturesKHR>();
std::cout << "\tPipelineExectuablePropertiesFeatures:\n";
std::cout << "\t\tpipelineExecutableInfo : " << !!pipelineExecutablePropertiesFeatures.pipelineExecutableInfo
<< "\n";
std::cout << "\n";
}
vk::PhysicalDeviceProtectedMemoryFeatures const & protectedMemoryFeatures =
features2.get<vk::PhysicalDeviceProtectedMemoryFeatures>();
std::cout << "\tProtectedMemoryFeatures:\n";
std::cout << "\t\tprotectedMemory : " << !!protectedMemoryFeatures.protectedMemory << "\n";
std::cout << "\n";
if ( vk::su::contains( extensionProperties, "VK_NV_representative_fragment_test" ) )
{
vk::PhysicalDeviceRepresentativeFragmentTestFeaturesNV const & representativeFragmentTestFeatures =
features2.get<vk::PhysicalDeviceRepresentativeFragmentTestFeaturesNV>();
std::cout << "\tRepresentativeFragmentTestFeatures:\n";
std::cout << "\t\trepresentativeFragmentTest : "
<< !!representativeFragmentTestFeatures.representativeFragmentTest << "\n";
std::cout << "\n";
}
vk::PhysicalDeviceSamplerYcbcrConversionFeatures const & samplerYcbcrConversionFeatures =
features2.get<vk::PhysicalDeviceSamplerYcbcrConversionFeatures>();
std::cout << "\tSamplerYcbcrConversionFeatures:\n";
std::cout << "\t\tsamplerYcbcrConversion : " << !!samplerYcbcrConversionFeatures.samplerYcbcrConversion << "\n";
std::cout << "\n";
if ( vk::su::contains( extensionProperties, "VK_EXT_scalar_block_layout" ) )
{
vk::PhysicalDeviceScalarBlockLayoutFeaturesEXT const & scalarBlockLayoutFeatures =
features2.get<vk::PhysicalDeviceScalarBlockLayoutFeaturesEXT>();
std::cout << "\tScalarBlockLayoutFeatures:\n";
std::cout << "\t\tscalarBlockLayout : " << !!scalarBlockLayoutFeatures.scalarBlockLayout << "\n";
std::cout << "\n";
}
if ( vk::su::contains( extensionProperties, "VK_KHR_shader_atomic_int64" ) )
{
vk::PhysicalDeviceShaderAtomicInt64FeaturesKHR const & shaderAtomicInt64Features =
features2.get<vk::PhysicalDeviceShaderAtomicInt64FeaturesKHR>();
std::cout << "\tShaderAtomicInt64Features:\n";
std::cout << "\t\tshaderBufferInt64Atomics : " << !!shaderAtomicInt64Features.shaderBufferInt64Atomics << "\n";
std::cout << "\t\tshaderSharedInt64Atomics : " << !!shaderAtomicInt64Features.shaderSharedInt64Atomics << "\n";
std::cout << "\n";
}
if ( vk::su::contains( extensionProperties, "VK_EXT_shader_demote_to_helper_invocation" ) )
{
vk::PhysicalDeviceShaderDemoteToHelperInvocationFeaturesEXT const & shaderDemoteToHelperInvocationFeatures =
features2.get<vk::PhysicalDeviceShaderDemoteToHelperInvocationFeaturesEXT>();
std::cout << "\tShaderDemoteToHelperInvocationFeatures:\n";
std::cout << "\t\tshaderDemoteToHelperInvocation : "
<< !!shaderDemoteToHelperInvocationFeatures.shaderDemoteToHelperInvocation << "\n";
std::cout << "\n";
}
vk::PhysicalDeviceShaderDrawParametersFeatures const & shaderDrawParametersFeature =
features2.get<vk::PhysicalDeviceShaderDrawParametersFeatures>();
std::cout << "\tShaderDrawParametersFeature:\n";
std::cout << "\t\tshaderDrawParameters : " << !!shaderDrawParametersFeature.shaderDrawParameters << "\n";
std::cout << "\n";
if ( vk::su::contains( extensionProperties, "VK_KHR_shader_float16_int8" ) )
{
vk::PhysicalDeviceShaderFloat16Int8FeaturesKHR const & shaderFloat16Int8Features =
features2.get<vk::PhysicalDeviceShaderFloat16Int8FeaturesKHR>();
std::cout << "\tShaderFloat16Int8Features:\n";
std::cout << "\t\tshaderFloat16 : " << !!shaderFloat16Int8Features.shaderFloat16 << "\n";
std::cout << "\t\tshaderInt8 : " << !!shaderFloat16Int8Features.shaderInt8 << "\n";
std::cout << "\n";
}
if ( vk::su::contains( extensionProperties, "VK_NV_shader_image_footprint" ) )
{
vk::PhysicalDeviceShaderImageFootprintFeaturesNV const & shaderImageFootprintFeatures =
features2.get<vk::PhysicalDeviceShaderImageFootprintFeaturesNV>();
std::cout << "\tShaderImageFootprintFeatures:\n";
std::cout << "\t\timageFootprint : " << !!shaderImageFootprintFeatures.imageFootprint << "\n";
std::cout << "\n";
}
if ( vk::su::contains( extensionProperties, "VK_INTEL_shader_integer_functions2" ) )
{
vk::PhysicalDeviceShaderIntegerFunctions2FeaturesINTEL const & shaderIntegerFunctions2Features =
features2.get<vk::PhysicalDeviceShaderIntegerFunctions2FeaturesINTEL>();
std::cout << "\tShaderIntegerFunctions2Features:\n";
std::cout << "\t\tshaderIntegerFunctions2 : " << !!shaderIntegerFunctions2Features.shaderIntegerFunctions2
<< "\n";
std::cout << "\n";
}
if ( vk::su::contains( extensionProperties, "VK_NV_shader_sm_builtins" ) )
{
vk::PhysicalDeviceShaderSMBuiltinsFeaturesNV const & shaderSMBuiltinsFeatures =
features2.get<vk::PhysicalDeviceShaderSMBuiltinsFeaturesNV>();
std::cout << "\tShaderSMBuiltinsFeatures:\n";
std::cout << "\t\tshaderSMBuiltins : " << !!shaderSMBuiltinsFeatures.shaderSMBuiltins << "\n";
std::cout << "\n";
}
if ( vk::su::contains( extensionProperties, "VK_KHR_shader_subgroup_extended_types" ) )
{
vk::PhysicalDeviceShaderSubgroupExtendedTypesFeaturesKHR const & shaderSubgroupExtendedTypesFeatures =
features2.get<vk::PhysicalDeviceShaderSubgroupExtendedTypesFeaturesKHR>();
std::cout << "\tShaderSubgroupExtendedTypeFeatures:\n";
std::cout << "\t\tshaderSubgroupExtendedTypes : "
<< !!shaderSubgroupExtendedTypesFeatures.shaderSubgroupExtendedTypes << "\n";
std::cout << "\n";
}
if ( vk::su::contains( extensionProperties, "VK_NV_shading_rate_image" ) )
{
vk::PhysicalDeviceShadingRateImageFeaturesNV const & shadingRateImageFeatures =
features2.get<vk::PhysicalDeviceShadingRateImageFeaturesNV>();
std::cout << "\tShadingRateImageFeatures:\n";
std::cout << "\t\tshadingRateCoarseSampleOrder : " << !!shadingRateImageFeatures.shadingRateCoarseSampleOrder
<< "\n";
std::cout << "\t\tshadingRateImage : " << !!shadingRateImageFeatures.shadingRateImage << "\n";
std::cout << "\n";
}
if ( vk::su::contains( extensionProperties, "VK_EXT_subgroup_size_control" ) )
{
vk::PhysicalDeviceSubgroupSizeControlFeaturesEXT const & subgroupSizeControlFeatures =
features2.get<vk::PhysicalDeviceSubgroupSizeControlFeaturesEXT>();
std::cout << "\tSubgroupSizeControlFeatures:\n";
std::cout << "\t\tcomputeFullSubgroups : " << !!subgroupSizeControlFeatures.computeFullSubgroups << "\n";
std::cout << "\t\tsubgroupSizeControl : " << !!subgroupSizeControlFeatures.subgroupSizeControl << "\n";
std::cout << "\n";
}
if ( vk::su::contains( extensionProperties, "VK_EXT_texel_buffer_alignment" ) )
{
vk::PhysicalDeviceTexelBufferAlignmentFeaturesEXT const & texelBufferAlignmentFeatures =
features2.get<vk::PhysicalDeviceTexelBufferAlignmentFeaturesEXT>();
std::cout << "\tTexelBufferAlignmentFeatures:\n";
std::cout << "\t\ttexelBufferAlignment : " << !!texelBufferAlignmentFeatures.texelBufferAlignment << "\n";
std::cout << "\n";
}
if ( vk::su::contains( extensionProperties, "VK_EXT_texture_compression_astc_hdr" ) )
{
vk::PhysicalDeviceTextureCompressionASTCHDRFeaturesEXT const & textureCompressionASTCHDRFeatures =
features2.get<vk::PhysicalDeviceTextureCompressionASTCHDRFeaturesEXT>();
std::cout << "\tTextureCompressionASTCHHRFeatures:\n";
std::cout << "\t\ttextureCompressionASTC_HDR : "
<< !!textureCompressionASTCHDRFeatures.textureCompressionASTC_HDR << "\n";
std::cout << "\n";
}
if ( vk::su::contains( extensionProperties, "VK_KHR_timeline_semaphore" ) )
{
vk::PhysicalDeviceTimelineSemaphoreFeaturesKHR const & timelineSemaphoreFeatures =
features2.get<vk::PhysicalDeviceTimelineSemaphoreFeaturesKHR>();
std::cout << "\tTimelineSemaphoreFeatures:\n";
std::cout << "\t\ttimelineSemaphore :" << !!timelineSemaphoreFeatures.timelineSemaphore << "\n";
std::cout << "\n";
}
if ( vk::su::contains( extensionProperties, "VK_EXT_transform_feedback" ) )
{
vk::PhysicalDeviceTransformFeedbackFeaturesEXT const & transformFeedbackFeatures =
features2.get<vk::PhysicalDeviceTransformFeedbackFeaturesEXT>();
std::cout << "\tTransformFeedbackFeatures:\n";
std::cout << "\t\tgeometryStreams : " << !!transformFeedbackFeatures.geometryStreams << "\n";
std::cout << "\t\ttransformFeedback : " << !!transformFeedbackFeatures.transformFeedback << "\n";
std::cout << "\n";
}
if ( vk::su::contains( extensionProperties, "VK_KHR_uniform_buffer_standard_layout" ) )
{
vk::PhysicalDeviceUniformBufferStandardLayoutFeaturesKHR const & uniformBufferStandardLayoutFeatures =
features2.get<vk::PhysicalDeviceUniformBufferStandardLayoutFeaturesKHR>();
std::cout << "\tUniformBufferStandardLayoutFeatures:\n";
std::cout << "\t\tuniformBufferStandardLayout : "
<< !!uniformBufferStandardLayoutFeatures.uniformBufferStandardLayout << "\n";
std::cout << "\n";
}
if ( vk::su::contains( extensionProperties, "VK_KHR_variable_pointers" ) )
{
vk::PhysicalDeviceVariablePointersFeatures const & variablePointersFeatures =
features2.get<vk::PhysicalDeviceVariablePointersFeatures>();
std::cout << "\tVariablePointersFeatures:\n";
std::cout << "\t\tvariablePointers : " << !!variablePointersFeatures.variablePointers << "\n";
std::cout << "\t\tvariablePointersStorageBuffer : " << !!variablePointersFeatures.variablePointersStorageBuffer
<< "\n";
std::cout << "\n";
}
if ( vk::su::contains( extensionProperties, "VK_EXT_vertex_attribute_divisor" ) )
{
vk::PhysicalDeviceVertexAttributeDivisorFeaturesEXT const & vertexAttributeDivisorFeatures =
features2.get<vk::PhysicalDeviceVertexAttributeDivisorFeaturesEXT>();
std::cout << "\tVertexAttributeDivisorFeature:\n";
std::cout << "\t\tvertexAttributeInstanceRateDivisor : "
<< !!vertexAttributeDivisorFeatures.vertexAttributeInstanceRateDivisor << "\n";
std::cout << "\t\tvertexAttributeInstanceRateZeroDivisor : "
<< !!vertexAttributeDivisorFeatures.vertexAttributeInstanceRateZeroDivisor << "\n";
std::cout << "\n";
}
if ( vk::su::contains( extensionProperties, "VK_KHR_vulkan_memory_model" ) )
{
vk::PhysicalDeviceVulkanMemoryModelFeaturesKHR const & vulkanMemoryModelFeatures =
features2.get<vk::PhysicalDeviceVulkanMemoryModelFeaturesKHR>();
std::cout << "\tVulkanMemoryModelFeatures:\n";
std::cout << "\t\tvulkanMemoryModel : "
<< !!vulkanMemoryModelFeatures.vulkanMemoryModel << "\n";
std::cout << "\t\tvulkanMemoryModelAvailabilityVisibilityChains : "
<< !!vulkanMemoryModelFeatures.vulkanMemoryModelAvailabilityVisibilityChains << "\n";
std::cout << "\t\tvulkanMemoryModelDeviceScope : "
<< !!vulkanMemoryModelFeatures.vulkanMemoryModelDeviceScope << "\n";
std::cout << "\n";
}
if ( vk::su::contains( extensionProperties, "VK_KHR_sampler_ycbcr_conversion" ) )
{
vk::PhysicalDeviceYcbcrImageArraysFeaturesEXT const & ycbcrImageArraysFeatures =
features2.get<vk::PhysicalDeviceYcbcrImageArraysFeaturesEXT>();
std::cout << "\tYcbcrImageArraysFeatures:\n";
std::cout << "\t\tycbcrImageArrays : " << !!ycbcrImageArraysFeatures.ycbcrImageArrays << "\n";
std::cout << "\n";
}
}
/* VULKAN_KEY_END */
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,35 @@
# Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_PhysicalDeviceGroups)
set(HEADERS
)
set(SOURCES
PhysicalDeviceGroups.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_PhysicalDeviceGroups
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_PhysicalDeviceGroups PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_PhysicalDeviceGroups PRIVATE utils)

View File

@ -0,0 +1,107 @@
// Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : PhysicalDeviceGroups
// Get the PhysicalDeviceGroups.
#include "../utils/utils.hpp"
#include "vulkan/vulkan.hpp"
#include <vector>
static char const * AppName = "PhysicalDeviceGroups";
static char const * EngineName = "Vulkan.hpp";
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
std::unique_ptr<vk::raii::Instance> instance =
vk::raii::su::makeUniqueInstance( *context, AppName, EngineName, {}, {}, VK_API_VERSION_1_1 );
#if !defined( NDEBUG )
std::unique_ptr<vk::raii::DebugUtilsMessengerEXT> debugUtilsMessenger =
vk::raii::su::makeUniqueDebugUtilsMessengerEXT( *instance );
#endif
/* VULKAN_KEY_START */
std::vector<vk::PhysicalDeviceGroupProperties> groupProperties = instance->enumeratePhysicalDeviceGroups();
std::cout << std::boolalpha;
for ( size_t i = 0; i < groupProperties.size(); i++ )
{
std::cout << "Group Properties " << i << " :\n";
std::cout << "\t"
<< "physicalDeviceCount = " << groupProperties[i].physicalDeviceCount << "\n";
std::cout << "\t"
<< "physicalDevices:\n";
for ( size_t j = 0; j < groupProperties[i].physicalDeviceCount; j++ )
{
std::unique_ptr<vk::raii::PhysicalDevice> physicalDevice = vk::raii::su::make_unique<vk::raii::PhysicalDevice>(
static_cast<VkPhysicalDevice>( groupProperties[i].physicalDevices[j] ), instance->getDispatcher() );
std::cout << "\t\t" << j << " : " << physicalDevice->getProperties().deviceName << "\n";
}
std::cout << "\t"
<< "subsetAllocation = " << !!groupProperties[i].subsetAllocation << "\n";
std::cout << "\n";
if ( 1 < groupProperties[i].physicalDeviceCount )
{
std::unique_ptr<vk::raii::PhysicalDevice> physicalDevice = vk::raii::su::make_unique<vk::raii::PhysicalDevice>(
static_cast<VkPhysicalDevice>( groupProperties[i].physicalDevices[0] ), instance->getDispatcher() );
// get the QueueFamilyProperties of the first PhysicalDevice
std::vector<vk::QueueFamilyProperties> queueFamilyProperties = physicalDevice->getQueueFamilyProperties();
// get the first index into queueFamiliyProperties which supports graphics
auto propertyIterator = std::find_if(
queueFamilyProperties.begin(), queueFamilyProperties.end(), []( vk::QueueFamilyProperties const & qfp ) {
return qfp.queueFlags & vk::QueueFlagBits::eGraphics;
} );
size_t graphicsQueueFamilyIndex = std::distance( queueFamilyProperties.begin(), propertyIterator );
assert( graphicsQueueFamilyIndex < queueFamilyProperties.size() );
// create a Device
float queuePriority = 0.0f;
vk::DeviceQueueCreateInfo deviceQueueCreateInfo(
{}, static_cast<uint32_t>( graphicsQueueFamilyIndex ), 1, &queuePriority );
vk::StructureChain<vk::DeviceCreateInfo, vk::DeviceGroupDeviceCreateInfo> deviceCreateInfoChain(
{ {}, deviceQueueCreateInfo },
{ groupProperties[i].physicalDeviceCount, groupProperties[i].physicalDevices } );
std::unique_ptr<vk::raii::Device> device =
vk::raii::su::make_unique<vk::raii::Device>( *physicalDevice, deviceCreateInfoChain.get<vk::DeviceCreateInfo>() );
}
}
/* VULKAN_KEY_END */
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,37 @@
# Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
if(!MSVC)
cmake_minimum_required(VERSION 3.2)
project(RAII_PhysicalDeviceMemoryProperties)
set(HEADERS
)
set(SOURCES
PhysicalDeviceMemoryProperties.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_PhysicalDeviceMemoryProperties
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_PhysicalDeviceMemoryProperties PROPERTIES FOLDER "RAIISamples")
target_link_libraries(RAII_PhysicalDeviceMemoryProperties PRIVATE utils)
endif(!MSVC)

View File

@ -0,0 +1,119 @@
// Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : PhysicalDeviceMemoryProperties
// Get memory properties per physical device.
#include "../utils/utils.hpp"
#include "vulkan/vulkan.hpp"
#include <sstream>
#include <vector>
static char const * AppName = "PhysicalDeviceMemoryProperties";
static char const * EngineName = "Vulkan.hpp";
std::string formatSize( vk::DeviceSize size )
{
std::ostringstream oss;
if ( size < 1024 )
{
oss << size << " B";
}
else if ( size < 1024 * 1024 )
{
oss << size / 1024.f << " KB";
}
else if ( size < 1024 * 1024 * 1024 )
{
oss << size / ( 1024.0f * 1024.0f ) << " MB";
}
else
{
oss << size / ( 1024.0f * 1024.0f * 1024.0f ) << " GB";
}
return oss.str();
}
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::ContextHandle<>> contextHandle = std::make_unique<vk::ContextHandle<>>();
std::unique_ptr<vk::InstanceHandle<>> instanceHandle =
vk::su::makeUniqueInstanceHandle( *contextHandle, AppName, EngineName, {}, {}, VK_API_VERSION_1_1 );
#if !defined( NDEBUG )
std::unique_ptr<vk::DebugUtilsMessengerEXTHandle<>> debugUtilsMessenger =
vk::su::makeUniqueDebugUtilsMessengerEXTHandle( *instanceHandle );
#endif
// enumerate the physicalDevices
std::unique_ptr<vk::PhysicalDeviceHandles<>> physicalDeviceHandles =
std::make_unique<vk::PhysicalDeviceHandles<>>( *instanceHandle );
/* VULKAN_KEY_START */
for ( size_t i = 0; i < physicalDeviceHandles->size(); i++ )
{
// some properties are only valid, if a corresponding extension is available!
std::vector<vk::ExtensionProperties> extensionProperties =
(*physicalDeviceHandles)[i].enumerateDeviceExtensionProperties();
bool containsMemoryBudget = vk::su::contains( extensionProperties, "VK_EXT_memory_budget" );
std::cout << "PhysicalDevice " << i << " :\n";
auto memoryProperties2 =
(*physicalDeviceHandles)[i]
.getMemoryProperties2<vk::PhysicalDeviceMemoryProperties2, vk::PhysicalDeviceMemoryBudgetPropertiesEXT>();
vk::PhysicalDeviceMemoryProperties const & memoryProperties =
memoryProperties2.get<vk::PhysicalDeviceMemoryProperties2>().memoryProperties;
vk::PhysicalDeviceMemoryBudgetPropertiesEXT const & memoryBudgetProperties =
memoryProperties2.get<vk::PhysicalDeviceMemoryBudgetPropertiesEXT>();
std::cout << "memoryHeapCount: " << memoryProperties.memoryHeapCount << "\n";
for ( uint32_t j = 0; j < memoryProperties.memoryHeapCount; j++ )
{
std::cout << " " << j << ": size = " << formatSize( memoryProperties.memoryHeaps[j].size )
<< ", flags = " << vk::to_string( memoryProperties.memoryHeaps[j].flags ) << "\n";
if ( containsMemoryBudget )
{
std::cout << " heapBudget = " << formatSize( memoryBudgetProperties.heapBudget[j] )
<< ", heapUsage = " << formatSize( memoryBudgetProperties.heapUsage[j] ) << "\n";
}
}
std::cout << "memoryTypeCount: " << memoryProperties.memoryTypeCount << "\n";
for ( uint32_t j = 0; j < memoryProperties.memoryTypeCount; j++ )
{
std::cout << " " << j << ": heapIndex = " << memoryProperties.memoryTypes[j].heapIndex
<< ", flags = " << vk::to_string( memoryProperties.memoryTypes[j].propertyFlags ) << "\n";
}
}
/* VULKAN_KEY_END */
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,35 @@
# Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_PhysicalDeviceProperties)
set(HEADERS
)
set(SOURCES
PhysicalDeviceProperties.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_PhysicalDeviceProperties
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_PhysicalDeviceProperties PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_PhysicalDeviceProperties PRIVATE utils)

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,35 @@
# Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_PhysicalDeviceQueueFamilyProperties)
set(HEADERS
)
set(SOURCES
PhysicalDeviceQueueFamilyProperties.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_PhysicalDeviceQueueFamilyProperties
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_PhysicalDeviceQueueFamilyProperties PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_PhysicalDeviceQueueFamilyProperties PRIVATE utils)

View File

@ -0,0 +1,101 @@
// Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : PhysicalDeviceQueueFamilyProperties
// Get queue family properties per physical device.
#include "../utils/utils.hpp"
#include "vulkan/vulkan.hpp"
#include <iomanip>
#include <sstream>
#include <vector>
static char const * AppName = "PhysicalDeviceQueueFamilyProperties";
static char const * EngineName = "Vulkan.hpp";
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
std::unique_ptr<vk::raii::Instance> instance =
vk::raii::su::makeUniqueInstance( *context, AppName, EngineName, {}, {}, VK_API_VERSION_1_1 );
#if !defined( NDEBUG )
std::unique_ptr<vk::raii::DebugUtilsMessengerEXT> debugUtilsMessenger =
vk::raii::su::makeUniqueDebugUtilsMessengerEXT( *instance );
#endif
// enumerate the physicalDevices
vk::raii::PhysicalDevices physicalDevices( *instance );
/* VULKAN_KEY_START */
std::cout << std::boolalpha;
for ( size_t i = 0; i < physicalDevices.size(); i++ )
{
// some features are only valid, if a corresponding extension is available!
std::vector<vk::ExtensionProperties> extensionProperties =
physicalDevices[i].enumerateDeviceExtensionProperties();
std::cout << "PhysicalDevice " << i << " :" << std::endl;
// need to explicitly specify all the template arguments for getQueueFamilyProperties2 to make the compiler happy
using Chain = vk::StructureChain<vk::QueueFamilyProperties2, vk::QueueFamilyCheckpointPropertiesNV>;
auto queueFamilyProperties2 = physicalDevices[i].getQueueFamilyProperties2<Chain>();
for ( size_t j = 0; j < queueFamilyProperties2.size(); j++ )
{
std::cout << "\tQueueFamily " << j << " :" << std::endl;
vk::QueueFamilyProperties const & properties =
queueFamilyProperties2[j].get<vk::QueueFamilyProperties2>().queueFamilyProperties;
std::cout << "\t\tQueueFamilyProperties:" << std::endl;
std::cout << "\t\t\tqueueFlags = " << vk::to_string( properties.queueFlags ) << std::endl;
std::cout << "\t\t\tqueueCount = " << properties.queueCount << std::endl;
std::cout << "\t\t\ttimestampValidBits = " << properties.timestampValidBits << std::endl;
std::cout << "\t\t\tminImageTransferGranularity = " << properties.minImageTransferGranularity.width << " x "
<< properties.minImageTransferGranularity.height << " x "
<< properties.minImageTransferGranularity.depth << std::endl;
std::cout << std::endl;
if ( vk::su::contains( extensionProperties, "VK_NV_device_diagnostic_checkpoints" ) )
{
vk::QueueFamilyCheckpointPropertiesNV const & checkpointProperties =
queueFamilyProperties2[j].get<vk::QueueFamilyCheckpointPropertiesNV>();
std::cout << "\t\tCheckPointPropertiesNV:" << std::endl;
std::cout << "\t\t\tcheckpointExecutionStageMask = "
<< vk::to_string( checkpointProperties.checkpointExecutionStageMask ) << std::endl;
std::cout << std::endl;
}
}
}
/* VULKAN_KEY_END */
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,35 @@
# Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_PipelineCache)
set(HEADERS
)
set(SOURCES
PipelineCache.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_PipelineCache
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_PipelineCache PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_PipelineCache PRIVATE utils)

View File

@ -0,0 +1,416 @@
// Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : PipelineCache
// This sample tries to save and reuse pipeline cache data between runs.
#if defined( _MSC_VER )
// no need to ignore any warnings with MSVC
#elif defined( __clang__ )
# pragma clang diagnostic ignored "-Wmissing-braces"
#elif defined( __GNUC__ )
#else
// unknow compiler... just ignore the warnings for yourselves ;)
#endif
#include "../../samples/utils/geometries.hpp"
#include "../../samples/utils/math.hpp"
#include "../utils/shaders.hpp"
#include "../utils/utils.hpp"
#include "SPIRV/GlslangToSpv.h"
#include "vulkan/vulkan.hpp"
#include <fstream>
#include <iomanip>
#include <thread>
// For timestamp code (getMilliseconds)
#ifdef WIN32
# include <Windows.h>
#else
# include <sys/time.h>
#endif
typedef unsigned long long timestamp_t;
timestamp_t getMilliseconds()
{
#ifdef WIN32
LARGE_INTEGER frequency;
BOOL useQPC = QueryPerformanceFrequency( &frequency );
if ( useQPC )
{
LARGE_INTEGER now;
QueryPerformanceCounter( &now );
return ( 1000LL * now.QuadPart ) / frequency.QuadPart;
}
else
{
return GetTickCount();
}
#else
struct timeval now;
gettimeofday( &now, NULL );
return ( now.tv_usec / 1000 ) + (timestamp_t)now.tv_sec;
#endif
}
static char const * AppName = "PipelineCache";
static char const * EngineName = "Vulkan.hpp";
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
std::unique_ptr<vk::raii::Instance> instance =
vk::raii::su::makeUniqueInstance( *context, AppName, EngineName, {}, vk::su::getInstanceExtensions() );
#if !defined( NDEBUG )
std::unique_ptr<vk::raii::DebugUtilsMessengerEXT> debugUtilsMessenger =
vk::raii::su::makeUniqueDebugUtilsMessengerEXT( *instance );
#endif
std::unique_ptr<vk::raii::PhysicalDevice> physicalDevice = vk::raii::su::makeUniquePhysicalDevice( *instance );
vk::PhysicalDeviceProperties properties = physicalDevice->getProperties();
vk::raii::su::SurfaceData surfaceData( *instance, AppName, vk::Extent2D( 500, 500 ) );
std::pair<uint32_t, uint32_t> graphicsAndPresentQueueFamilyIndex =
vk::raii::su::findGraphicsAndPresentQueueFamilyIndex( *physicalDevice, *surfaceData.surface );
std::unique_ptr<vk::raii::Device> device = vk::raii::su::makeUniqueDevice(
*physicalDevice, graphicsAndPresentQueueFamilyIndex.first, vk::su::getDeviceExtensions() );
std::unique_ptr<vk::raii::CommandPool> commandPool =
vk::raii::su::makeUniqueCommandPool( *device, graphicsAndPresentQueueFamilyIndex.first );
std::unique_ptr<vk::raii::CommandBuffer> commandBuffer =
vk::raii::su::makeUniqueCommandBuffer( *device, *commandPool );
std::unique_ptr<vk::raii::Queue> graphicsQueue =
vk::raii::su::make_unique<vk::raii::Queue>( *device, graphicsAndPresentQueueFamilyIndex.first, 0 );
std::unique_ptr<vk::raii::Queue> presentQueue =
vk::raii::su::make_unique<vk::raii::Queue>( *device, graphicsAndPresentQueueFamilyIndex.second, 0 );
vk::raii::su::SwapChainData swapChainData( *physicalDevice,
*device,
*surfaceData.surface,
surfaceData.extent,
vk::ImageUsageFlagBits::eColorAttachment |
vk::ImageUsageFlagBits::eTransferSrc,
{},
graphicsAndPresentQueueFamilyIndex.first,
graphicsAndPresentQueueFamilyIndex.second );
vk::raii::su::DepthBufferData depthBufferData(
*physicalDevice, *device, vk::Format::eD16Unorm, surfaceData.extent );
vk::raii::su::TextureData textureData( *physicalDevice, *device );
commandBuffer->begin( vk::CommandBufferBeginInfo() );
textureData.setImage( *commandBuffer, vk::su::MonochromeImageGenerator( { 118, 185, 0 } ) );
vk::raii::su::BufferData uniformBufferData(
*physicalDevice, *device, sizeof( glm::mat4x4 ), vk::BufferUsageFlagBits::eUniformBuffer );
glm::mat4x4 mvpcMatrix = vk::su::createModelViewProjectionClipMatrix( surfaceData.extent );
vk::raii::su::copyToDevice( *uniformBufferData.deviceMemory, mvpcMatrix );
std::unique_ptr<vk::raii::DescriptorSetLayout> descriptorSetLayout = vk::raii::su::makeUniqueDescriptorSetLayout(
*device,
{ { vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eVertex },
{ vk::DescriptorType::eCombinedImageSampler, 1, vk::ShaderStageFlagBits::eFragment } } );
std::unique_ptr<vk::raii::PipelineLayout> pipelineLayout =
vk::raii::su::makeUniquePipelineLayout( *device, *descriptorSetLayout );
vk::Format colorFormat =
vk::su::pickSurfaceFormat( physicalDevice->getSurfaceFormatsKHR( **surfaceData.surface ) ).format;
std::unique_ptr<vk::raii::RenderPass> renderPass =
vk::raii::su::makeUniqueRenderPass( *device, colorFormat, depthBufferData.format );
glslang::InitializeProcess();
std::unique_ptr<vk::raii::ShaderModule> vertexShaderModule =
vk::raii::su::makeUniqueShaderModule( *device, vk::ShaderStageFlagBits::eVertex, vertexShaderText_PT_T );
std::unique_ptr<vk::raii::ShaderModule> fragmentShaderModule =
vk::raii::su::makeUniqueShaderModule( *device, vk::ShaderStageFlagBits::eFragment, fragmentShaderText_T_C );
glslang::FinalizeProcess();
std::vector<std::unique_ptr<vk::raii::Framebuffer>> framebuffers = vk::raii::su::makeUniqueFramebuffers(
*device, *renderPass, swapChainData.imageViews, depthBufferData.imageView, surfaceData.extent );
vk::raii::su::BufferData vertexBufferData(
*physicalDevice, *device, sizeof( texturedCubeData ), vk::BufferUsageFlagBits::eVertexBuffer );
vk::raii::su::copyToDevice(
*vertexBufferData.deviceMemory, texturedCubeData, sizeof( texturedCubeData ) / sizeof( texturedCubeData[0] ) );
std::unique_ptr<vk::raii::DescriptorPool> descriptorPool = vk::raii::su::makeUniqueDescriptorPool(
*device, { { vk::DescriptorType::eUniformBuffer, 1 }, { vk::DescriptorType::eCombinedImageSampler, 1 } } );
std::unique_ptr<vk::raii::DescriptorSet> descriptorSet =
vk::raii::su::makeUniqueDescriptorSet( *device, *descriptorPool, *descriptorSetLayout );
vk::raii::su::updateDescriptorSets( *device,
*descriptorSet,
{ { vk::DescriptorType::eUniformBuffer, *uniformBufferData.buffer, nullptr } },
{ textureData } );
/* VULKAN_KEY_START */
// Check disk for existing cache data
size_t startCacheSize = 0;
char * startCacheData = nullptr;
std::string cacheFileName = "pipeline_cache_data.bin";
std::ifstream readCacheStream( cacheFileName, std::ios_base::in | std::ios_base::binary );
if ( readCacheStream.good() )
{
// Determine cache size
readCacheStream.seekg( 0, readCacheStream.end );
startCacheSize = static_cast<size_t>( readCacheStream.tellg() );
readCacheStream.seekg( 0, readCacheStream.beg );
// Allocate memory to hold the initial cache data
startCacheData = (char *)std::malloc( startCacheSize );
// Read the data into our buffer
readCacheStream.read( startCacheData, startCacheSize );
// Clean up and print results
readCacheStream.close();
std::cout << " Pipeline cache HIT!\n";
std::cout << " cacheData loaded from " << cacheFileName << "\n";
}
else
{
// No cache found on disk
std::cout << " Pipeline cache miss!\n";
}
if ( startCacheData != nullptr )
{
// Check for cache validity
//
// TODO: Update this as the spec evolves. The fields are not defined by the header.
//
// The code below supports SDK 0.10 Vulkan spec, which contains the following table:
//
// Offset Size Meaning
// ------ ------------ ------------------------------------------------------------------
// 0 4 a device ID equal to VkPhysicalDeviceProperties::DeviceId written
// as a stream of bytes, with the least significant byte first
//
// 4 VK_UUID_SIZE a pipeline cache ID equal to VkPhysicalDeviceProperties::pipelineCacheUUID
//
//
// The code must be updated for latest Vulkan spec, which contains the following table:
//
// Offset Size Meaning
// ------ ------------ ------------------------------------------------------------------
// 0 4 length in bytes of the entire pipeline cache header written as a
// stream of bytes, with the least significant byte first
// 4 4 a VkPipelineCacheHeaderVersion value written as a stream of bytes,
// with the least significant byte first
// 8 4 a vendor ID equal to VkPhysicalDeviceProperties::vendorID written
// as a stream of bytes, with the least significant byte first
// 12 4 a device ID equal to VkPhysicalDeviceProperties::deviceID written
// as a stream of bytes, with the least significant byte first
// 16 VK_UUID_SIZE a pipeline cache ID equal to VkPhysicalDeviceProperties::pipelineCacheUUID
uint32_t headerLength = 0;
uint32_t cacheHeaderVersion = 0;
uint32_t vendorID = 0;
uint32_t deviceID = 0;
uint8_t pipelineCacheUUID[VK_UUID_SIZE] = {};
memcpy( &headerLength, (uint8_t *)startCacheData + 0, 4 );
memcpy( &cacheHeaderVersion, (uint8_t *)startCacheData + 4, 4 );
memcpy( &vendorID, (uint8_t *)startCacheData + 8, 4 );
memcpy( &deviceID, (uint8_t *)startCacheData + 12, 4 );
memcpy( pipelineCacheUUID, (uint8_t *)startCacheData + 16, VK_UUID_SIZE );
// Check each field and report bad values before freeing existing cache
bool badCache = false;
if ( headerLength <= 0 )
{
badCache = true;
std::cout << " Bad header length in " << cacheFileName << ".\n";
std::cout << " Cache contains: " << std::hex << std::setw( 8 ) << headerLength << "\n";
}
if ( cacheHeaderVersion != VK_PIPELINE_CACHE_HEADER_VERSION_ONE )
{
badCache = true;
std::cout << " Unsupported cache header version in " << cacheFileName << ".\n";
std::cout << " Cache contains: " << std::hex << std::setw( 8 ) << cacheHeaderVersion << "\n";
}
if ( vendorID != properties.vendorID )
{
badCache = true;
std::cout << " Vender ID mismatch in " << cacheFileName << ".\n";
std::cout << " Cache contains: " << std::hex << std::setw( 8 ) << vendorID << "\n";
std::cout << " Driver expects: " << std::hex << std::setw( 8 ) << properties.vendorID << "\n";
}
if ( deviceID != properties.deviceID )
{
badCache = true;
std::cout << " Device ID mismatch in " << cacheFileName << ".\n";
std::cout << " Cache contains: " << std::hex << std::setw( 8 ) << deviceID << "\n";
std::cout << " Driver expects: " << std::hex << std::setw( 8 ) << properties.deviceID << "\n";
}
if ( memcmp( pipelineCacheUUID, properties.pipelineCacheUUID, sizeof( pipelineCacheUUID ) ) != 0 )
{
badCache = true;
std::cout << " UUID mismatch in " << cacheFileName << ".\n";
std::cout << " Cache contains: " << vk::su::UUID( pipelineCacheUUID ) << "\n";
std::cout << " Driver expects: " << vk::su::UUID( properties.pipelineCacheUUID ) << "\n";
}
if ( badCache )
{
// Don't submit initial cache data if any version info is incorrect
free( startCacheData );
startCacheSize = 0;
startCacheData = nullptr;
// And clear out the old cache file for use in next run
std::cout << " Deleting cache entry " << cacheFileName << " to repopulate.\n";
if ( remove( cacheFileName.c_str() ) != 0 )
{
std::cerr << "Reading error";
exit( EXIT_FAILURE );
}
}
}
// Feed the initial cache data into cache creation
vk::PipelineCacheCreateInfo pipelineCacheCreateInfo( {}, startCacheSize, startCacheData );
std::unique_ptr<vk::raii::PipelineCache> pipelineCache =
vk::raii::su::make_unique<vk::raii::PipelineCache>( *device, pipelineCacheCreateInfo );
// Free our initialData now that pipeline cache has been created
free( startCacheData );
startCacheData = NULL;
// Time (roughly) taken to create the graphics pipeline
timestamp_t start = getMilliseconds();
std::unique_ptr<vk::raii::Pipeline> graphicsPipeline = vk::raii::su::makeUniqueGraphicsPipeline(
*device,
*pipelineCache,
*vertexShaderModule,
nullptr,
*fragmentShaderModule,
nullptr,
sizeof( texturedCubeData[0] ),
{ { vk::Format::eR32G32B32A32Sfloat, 0 }, { vk::Format::eR32G32Sfloat, 16 } },
vk::FrontFace::eClockwise,
true,
*pipelineLayout,
*renderPass );
timestamp_t elapsed = getMilliseconds() - start;
std::cout << " vkCreateGraphicsPipeline time: " << (double)elapsed << " ms\n";
std::unique_ptr<vk::raii::Semaphore> imageAcquiredSemaphore =
vk::raii::su::make_unique<vk::raii::Semaphore>( *device, vk::SemaphoreCreateInfo() );
// Get the index of the next available swapchain image:
vk::Result result;
uint32_t imageIndex;
std::tie( result, imageIndex ) =
swapChainData.swapChain->acquireNextImage( vk::su::FenceTimeout, **imageAcquiredSemaphore );
assert( result == vk::Result::eSuccess );
assert( imageIndex < swapChainData.images.size() );
std::array<vk::ClearValue, 2> clearValues;
clearValues[0].color = vk::ClearColorValue( std::array<float, 4>( { { 0.2f, 0.2f, 0.2f, 0.2f } } ) );
clearValues[1].depthStencil = vk::ClearDepthStencilValue( 1.0f, 0 );
commandBuffer->beginRenderPass(
vk::RenderPassBeginInfo(
**renderPass, **framebuffers[imageIndex], vk::Rect2D( vk::Offset2D(), surfaceData.extent ), clearValues ),
vk::SubpassContents::eInline );
commandBuffer->bindPipeline( vk::PipelineBindPoint::eGraphics, **graphicsPipeline );
commandBuffer->bindDescriptorSets( vk::PipelineBindPoint::eGraphics, **pipelineLayout, 0, { **descriptorSet }, {} );
commandBuffer->bindVertexBuffers( 0, { **vertexBufferData.buffer }, { 0 } );
commandBuffer->setViewport( 0,
vk::Viewport( 0.0f,
0.0f,
static_cast<float>( surfaceData.extent.width ),
static_cast<float>( surfaceData.extent.height ),
0.0f,
1.0f ) );
commandBuffer->setScissor( 0, vk::Rect2D( vk::Offset2D( 0, 0 ), surfaceData.extent ) );
commandBuffer->draw( 12 * 3, 1, 0, 0 );
commandBuffer->endRenderPass();
commandBuffer->end();
std::unique_ptr<vk::raii::Fence> drawFence = vk::raii::su::make_unique<vk::raii::Fence>( *device, vk::FenceCreateInfo() );
vk::PipelineStageFlags waitDestinationStageMask( vk::PipelineStageFlagBits::eColorAttachmentOutput );
vk::SubmitInfo submitInfo( **imageAcquiredSemaphore, waitDestinationStageMask, **commandBuffer );
graphicsQueue->submit( submitInfo, **drawFence );
while ( vk::Result::eTimeout == device->waitForFences( { **drawFence }, VK_TRUE, vk::su::FenceTimeout ) )
;
vk::PresentInfoKHR presentInfoKHR( nullptr, **swapChainData.swapChain, imageIndex );
result = presentQueue->presentKHR( presentInfoKHR );
switch ( result )
{
case vk::Result::eSuccess: break;
case vk::Result::eSuboptimalKHR:
std::cout << "vk::Queue::presentKHR returned vk::Result::eSuboptimalKHR !\n";
break;
default: assert( false ); // an unexpected result is returned !
}
std::this_thread::sleep_for( std::chrono::milliseconds( 1000 ) );
// Store away the cache that we've populated. This could conceivably happen
// earlier, depends on when the pipeline cache stops being populated
// internally.
std::vector<uint8_t> endCacheData = pipelineCache->getData();
// Write the file to disk, overwriting whatever was there
std::ofstream writeCacheStream( cacheFileName, std::ios_base::out | std::ios_base::binary );
if ( writeCacheStream.good() )
{
writeCacheStream.write( reinterpret_cast<char const *>( endCacheData.data() ), endCacheData.size() );
writeCacheStream.close();
std::cout << " cacheData written to " << cacheFileName << "\n";
}
else
{
// Something bad happened
std::cout << " Unable to write cache data to disk!\n";
}
/* VULKAN_KEY_END */
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,35 @@
# Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_PipelineDerivative)
set(HEADERS
)
set(SOURCES
PipelineDerivative.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_PipelineDerivative
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_PipelineDerivative PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_PipelineDerivative PRIVATE utils)

View File

@ -0,0 +1,332 @@
// Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : PipelineDerivative
// This sample creates pipeline derivative and draws with it.
#if defined( _MSC_VER )
// no need to ignore any warnings with MSVC
#elif defined( __clang__ )
# pragma clang diagnostic ignored "-Wmissing-braces"
#elif defined( __GNUC__ )
#else
// unknow compiler... just ignore the warnings for yourselves ;)
#endif
#include "../../samples/utils/geometries.hpp"
#include "../../samples/utils/math.hpp"
#include "../utils/shaders.hpp"
#include "../utils/utils.hpp"
#include "SPIRV/GlslangToSpv.h"
#include "vulkan/vulkan.hpp"
#include <thread>
static char const * AppName = "PipelineDerivative";
static char const * EngineName = "Vulkan.hpp";
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
std::unique_ptr<vk::raii::Instance> instance =
vk::raii::su::makeUniqueInstance( *context, AppName, EngineName, {}, vk::su::getInstanceExtensions() );
#if !defined( NDEBUG )
std::unique_ptr<vk::raii::DebugUtilsMessengerEXT> debugUtilsMessenger =
vk::raii::su::makeUniqueDebugUtilsMessengerEXT( *instance );
#endif
std::unique_ptr<vk::raii::PhysicalDevice> physicalDevice = vk::raii::su::makeUniquePhysicalDevice( *instance );
vk::raii::su::SurfaceData surfaceData( *instance, AppName, vk::Extent2D( 500, 500 ) );
std::pair<uint32_t, uint32_t> graphicsAndPresentQueueFamilyIndex =
vk::raii::su::findGraphicsAndPresentQueueFamilyIndex( *physicalDevice, *surfaceData.surface );
std::unique_ptr<vk::raii::Device> device = vk::raii::su::makeUniqueDevice(
*physicalDevice, graphicsAndPresentQueueFamilyIndex.first, vk::su::getDeviceExtensions() );
std::unique_ptr<vk::raii::CommandPool> commandPool =
vk::raii::su::makeUniqueCommandPool( *device, graphicsAndPresentQueueFamilyIndex.first );
std::unique_ptr<vk::raii::CommandBuffer> commandBuffer =
vk::raii::su::makeUniqueCommandBuffer( *device, *commandPool );
std::unique_ptr<vk::raii::Queue> graphicsQueue =
vk::raii::su::make_unique<vk::raii::Queue>( *device, graphicsAndPresentQueueFamilyIndex.first, 0 );
std::unique_ptr<vk::raii::Queue> presentQueue =
vk::raii::su::make_unique<vk::raii::Queue>( *device, graphicsAndPresentQueueFamilyIndex.second, 0 );
vk::raii::su::SwapChainData swapChainData( *physicalDevice,
*device,
*surfaceData.surface,
surfaceData.extent,
vk::ImageUsageFlagBits::eColorAttachment |
vk::ImageUsageFlagBits::eTransferSrc,
{},
graphicsAndPresentQueueFamilyIndex.first,
graphicsAndPresentQueueFamilyIndex.second );
vk::raii::su::DepthBufferData depthBufferData(
*physicalDevice, *device, vk::Format::eD16Unorm, surfaceData.extent );
vk::raii::su::TextureData textureData( *physicalDevice, *device );
commandBuffer->begin( vk::CommandBufferBeginInfo() );
textureData.setImage( *commandBuffer, vk::su::CheckerboardImageGenerator() );
vk::raii::su::BufferData uniformBufferData(
*physicalDevice, *device, sizeof( glm::mat4x4 ), vk::BufferUsageFlagBits::eUniformBuffer );
glm::mat4x4 mvpcMatrix = vk::su::createModelViewProjectionClipMatrix( surfaceData.extent );
vk::raii::su::copyToDevice( *uniformBufferData.deviceMemory, mvpcMatrix );
std::unique_ptr<vk::raii::DescriptorSetLayout> descriptorSetLayout = vk::raii::su::makeUniqueDescriptorSetLayout(
*device,
{ { vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eVertex },
{ vk::DescriptorType::eCombinedImageSampler, 1, vk::ShaderStageFlagBits::eFragment } } );
std::unique_ptr<vk::raii::PipelineLayout> pipelineLayout =
vk::raii::su::makeUniquePipelineLayout( *device, *descriptorSetLayout );
vk::Format colorFormat =
vk::su::pickSurfaceFormat( physicalDevice->getSurfaceFormatsKHR( **surfaceData.surface ) ).format;
std::unique_ptr<vk::raii::RenderPass> renderPass =
vk::raii::su::makeUniqueRenderPass( *device, colorFormat, depthBufferData.format );
glslang::InitializeProcess();
std::unique_ptr<vk::raii::ShaderModule> vertexShaderModule =
vk::raii::su::makeUniqueShaderModule( *device, vk::ShaderStageFlagBits::eVertex, vertexShaderText_PT_T );
std::unique_ptr<vk::raii::ShaderModule> fragmentShaderModule =
vk::raii::su::makeUniqueShaderModule( *device, vk::ShaderStageFlagBits::eFragment, fragmentShaderText_T_C );
glslang::FinalizeProcess();
std::vector<std::unique_ptr<vk::raii::Framebuffer>> framebuffers = vk::raii::su::makeUniqueFramebuffers(
*device, *renderPass, swapChainData.imageViews, depthBufferData.imageView, surfaceData.extent );
vk::raii::su::BufferData vertexBufferData(
*physicalDevice, *device, sizeof( texturedCubeData ), vk::BufferUsageFlagBits::eVertexBuffer );
vk::raii::su::copyToDevice(
*vertexBufferData.deviceMemory, texturedCubeData, sizeof( texturedCubeData ) / sizeof( texturedCubeData[0] ) );
std::unique_ptr<vk::raii::DescriptorPool> descriptorPool = vk::raii::su::makeUniqueDescriptorPool(
*device, { { vk::DescriptorType::eUniformBuffer, 1 }, { vk::DescriptorType::eCombinedImageSampler, 1 } } );
std::unique_ptr<vk::raii::DescriptorSet> descriptorSet =
vk::raii::su::makeUniqueDescriptorSet( *device, *descriptorPool, *descriptorSetLayout );
vk::raii::su::updateDescriptorSets( *device,
*descriptorSet,
{ { vk::DescriptorType::eUniformBuffer, *uniformBufferData.buffer, nullptr } },
{ textureData } );
std::unique_ptr<vk::raii::PipelineCache> pipelineCache =
vk::raii::su::make_unique<vk::raii::PipelineCache>( *device, vk::PipelineCacheCreateInfo() );
/* VULKAN_KEY_START */
// Create two pipelines.
//
// First pipeline has VK_PIPELINE_CREATE_ALLOW_DERIVATIVES_BIT set.
// Second pipeline has a modified fragment shader and sets the VK_PIPELINE_CREATE_DERIVATIVE_BIT flag.
std::array<vk::PipelineShaderStageCreateInfo, 2> pipelineShaderStageCreateInfos = {
vk::PipelineShaderStageCreateInfo( {}, vk::ShaderStageFlagBits::eVertex, **vertexShaderModule, "main" ),
vk::PipelineShaderStageCreateInfo( {}, vk::ShaderStageFlagBits::eFragment, **fragmentShaderModule, "main" )
};
vk::VertexInputBindingDescription vertexInputBindingDescription( 0, sizeof( texturedCubeData[0] ) );
std::array<vk::VertexInputAttributeDescription, 2> vertexInputAttributeDescriptions = {
vk::VertexInputAttributeDescription( 0, 0, vk::Format::eR32G32B32A32Sfloat, 0 ),
vk::VertexInputAttributeDescription( 1, 0, vk::Format::eR32G32B32A32Sfloat, 16 )
};
vk::PipelineVertexInputStateCreateInfo pipelineVertexInputStateCreateInfo(
{}, vertexInputBindingDescription, vertexInputAttributeDescriptions );
vk::PipelineInputAssemblyStateCreateInfo pipelineInputAssemblyStateCreateInfo(
{}, vk::PrimitiveTopology::eTriangleList );
vk::PipelineViewportStateCreateInfo pipelineViewportStateCreateInfo( {}, 1, nullptr, 1, nullptr );
vk::PipelineRasterizationStateCreateInfo pipelineRasterizationStateCreateInfo( {},
false,
false,
vk::PolygonMode::eFill,
vk::CullModeFlagBits::eBack,
vk::FrontFace::eClockwise,
false,
0.0f,
0.0f,
0.0f,
1.0f );
vk::PipelineMultisampleStateCreateInfo pipelineMultisampleStateCreateInfo( {}, vk::SampleCountFlagBits::e1 );
vk::StencilOpState stencilOpState(
vk::StencilOp::eKeep, vk::StencilOp::eKeep, vk::StencilOp::eKeep, vk::CompareOp::eAlways );
vk::PipelineDepthStencilStateCreateInfo pipelineDepthStencilStateCreateInfo(
{}, true, true, vk::CompareOp::eLessOrEqual, false, false, stencilOpState, stencilOpState );
vk::ColorComponentFlags colorComponentFlags( vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG |
vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA );
vk::PipelineColorBlendAttachmentState pipelineColorBlendAttachmentState( false,
vk::BlendFactor::eZero,
vk::BlendFactor::eZero,
vk::BlendOp::eAdd,
vk::BlendFactor::eZero,
vk::BlendFactor::eZero,
vk::BlendOp::eAdd,
colorComponentFlags );
vk::PipelineColorBlendStateCreateInfo pipelineColorBlendStateCreateInfo(
{}, false, vk::LogicOp::eNoOp, pipelineColorBlendAttachmentState, { { 1.0f, 1.0f, 1.0f, 1.0f } } );
std::array<vk::DynamicState, 2> dynamicStates = { vk::DynamicState::eViewport, vk::DynamicState::eScissor };
vk::PipelineDynamicStateCreateInfo pipelineDynamicStateCreateInfo( {}, dynamicStates );
vk::GraphicsPipelineCreateInfo graphicsPipelineCreateInfo( vk::PipelineCreateFlagBits::eAllowDerivatives,
pipelineShaderStageCreateInfos,
&pipelineVertexInputStateCreateInfo,
&pipelineInputAssemblyStateCreateInfo,
nullptr,
&pipelineViewportStateCreateInfo,
&pipelineRasterizationStateCreateInfo,
&pipelineMultisampleStateCreateInfo,
&pipelineDepthStencilStateCreateInfo,
&pipelineColorBlendStateCreateInfo,
&pipelineDynamicStateCreateInfo,
**pipelineLayout,
**renderPass );
std::unique_ptr<vk::raii::Pipeline> basePipeline =
vk::raii::su::make_unique<vk::raii::Pipeline>( *device, *pipelineCache, graphicsPipelineCreateInfo );
switch ( basePipeline->getConstructorSuccessCode() )
{
case vk::Result::eSuccess: break;
case vk::Result::ePipelineCompileRequiredEXT:
// something meaningfull here
break;
default: assert( false ); // should never happen
}
// Now create the derivative pipeline, using a different fragment shader
// This shader will shade the cube faces with interpolated colors
const std::string fragmentShaderText_T_C_2 = R"(
#version 450
layout (location = 0) in vec2 inTexCoord;
layout (location = 0) out vec4 outColor;
void main()
{
outColor = vec4(inTexCoord.x, inTexCoord.y, 1.0f - inTexCoord.x - inTexCoord.y, 1.0f);
}
)";
// Convert GLSL to SPIR-V
glslang::InitializeProcess();
std::unique_ptr<vk::raii::ShaderModule> fragmentShaderModule2 =
vk::raii::su::makeUniqueShaderModule( *device, vk::ShaderStageFlagBits::eFragment, fragmentShaderText_T_C_2 );
glslang::FinalizeProcess();
// Modify pipeline info to reflect derivation
pipelineShaderStageCreateInfos[1] =
vk::PipelineShaderStageCreateInfo( {}, vk::ShaderStageFlagBits::eFragment, **fragmentShaderModule2, "main" );
graphicsPipelineCreateInfo.flags = vk::PipelineCreateFlagBits::eDerivative;
graphicsPipelineCreateInfo.basePipelineHandle = **basePipeline;
graphicsPipelineCreateInfo.basePipelineIndex = -1;
// And create the derived pipeline
std::unique_ptr<vk::raii::Pipeline> derivedPipeline =
vk::raii::su::make_unique<vk::raii::Pipeline>( *device, *pipelineCache, graphicsPipelineCreateInfo );
switch ( derivedPipeline->getConstructorSuccessCode() )
{
case vk::Result::eSuccess: break;
case vk::Result::ePipelineCompileRequiredEXT:
// something meaningfull here
break;
default: assert( false ); // should never happen
}
/* VULKAN_KEY_END */
std::unique_ptr<vk::raii::Semaphore> imageAcquiredSemaphore =
vk::raii::su::make_unique<vk::raii::Semaphore>( *device, vk::SemaphoreCreateInfo() );
// Get the index of the next available swapchain image
vk::Result result;
uint32_t imageIndex;
std::tie( result, imageIndex ) =
swapChainData.swapChain->acquireNextImage( vk::su::FenceTimeout, **imageAcquiredSemaphore );
assert( result == vk::Result::eSuccess );
assert( imageIndex < swapChainData.images.size() );
std::array<vk::ClearValue, 2> clearValues;
clearValues[0].color = vk::ClearColorValue( std::array<float, 4>( { { 0.2f, 0.2f, 0.2f, 0.2f } } ) );
clearValues[1].depthStencil = vk::ClearDepthStencilValue( 1.0f, 0 );
commandBuffer->beginRenderPass(
vk::RenderPassBeginInfo(
**renderPass, **framebuffers[imageIndex], vk::Rect2D( vk::Offset2D(), surfaceData.extent ), clearValues ),
vk::SubpassContents::eInline );
commandBuffer->bindPipeline( vk::PipelineBindPoint::eGraphics, **derivedPipeline );
commandBuffer->bindDescriptorSets( vk::PipelineBindPoint::eGraphics, **pipelineLayout, 0, { **descriptorSet }, {} );
commandBuffer->bindVertexBuffers( 0, { **vertexBufferData.buffer }, { 0 } );
commandBuffer->setViewport( 0,
vk::Viewport( 0.0f,
0.0f,
static_cast<float>( surfaceData.extent.width ),
static_cast<float>( surfaceData.extent.height ),
0.0f,
1.0f ) );
commandBuffer->setScissor( 0, vk::Rect2D( vk::Offset2D( 0, 0 ), surfaceData.extent ) );
commandBuffer->draw( 12 * 3, 1, 0, 0 );
commandBuffer->endRenderPass();
commandBuffer->end();
std::unique_ptr<vk::raii::Fence> drawFence = vk::raii::su::make_unique<vk::raii::Fence>( *device, vk::FenceCreateInfo() );
vk::PipelineStageFlags waitDestinationStageMask( vk::PipelineStageFlagBits::eColorAttachmentOutput );
vk::SubmitInfo submitInfo( **imageAcquiredSemaphore, waitDestinationStageMask, **commandBuffer );
graphicsQueue->submit( submitInfo, **drawFence );
while ( vk::Result::eTimeout == device->waitForFences( { **drawFence }, VK_TRUE, vk::su::FenceTimeout ) )
;
vk::PresentInfoKHR presentInfoKHR( nullptr, **swapChainData.swapChain, imageIndex );
result = presentQueue->presentKHR( presentInfoKHR );
switch ( result )
{
case vk::Result::eSuccess: break;
case vk::Result::eSuboptimalKHR:
std::cout << "vk::Queue::presentKHR returned vk::Result::eSuboptimalKHR !\n";
break;
default: assert( false ); // an unexpected result is returned !
}
std::this_thread::sleep_for( std::chrono::milliseconds( 1000 ) );
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,35 @@
# Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_PushConstants)
set(HEADERS
)
set(SOURCES
PushConstants.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_PushConstants
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_PushConstants PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_PushConstants PRIVATE utils)

View File

@ -0,0 +1,280 @@
// Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : PushConstants
// Use push constants in a simple shader, validate the correct value was read.
#if defined( _MSC_VER )
// no need to ignore any warnings with MSVC
#elif defined( __clang__ )
# pragma clang diagnostic ignored "-Wmissing-braces"
#elif defined( __GNUC__ )
#else
// unknow compiler... just ignore the warnings for yourselves ;)
#endif
#include "../../samples/utils/geometries.hpp"
#include "../../samples/utils/math.hpp"
#include "../utils/shaders.hpp"
#include "../utils/utils.hpp"
#include "SPIRV/GlslangToSpv.h"
#include "vulkan/vulkan.hpp"
#include <iostream>
#include <thread>
static char const * AppName = "PushConstants";
static char const * EngineName = "Vulkan.hpp";
const std::string fragmentShaderText = R"(
#version 400
#extension GL_ARB_separate_shader_objects : enable
#extension GL_ARB_shading_language_420pack : enable
layout (push_constant) uniform pushBlock
{
int iFoo;
float fBar;
} pushConstantsBlock;
layout (location = 0) in vec2 inTexCoords;
layout (location = 0) out vec4 outColor;
void main()
{
vec4 green = vec4(0.0f, 1.0f, 0.0f, 1.0f);
vec4 red = vec4(1.0f, 0.0f, 0.0f, 1.0f);
// Start with passing color
vec4 resColor = green;
// See if we've read in the correct push constants
if ((pushConstantsBlock.iFoo != 2) || (pushConstantsBlock.fBar != 1.0f))
{
resColor = red;
}
// Create a border to see the cube more easily
if ((inTexCoords.x < 0.01f) || (0.99f < inTexCoords.x)
|| (inTexCoords.y < 0.01f) || (0.99f < inTexCoords.y))
{
resColor *= vec4(0.1f, 0.1f, 0.1f, 1.0f);
}
outColor = resColor;
}
)";
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
std::unique_ptr<vk::raii::Instance> instance =
vk::raii::su::makeUniqueInstance( *context, AppName, EngineName, {}, vk::su::getInstanceExtensions() );
#if !defined( NDEBUG )
std::unique_ptr<vk::raii::DebugUtilsMessengerEXT> debugUtilsMessenger =
vk::raii::su::makeUniqueDebugUtilsMessengerEXT( *instance );
#endif
std::unique_ptr<vk::raii::PhysicalDevice> physicalDevice = vk::raii::su::makeUniquePhysicalDevice( *instance );
vk::raii::su::SurfaceData surfaceData( *instance, AppName, vk::Extent2D( 500, 500 ) );
std::pair<uint32_t, uint32_t> graphicsAndPresentQueueFamilyIndex =
vk::raii::su::findGraphicsAndPresentQueueFamilyIndex( *physicalDevice, *surfaceData.surface );
std::unique_ptr<vk::raii::Device> device = vk::raii::su::makeUniqueDevice(
*physicalDevice, graphicsAndPresentQueueFamilyIndex.first, vk::su::getDeviceExtensions() );
std::unique_ptr<vk::raii::CommandPool> commandPool =
vk::raii::su::makeUniqueCommandPool( *device, graphicsAndPresentQueueFamilyIndex.first );
std::unique_ptr<vk::raii::CommandBuffer> commandBuffer =
vk::raii::su::makeUniqueCommandBuffer( *device, *commandPool );
std::unique_ptr<vk::raii::Queue> graphicsQueue =
vk::raii::su::make_unique<vk::raii::Queue>( *device, graphicsAndPresentQueueFamilyIndex.first, 0 );
std::unique_ptr<vk::raii::Queue> presentQueue =
vk::raii::su::make_unique<vk::raii::Queue>( *device, graphicsAndPresentQueueFamilyIndex.second, 0 );
vk::raii::su::SwapChainData swapChainData( *physicalDevice,
*device,
*surfaceData.surface,
surfaceData.extent,
vk::ImageUsageFlagBits::eColorAttachment |
vk::ImageUsageFlagBits::eTransferSrc,
{},
graphicsAndPresentQueueFamilyIndex.first,
graphicsAndPresentQueueFamilyIndex.second );
vk::raii::su::DepthBufferData depthBufferData(
*physicalDevice, *device, vk::Format::eD16Unorm, surfaceData.extent );
vk::raii::su::BufferData uniformBufferData(
*physicalDevice, *device, sizeof( glm::mat4x4 ), vk::BufferUsageFlagBits::eUniformBuffer );
glm::mat4x4 mvpcMatrix = vk::su::createModelViewProjectionClipMatrix( surfaceData.extent );
vk::raii::su::copyToDevice( *uniformBufferData.deviceMemory, mvpcMatrix );
vk::Format colorFormat =
vk::su::pickSurfaceFormat( physicalDevice->getSurfaceFormatsKHR( **surfaceData.surface ) ).format;
std::unique_ptr<vk::raii::RenderPass> renderPass =
vk::raii::su::makeUniqueRenderPass( *device, colorFormat, depthBufferData.format );
glslang::InitializeProcess();
std::unique_ptr<vk::raii::ShaderModule> vertexShaderModule =
vk::raii::su::makeUniqueShaderModule( *device, vk::ShaderStageFlagBits::eVertex, vertexShaderText_PT_T );
std::unique_ptr<vk::raii::ShaderModule> fragmentShaderModule =
vk::raii::su::makeUniqueShaderModule( *device, vk::ShaderStageFlagBits::eFragment, fragmentShaderText );
glslang::FinalizeProcess();
std::vector<std::unique_ptr<vk::raii::Framebuffer>> framebuffers = vk::raii::su::makeUniqueFramebuffers(
*device, *renderPass, swapChainData.imageViews, depthBufferData.imageView, surfaceData.extent );
vk::raii::su::BufferData vertexBufferData(
*physicalDevice, *device, sizeof( texturedCubeData ), vk::BufferUsageFlagBits::eVertexBuffer );
vk::raii::su::copyToDevice(
*vertexBufferData.deviceMemory, texturedCubeData, sizeof( texturedCubeData ) / sizeof( texturedCubeData[0] ) );
// Create binding and layout for the following, matching contents of shader
// binding 0 = uniform buffer (MVP)
std::unique_ptr<vk::raii::DescriptorSetLayout> descriptorSetLayout = vk::raii::su::makeUniqueDescriptorSetLayout(
*device, { { vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eVertex } } );
/* VULKAN_KEY_START */
// Set up our push constant range, which mirrors the declaration of
vk::PushConstantRange pushConstantRanges( vk::ShaderStageFlagBits::eFragment, 0, 8 );
vk::PipelineLayoutCreateInfo pipelineLayoutCreateInfo( {}, **descriptorSetLayout, pushConstantRanges );
std::unique_ptr<vk::raii::PipelineLayout> pipelineLayout =
vk::raii::su::make_unique<vk::raii::PipelineLayout>( *device, pipelineLayoutCreateInfo );
// Create a single pool to contain data for our descriptor set
std::array<vk::DescriptorPoolSize, 2> poolSizes = { vk::DescriptorPoolSize( vk::DescriptorType::eUniformBuffer, 1 ),
vk::DescriptorPoolSize(
vk::DescriptorType::eCombinedImageSampler, 1 ) };
vk::DescriptorPoolCreateInfo descriptorPoolCreateInfo(
vk::DescriptorPoolCreateFlagBits::eFreeDescriptorSet, 1, poolSizes );
std::unique_ptr<vk::raii::DescriptorPool> descriptorPool =
vk::raii::su::make_unique<vk::raii::DescriptorPool>( *device, descriptorPoolCreateInfo );
// Populate descriptor sets
vk::DescriptorSetAllocateInfo descriptorSetAllocateInfo( **descriptorPool, **descriptorSetLayout );
std::unique_ptr<vk::raii::DescriptorSet> descriptorSet = vk::raii::su::make_unique<vk::raii::DescriptorSet>(
std::move( vk::raii::DescriptorSets( *device, descriptorSetAllocateInfo ).front() ) );
// Populate with info about our uniform buffer for MVP
vk::DescriptorBufferInfo bufferInfo( **uniformBufferData.buffer, 0, sizeof( glm::mat4x4 ) );
vk::WriteDescriptorSet writeDescriptorSet(
**descriptorSet, 0, 0, vk::DescriptorType::eUniformBuffer, {}, bufferInfo );
device->updateDescriptorSets( writeDescriptorSet, nullptr );
// Create our push constant data, which matches shader expectations
std::array<unsigned, 2> pushConstants = { { (unsigned)2, (unsigned)0x3F800000 } };
// Ensure we have enough room for push constant data
assert( ( sizeof( pushConstants ) <= physicalDevice->getProperties().limits.maxPushConstantsSize ) &&
"Too many push constants" );
commandBuffer->begin( vk::CommandBufferBeginInfo() );
commandBuffer->pushConstants<unsigned>( **pipelineLayout, vk::ShaderStageFlagBits::eFragment, 0, pushConstants );
/* VULKAN_KEY_END */
std::unique_ptr<vk::raii::PipelineCache> pipelineCache =
vk::raii::su::make_unique<vk::raii::PipelineCache>( *device, vk::PipelineCacheCreateInfo() );
std::unique_ptr<vk::raii::Pipeline> graphicsPipeline = vk::raii::su::makeUniqueGraphicsPipeline(
*device,
*pipelineCache,
*vertexShaderModule,
nullptr,
*fragmentShaderModule,
nullptr,
sizeof( texturedCubeData[0] ),
{ { vk::Format::eR32G32B32A32Sfloat, 0 }, { vk::Format::eR32G32Sfloat, 16 } },
vk::FrontFace::eClockwise,
true,
*pipelineLayout,
*renderPass );
std::unique_ptr<vk::raii::Semaphore> imageAcquiredSemaphore =
vk::raii::su::make_unique<vk::raii::Semaphore>( *device, vk::SemaphoreCreateInfo() );
vk::Result result;
uint32_t imageIndex;
std::tie( result, imageIndex ) =
swapChainData.swapChain->acquireNextImage( vk::su::FenceTimeout, **imageAcquiredSemaphore );
assert( result == vk::Result::eSuccess );
assert( imageIndex < swapChainData.images.size() );
std::array<vk::ClearValue, 2> clearValues;
clearValues[0].color = vk::ClearColorValue( std::array<float, 4>( { { 0.2f, 0.2f, 0.2f, 0.2f } } ) );
clearValues[1].depthStencil = vk::ClearDepthStencilValue( 1.0f, 0 );
vk::RenderPassBeginInfo renderPassBeginInfo(
**renderPass, **framebuffers[imageIndex], vk::Rect2D( vk::Offset2D( 0, 0 ), surfaceData.extent ), clearValues );
commandBuffer->beginRenderPass( renderPassBeginInfo, vk::SubpassContents::eInline );
commandBuffer->bindPipeline( vk::PipelineBindPoint::eGraphics, **graphicsPipeline );
commandBuffer->bindDescriptorSets(
vk::PipelineBindPoint::eGraphics, **pipelineLayout, 0, { **descriptorSet }, nullptr );
commandBuffer->bindVertexBuffers( 0, { **vertexBufferData.buffer }, { 0 } );
commandBuffer->setViewport( 0,
vk::Viewport( 0.0f,
0.0f,
static_cast<float>( surfaceData.extent.width ),
static_cast<float>( surfaceData.extent.height ),
0.0f,
1.0f ) );
commandBuffer->setScissor( 0, vk::Rect2D( vk::Offset2D( 0, 0 ), surfaceData.extent ) );
commandBuffer->draw( 12 * 3, 1, 0, 0 );
commandBuffer->endRenderPass();
commandBuffer->end();
std::unique_ptr<vk::raii::Fence> drawFence = vk::raii::su::make_unique<vk::raii::Fence>( *device, vk::FenceCreateInfo() );
vk::PipelineStageFlags waitDestinationStageMask( vk::PipelineStageFlagBits::eColorAttachmentOutput );
vk::SubmitInfo submitInfo( **imageAcquiredSemaphore, waitDestinationStageMask, **commandBuffer );
graphicsQueue->submit( submitInfo, **drawFence );
while ( vk::Result::eTimeout == device->waitForFences( { **drawFence }, VK_TRUE, vk::su::FenceTimeout ) )
;
vk::PresentInfoKHR presentInfoKHR( nullptr, **swapChainData.swapChain, imageIndex );
result = presentQueue->presentKHR( presentInfoKHR );
switch ( result )
{
case vk::Result::eSuccess: break;
case vk::Result::eSuboptimalKHR:
std::cout << "vk::Queue::presentKHR returned vk::Result::eSuboptimalKHR !\n";
break;
default: assert( false ); // an unexpected result is returned !
}
std::this_thread::sleep_for( std::chrono::milliseconds( 1000 ) );
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,35 @@
# Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_PushDescriptors)
set(HEADERS
)
set(SOURCES
PushDescriptors.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_PushDescriptors
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_PushDescriptors PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_PushDescriptors PRIVATE utils)

View File

@ -0,0 +1,247 @@
// Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : PushDescriptors
// Use Push Descriptors to Draw Textured Cube
#include "../../samples/utils/geometries.hpp"
#include "../../samples/utils/math.hpp"
#include "../utils/shaders.hpp"
#include "../utils/utils.hpp"
#include "SPIRV/GlslangToSpv.h"
#include "vulkan/vulkan.hpp"
#include <iostream>
#include <thread>
static char const * AppName = "PushDescriptors";
static char const * EngineName = "Vulkan.hpp";
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
/* VULKAN_KEY_START */
// To use PUSH_DESCRIPTOR, you must also specify GET_PHYSICAL_DEVICE_PROPERTIES_2
std::vector<vk::ExtensionProperties> extensionProperties = context->enumerateInstanceExtensionProperties();
auto propertyIterator =
std::find_if( extensionProperties.begin(), extensionProperties.end(), []( vk::ExtensionProperties ep ) {
return ( strcmp( ep.extensionName, VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME ) == 0 );
} );
if ( propertyIterator == extensionProperties.end() )
{
std::cout << "No GET_PHYSICAL_DEVICE_PROPERTIES_2 extension" << std::endl;
return 0;
}
std::vector<std::string> instanceExtensions = vk::su::getInstanceExtensions();
instanceExtensions.push_back( VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME );
std::unique_ptr<vk::raii::Instance> instance =
vk::raii::su::makeUniqueInstance( *context, AppName, EngineName, {}, instanceExtensions );
#if !defined( NDEBUG )
std::unique_ptr<vk::raii::DebugUtilsMessengerEXT> debugUtilsMessenger =
vk::raii::su::makeUniqueDebugUtilsMessengerEXT( *instance );
#endif
std::unique_ptr<vk::raii::PhysicalDevice> physicalDevice = vk::raii::su::makeUniquePhysicalDevice( *instance );
// Once instance is created, need to make sure the extension is available
extensionProperties = physicalDevice->enumerateDeviceExtensionProperties();
propertyIterator =
std::find_if( extensionProperties.begin(), extensionProperties.end(), []( vk::ExtensionProperties ep ) {
return ( strcmp( ep.extensionName, VK_KHR_PUSH_DESCRIPTOR_EXTENSION_NAME ) == 0 );
} );
if ( propertyIterator == extensionProperties.end() )
{
std::cout << "No extension for push descriptors" << std::endl;
return 0;
}
std::vector<std::string> deviceExtensions = vk::su::getDeviceExtensions();
deviceExtensions.push_back( VK_KHR_PUSH_DESCRIPTOR_EXTENSION_NAME );
vk::raii::su::SurfaceData surfaceData( *instance, AppName, vk::Extent2D( 500, 500 ) );
std::pair<uint32_t, uint32_t> graphicsAndPresentQueueFamilyIndex =
vk::raii::su::findGraphicsAndPresentQueueFamilyIndex( *physicalDevice, *surfaceData.surface );
std::unique_ptr<vk::raii::Device> device =
vk::raii::su::makeUniqueDevice( *physicalDevice, graphicsAndPresentQueueFamilyIndex.first, deviceExtensions );
std::unique_ptr<vk::raii::CommandPool> commandPool =
vk::raii::su::makeUniqueCommandPool( *device, graphicsAndPresentQueueFamilyIndex.first );
std::unique_ptr<vk::raii::CommandBuffer> commandBuffer =
vk::raii::su::makeUniqueCommandBuffer( *device, *commandPool );
std::unique_ptr<vk::raii::Queue> graphicsQueue =
vk::raii::su::make_unique<vk::raii::Queue>( *device, graphicsAndPresentQueueFamilyIndex.first, 0 );
std::unique_ptr<vk::raii::Queue> presentQueue =
vk::raii::su::make_unique<vk::raii::Queue>( *device, graphicsAndPresentQueueFamilyIndex.second, 0 );
vk::raii::su::SwapChainData swapChainData( *physicalDevice,
*device,
*surfaceData.surface,
surfaceData.extent,
vk::ImageUsageFlagBits::eColorAttachment |
vk::ImageUsageFlagBits::eTransferSrc,
{},
graphicsAndPresentQueueFamilyIndex.first,
graphicsAndPresentQueueFamilyIndex.second );
vk::raii::su::DepthBufferData depthBufferData(
*physicalDevice, *device, vk::Format::eD16Unorm, surfaceData.extent );
vk::raii::su::TextureData textureData( *physicalDevice, *device );
commandBuffer->begin( vk::CommandBufferBeginInfo() );
textureData.setImage( *commandBuffer, vk::su::CheckerboardImageGenerator() );
vk::raii::su::BufferData uniformBufferData(
*physicalDevice, *device, sizeof( glm::mat4x4 ), vk::BufferUsageFlagBits::eUniformBuffer );
glm::mat4x4 mvpcMatrix = vk::su::createModelViewProjectionClipMatrix( surfaceData.extent );
vk::raii::su::copyToDevice( *uniformBufferData.deviceMemory, mvpcMatrix );
// Need to specify that descriptor set layout will be for push descriptors
std::unique_ptr<vk::raii::DescriptorSetLayout> descriptorSetLayout = vk::raii::su::makeUniqueDescriptorSetLayout(
*device,
{ { vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eVertex },
{ vk::DescriptorType::eCombinedImageSampler, 1, vk::ShaderStageFlagBits::eFragment } },
vk::DescriptorSetLayoutCreateFlagBits::ePushDescriptorKHR );
std::unique_ptr<vk::raii::PipelineLayout> pipelineLayout =
vk::raii::su::makeUniquePipelineLayout( *device, *descriptorSetLayout );
vk::Format colorFormat =
vk::su::pickSurfaceFormat( physicalDevice->getSurfaceFormatsKHR( **surfaceData.surface ) ).format;
std::unique_ptr<vk::raii::RenderPass> renderPass =
vk::raii::su::makeUniqueRenderPass( *device, colorFormat, depthBufferData.format );
glslang::InitializeProcess();
std::unique_ptr<vk::raii::ShaderModule> vertexShaderModule =
vk::raii::su::makeUniqueShaderModule( *device, vk::ShaderStageFlagBits::eVertex, vertexShaderText_PT_T );
std::unique_ptr<vk::raii::ShaderModule> fragmentShaderModule =
vk::raii::su::makeUniqueShaderModule( *device, vk::ShaderStageFlagBits::eFragment, fragmentShaderText_T_C );
glslang::FinalizeProcess();
std::vector<std::unique_ptr<vk::raii::Framebuffer>> framebuffers = vk::raii::su::makeUniqueFramebuffers(
*device, *renderPass, swapChainData.imageViews, depthBufferData.imageView, surfaceData.extent );
vk::raii::su::BufferData vertexBufferData(
*physicalDevice, *device, sizeof( texturedCubeData ), vk::BufferUsageFlagBits::eVertexBuffer );
vk::raii::su::copyToDevice(
*vertexBufferData.deviceMemory, texturedCubeData, sizeof( texturedCubeData ) / sizeof( texturedCubeData[0] ) );
std::unique_ptr<vk::raii::PipelineCache> pipelineCache =
vk::raii::su::make_unique<vk::raii::PipelineCache>( *device, vk::PipelineCacheCreateInfo() );
std::unique_ptr<vk::raii::Pipeline> graphicsPipeline = vk::raii::su::makeUniqueGraphicsPipeline(
*device,
*pipelineCache,
*vertexShaderModule,
nullptr,
*fragmentShaderModule,
nullptr,
sizeof( texturedCubeData[0] ),
{ { vk::Format::eR32G32B32A32Sfloat, 0 }, { vk::Format::eR32G32Sfloat, 16 } },
vk::FrontFace::eClockwise,
true,
*pipelineLayout,
*renderPass );
// Get the index of the next available swapchain image:
std::unique_ptr<vk::raii::Semaphore> imageAcquiredSemaphore =
vk::raii::su::make_unique<vk::raii::Semaphore>( *device, vk::SemaphoreCreateInfo() );
vk::Result result;
uint32_t imageIndex;
std::tie( result, imageIndex ) =
swapChainData.swapChain->acquireNextImage( vk::su::FenceTimeout, **imageAcquiredSemaphore );
assert( result == vk::Result::eSuccess );
assert( imageIndex < swapChainData.images.size() );
std::array<vk::ClearValue, 2> clearValues;
clearValues[0].color = vk::ClearColorValue( std::array<float, 4>( { { 0.2f, 0.2f, 0.2f, 0.2f } } ) );
clearValues[1].depthStencil = vk::ClearDepthStencilValue( 1.0f, 0 );
vk::RenderPassBeginInfo renderPassBeginInfo(
**renderPass, **framebuffers[imageIndex], vk::Rect2D( vk::Offset2D( 0, 0 ), surfaceData.extent ), clearValues );
commandBuffer->beginRenderPass( renderPassBeginInfo, vk::SubpassContents::eInline );
commandBuffer->bindPipeline( vk::PipelineBindPoint::eGraphics, **graphicsPipeline );
vk::DescriptorBufferInfo bufferInfo( **uniformBufferData.buffer, 0, sizeof( glm::mat4x4 ) );
vk::DescriptorImageInfo imageInfo(
**textureData.sampler, **textureData.imageData->imageView, vk::ImageLayout::eShaderReadOnlyOptimal );
vk::WriteDescriptorSet writeDescriptorSets[2] = {
vk::WriteDescriptorSet( {}, 0, 0, vk::DescriptorType::eUniformBuffer, {}, bufferInfo ),
vk::WriteDescriptorSet( {}, 1, 0, vk::DescriptorType::eCombinedImageSampler, imageInfo )
};
// this call is from an extension and needs the dynamic dispatcher !!
commandBuffer->pushDescriptorSetKHR(
vk::PipelineBindPoint::eGraphics, **pipelineLayout, 0, { 2, writeDescriptorSets } );
commandBuffer->bindVertexBuffers( 0, { **vertexBufferData.buffer }, { 0 } );
commandBuffer->setViewport( 0,
vk::Viewport( 0.0f,
0.0f,
static_cast<float>( surfaceData.extent.width ),
static_cast<float>( surfaceData.extent.height ),
0.0f,
1.0f ) );
commandBuffer->setScissor( 0, vk::Rect2D( vk::Offset2D( 0, 0 ), surfaceData.extent ) );
commandBuffer->draw( 12 * 3, 1, 0, 0 );
commandBuffer->endRenderPass();
commandBuffer->end();
std::unique_ptr<vk::raii::Fence> drawFence = vk::raii::su::make_unique<vk::raii::Fence>( *device, vk::FenceCreateInfo() );
vk::PipelineStageFlags waitDestinationStageMask( vk::PipelineStageFlagBits::eColorAttachmentOutput );
vk::SubmitInfo submitInfo( **imageAcquiredSemaphore, waitDestinationStageMask, **commandBuffer );
graphicsQueue->submit( submitInfo, **drawFence );
while ( vk::Result::eTimeout == device->waitForFences( { **drawFence }, VK_TRUE, vk::su::FenceTimeout ) )
;
vk::PresentInfoKHR presentInfoKHR( nullptr, **swapChainData.swapChain, imageIndex );
result = presentQueue->presentKHR( presentInfoKHR );
switch ( result )
{
case vk::Result::eSuccess: break;
case vk::Result::eSuboptimalKHR:
std::cout << "vk::Queue::presentKHR returned vk::Result::eSuboptimalKHR !\n";
break;
default: assert( false ); // an unexpected result is returned !
}
std::this_thread::sleep_for( std::chrono::milliseconds( 1000 ) );
/* VULKAN_KEY_END */
device->waitIdle();
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,43 @@
# Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_RayTracing)
set(HEADERS
CameraManipulator.hpp
)
set(SOURCES
CameraManipulator.cpp
RayTracing.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_RayTracing
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_RayTracing PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_RayTracing PRIVATE utils)
target_include_directories(RAII_RayTracing PUBLIC
${CMAKE_SOURCE_DIR}/samples/RayTracing/common
${CMAKE_SOURCE_DIR}/samples/RayTracing/vulkannv
${CMAKE_SOURCE_DIR}/stb
${CMAKE_SOURCE_DIR}/tinyobjloader
)

View File

@ -0,0 +1,439 @@
// Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ignore warning 4127: conditional expression is constant
#if defined( _MSC_VER )
# pragma warning( disable : 4127 )
#elif defined( __clang__ )
# if ( 10 <= __clang_major__ )
# pragma clang diagnostic ignored "-Wdeprecated-volatile" // to keep glm/detail/type_half.inl compiling
# endif
#elif defined( __GNUC__ )
// don't know how to switch off that warning here
#else
// unknow compiler... just ignore the warnings for yourselves ;)
#endif
#include "CameraManipulator.hpp"
#include <glm/glm.hpp>
#include <glm/gtx/rotate_vector.hpp>
namespace vk
{
namespace su
{
const float trackballSize = 0.8f;
//-----------------------------------------------------------------------------
// MATH functions
//
template <typename T>
bool isZero( const T & _a )
{
return fabs( _a ) < std::numeric_limits<T>::epsilon();
}
template <typename T>
bool isOne( const T & _a )
{
return areEqual( _a, (T)1 );
}
inline float sign( float s )
{
return ( s < 0.f ) ? -1.f : 1.f;
}
CameraManipulator::CameraManipulator()
{
update();
}
glm::vec3 const & CameraManipulator::getCameraPosition() const
{
return m_cameraPosition;
}
glm::vec3 const & CameraManipulator::getCenterPosition() const
{
return m_centerPosition;
}
glm::mat4 const & CameraManipulator::getMatrix() const
{
return m_matrix;
}
CameraManipulator::Mode CameraManipulator::getMode() const
{
return m_mode;
}
glm::ivec2 const & CameraManipulator::getMousePosition() const
{
return m_mousePosition;
}
float CameraManipulator::getRoll() const
{
return m_roll;
}
float CameraManipulator::getSpeed() const
{
return m_speed;
}
glm::vec3 const & CameraManipulator::getUpVector() const
{
return m_upVector;
}
glm::u32vec2 const & CameraManipulator::getWindowSize() const
{
return m_windowSize;
}
CameraManipulator::Action
CameraManipulator::mouseMove( glm::ivec2 const & position, MouseButton mouseButton, ModifierFlags & modifiers )
{
Action curAction = Action::None;
switch ( mouseButton )
{
case MouseButton::Left:
if ( ( ( modifiers & ModifierFlagBits::Ctrl ) && ( modifiers & ModifierFlagBits::Shift ) ) ||
( modifiers & ModifierFlagBits::Alt ) )
{
curAction = m_mode == Mode::Examine ? Action::LookAround : Action::Orbit;
}
else if ( modifiers & ModifierFlagBits::Shift )
{
curAction = Action::Dolly;
}
else if ( modifiers & ModifierFlagBits::Ctrl )
{
curAction = Action::Pan;
}
else
{
curAction = m_mode == Mode::Examine ? Action::Orbit : Action::LookAround;
}
break;
case MouseButton::Middle: curAction = Action::Pan; break;
case MouseButton::Right: curAction = Action::Dolly; break;
default: assert( false );
}
assert( curAction != Action::None );
motion( position, curAction );
return curAction;
}
void CameraManipulator::setLookat( const glm::vec3 & cameraPosition,
const glm::vec3 & centerPosition,
const glm::vec3 & upVector )
{
m_cameraPosition = cameraPosition;
m_centerPosition = centerPosition;
m_upVector = upVector;
update();
}
void CameraManipulator::setMode( Mode mode )
{
m_mode = mode;
}
void CameraManipulator::setMousePosition( glm::ivec2 const & position )
{
m_mousePosition = position;
}
void CameraManipulator::setRoll( float roll )
{
m_roll = roll;
update();
}
void CameraManipulator::setSpeed( float speed )
{
m_speed = speed;
}
void CameraManipulator::setWindowSize( glm::ivec2 const & size )
{
m_windowSize = size;
}
void CameraManipulator::wheel( int value )
{
float fValue = static_cast<float>( value );
float dx = ( fValue * std::abs( fValue ) ) / static_cast<float>( m_windowSize[0] );
glm::vec3 z = m_cameraPosition - m_centerPosition;
float length = z.length() * 0.1f;
length = length < 0.001f ? 0.001f : length;
dx *= m_speed;
dolly( glm::vec2( dx, dx ) );
update();
}
void CameraManipulator::dolly( glm::vec2 const & delta )
{
glm::vec3 z = m_centerPosition - m_cameraPosition;
float length = glm::length( z );
// We are at the point of interest, and don't know any direction, so do nothing!
if ( isZero( length ) )
{
return;
}
// Use the larger movement.
float dd;
if ( m_mode != Mode::Examine )
{
dd = -delta[1];
}
else
{
dd = fabs( delta[0] ) > fabs( delta[1] ) ? delta[0] : -delta[1];
}
float factor = m_speed * dd / length;
// Adjust speed based on distance.
length /= 10;
length = length < 0.001f ? 0.001f : length;
factor *= length;
// Don't move to or through the point of interest.
if ( 1.0f <= factor )
{
return;
}
z *= factor;
// Not going up
if ( m_mode == Mode::Walk )
{
if ( m_upVector.y > m_upVector.z )
{
z.y = 0;
}
else
{
z.z = 0;
}
}
m_cameraPosition += z;
// In fly mode, the interest moves with us.
if ( m_mode != Mode::Examine )
{
m_centerPosition += z;
}
}
void CameraManipulator::motion( glm::ivec2 const & position, Action action )
{
glm::vec2 delta( float( position[0] - m_mousePosition[0] ) / float( m_windowSize[0] ),
float( position[1] - m_mousePosition[1] ) / float( m_windowSize[1] ) );
switch ( action )
{
case Action::Orbit:
if ( m_mode == Mode::Trackball )
{
orbit( delta, true ); // trackball(position);
}
else
{
orbit( delta, false );
}
break;
case Action::Dolly: dolly( delta ); break;
case Action::Pan: pan( delta ); break;
case Action::LookAround:
if ( m_mode == Mode::Trackball )
{
trackball( position );
}
else
{
orbit( glm::vec2( delta[0], -delta[1] ), true );
}
break;
default: break;
}
update();
m_mousePosition = position;
}
void CameraManipulator::orbit( glm::vec2 const & delta, bool invert )
{
if ( isZero( delta[0] ) && isZero( delta[1] ) )
{
return;
}
// Full width will do a full turn
float dx = delta[0] * float( glm::two_pi<float>() );
float dy = delta[1] * float( glm::two_pi<float>() );
// Get the camera
glm::vec3 origin( invert ? m_cameraPosition : m_centerPosition );
glm::vec3 position( invert ? m_centerPosition : m_cameraPosition );
// Get the length of sight
glm::vec3 centerToEye( position - origin );
float radius = glm::length( centerToEye );
centerToEye = glm::normalize( centerToEye );
// Find the rotation around the UP axis (Y)
glm::vec3 zAxis( centerToEye );
glm::mat4 yRotation = glm::rotate( -dx, m_upVector );
// Apply the (Y) rotation to the eye-center vector
glm::vec4 tmpVector = yRotation * glm::vec4( centerToEye.x, centerToEye.y, centerToEye.z, 0.0f );
centerToEye = glm::vec3( tmpVector.x, tmpVector.y, tmpVector.z );
// Find the rotation around the X vector: cross between eye-center and up (X)
glm::vec3 xAxis = glm::cross( m_upVector, zAxis );
xAxis = glm::normalize( xAxis );
glm::mat4 xRotation = glm::rotate( -dy, xAxis );
// Apply the (X) rotation to the eye-center vector
tmpVector = xRotation * glm::vec4( centerToEye.x, centerToEye.y, centerToEye.z, 0 );
glm::vec3 rotatedVector( tmpVector.x, tmpVector.y, tmpVector.z );
if ( sign( rotatedVector.x ) == sign( centerToEye.x ) )
{
centerToEye = rotatedVector;
}
// Make the vector as long as it was originally
centerToEye *= radius;
// Finding the new position
glm::vec3 newPosition = centerToEye + origin;
if ( !invert )
{
m_cameraPosition = newPosition; // Normal: change the position of the camera
}
else
{
m_centerPosition = newPosition; // Inverted: change the interest point
}
}
void CameraManipulator::pan( glm::vec2 const & delta )
{
glm::vec3 z( m_cameraPosition - m_centerPosition );
float length = static_cast<float>( glm::length( z ) ) / 0.785f; // 45 degrees
z = glm::normalize( z );
glm::vec3 x = glm::normalize( glm::cross( m_upVector, z ) );
glm::vec3 y = glm::normalize( glm::cross( z, x ) );
x *= -delta[0] * length;
y *= delta[1] * length;
if ( m_mode == Mode::Fly )
{
x = -x;
y = -y;
}
m_cameraPosition += x + y;
m_centerPosition += x + y;
}
double CameraManipulator::projectOntoTBSphere( const glm::vec2 & p )
{
double z;
double d = length( p );
if ( d < trackballSize * 0.70710678118654752440 )
{
// inside sphere
z = sqrt( trackballSize * trackballSize - d * d );
}
else
{
// on hyperbola
double t = trackballSize / 1.41421356237309504880;
z = t * t / d;
}
return z;
}
void CameraManipulator::trackball( glm::ivec2 const & position )
{
glm::vec2 p0( 2 * ( m_mousePosition[0] - m_windowSize[0] / 2 ) / double( m_windowSize[0] ),
2 * ( m_windowSize[1] / 2 - m_mousePosition[1] ) / double( m_windowSize[1] ) );
glm::vec2 p1( 2 * ( position[0] - m_windowSize[0] / 2 ) / double( m_windowSize[0] ),
2 * ( m_windowSize[1] / 2 - position[1] ) / double( m_windowSize[1] ) );
// determine the z coordinate on the sphere
glm::vec3 pTB0( p0[0], p0[1], projectOntoTBSphere( p0 ) );
glm::vec3 pTB1( p1[0], p1[1], projectOntoTBSphere( p1 ) );
// calculate the rotation axis via cross product between p0 and p1
glm::vec3 axis = glm::cross( pTB0, pTB1 );
axis = glm::normalize( axis );
// calculate the angle
float t = glm::length( pTB0 - pTB1 ) / ( 2.f * trackballSize );
// clamp between -1 and 1
if ( t > 1.0f )
{
t = 1.0f;
}
else if ( t < -1.0f )
{
t = -1.0f;
}
float rad = 2.0f * asin( t );
{
glm::vec4 rot_axis = m_matrix * glm::vec4( axis, 0 );
glm::mat4 rot_mat = glm::rotate( rad, glm::vec3( rot_axis.x, rot_axis.y, rot_axis.z ) );
glm::vec3 pnt = m_cameraPosition - m_centerPosition;
glm::vec4 pnt2 = rot_mat * glm::vec4( pnt.x, pnt.y, pnt.z, 1 );
m_cameraPosition = m_centerPosition + glm::vec3( pnt2.x, pnt2.y, pnt2.z );
glm::vec4 up2 = rot_mat * glm::vec4( m_upVector.x, m_upVector.y, m_upVector.z, 0 );
m_upVector = glm::vec3( up2.x, up2.y, up2.z );
}
}
void CameraManipulator::update()
{
m_matrix = glm::lookAt( m_cameraPosition, m_centerPosition, m_upVector );
if ( !isZero( m_roll ) )
{
glm::mat4 rot = glm::rotate( m_roll, glm::vec3( 0, 0, 1 ) );
m_matrix = m_matrix * rot;
}
}
} // namespace su
} // namespace vk

View File

@ -0,0 +1,89 @@
// Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#pragma once
#if defined( _MSC_VER )
# pragma warning( push )
# pragma warning( disable : 4127 ) // conditional expression is constant (glm)
#endif
#include <glm/glm.hpp>
#if defined( _MSC_VER )
# pragma warning( pop )
#endif
#include <vulkan/vulkan.hpp>
namespace vk
{
namespace su
{
class CameraManipulator
{
public:
enum class Action { None, Orbit, Dolly, Pan, LookAround };
enum class Mode { Examine, Fly, Walk, Trackball };
enum class MouseButton { None, Left, Middle, Right };
enum class ModifierFlagBits : uint32_t { Shift = 1, Ctrl = 2, Alt = 4 };
using ModifierFlags = vk::Flags<ModifierFlagBits>;
public:
CameraManipulator();
glm::vec3 const& getCameraPosition() const;
glm::vec3 const& getCenterPosition() const;
glm::mat4 const& getMatrix() const;
Mode getMode() const;
glm::ivec2 const& getMousePosition() const;
float getRoll() const;
float getSpeed() const;
glm::vec3 const& getUpVector() const;
glm::u32vec2 const& getWindowSize() const;
Action mouseMove(glm::ivec2 const& position, MouseButton mouseButton, ModifierFlags & modifiers);
void setLookat(const glm::vec3& cameraPosition, const glm::vec3& centerPosition, const glm::vec3& upVector);
void setMode(Mode mode);
void setMousePosition(glm::ivec2 const& position);
void setRoll(float roll); // roll in radians
void setSpeed(float speed);
void setWindowSize(glm::ivec2 const& size);
void wheel(int value);
private:
void dolly(glm::vec2 const& delta);
void motion(glm::ivec2 const& position, Action action = Action::None);
void orbit(glm::vec2 const& delta, bool invert = false);
void pan(glm::vec2 const& delta);
double projectOntoTBSphere(const glm::vec2& p);
void trackball(glm::ivec2 const& position);
void update();
private:
glm::vec3 m_cameraPosition = glm::vec3(10, 10, 10);
glm::vec3 m_centerPosition = glm::vec3(0, 0, 0);
glm::vec3 m_upVector = glm::vec3(0, 1, 0);
float m_roll = 0; // Rotation around the Z axis in RAD
glm::mat4 m_matrix = glm::mat4(1);
glm::u32vec2 m_windowSize = glm::u32vec2(1, 1);
float m_speed = 30.0f;
glm::ivec2 m_mousePosition = glm::ivec2(0, 0);
Mode m_mode = Mode::Examine;
};
} // namespace su
} // namespace vk

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,35 @@
# Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_SecondaryCommandBuffer)
set(HEADERS
)
set(SOURCES
SecondaryCommandBuffer.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_SecondaryCommandBuffer
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_SecondaryCommandBuffer PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_SecondaryCommandBuffer PRIVATE utils)

View File

@ -0,0 +1,282 @@
// Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : SecondaryCommandBuffer
// Draw several cubes using primary and secondary command buffers
#if defined( _MSC_VER )
// no need to ignore any warnings with MSVC
#elif defined( __clang__ )
# pragma clang diagnostic ignored "-Wmissing-braces"
#elif defined( __GNUC__ )
// no need to ignore any warnings with GCC
#else
// unknow compiler... just ignore the warnings for yourselves ;)
#endif
#include "../../samples/utils/geometries.hpp"
#include "../../samples/utils/math.hpp"
#include "../utils/shaders.hpp"
#include "../utils/utils.hpp"
#include "SPIRV/GlslangToSpv.h"
#include "vulkan/vulkan.hpp"
#include <iostream>
#include <thread>
static char const * AppName = "SecondaryCommandBuffer";
static char const * EngineName = "Vulkan.hpp";
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
std::unique_ptr<vk::raii::Instance> instance =
vk::raii::su::makeUniqueInstance( *context, AppName, EngineName, {}, vk::su::getInstanceExtensions() );
#if !defined( NDEBUG )
std::unique_ptr<vk::raii::DebugUtilsMessengerEXT> debugUtilsMessenger =
vk::raii::su::makeUniqueDebugUtilsMessengerEXT( *instance );
#endif
std::unique_ptr<vk::raii::PhysicalDevice> physicalDevice = vk::raii::su::makeUniquePhysicalDevice( *instance );
vk::raii::su::SurfaceData surfaceData( *instance, AppName, vk::Extent2D( 500, 500 ) );
std::pair<uint32_t, uint32_t> graphicsAndPresentQueueFamilyIndex =
vk::raii::su::findGraphicsAndPresentQueueFamilyIndex( *physicalDevice, *surfaceData.surface );
std::unique_ptr<vk::raii::Device> device = vk::raii::su::makeUniqueDevice(
*physicalDevice, graphicsAndPresentQueueFamilyIndex.first, vk::su::getDeviceExtensions() );
std::unique_ptr<vk::raii::CommandPool> commandPool =
vk::raii::su::makeUniqueCommandPool( *device, graphicsAndPresentQueueFamilyIndex.first );
std::unique_ptr<vk::raii::CommandBuffer> commandBuffer =
vk::raii::su::makeUniqueCommandBuffer( *device, *commandPool );
std::unique_ptr<vk::raii::Queue> graphicsQueue =
vk::raii::su::make_unique<vk::raii::Queue>( *device, graphicsAndPresentQueueFamilyIndex.first, 0 );
std::unique_ptr<vk::raii::Queue> presentQueue =
vk::raii::su::make_unique<vk::raii::Queue>( *device, graphicsAndPresentQueueFamilyIndex.second, 0 );
vk::raii::su::SwapChainData swapChainData( *physicalDevice,
*device,
*surfaceData.surface,
surfaceData.extent,
vk::ImageUsageFlagBits::eColorAttachment |
vk::ImageUsageFlagBits::eTransferSrc,
{},
graphicsAndPresentQueueFamilyIndex.first,
graphicsAndPresentQueueFamilyIndex.second );
vk::raii::su::DepthBufferData depthBufferData(
*physicalDevice, *device, vk::Format::eD16Unorm, surfaceData.extent );
vk::raii::su::BufferData uniformBufferData(
*physicalDevice, *device, sizeof( glm::mat4x4 ), vk::BufferUsageFlagBits::eUniformBuffer );
glm::mat4x4 mvpcMatrix = vk::su::createModelViewProjectionClipMatrix( surfaceData.extent );
vk::raii::su::copyToDevice( *uniformBufferData.deviceMemory, mvpcMatrix );
std::unique_ptr<vk::raii::DescriptorSetLayout> descriptorSetLayout = vk::raii::su::makeUniqueDescriptorSetLayout(
*device,
{ { vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eVertex },
{ vk::DescriptorType::eCombinedImageSampler, 1, vk::ShaderStageFlagBits::eFragment } } );
std::unique_ptr<vk::raii::PipelineLayout> pipelineLayout =
vk::raii::su::makeUniquePipelineLayout( *device, *descriptorSetLayout );
vk::Format colorFormat =
vk::su::pickSurfaceFormat( physicalDevice->getSurfaceFormatsKHR( **surfaceData.surface ) ).format;
std::unique_ptr<vk::raii::RenderPass> renderPass =
vk::raii::su::makeUniqueRenderPass( *device,
colorFormat,
depthBufferData.format,
vk::AttachmentLoadOp::eClear,
vk::ImageLayout::eColorAttachmentOptimal );
glslang::InitializeProcess();
std::unique_ptr<vk::raii::ShaderModule> vertexShaderModule =
vk::raii::su::makeUniqueShaderModule( *device, vk::ShaderStageFlagBits::eVertex, vertexShaderText_PT_T );
std::unique_ptr<vk::raii::ShaderModule> fragmentShaderModule =
vk::raii::su::makeUniqueShaderModule( *device, vk::ShaderStageFlagBits::eFragment, fragmentShaderText_T_C );
glslang::FinalizeProcess();
std::vector<std::unique_ptr<vk::raii::Framebuffer>> framebuffers = vk::raii::su::makeUniqueFramebuffers(
*device, *renderPass, swapChainData.imageViews, depthBufferData.imageView, surfaceData.extent );
vk::raii::su::BufferData vertexBufferData(
*physicalDevice, *device, sizeof( texturedCubeData ), vk::BufferUsageFlagBits::eVertexBuffer );
vk::raii::su::copyToDevice(
*vertexBufferData.deviceMemory, texturedCubeData, sizeof( texturedCubeData ) / sizeof( texturedCubeData[0] ) );
std::unique_ptr<vk::raii::PipelineCache> pipelineCache =
vk::raii::su::make_unique<vk::raii::PipelineCache>( *device, vk::PipelineCacheCreateInfo() );
std::unique_ptr<vk::raii::Pipeline> graphicsPipeline = vk::raii::su::makeUniqueGraphicsPipeline(
*device,
*pipelineCache,
*vertexShaderModule,
nullptr,
*fragmentShaderModule,
nullptr,
sizeof( texturedCubeData[0] ),
{ { vk::Format::eR32G32B32A32Sfloat, 0 }, { vk::Format::eR32G32Sfloat, 16 } },
vk::FrontFace::eClockwise,
true,
*pipelineLayout,
*renderPass );
commandBuffer->begin( vk::CommandBufferBeginInfo() );
vk::raii::su::TextureData greenTextureData( *physicalDevice, *device );
greenTextureData.setImage( *commandBuffer, vk::su::MonochromeImageGenerator( { 118, 185, 0 } ) );
vk::raii::su::TextureData checkeredTextureData( *physicalDevice, *device );
checkeredTextureData.setImage( *commandBuffer, vk::su::CheckerboardImageGenerator() );
// create two identical descriptor sets, each with a different texture but identical UBOs
std::unique_ptr<vk::raii::DescriptorPool> descriptorPool = vk::raii::su::makeUniqueDescriptorPool(
*device, { { vk::DescriptorType::eUniformBuffer, 2 }, { vk::DescriptorType::eCombinedImageSampler, 2 } } );
std::array<vk::DescriptorSetLayout, 2> layouts = { **descriptorSetLayout, **descriptorSetLayout };
vk::DescriptorSetAllocateInfo descriptorSetAllocateInfo( **descriptorPool, layouts );
vk::raii::DescriptorSets descriptorSets( *device, descriptorSetAllocateInfo );
assert( descriptorSets.size() == 2 );
vk::raii::su::updateDescriptorSets( *device,
descriptorSets[0],
{ { vk::DescriptorType::eUniformBuffer, *uniformBufferData.buffer, {} } },
greenTextureData );
vk::raii::su::updateDescriptorSets( *device,
descriptorSets[1],
{ { vk::DescriptorType::eUniformBuffer, *uniformBufferData.buffer, {} } },
checkeredTextureData );
/* VULKAN_KEY_START */
// create four secondary command buffers, for each quadrant of the screen
vk::CommandBufferAllocateInfo commandBufferAllocateInfo( **commandPool, vk::CommandBufferLevel::eSecondary, 4 );
vk::raii::CommandBuffers secondaryCommandBuffers( *device, commandBufferAllocateInfo );
// Get the index of the next available swapchain image:
std::unique_ptr<vk::raii::Semaphore> imageAcquiredSemaphore =
vk::raii::su::make_unique<vk::raii::Semaphore>( *device, vk::SemaphoreCreateInfo() );
vk::Result result;
uint32_t imageIndex;
std::tie( result, imageIndex ) =
swapChainData.swapChain->acquireNextImage( vk::su::FenceTimeout, **imageAcquiredSemaphore );
assert( result == vk::Result::eSuccess );
assert( imageIndex < swapChainData.images.size() );
vk::raii::su::setImageLayout( *commandBuffer,
static_cast<vk::Image>( swapChainData.images[imageIndex] ),
swapChainData.colorFormat,
vk::ImageLayout::eUndefined,
vk::ImageLayout::eColorAttachmentOptimal );
const vk::DeviceSize offset = 0;
vk::Viewport viewport( 0.0f, 0.0f, 200.0f, 200.0f, 0.0f, 1.0f );
vk::Rect2D scissor( vk::Offset2D( 0, 0 ), vk::Extent2D( surfaceData.extent ) );
// now we record four separate command buffers, one for each quadrant of the screen
vk::CommandBufferInheritanceInfo commandBufferInheritanceInfo( **renderPass, 0, **framebuffers[imageIndex] );
vk::CommandBufferBeginInfo secondaryBeginInfo( vk::CommandBufferUsageFlagBits::eOneTimeSubmit |
vk::CommandBufferUsageFlagBits::eRenderPassContinue,
&commandBufferInheritanceInfo );
std::array<vk::CommandBuffer, 4> executeCommandBuffers;
for ( int i = 0; i < 4; i++ )
{
viewport.x = 25.0f + 250.0f * ( i % 2 );
viewport.y = 25.0f + 250.0f * ( i / 2 );
secondaryCommandBuffers[i].begin( secondaryBeginInfo );
secondaryCommandBuffers[i].bindPipeline( vk::PipelineBindPoint::eGraphics, **graphicsPipeline );
secondaryCommandBuffers[i].bindDescriptorSets(
vk::PipelineBindPoint::eGraphics, **pipelineLayout, 0, { *descriptorSets[i == 0 || i == 3] }, nullptr );
secondaryCommandBuffers[i].bindVertexBuffers( 0, { **vertexBufferData.buffer }, offset );
secondaryCommandBuffers[i].setViewport( 0, viewport );
secondaryCommandBuffers[i].setScissor( 0, scissor );
secondaryCommandBuffers[i].draw( 12 * 3, 1, 0, 0 );
secondaryCommandBuffers[i].end();
executeCommandBuffers[i] = *secondaryCommandBuffers[i];
}
std::array<vk::ClearValue, 2> clearValues;
clearValues[0].color = vk::ClearColorValue( std::array<float, 4>( { { 0.2f, 0.2f, 0.2f, 0.2f } } ) );
clearValues[1].depthStencil = vk::ClearDepthStencilValue( 1.0f, 0 );
vk::RenderPassBeginInfo renderPassBeginInfo(
**renderPass, **framebuffers[imageIndex], vk::Rect2D( vk::Offset2D( 0, 0 ), surfaceData.extent ), clearValues );
// specifying VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS means this render pass may ONLY call
// vkCmdExecuteCommands
commandBuffer->beginRenderPass( renderPassBeginInfo, vk::SubpassContents::eSecondaryCommandBuffers );
commandBuffer->executeCommands( executeCommandBuffers );
commandBuffer->endRenderPass();
vk::ImageSubresourceRange imageSubresourceRange( vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1 );
vk::ImageMemoryBarrier prePresentBarrier( vk::AccessFlagBits::eColorAttachmentWrite,
vk::AccessFlagBits::eMemoryRead,
vk::ImageLayout::eColorAttachmentOptimal,
vk::ImageLayout::ePresentSrcKHR,
VK_QUEUE_FAMILY_IGNORED,
VK_QUEUE_FAMILY_IGNORED,
static_cast<vk::Image>( swapChainData.images[imageIndex] ),
imageSubresourceRange );
commandBuffer->pipelineBarrier( vk::PipelineStageFlagBits::eColorAttachmentOutput,
vk::PipelineStageFlagBits::eBottomOfPipe,
vk::DependencyFlags(),
nullptr,
nullptr,
prePresentBarrier );
commandBuffer->end();
std::unique_ptr<vk::raii::Fence> drawFence = vk::raii::su::make_unique<vk::raii::Fence>( *device, vk::FenceCreateInfo() );
vk::PipelineStageFlags waitDestinationStageMask( vk::PipelineStageFlagBits::eColorAttachmentOutput );
vk::SubmitInfo submitInfo( **imageAcquiredSemaphore, waitDestinationStageMask, **commandBuffer );
graphicsQueue->submit( submitInfo, **drawFence );
while ( vk::Result::eTimeout == device->waitForFences( { **drawFence }, VK_TRUE, vk::su::FenceTimeout ) )
;
result = presentQueue->presentKHR( vk::PresentInfoKHR( {}, **swapChainData.swapChain, imageIndex, {} ) );
switch ( result )
{
case vk::Result::eSuccess: break;
case vk::Result::eSuboptimalKHR:
std::cout << "vk::Queue::presentKHR returned vk::Result::eSuboptimalKHR !\n";
break;
default: assert( false ); // an unexpected result is returned !
}
std::this_thread::sleep_for( std::chrono::milliseconds( 1000 ) );
/* VULKAN_KEY_END */
device->waitIdle();
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,35 @@
# Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_SeparateImageSampler)
set(HEADERS
)
set(SOURCES
SeparateImageSampler.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_SeparateImageSampler
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_SeparateImageSampler PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_SeparateImageSampler PRIVATE utils)

View File

@ -0,0 +1,302 @@
// Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : SeparateImageSampler
// Use separate image and sampler in descriptor set and shader to draw a textured cube.
#if defined( _MSC_VER )
// no need to ignore any warnings with MSVC
#elif defined( __clang__ )
# pragma clang diagnostic ignored "-Wmissing-braces"
#elif defined( __GNUC__ )
#else
// unknow compiler... just ignore the warnings for yourselves ;)
#endif
#include "../../samples/utils/geometries.hpp"
#include "../../samples/utils/math.hpp"
#include "../utils/shaders.hpp"
#include "../utils/utils.hpp"
#include "SPIRV/GlslangToSpv.h"
#include "vulkan/vulkan.hpp"
#include <iostream>
#include <thread>
static char const * AppName = "SeparateImageSampler";
static char const * EngineName = "Vulkan.hpp";
const std::string fragmentShaderTextTS_T_C = R"(
#version 400
#extension GL_ARB_separate_shader_objects : enable
#extension GL_ARB_shading_language_420pack : enable
layout (set = 0, binding = 1) uniform texture2D tex;
layout (set = 0, binding = 2) uniform sampler samp;
layout (location = 0) in vec2 inTexCoords;
layout (location = 0) out vec4 outColor;
void main()
{
// Combine the selected texture with sampler as a parameter
vec4 resColor = texture(sampler2D(tex, samp), inTexCoords);
// Create a border to see the cube more easily
if ((inTexCoords.x < 0.01f) || (0.99f < inTexCoords.x)
|| (inTexCoords.y < 0.01f) || (0.99f < inTexCoords.y))
{
resColor *= vec4(0.1f, 0.1f, 0.1f, 1.0f);
}
outColor = resColor;
}
)";
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
std::unique_ptr<vk::raii::Instance> instance =
vk::raii::su::makeUniqueInstance( *context, AppName, EngineName, {}, vk::su::getInstanceExtensions() );
#if !defined( NDEBUG )
std::unique_ptr<vk::raii::DebugUtilsMessengerEXT> debugUtilsMessenger =
vk::raii::su::makeUniqueDebugUtilsMessengerEXT( *instance );
#endif
std::unique_ptr<vk::raii::PhysicalDevice> physicalDevice = vk::raii::su::makeUniquePhysicalDevice( *instance );
vk::raii::su::SurfaceData surfaceData( *instance, AppName, vk::Extent2D( 500, 500 ) );
std::pair<uint32_t, uint32_t> graphicsAndPresentQueueFamilyIndex =
vk::raii::su::findGraphicsAndPresentQueueFamilyIndex( *physicalDevice, *surfaceData.surface );
std::unique_ptr<vk::raii::Device> device = vk::raii::su::makeUniqueDevice(
*physicalDevice, graphicsAndPresentQueueFamilyIndex.first, vk::su::getDeviceExtensions() );
std::unique_ptr<vk::raii::CommandPool> commandPool =
vk::raii::su::makeUniqueCommandPool( *device, graphicsAndPresentQueueFamilyIndex.first );
std::unique_ptr<vk::raii::CommandBuffer> commandBuffer =
vk::raii::su::makeUniqueCommandBuffer( *device, *commandPool );
std::unique_ptr<vk::raii::Queue> graphicsQueue =
vk::raii::su::make_unique<vk::raii::Queue>( *device, graphicsAndPresentQueueFamilyIndex.first, 0 );
std::unique_ptr<vk::raii::Queue> presentQueue =
vk::raii::su::make_unique<vk::raii::Queue>( *device, graphicsAndPresentQueueFamilyIndex.second, 0 );
vk::raii::su::SwapChainData swapChainData( *physicalDevice,
*device,
*surfaceData.surface,
surfaceData.extent,
vk::ImageUsageFlagBits::eColorAttachment |
vk::ImageUsageFlagBits::eTransferSrc,
{},
graphicsAndPresentQueueFamilyIndex.first,
graphicsAndPresentQueueFamilyIndex.second );
vk::raii::su::DepthBufferData depthBufferData(
*physicalDevice, *device, vk::Format::eD16Unorm, surfaceData.extent );
vk::raii::su::BufferData uniformBufferData(
*physicalDevice, *device, sizeof( glm::mat4x4 ), vk::BufferUsageFlagBits::eUniformBuffer );
glm::mat4x4 mvpcMatrix = vk::su::createModelViewProjectionClipMatrix( surfaceData.extent );
vk::raii::su::copyToDevice( *uniformBufferData.deviceMemory, mvpcMatrix );
vk::Format colorFormat =
vk::su::pickSurfaceFormat( physicalDevice->getSurfaceFormatsKHR( **surfaceData.surface ) ).format;
std::unique_ptr<vk::raii::RenderPass> renderPass =
vk::raii::su::makeUniqueRenderPass( *device, colorFormat, depthBufferData.format );
glslang::InitializeProcess();
std::unique_ptr<vk::raii::ShaderModule> vertexShaderModule =
vk::raii::su::makeUniqueShaderModule( *device, vk::ShaderStageFlagBits::eVertex, vertexShaderText_PT_T );
std::unique_ptr<vk::raii::ShaderModule> fragmentShaderModule =
vk::raii::su::makeUniqueShaderModule( *device, vk::ShaderStageFlagBits::eFragment, fragmentShaderTextTS_T_C );
glslang::FinalizeProcess();
std::vector<std::unique_ptr<vk::raii::Framebuffer>> framebuffers = vk::raii::su::makeUniqueFramebuffers(
*device, *renderPass, swapChainData.imageViews, depthBufferData.imageView, surfaceData.extent );
vk::raii::su::BufferData vertexBufferData(
*physicalDevice, *device, sizeof( texturedCubeData ), vk::BufferUsageFlagBits::eVertexBuffer );
vk::raii::su::copyToDevice(
*vertexBufferData.deviceMemory, texturedCubeData, sizeof( texturedCubeData ) / sizeof( texturedCubeData[0] ) );
/* VULKAN_KEY_START */
commandBuffer->begin( vk::CommandBufferBeginInfo() );
// Create the separate image
vk::raii::su::TextureData textureData( *physicalDevice, *device );
textureData.setImage( *commandBuffer, vk::su::MonochromeImageGenerator( { 118, 185, 0 } ) );
// Create the separate sampler
vk::SamplerCreateInfo samplerCreateInfo( {},
vk::Filter::eNearest,
vk::Filter::eNearest,
vk::SamplerMipmapMode::eNearest,
vk::SamplerAddressMode::eClampToEdge,
vk::SamplerAddressMode::eClampToEdge,
vk::SamplerAddressMode::eClampToEdge,
0.0f,
false,
1.0f,
false,
vk::CompareOp::eNever,
0.0f,
0.0f,
vk::BorderColor::eFloatOpaqueWhite );
std::unique_ptr<vk::raii::Sampler> sampler = vk::raii::su::make_unique<vk::raii::Sampler>( *device, samplerCreateInfo );
// Create binding and layout for the following, matching contents of shader
// binding 0 = uniform buffer (MVP)
// binding 1 = texture2D
// binding 2 = sampler
std::array<vk::DescriptorSetLayoutBinding, 3> resourceBindings = {
{ vk::DescriptorSetLayoutBinding( 0, vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eVertex ),
vk::DescriptorSetLayoutBinding( 1, vk::DescriptorType::eSampledImage, 1, vk::ShaderStageFlagBits::eFragment ),
vk::DescriptorSetLayoutBinding( 2, vk::DescriptorType::eSampler, 1, vk::ShaderStageFlagBits::eFragment ) }
};
vk::DescriptorSetLayoutCreateInfo descriptorSetLayoutCreateInfo( {}, resourceBindings );
std::unique_ptr<vk::raii::DescriptorSetLayout> descriptorSetLayout =
vk::raii::su::make_unique<vk::raii::DescriptorSetLayout>( *device, descriptorSetLayoutCreateInfo );
// Create pipeline layout
vk::PipelineLayoutCreateInfo pipelineLayoutCreateInfo( {}, **descriptorSetLayout );
std::unique_ptr<vk::raii::PipelineLayout> pipelineLayout =
vk::raii::su::make_unique<vk::raii::PipelineLayout>( *device, pipelineLayoutCreateInfo );
// Create a single pool to contain data for the descriptor set
std::array<vk::DescriptorPoolSize, 3> poolSizes = {
{ vk::DescriptorPoolSize( vk::DescriptorType::eUniformBuffer, 1 ),
vk::DescriptorPoolSize( vk::DescriptorType::eSampledImage, 1 ),
vk::DescriptorPoolSize( vk::DescriptorType::eSampler, 1 ) }
};
vk::DescriptorPoolCreateInfo descriptorPoolCreateInfo(
vk::DescriptorPoolCreateFlagBits::eFreeDescriptorSet, 1, poolSizes );
std::unique_ptr<vk::raii::DescriptorPool> descriptorPool =
vk::raii::su::make_unique<vk::raii::DescriptorPool>( *device, descriptorPoolCreateInfo );
// Populate descriptor sets
vk::DescriptorSetAllocateInfo descriptorSetAllocateInfo( **descriptorPool, **descriptorSetLayout );
std::unique_ptr<vk::raii::DescriptorSet> descriptorSet = vk::raii::su::make_unique<vk::raii::DescriptorSet>(
std::move( vk::raii::DescriptorSets( *device, descriptorSetAllocateInfo ).front() ) );
vk::DescriptorBufferInfo bufferInfo( **uniformBufferData.buffer, 0, sizeof( glm::mat4x4 ) );
vk::DescriptorImageInfo imageInfo(
**textureData.sampler, **textureData.imageData->imageView, vk::ImageLayout::eShaderReadOnlyOptimal );
vk::DescriptorImageInfo samplerInfo( **sampler, {}, {} );
std::array<vk::WriteDescriptorSet, 3> descriptorWrites = {
{ vk::WriteDescriptorSet( **descriptorSet, 0, 0, vk::DescriptorType::eUniformBuffer, {}, bufferInfo ),
vk::WriteDescriptorSet( **descriptorSet, 1, 0, vk::DescriptorType::eSampledImage, imageInfo ),
vk::WriteDescriptorSet( **descriptorSet, 2, 0, vk::DescriptorType::eSampler, samplerInfo ) }
};
device->updateDescriptorSets( descriptorWrites, nullptr );
/* VULKAN_KEY_END */
std::unique_ptr<vk::raii::PipelineCache> pipelineCache =
vk::raii::su::make_unique<vk::raii::PipelineCache>( *device, vk::PipelineCacheCreateInfo() );
std::unique_ptr<vk::raii::Pipeline> graphicsPipeline = vk::raii::su::makeUniqueGraphicsPipeline(
*device,
*pipelineCache,
*vertexShaderModule,
nullptr,
*fragmentShaderModule,
nullptr,
sizeof( texturedCubeData[0] ),
{ { vk::Format::eR32G32B32A32Sfloat, 0 }, { vk::Format::eR32G32Sfloat, 16 } },
vk::FrontFace::eClockwise,
true,
*pipelineLayout,
*renderPass );
// Get the index of the next available swapchain image:
std::unique_ptr<vk::raii::Semaphore> imageAcquiredSemaphore =
vk::raii::su::make_unique<vk::raii::Semaphore>( *device, vk::SemaphoreCreateInfo() );
vk::Result result;
uint32_t imageIndex;
std::tie( result, imageIndex ) =
swapChainData.swapChain->acquireNextImage( vk::su::FenceTimeout, **imageAcquiredSemaphore );
assert( result == vk::Result::eSuccess );
assert( imageIndex < swapChainData.images.size() );
std::array<vk::ClearValue, 2> clearValues;
clearValues[0].color = vk::ClearColorValue( std::array<float, 4>( { { 0.2f, 0.2f, 0.2f, 0.2f } } ) );
clearValues[1].depthStencil = vk::ClearDepthStencilValue( 1.0f, 0 );
vk::RenderPassBeginInfo renderPassBeginInfo(
**renderPass, **framebuffers[imageIndex], vk::Rect2D( vk::Offset2D( 0, 0 ), surfaceData.extent ), clearValues );
commandBuffer->beginRenderPass( renderPassBeginInfo, vk::SubpassContents::eInline );
commandBuffer->bindPipeline( vk::PipelineBindPoint::eGraphics, **graphicsPipeline );
commandBuffer->bindDescriptorSets(
vk::PipelineBindPoint::eGraphics, **pipelineLayout, 0, { **descriptorSet }, nullptr );
commandBuffer->bindVertexBuffers( 0, { **vertexBufferData.buffer }, { 0 } );
commandBuffer->setViewport( 0,
vk::Viewport( 0.0f,
0.0f,
static_cast<float>( surfaceData.extent.width ),
static_cast<float>( surfaceData.extent.height ),
0.0f,
1.0f ) );
commandBuffer->setScissor( 0, vk::Rect2D( vk::Offset2D( 0, 0 ), surfaceData.extent ) );
commandBuffer->draw( 12 * 3, 1, 0, 0 );
commandBuffer->endRenderPass();
commandBuffer->end();
std::unique_ptr<vk::raii::Fence> drawFence = vk::raii::su::make_unique<vk::raii::Fence>( *device, vk::FenceCreateInfo() );
vk::PipelineStageFlags waitDestinationStageMask( vk::PipelineStageFlagBits::eColorAttachmentOutput );
vk::SubmitInfo submitInfo( **imageAcquiredSemaphore, waitDestinationStageMask, **commandBuffer );
graphicsQueue->submit( submitInfo, **drawFence );
while ( vk::Result::eTimeout == device->waitForFences( { **drawFence }, VK_TRUE, vk::su::FenceTimeout ) )
;
vk::PresentInfoKHR presentInfoKHR( nullptr, **swapChainData.swapChain, imageIndex );
result = presentQueue->presentKHR( presentInfoKHR );
switch ( result )
{
case vk::Result::eSuccess: break;
case vk::Result::eSuboptimalKHR:
std::cout << "vk::Queue::presentKHR returned vk::Result::eSuboptimalKHR !\n";
break;
default: assert( false ); // an unexpected result is returned !
}
std::this_thread::sleep_for( std::chrono::milliseconds( 1000 ) );
device->waitIdle();
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,39 @@
# Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_SurfaceCapabilities)
set(HEADERS
)
set(SOURCES
SurfaceCapabilities.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
# Win32 exclusive vk::SurfaceCapabilitiesFullScreenExclusiveEXT is used
if(WIN32)
add_executable(RAII_SurfaceCapabilities
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_SurfaceCapabilities PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_SurfaceCapabilities PRIVATE utils)
endif()

View File

@ -0,0 +1,181 @@
// Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : SurfaceCapabilities
// Get surface capabilities.
#include "../utils/utils.hpp"
#include "vulkan/vulkan.hpp"
#include <iomanip>
#include <sstream>
#include <vector>
static char const * AppName = "SurfaceCapabilities";
static char const * EngineName = "Vulkan.hpp";
void cout( vk::SurfaceCapabilitiesKHR const & surfaceCapabilities )
{
std::cout << "\tCapabilities:\n";
std::cout << "\t\t"
<< "currentExtent = " << surfaceCapabilities.currentExtent.width << " x "
<< surfaceCapabilities.currentExtent.height << "\n";
std::cout << "\t\t"
<< "currentTransform = " << vk::to_string( surfaceCapabilities.currentTransform ) << "\n";
std::cout << "\t\t"
<< "maxImageArrayLayers = " << surfaceCapabilities.maxImageArrayLayers << "\n";
std::cout << "\t\t"
<< "maxImageCount = " << surfaceCapabilities.maxImageCount << "\n";
std::cout << "\t\t"
<< "maxImageExtent = " << surfaceCapabilities.maxImageExtent.width << " x "
<< surfaceCapabilities.maxImageExtent.height << "\n";
std::cout << "\t\t"
<< "minImageCount = " << surfaceCapabilities.minImageCount << "\n";
std::cout << "\t\t"
<< "minImageExtent = " << surfaceCapabilities.minImageExtent.width << " x "
<< surfaceCapabilities.minImageExtent.height << "\n";
std::cout << "\t\t"
<< "supportedCompositeAlpha = " << vk::to_string( surfaceCapabilities.supportedCompositeAlpha ) << "\n";
std::cout << "\t\t"
<< "supportedTransforms = " << vk::to_string( surfaceCapabilities.supportedTransforms ) << "\n";
std::cout << "\t\t"
<< "supportedUsageFlags = " << vk::to_string( surfaceCapabilities.supportedUsageFlags ) << "\n";
std::cout << "\n";
}
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
std::vector<vk::ExtensionProperties> instanceExtensionProperties = context->enumerateInstanceExtensionProperties();
bool supportsGetSurfaceCapabilities2 =
( std::find_if( instanceExtensionProperties.begin(),
instanceExtensionProperties.end(),
[]( vk::ExtensionProperties const & ep ) {
return strcmp( ep.extensionName, VK_KHR_GET_SURFACE_CAPABILITIES_2_EXTENSION_NAME ) == 0;
} ) != instanceExtensionProperties.end() );
std::vector<std::string> extensions = vk::su::getInstanceExtensions();
if ( supportsGetSurfaceCapabilities2 )
{
extensions.push_back( VK_KHR_GET_SURFACE_CAPABILITIES_2_EXTENSION_NAME );
}
std::unique_ptr<vk::raii::Instance> instance =
vk::raii::su::makeUniqueInstance( *context, AppName, EngineName, {}, extensions );
#if !defined( NDEBUG )
std::unique_ptr<vk::raii::DebugUtilsMessengerEXT> debugUtilsMessenger =
vk::raii::su::makeUniqueDebugUtilsMessengerEXT( *instance );
#endif
// enumerate the physicalDevices
vk::raii::PhysicalDevices physicalDevices( *instance );
vk::raii::su::SurfaceData surfaceData( *instance, AppName, vk::Extent2D( 500, 500 ) );
/* VULKAN_KEY_START */
std::cout << std::boolalpha;
for ( size_t i = 0; i < physicalDevices.size(); i++ )
{
// some properties are only valid, if a corresponding extension is available!
std::vector<vk::ExtensionProperties> extensionProperties =
physicalDevices[i].enumerateDeviceExtensionProperties();
std::cout << "PhysicalDevice " << i << "\n";
if ( supportsGetSurfaceCapabilities2 )
{
auto surfaceCapabilities2 =
physicalDevices[i]
.getSurfaceCapabilities2KHR<vk::SurfaceCapabilities2KHR,
vk::DisplayNativeHdrSurfaceCapabilitiesAMD,
vk::SharedPresentSurfaceCapabilitiesKHR,
vk::SurfaceCapabilitiesFullScreenExclusiveEXT,
vk::SurfaceProtectedCapabilitiesKHR>( { **surfaceData.surface } );
vk::SurfaceCapabilitiesKHR const & surfaceCapabilities =
surfaceCapabilities2.get<vk::SurfaceCapabilities2KHR>().surfaceCapabilities;
cout( surfaceCapabilities );
if ( vk::su::contains( extensionProperties, "VK_AMD_display_native_hdr" ) )
{
vk::DisplayNativeHdrSurfaceCapabilitiesAMD displayNativeHdrSurfaceCapabilities =
surfaceCapabilities2.get<vk::DisplayNativeHdrSurfaceCapabilitiesAMD>();
std::cout << "\tDisplayNativeHdrSurfaceCapabilitiesAMD:\n";
std::cout << "\t\t"
<< "localDimmingSupport = " << !!displayNativeHdrSurfaceCapabilities.localDimmingSupport << "\n";
std::cout << "\n";
}
if ( vk::su::contains( extensionProperties, "VK_KHR_shared_presentable_image" ) )
{
vk::SharedPresentSurfaceCapabilitiesKHR sharedPresentSurfaceCapabilities =
surfaceCapabilities2.get<vk::SharedPresentSurfaceCapabilitiesKHR>();
std::cout << "\tSharedPresentSurfaceCapabilitiesKHR:\n";
std::cout << "\t\t"
<< "sharedPresentSupportedUsageFlags = "
<< vk::to_string( sharedPresentSurfaceCapabilities.sharedPresentSupportedUsageFlags ) << "\n";
std::cout << "\n";
}
if ( vk::su::contains( extensionProperties, "VK_EXT_full_screen_exclusive" ) )
{
vk::SurfaceCapabilitiesFullScreenExclusiveEXT surfaceCapabilitiesFullScreenExclusive =
surfaceCapabilities2.get<vk::SurfaceCapabilitiesFullScreenExclusiveEXT>();
std::cout << "\tSurfaceCapabilitiesFullScreenExclusiveEXT:\n";
std::cout << "\t\t"
<< "fullScreenExclusiveSupported = "
<< !!surfaceCapabilitiesFullScreenExclusive.fullScreenExclusiveSupported << "\n";
std::cout << "\n";
}
if ( vk::su::contains( extensionProperties, "VK_KHR_surface_protected_capabilities" ) )
{
vk::SurfaceProtectedCapabilitiesKHR surfaceProtectedCapabilities =
surfaceCapabilities2.get<vk::SurfaceProtectedCapabilitiesKHR>();
std::cout << "\tSurfaceProtectedCapabilitiesKHR:\n";
std::cout << "\t\t"
<< "supportsProtected = " << !!surfaceProtectedCapabilities.supportsProtected << "\n";
std::cout << "\n";
}
}
else
{
vk::SurfaceCapabilitiesKHR surfaceCapabilities =
physicalDevices[i].getSurfaceCapabilitiesKHR( **surfaceData.surface );
cout( surfaceCapabilities );
}
}
/* VULKAN_KEY_END */
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

View File

@ -0,0 +1,35 @@
# Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.2)
project(RAII_SurfaceFormats)
set(HEADERS
)
set(SOURCES
SurfaceFormats.cpp
)
source_group(headers FILES ${HEADERS})
source_group(sources FILES ${SOURCES})
add_executable(RAII_SurfaceFormats
${HEADERS}
${SOURCES}
)
set_target_properties(RAII_SurfaceFormats PROPERTIES FOLDER "RAII_Samples")
target_link_libraries(RAII_SurfaceFormats PRIVATE utils)

View File

@ -0,0 +1,82 @@
// Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// VulkanHpp Samples : SurfaceFormats
// Get surface formats.
#include "../utils/utils.hpp"
#include "vulkan/vulkan.hpp"
#include <iomanip>
#include <sstream>
#include <vector>
static char const * AppName = "SurfaceFormats";
static char const * EngineName = "Vulkan.hpp";
int main( int /*argc*/, char ** /*argv*/ )
{
try
{
std::unique_ptr<vk::raii::Context> context = vk::raii::su::make_unique<vk::raii::Context>();
std::unique_ptr<vk::raii::Instance> instance =
vk::raii::su::makeUniqueInstance( *context, AppName, EngineName, {}, vk::su::getInstanceExtensions() );
#if !defined( NDEBUG )
std::unique_ptr<vk::raii::DebugUtilsMessengerEXT> debugUtilsMessenger =
vk::raii::su::makeUniqueDebugUtilsMessengerEXT( *instance );
#endif
// enumerate the physicalDevices
vk::raii::PhysicalDevices physicalDevices( *instance );
vk::raii::su::SurfaceData surfaceData( *instance, AppName, vk::Extent2D( 500, 500 ) );
/* VULKAN_KEY_START */
std::cout << std::boolalpha;
for ( size_t i = 0; i < physicalDevices.size(); i++ )
{
std::cout << "PhysicalDevice " << i << "\n";
std::vector<vk::SurfaceFormatKHR> surfaceFormats =
physicalDevices[i].getSurfaceFormatsKHR( **surfaceData.surface );
for ( size_t j = 0; j < surfaceFormats.size(); j++ )
{
std::cout << "\tFormat " << j << "\n";
std::cout << "\t\t"
<< "colorSpace = " << vk::to_string( surfaceFormats[j].colorSpace ) << "\n";
std::cout << "\t\t"
<< "format = " << vk::to_string( surfaceFormats[j].format ) << "\n";
std::cout << "\n";
}
}
/* VULKAN_KEY_END */
}
catch ( vk::SystemError & err )
{
std::cout << "vk::SystemError: " << err.what() << std::endl;
exit( -1 );
}
catch ( std::exception & err )
{
std::cout << "std::exception: " << err.what() << std::endl;
exit( -1 );
}
catch ( ... )
{
std::cout << "unknown error\n";
exit( -1 );
}
return 0;
}

Some files were not shown because too many files have changed in this diff Show More