Skip to content

Draw You a Triangle for Great Good

Devin Brite edited this page Jul 14, 2020 · 8 revisions

Foreword

Make sure you've read the first few chapters of Learn Wgpu, Introduction through The Swapchain, so that you have the tools you need to get started.

Prerequisites

  • Surface
  • Adapter
  • Device
  • Queue
  • SwapChain

Vertices & Shaders

First, create some vertices and get them ready for use.

Now you should have Buffer of vertices and an easy way to get the VertexBufferDescriptor of said vertices.

At some point you'll need to write shaders. The vertex shader for this example looks like:

#version 450

layout(location=0) in vec3 a_position;
layout(location=1) in vec3 a_color;

layout(location=0) out vec3 v_color;

void main() {
    v_color = a_color;
    gl_Position = vec4(a_position, 1.0);
}
// shader.frag
#version 450

layout(location=0) out vec4 f_color;

void main() {
    f_color = vec4(0.3, 0.2, 0.1, 1.0);
}

You'll need to compile to spirv with shaderc, then read the spirv into bytes, and create your ShaderModules.

Once that's done we can create a RenderPipeline using the shader modules and VertexBufferDescriptor from earlier.

We'll talk about indices later, but for now use index_format: IndexFormat::Uint32.

render() -- the function we call every "frame"

Grab the next swapchain image

Create a CommandEncoder

Begin a RenderPass using the command encoder

Set the RenderPass's pipeline

Set the RenderPass's vertex buffer

Draw the RenderPass (use indices 0..3)

Finish the CommandEncoder and submit the resulting CommandBuffer to the command Queue

Done!

you've drawn a hello triangle!

good job, you :)