tambre tambre - 9 months ago 130
C++ Question

How to draw primitives in Vulkan?

Assuming that Vulkan has already been initialized, you're recording to a command buffer, you have a frame buffer and a render pass, how does one draw primitive 2D geometric shapes using Vulkan?

vkCmdBeginRenderPass(command_buffer, &render_pass_info, VK_SUBPASS_CONTENTS_INLINE);

// Draw primitives here



The drawing setup is quite involved, but the actual calls required to draw are fairly straightforward. From the tri.c (which draws a 2D triangle):

// ...
vkCmdBeginRenderPass(demo->draw_cmd, &rp_begin, VK_SUBPASS_CONTENTS_INLINE);
vkCmdBindPipeline(demo->draw_cmd, VK_PIPELINE_BIND_POINT_GRAPHICS,
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);
// ...

This snippet assumes that you've already gotten the VkPipeline (which include shaders, etc.), VkBuffer (for the vertex buffer), and the VkCommandBuffer in appropriate states. It's the vkCmdDraw that actually issues the command to draw, once the containing VkCommandBuffer is executed.