Vulkan 编程指南 - 实例 (Vulkan Tutorial / Instance / 01_instance_creation.cpp)

2023-11-27 22:20

本文主要是介绍Vulkan 编程指南 - 实例 (Vulkan Tutorial / Instance / 01_instance_creation.cpp),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Vulkan 编程指南 - 实例 (Vulkan Tutorial / Instance / 01_instance_creation.cpp)

仅供个人学习、研究使用,建议大家阅读 Vulkan Tutorial

Drawing a triangle / Setup / Instance
https://vulkan-tutorial.com/Drawing_a_triangle/Setup/Instance

Vulkan Tutorial
https://vulkan-tutorial.com/

GitHub Repository
https://github.com/Overv/VulkanTutorial

1 Instance (实例)

1.1 Creating an instance

The very first thing you need to do is initialize the Vulkan library by creating an instance. The instance is the connection between your application and the Vulkan library and creating it involves specifying some details about your application to the driver.
我们首先创建一个实例来初始化 Vulkan 库。这个实例是你的应用程序和 Vulkan 库之间的连接,创建它需要向驱动指定一些关于你的应用程序的信息。

Start by adding a createInstance function and invoking it in the initVulkan function.

void initVulkan() {createInstance();
}

Additionally add a data member to hold the handle to the instance (添加了一个存储实例句柄的私有成员):

private:
VkInstance instance;

Now, to create an instance we’ll first have to fill in a struct with some information about our application. This data is technically optional, but it may provide some useful information to the driver in order to optimize our specific application (e.g. because it uses a well-known graphics engine with certain special behavior).
现在,为了创建一个实例,我们首先要在一个结构中填写关于我们应用程序的一些信息。这些数据在技术上是可选的,但填写的信息可能会作为驱动程序的优化依据,让驱动程序进行一些特殊的优化。例如,应用程序使用了某个引擎,驱动程序对这个引擎有一些特殊处理,这时就可能有很大的优化提升。

This struct is called VkApplicationInfo:

void createInstance() {VkApplicationInfo appInfo{};appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;appInfo.pApplicationName = "Hello Triangle";appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);appInfo.pEngineName = "No Engine";appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);appInfo.apiVersion = VK_API_VERSION_1_0;
}

As mentioned before, many structs in Vulkan require you to explicitly specify the type in the sType member. This is also one of the many structs with a pNext member that can point to extension information in the future. We’re using value initialization here to leave it as nullptr.
之前提到,Vulkan 的很多结构体需要我们显式地在 sType 成员变量中指定结构体的类型。此外,许多 Vulkan 结构体还有一个 pNext 成员变量,用来指向未来可能扩展的参数信息,现在,我们并没有使用它,将其设置为 nullptr

A lot of information in Vulkan is passed through structs instead of function parameters and we’ll have to fill in one more struct to provide sufficient information for creating an instance. This next struct is not optional and tells the Vulkan driver which global extensions and validation layers we want to use. Global here means that they apply to the entire program and not a specific device, which will become clear in the next few chapters.
Vulkan 倾向于通过结构体传递信息,我们需要填写一个或多个结构体来提供足够的信息创建 Vulkan 实例。下面的这个结构体是必须的,它告诉 Vulkan 的驱动程序需要使用的全局扩展和校验层。全局是指这里的设置对于整个应用程序都有效,而不仅仅对一个设备有效。

VkInstanceCreateInfo createInfo{};
createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
createInfo.pApplicationInfo = &appInfo;

The first two parameters are straightforward. The next two layers specify the desired global extensions. As mentioned in the overview chapter, Vulkan is a platform agnostic API, which means that you need an extension to interface with the window system. GLFW has a handy built-in function that returns the extension(s) it needs to do that which we can pass to the struct.

上面代码中填写得两个参数非常直白,不用多解释。接下来,我们需要指定需要的全局扩展。正如在概述章节中提到的,Vulkan 是一个与平台无关的 API,这意味着你需要一个扩展来与窗口系统对接。GLFW 有一个方便的内置函数,可以返回它所需要的扩展,我们可以将其传递给结构。

uint32_t glfwExtensionCount = 0;
const char** glfwExtensions;glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount);createInfo.enabledExtensionCount = glfwExtensionCount;
createInfo.ppEnabledExtensionNames = glfwExtensions;

The last two members of the struct determine the global validation layers to enable. We’ll talk about these more in-depth in the next chapter, so just leave these empty for now.
结构体的最后两个成员变量用来指定全局校验层。在这里,我们将其设置为 0,不使用它。

createInfo.enabledLayerCount = 0;

We’ve now specified everything Vulkan needs to create an instance and we can finally issue the vkCreateInstance call.
填写完所有必要的信息,我们就可以调用 vkCreateInstance 函数来创建 Vulkan 实例。

VkResult result = vkCreateInstance(&createInfo, nullptr, &instance);

As you’ll see, the general pattern that object creation function parameters in Vulkan follow is:

  • Pointer to struct with creation info (一个包含了创建信息的结构体指针)
  • Pointer to custom allocator callbacks, always nullptr in this tutorial (一个自定义的分配器回调函数,在本教程,我们没有使用自定义的分配器,总是将它设置为 nullptr)
  • Pointer to the variable that stores the handle to the new object (一个指向新对象句柄存储位置的指针)

If everything went well then the handle to the instance was stored in the VkInstance class member. Nearly all Vulkan functions return a value of type VkResult that is either VK_SUCCESS or an error code. To check if the instance was created successfully, we don’t need to store the result and can just use a check for the success value instead.
如果一切顺利,我们创建的实例的句柄就被存储在了类的 VkInstance 成员变量中。几乎所有 Vulkan 函数调用都会返回一个 VkResult 来反应函数调用的结果,它的值可以是 VK_SUCCESS 表示调用成功,或是一个错误代码,表示调用失败。为了检测实例是否创建成功,我们可以直接将创建函数在条件语句中使用,不需要存储它的返回值。

if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS) {throw std::runtime_error("failed to create instance!");
}

Now run the program to make sure that the instance is created successfully.

1.2 Encountered VK_ERROR_INCOMPATIBLE_DRIVER

If using MacOS with the latest MoltenVK sdk, you may get VK_ERROR_INCOMPATIBLE_DRIVER returned from vkCreateInstance. According to the Getting Start Notes. Beginning with the 1.3.216 Vulkan SDK, the VK_KHR_PORTABILITY_subset extension is mandatory.
从 Vulkan SDK 1.3.216 开始,VK_KHR_PORTABILITY_subset 扩展是强制性的。

To get over this error, first add the VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR bit to VkInstanceCreateInfo struct’s flags, then add VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME to instance enabled extension list.

Typically the code could be like this:

...std::vector<const char*> requiredExtensions;for(uint32_t i = 0; i < glfwExtensionCount; i++) {requiredExtensions.emplace_back(glfwExtensions[i]);
}requiredExtensions.emplace_back(VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME);createInfo.flags |= VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR;createInfo.enabledExtensionCount = (uint32_t) requiredExtensions.size();
createInfo.ppEnabledExtensionNames = requiredExtensions.data();if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS) {throw std::runtime_error("failed to create instance!");
}

1.3 Checking for extension support (检测扩展支持)

If you look at the vkCreateInstance documentation then you’ll see that one of the possible error codes is VK_ERROR_EXTENSION_NOT_PRESENT. We could simply specify the extensions we require and terminate if that error code comes back. That makes sense for essential extensions like the window system interface, but what if we want to check for optional functionality?
如果读者看过 vkCreateInstance 函数的官方文档,可能会知道它返回的中一个错误代码 VK_ERROR_EXTENSION_NOT_PRESENT。我们可以利用这个错误代码在扩展不能满足时直接结束我们的程序,这对于像窗口系统这种必要的扩展来说非常适合。但有时,我们请求的扩展可能是非必须的,有了很好,没有的话,程序仍然可以运行。

To retrieve a list of supported extensions before creating an instance, there’s the vkEnumerateInstanceExtensionProperties function. It takes a pointer to a variable that stores the number of extensions and an array of VkExtensionProperties to store details of the extensions. It also takes an optional first parameter that allows us to filter extensions by a specific validation layer, which we’ll ignore for now.
为了在创建实例之前检索支持的扩展列表,有一个 vkEnumerateInstanceExtensionProperties 函数。它需要一个存储扩展数量的变量指针和一个 VkExtensionProperties 的数组来存储扩展的细节。它还需要一个可选的第一个参数,允许我们通过一个特定的验证层来过滤扩展,我们现在将忽略这个参数。

To allocate an array to hold the extension details we first need to know how many there are. You can request just the number of extensions by leaving the latter parameter empty:
我们首先需要知道扩展的数量,以便分配合适的数组大小来存储信息。可以通过下面的代码来获取扩展的数量。

uint32_t extensionCount = 0;
vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, nullptr);

Now allocate an array to hold the extension details (include <vector>):

std::vector<VkExtensionProperties> extensions(extensionCount);

Finally we can query the extension details.
最后,我们可以查询扩展的详细信息。

vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, extensions.data());

Each VkExtensionProperties struct contains the name and version of an extension. We can list them with a simple for loop (\t is a tab for indentation).
每个 VkExtensionProperties 结构包含一个扩展的名称和版本。

std::cout << "available extensions:\n";for (const auto& extension : extensions) {std::cout << '\t' << extension.extensionName << '\n';
}

You can add this code to the createInstance function if you’d like to provide some details about the Vulkan support. As a challenge, try to create a function that checks if all of the extensions returned by glfwGetRequiredInstanceExtensions are included in the supported extensions list.
如果你想提供一些关于 Vulkan 支持的细节,你可以在 createInstance 函数中加入这段代码。尝试创建一个函数,检查由 glfwGetRequiredInstanceExtensions 返回的所有扩展是否包含在支持的扩展列表中。

1.4 Cleaning up

The VkInstance should be only destroyed right before the program exits. It can be destroyed in cleanup with the vkDestroyInstance function.
VkInstance 应该只在程序退出前销毁,它可以在 cleanup 中用 vkDestroyInstance 函数销毁。

void cleanup() {vkDestroyInstance(instance, nullptr);glfwDestroyWindow(window);glfwTerminate();
}

The parameters for the vkDestroyInstance function are straightforward. As mentioned in the previous chapter, the allocation and deallocation functions in Vulkan have an optional allocator callback that we’ll ignore by passing nullptr to it. All of the other Vulkan resources that we’ll create in the following chapters should be cleaned up before the instance is destroyed.
vkDestroyInstance 函数的参数非常直白。之前提到,Vulkan 对象的分配和清除函数都有一个可选的分配器回调参数,在本教程,我们没有自定义的分配器,所以,将其设置为 nullptr。除了 Vulkan 实例,其余我们使用 Vulkan 创建的对象也需要被清除,且应该在 Vulkan 实例清除之前被清除。

Before continuing with the more complex steps after instance creation, it’s time to evaluate our debugging options by checking out validation layers.

01_instance_creation.cpp
https://github.com/Overv/VulkanTutorial/blob/main/code/01_instance_creation.cpp

01_instance_creation.cpp

#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>#include <iostream>
#include <stdexcept>
#include <cstdlib>const uint32_t WIDTH = 800;
const uint32_t HEIGHT = 600;class HelloTriangleApplication {
public:void run() {initWindow();initVulkan();mainLoop();cleanup();}private:GLFWwindow* window;VkInstance instance;void initWindow() {glfwInit();glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE);window = glfwCreateWindow(WIDTH, HEIGHT, "yongqiang", nullptr, nullptr);}void initVulkan() {createInstance();}void mainLoop() {while (!glfwWindowShouldClose(window)) {glfwPollEvents();}}void cleanup() {vkDestroyInstance(instance, nullptr);glfwDestroyWindow(window);glfwTerminate();}void createInstance() {VkApplicationInfo appInfo{};appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;appInfo.pApplicationName = "Hello Triangle";appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);appInfo.pEngineName = "No Engine";appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);appInfo.apiVersion = VK_API_VERSION_1_0;VkInstanceCreateInfo createInfo{};createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;createInfo.pApplicationInfo = &appInfo;uint32_t glfwExtensionCount = 0;const char** glfwExtensions;glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount);createInfo.enabledExtensionCount = glfwExtensionCount;createInfo.ppEnabledExtensionNames = glfwExtensions;createInfo.enabledLayerCount = 0;if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS) {throw std::runtime_error("failed to create instance!");}}
};int main() {HelloTriangleApplication app;try {app.run();} catch (const std::exception& e) {std::cerr << e.what() << std::endl;return EXIT_FAILURE;}return EXIT_SUCCESS;
}

Makefile

CFLAGS = -std=c++17 -O2
LDFLAGS = -lglfw -lvulkan -ldl -lpthread -lX11 -lXxf86vm -lXrandr -lXiVulkanTest: instance_creation_01.cppg++ $(CFLAGS) -o VulkanTest instance_creation_01.cpp $(LDFLAGS).PHONY: test cleantest: VulkanTest./VulkanTestclean:rm -f VulkanTest
yongqiang@yongqiang:~/vulkan_workspace/instance_creation_01$ make clean
rm -f VulkanTest
yongqiang@yongqiang:~/vulkan_workspace/instance_creation_01$
yongqiang@yongqiang:~/vulkan_workspace/instance_creation_01$ make test
g++ -std=c++17 -O2 -o VulkanTest instance_creation_01.cpp -lglfw -lvulkan -ldl -lpthread -lX11 -lXxf86vm -lXrandr -lXi
./VulkanTest
yongqiang@yongqiang:~/vulkan_workspace/instance_creation_01$
yongqiang@yongqiang:~/vulkan_workspace/instance_creation_01$ ls
Makefile  VulkanTest  instance_creation_01.cpp
yongqiang@yongqiang:~/vulkan_workspace/instance_creation_01$

在这里插入图片描述

References

https://yongqiang.blog.csdn.net/
Vulkan Tutorial https://vulkan-tutorial.com/
Vulkan 教程 https://geek-docs.com/vulkan/vulkan-tutorial/vulkan-tutorial-index.html

这篇关于Vulkan 编程指南 - 实例 (Vulkan Tutorial / Instance / 01_instance_creation.cpp)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/428561

相关文章

PostgreSQL中rank()窗口函数实用指南与示例

《PostgreSQL中rank()窗口函数实用指南与示例》在数据分析和数据库管理中,经常需要对数据进行排名操作,PostgreSQL提供了强大的窗口函数rank(),可以方便地对结果集中的行进行排名... 目录一、rank()函数简介二、基础示例:部门内员工薪资排名示例数据排名查询三、高级应用示例1. 每

SpringBoot结合Docker进行容器化处理指南

《SpringBoot结合Docker进行容器化处理指南》在当今快速发展的软件工程领域,SpringBoot和Docker已经成为现代Java开发者的必备工具,本文将深入讲解如何将一个SpringBo... 目录前言一、为什么选择 Spring Bootjavascript + docker1. 快速部署与

MySQL中的LENGTH()函数用法详解与实例分析

《MySQL中的LENGTH()函数用法详解与实例分析》MySQLLENGTH()函数用于计算字符串的字节长度,区别于CHAR_LENGTH()的字符长度,适用于多字节字符集(如UTF-8)的数据验证... 目录1. LENGTH()函数的基本语法2. LENGTH()函数的返回值2.1 示例1:计算字符串

创建Java keystore文件的完整指南及详细步骤

《创建Javakeystore文件的完整指南及详细步骤》本文详解Java中keystore的创建与配置,涵盖私钥管理、自签名与CA证书生成、SSL/TLS应用,强调安全存储及验证机制,确保通信加密和... 目录1. 秘密键(私钥)的理解与管理私钥的定义与重要性私钥的管理策略私钥的生成与存储2. 证书的创建与

Python包管理工具pip的升级指南

《Python包管理工具pip的升级指南》本文全面探讨Python包管理工具pip的升级策略,从基础升级方法到高级技巧,涵盖不同操作系统环境下的最佳实践,我们将深入分析pip的工作原理,介绍多种升级方... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

PowerShell中15个提升运维效率关键命令实战指南

《PowerShell中15个提升运维效率关键命令实战指南》作为网络安全专业人员的必备技能,PowerShell在系统管理、日志分析、威胁检测和自动化响应方面展现出强大能力,下面我们就来看看15个提升... 目录一、PowerShell在网络安全中的战略价值二、网络安全关键场景命令实战1. 系统安全基线核查

Java操作Word文档的全面指南

《Java操作Word文档的全面指南》在Java开发中,操作Word文档是常见的业务需求,广泛应用于合同生成、报表输出、通知发布、法律文书生成、病历模板填写等场景,本文将全面介绍Java操作Word文... 目录简介段落页头与页脚页码表格图片批注文本框目录图表简介Word编程最重要的类是org.apach

Python设置Cookie永不超时的详细指南

《Python设置Cookie永不超时的详细指南》Cookie是一种存储在用户浏览器中的小型数据片段,用于记录用户的登录状态、偏好设置等信息,下面小编就来和大家详细讲讲Python如何设置Cookie... 目录一、Cookie的作用与重要性二、Cookie过期的原因三、实现Cookie永不超时的方法(一)

Linux中压缩、网络传输与系统监控工具的使用完整指南

《Linux中压缩、网络传输与系统监控工具的使用完整指南》在Linux系统管理中,压缩与传输工具是数据备份和远程协作的桥梁,而系统监控工具则是保障服务器稳定运行的眼睛,下面小编就来和大家详细介绍一下它... 目录引言一、压缩与解压:数据存储与传输的优化核心1. zip/unzip:通用压缩格式的便捷操作2.

Linux中SSH服务配置的全面指南

《Linux中SSH服务配置的全面指南》作为网络安全工程师,SSH(SecureShell)服务的安全配置是我们日常工作中不可忽视的重要环节,本文将从基础配置到高级安全加固,全面解析SSH服务的各项参... 目录概述基础配置详解端口与监听设置主机密钥配置认证机制强化禁用密码认证禁止root直接登录实现双因素