如何在 Vulkan 中绘制图元?

How to draw primitives in Vulkan?

假设 Vulkan 已经初始化,你正在记录到一个命令缓冲区,你有一个帧缓冲区和一个渲染通道,如何使用 Vulkan 绘制原始 2D 几何形状?

vkCmdBeginRenderPass(command_buffer, &render_pass_info, VK_SUBPASS_CONTENTS_INLINE);

// Draw primitives here

vkCmdEndRenderPass(command_buffer);

绘图设置非常复杂,但绘图所需的实际调用非常简单。来自 tri.c(绘制二维三角形):

// ...
vkCmdBeginRenderPass(demo->draw_cmd, &rp_begin, VK_SUBPASS_CONTENTS_INLINE);
vkCmdBindPipeline(demo->draw_cmd, VK_PIPELINE_BIND_POINT_GRAPHICS,
                              demo->pipeline);
vkCmdBindDescriptorSets(demo->draw_cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, demo->pipeline_layout,
        0, 1, & demo->desc_set, 0, NULL);

VkViewport viewport = {};
viewport.height = (float) demo->height;
viewport.width = (float) demo->width;
viewport.minDepth = (float) 0.0f;
viewport.maxDepth = (float) 1.0f;
vkCmdSetViewport(demo->draw_cmd, 0, 1, &viewport);

VkRect2D scissor = {};
scissor.extent.width = demo->width;
scissor.extent.height = demo->height;
scissor.offset.x = 0;
scissor.offset.y = 0;
vkCmdSetScissor(demo->draw_cmd, 0, 1, &scissor);

VkDeviceSize offsets[1] = {0};
vkCmdBindVertexBuffers(demo->draw_cmd, VERTEX_BUFFER_BIND_ID, 1, &demo->vertices.buf, offsets);

vkCmdDraw(demo->draw_cmd, 3, 1, 0, 0);
vkCmdEndRenderPass(demo->draw_cmd);
// ...

此代码片段假定您已经获得 VkPipeline(包括着色器等)、VkBuffer(用于顶点缓冲区)和 VkCommandBuffer状态。一旦包含 VkCommandBuffer 被执行,实际上是 vkCmdDraw 发出绘制命令。