Introduction#
Part 2 introduced the vertex shader as the first programmable stage of the pipeline, and parts 4 to 7 built the matrices it uses. Now it’s time to write one. This post covers:
- What goes in to a vertex shader and what comes out
- The one job every vertex shader must do
- What else vertex shaders are used for, such as waves, wind and animation
- What a vertex shader can’t do
The demo is a live editor: change the code and the shape on screen updates as you type.
What Goes In, What Comes Out#
A vertex shader is a small function that the graphics card runs once for each vertex in a draw call, thousands or millions of times, in parallel. Each run handles one vertex, on its own. It’s written in a shading language: GLSL for OpenGL and WebGL (used here), HLSL for Direct3D, and MSL (Metal Shading Language) for Metal. They all look much like the C programming language, but you don’t need to know C: this post explains everything the examples use.
It receives three kinds of input:
- Attributes: the data stored with this particular vertex, such as its position, normal and texture coordinate (part 3). Each run gets different values.
- Uniforms: values that are the same for every vertex in the draw call, such as the model, view and projection matrices, or the current time. They’re set by the CPU before drawing.
- Built-in values provided by the graphics card, such as
gl_VertexID, the vertex’s number in the list of vertices.
And it produces two kinds of output:
- The position, in clip space (part 5). In GLSL it’s written to a built-in variable called
gl_Position. This is the one job every vertex shader must do. - Varyings: any other values you want to pass on, such as a colour, a normal or a texture coordinate. They’re blended across each triangle and handed to the fragment shader, as part 10 explains.
The most common vertex shader in the world looks something like this:
#version 300 es
layout(location = 0) in vec3 aPosition; // attribute
uniform mat4 uModelViewProj; // uniform: P × V × M
void main() {
gl_Position = uModelViewProj * vec4(aPosition, 1.0);
}
Line by line:
#version 300 essays which version of GLSL this is (the one WebGL2 uses).layout(location = 0) in vec3 aPosition;declares an input (in) calledaPosition, of typevec3: a group of three numbers, the vertex’s x, y and z.layout(location = 0)just says which slot of the vertex data it comes from. The semicolon ends the statement.uniform mat4 uModelViewProj;declares a uniform of typemat4, a 4×4 matrix: the model, view and projection matrices from part 5 multiplied together.- Everything after
//on a line is a comment: a note for humans, ignored by the computer. void main() { … }is the function the graphics card runs for each vertex. The code inside the curly brackets is its body.vec4(aPosition, 1.0)makes a group of four numbers: the position plus the extra w = 1 coordinate from part 4.*means multiply, so the line multiplies it by the matrix, moving the vertex from local space to clip space in one step, and stores the answer (=) ingl_Position.
Reading shader code#
A few more pieces of GLSL appear in the editor below:
- Types. Every variable has a type:
floatis a single decimal number,vec2,vec3andvec4are groups of 2, 3 or 4 numbers, andmat2andmat4are 2×2 and 4×4 matrices.vec3 p = aPosition;makes a new variablepholding a copy of the position. - Parts of a vector.
p.x,p.yandp.zare the separate numbers insidep.p.xzmeans the x and z parts together, as avec2. - Changing a value.
p.y += 0.5;adds 0.5 top.y. (-=subtracts and*=multiplies.) Numbers in GLSL are written with a decimal point, like4.0, to show they’re decimals. - Functions.
sin(x)(Angles, Sine and Cosine) gives a smooth wave that goes up and down between −1 and 1 as x increases, which is perfect for animation.length(v)is the length of a vector,cosis another wave (the same shape, shifted along), andnormalizeandmixare explained where they’re used.
Try It: A Live Vertex Shader#
The top part of the shader (the inputs, uniforms and outputs) is fixed and shown in grey. It uses uViewProj rather than the uModelViewProj above: just the view and projection matrices. That’s because this demo’s mesh sits at the centre of the world without being moved, so it has no model matrix (its model space and world space are the same). It also has two outputs, vWorld and vColor, which pass the moved position and a colour on to the fragment shader. Edit the body of main() below it. Pick a preset to start from, then change the numbers and see what happens. Drag the shape to turn it.
Edit the vertex shader and watch the mesh change
Things to try:
In Wave, change
4.0to12.0for shorter waves, or swapp.xforp.zto change direction. Games move water, flags and grass this way, with no extra work for the CPU.Twist does nothing to the flat grid, because the amount of twist depends on height and the grid is flat. Switch the shape to Sphere: the same code works on any mesh, because it only ever looks at one vertex at a time.
Colour by vertex number gives every vertex a random colour based on
gl_VertexID. Each triangle shows a blend of its three corners’ colours: proof that the colours really are worked out per vertex.Fix the mistake won’t compile (be translated into instructions the graphics card can run). While it’s broken, the picture greys out and keeps showing the last shader that worked. Read the error and the plain-English note under it, then fix the line. When it works, a hill rises out of the middle of the grid.
Show answer
vec3(…)turns the number inside it into a vec3 (three numbers), butp.yholds just one number, so they don’t fit. Deletevec3(and its matching), so the line adds a single number:p.y += uAmount * 0.6 * cos(length(p.xz) * 2.5);With the wireframe on, notice that the shape can only bend at vertices. Between them, the triangles stay flat. A vertex shader can only move the vertices that exist.
(The lighting is worked out in the fragment shader from the moved positions, using a trick explained later in Flat Shading with ddx and ddy, so you don’t need to update the normals yourself here.)
What Vertex Shaders Are Used For#
Besides transforming positions with matrices, real games use vertex shaders for:
- Skinning: bending a character’s mesh to follow its skeleton. Each vertex stores which bones affect it, and by how much, and the shader blends those bones’ matrices.
- Morph targets: blending between several versions of a mesh, such as facial expressions.
- Wind and water: moving grass, leaves, flags and waves with formulas like the ones above.
- Billboards: turning flat cards, such as the little images used for smoke and sparks, or distant trees, to always face the camera.
- Passing data along: computing values once per vertex, such as fog amount or a world-space position, for the fragment shader to use.
What Vertex Shaders Can’t Do#
- They can’t see other vertices. Each run only knows about its own vertex. That’s what lets thousands run in parallel, in any order.
- They can’t create or delete vertices. One vertex goes in, one comes out. (Some optional extra pipeline stages can add geometry, but WebGL doesn’t have them.)
- They don’t decide colours on screen. They can pass colours along, but which pixels get which colour is decided later, by rasterisation and the fragment shader.
A graphics card doesn’t run one vertex at a time. It gathers vertices into groups, typically 32 or 64, and runs the shader on the whole group at once, with every vertex in the group executing the same instruction at the same moment on different data. This is called SIMD (single instruction, multiple data), and it’s why a graphics card can afford thousands of tiny processors: they share the work of reading and understanding each instruction. It also explains why shaders are written so that every run does the same thing in the same order. How GPUs Run Shaders covers this in detail.
Summary#
- A vertex shader runs once per vertex, in parallel, each run on its own.
- Its inputs are attributes (per vertex), uniforms (per draw) and built-ins; its outputs are the clip-space position and varyings.
- Its one essential job is writing the position, usually P × V × M × position.
- It can move vertices for animation and effects, but can’t see neighbours or add vertices.
Next, part 8 untangles something that trips up everyone who moves between engines and APIs: matrix conventions. It’s optional on a first read, so if you’d rather keep going, skip to part 9, which follows the transformed triangles into the rasteriser to decide exactly which pixels they cover.
Further Reading#
- The Khronos Group, Vertex Shader: inputs, outputs and built-in variables in detail.
- LearnOpenGL, Shaders: GLSL from the beginning, with uniforms and varyings.
- WebGL2 Fundamentals, Shaders and GLSL: attributes, uniforms and varyings in WebGL2.
- Microsoft, Vertex shader stage: the same stage in Direct3D and HLSL.