Vertex shader

On this page 7

A vertex shader is a small program that runs on the graphics processing unit (GPU) once for every vertex of a mesh, transforming its position into clip space and computing the per-vertex data that later stages need. In Real-time 3D, it is the first programmable stage of the rasterization pipeline and the place where model, view and projection transformations are applied.

Because a vertex shader touches geometry rather than pixels, its cost scales with vertex count, not screen resolution. It is also the stage where artists and engineers implement skeletal skinning, wind animation on foliage, water waves and other forms of procedural deformation without changing the stored mesh.

How a vertex shader processes geometry

A vertex shader receives one vertex at a time together with its attributes and returns one transformed vertex. Each invocation is independent: it cannot see neighboring vertices or create new ones, which is exactly why GPUs can run thousands of invocations in parallel.

The mandatory output is a four-component clip-space position, written to gl_Position in GLSL or to a variable marked SV_Position in HLSL. Fixed-function hardware then performs clipping, the perspective divide by the w component and the viewport transform before rasterization turns triangles into fragments.

The table below lists the inputs and outputs that a typical vertex shader handles.

DataDirectionPurpose
Object-space positionInput attributeBase location of the vertex in the mesh
Normal and tangentInput attributeOrientation for lighting and normal mapping
Texture coordinatesInput attributeLookup positions for textures
Bone indices and weightsInput attributeSkinning influences from the skeleton
Transformation matricesUniform or constant bufferShared values for the whole draw call
Clip-space positionRequired outputFeeds clipping and rasterization
VaryingsOptional outputInterpolated across the triangle for the fragment shader
Typical vertex shader inputs and outputs

The transformation chain inside the vertex stage

The core job of most vertex shaders is the model-view-projection (MVP) chain, a sequence of 4×4 matrix multiplications that moves a point from the coordinates of the mesh to the coordinates of the screen. Engines often premultiply these matrices on the CPU to save arithmetic per vertex.

SpaceProduced byTypical use
Object spaceStored mesh dataModeling and skinning
World spaceModel matrixLighting, fog and world-aligned effects
View spaceView matrixDepth-based effects and camera-relative math
Clip spaceProjection matrixClipping and perspective divide
Normalized device coordinatesFixed-function divide by wViewport mapping and depth testing
Coordinate spaces in the vertex stage

Normals need special care: they are transformed by the inverse transpose of the model matrix so that they stay perpendicular to surfaces under non-uniform scaling. Forgetting this produces lighting that skews when an object is stretched along one axis.

Vertex shader compared with other shader stages

The vertex shader is one of several programmable stages, and its role is defined by what it runs on and what it may output. The fragment shader and the compute shader, which have their own entries in this topic, handle pixels and general-purpose work respectively.

StageRuns once perMain responsibility
Vertex shaderVertexPosition transformation and per-vertex data
Tessellation shadersPatch and generated vertexSubdividing surfaces on the GPU
Geometry shaderPrimitiveEmitting or discarding primitives
Mesh shaderWorkgroup of a meshletReplacing the vertex front end with flexible output
Fragment shaderRasterized fragmentFinal color, depth and lighting
Compute shaderThread in a dispatchGeneral GPU work outside the raster pipeline
Shader stages and their responsibilities

Work placed in the vertex shader is evaluated at the corners of a triangle and then linearly interpolated. This is cheaper than per-fragment evaluation, but it is accurate only for quantities that vary smoothly across the surface, which is why per-vertex Gouraud lighting has largely given way to per-pixel lighting.

Common uses in real-time engines

Beyond the MVP chain, vertex shaders carry a large share of animation and deformation in interactive applications. Moving this work from the CPU to the GPU keeps mesh buffers static and reduces bus traffic each frame.

  • Skeletal skinning blends each vertex between up to four or eight bone matrices according to its weights.
  • Morph targets add stored offsets for facial expressions and corrective shapes.
  • Vegetation sway uses sine waves, wind vectors and vertex colors as masks.
  • GPU instancing reads a per-instance matrix so one draw call renders many copies.
  • Billboards rotate quads to face the camera directly in the vertex stage.
  • Displacement from height maps offsets vertices along their normals.

In WebGL libraries such as Three.js and Babylon.js, developers usually extend built-in materials by injecting snippets into the generated vertex shader rather than writing a complete program, which preserves lighting and shadow support.

Performance limits and common mistakes

Vertex processing rarely limits performance on modern GPUs, but it becomes a bottleneck with dense meshes, heavy skinning or many shadow passes, because each shadow map renders the geometry again. Level of detail and culling reduce the number of vertices that reach the stage.

SymptomLikely causeFix
Objects vanish at bounding edgesDeformation moves vertices outside stale boundsEnlarge the bounding volume used for culling
Shadows detach from animated meshesShadow pass uses a different vertex shaderShare the deformation code across all passes
Lighting skews on scaled objectsNormals use the plain model matrixUse the inverse transpose matrix
Jittering geometry far from originInsufficient float precisionUse camera-relative rendering
Low frame rate on dense scenesToo many vertices per frameAdd level of detail and culling
Symptoms, causes and fixes

The post-transform vertex cache also matters: indexed meshes whose triangles reuse nearby vertices avoid rerunning the shader. Mesh optimization tools reorder indices to maximize cache hits, which can noticeably cut vertex workload.

The short version

A 3D model is a cloud of corner points joined into triangles. The vertex shader decides where each corner lands on your screen. It takes every point, moves it with the object, looks at it through the camera and flattens it into a picture.

Think of a puppeteer who adjusts each joint of a puppet before the photo is taken. The shader can also bend, sway or wobble shapes while the game runs. Trees move in the wind and characters walk, yet the stored model never changes.

Where it makes a difference

A small studio builds a browser game with a forest of 20,000 instanced trees. Animating every branch on the CPU would mean updating millions of vertices each frame and uploading them again, which a laptop cannot sustain at 60 frames per second.

Instead, the team writes a vertex shader that reads a wind direction uniform and uses vertex colors as sway masks: trunks stay fixed while leaf tips move the most. Each tree receives a random phase from its instance data so the forest does not move in lockstep. The same code runs in the shadow pass, so shadows follow the leaves. The result is convincing wind at negligible CPU cost, and the frame budget remains free for gameplay logic.