Field Notes · Real-Time 3D

The Graphics Pipeline,
from program to pixel

A ground-up mental model: how a 3D engine on the CPU turns a scene into commands, and how the GPU turns those commands into the colored pixels on your screen. Built general → specific. No filler.

Scope: game graphics · raster pipeline Format: takes / does / outputs Terms: English-first
The one idea everything hangs on

A 3D program does not draw pixels. The CPU/engine prepares scene data and writes a to-do list of commands. The GPU reads that list and executes it — turning geometry + data into pixels. CPU = author of the list. GPU = executor of the list.

§ 01

Where your program actually sits

Your .exe never talks to the GPU directly. It talks downward through a stack of layers, each one more concrete and less portable than the one above it.

Your code · Unity / Unreal / OpenGL app "render this scene" Graphics API · DirectX / Vulkan / Metal / OpenGL the vocabulary you write commands in GPU Driver translates API calls → this exact GPU's machine commands GPU Hardware thousands of cores executing in parallel Render Target / Framebuffer → Screen where the finished pixels land commands + data flow down more concrete ↓ · less portable ↓
Fig 1. The layer stack. Each call you make is re-translated all the way down.

Broad neighbors worth placing on the map

§ 02

The CPU side: building the to-do list

Before a single pixel is touched, the CPU does a lot of organizing. Think of one frame as three jobs in sequence.

① Main / Game thread — decide what exists

② Worker threads / engine jobs — decide what's worth drawing

Then a render prep step: find visible renderers → sort them (by render queue, material, shader pass, depth) → group by material/pass/target → batch where possible → build the actual render commands.

③ Render thread — submit the commands

For each render pass, then for each batch, the engine issues a tight sequence of binds followed by a draw:

Why "bind" is not "copy"

Bind = "make this already-existing GPU resource the active one for the next command." It's setting a pointer, not creating, copying, or moving data. Bind vertex buffer = "use this mesh's vertices next." Bind render target = "send output pixels here." The data was uploaded to GPU memory earlier; binding just points at it.

Correction to a common belief The CPU never colors a pixel. It assembles a command list. That's the whole job of this side.

§ 03

Seven words you must keep straight

These get blurred constantly. Lock them down and 80% of the confusion disappears.

TermWhat it actually is
ResourceData living in GPU memory — a buffer or a texture.
StateConfiguration / rules for rendering (blend mode, depth test, which shader).
CommandAn instruction to do work now.
ShaderProgrammable GPU code you wrote (HLSL/GLSL).
Pipeline stageA worker/station along the rendering route.
Draw callThe command that runs the graphics pipeline once.
DispatchThe command that runs the compute pipeline once.

The split that matters most: data (resource) vs rules (state) vs action (command). Binding sets up data and rules; a draw/dispatch is the action that fires.

§ 04

CPU and GPU run in parallel — and where it stalls

The CPU does not wait after every draw call. It throws commands into a queue and moves on. The GPU drains that queue on its own clock. They overlap by a frame.

CPU GPU build frame N build frame N+1 build frame N+2 render frame N render frame N+1 overlap: CPU on N+1 while GPU finishes N
Fig 2. Double buffering of work. The two processors are pipelined a frame apart.

When the CPU is forced to stall (block and wait)

Rule of thumb Anything that asks the GPU "are you done? give me the answer now" is a stall risk. Fire-and-forget is fast; round-trips are slow.

§ 05

Render passes & counting draw calls

A render pass is a logical stage with a target

Not "a run of the render thread." A pass = "do this rendering, for this purpose, into this target." One pass holds one or many draws/dispatches/blits.

"One GameObject = one draw call" is wrong

A better model:

draw calls ≈ visible batches × submeshes/materials × shader passes × cameras/passes
Drives count UPDrives count DOWN
shadows, depth prepassstatic/dynamic batching
multiple materials / submeshesGPU instancing
transparent sortingSRP Batcher (cuts CPU state-setup cost)
multiple cameras, XR eyes
post-processing, many forward lights
Nuance on the SRP Batcher

It doesn't always reduce the number of draw calls — it reduces the CPU cost of setting up state between them by keeping material data persistent on the GPU. Instancing reduces the count; the batcher reduces the per-call overhead. Different levers.

§ 06

The raster pipeline — the heart of it

One draw call sends geometry through this fixed route. Two stages are programmable (you write the shader); the rest are fixed-function hardware you only configure.

Draw Call Input Assembler fixed Vertex Shader PROGRAMMABLE Tessellation / Geometry opt FIXED-FUNCTION GEOMETRY Clipping · Perspective Divide (÷w) · Viewport Transform clip-space → NDC → screen-space pixel coordinates Rasterizer fixed triangles → fragments; interpolates UV / normal / depth Fragment / Pixel Shader PROGRAMMABLE Depth / Stencil Test fixed Blending / Output Merger fixed Render Target / Framebuffer
Fig 3. One draw call, top to bottom. Red = you write it · gray = you configure it.
§ 07

Each stage, in takes / does / outputs

Input Assembler fixed

takes
vertex buffer + index buffer + primitive topology
does
assembles primitives (usually triangles) from the raw vertices
outputs
structured per-vertex data, ready for the vertex shader

Vertex Shader programmable

takes
per-vertex attributes (position, normal, UV, tangent, color) + constants (MVP matrices, material params)
does
transforms local position → clip space; passes UV/normal/world-pos forward
outputs
a clip-space position as SV_POSITION, plus interpolatable attributes

Clip → Perspective Divide → Viewport fixed

takes
clip-space positions float4(x,y,z,w)
does
cuts geometry outside the frustum → divides xyz by w to get NDC → maps NDC to screen pixels
outputs
screen-space triangles
Subtle distinction students miss

Clip space ≠ NDC. Clip space is still homogeneous (the w is meaningful, used for clipping). NDC is what you get after dividing by w — a tidy cube where x,y,z ∈ [-1,1] (or [0,1] for z in D3D). The perspective effect (far things shrink) happens in that divide.

Rasterizer fixed

takes
screen-space triangles
does
finds which pixels a triangle covers → generates fragments → interpolates UV, normal, depth, world-pos across the surface
outputs
one fragment (pixel candidate) per covered sample, with interpolated data

Fragment / Pixel Shader programmable

takes
interpolated per-fragment data + textures/samplers + constants
does
computes the fragment's color — typically samples textures by UV and applies lighting using the normal
outputs
a color (and optionally depth)

Depth / Stencil Test fixed

takes
the fragment + its depth + the current depth/stencil state
does
keeps or rejects the fragment (is it in front of what's already there?)
outputs
surviving fragments

Typical opaque state: ZTest LEqual, ZWrite On. Typical post-process: ZTest Always, ZWrite Off (draw unconditionally).

Blending / Output Merger fixed

takes
the new fragment color + the color already in the render target
does
combines them per the blend state
outputs
the final pixel written to the render target

Opaque: Blend Off (overwrite). Alpha transparency: Blend SrcAlpha OneMinusSrcAlpha (mix by alpha).

Render target = where finished pixels live: screen backbuffer, a CameraColor texture, a RenderTexture, a G-buffer, a mask texture.

§ 08

Vertex buffer vs index buffer

Two buffers, two jobs. The vertex buffer holds the data; the index buffer holds the recipe for connecting it into triangles.

tri A tri B v0 v1 v2 v3 VERTEX BUFFER (the data) v0 → pos, normal, uv, tangent… v1 → pos, normal, uv, tangent… v2 → pos, normal, uv, tangent… v3 → pos, normal, uv, tangent… INDEX BUFFER (the recipe) 0, 1, 2 → triangle A 0, 2, 3 → triangle B 4 vertices reused to make 2 triangles — no data duplicated.
Fig 4. Indices point into the vertex buffer, so shared corners are stored once.

Why split them at all?

The classic puzzle: how many vertices in a cube?

CountWhat
8geometric corner positions
24render vertices for a hard-edged cube
36indices (12 triangles × 3)
Why 24, not 8

A render vertex is position + normal + UV + …, not just position. At a cube corner three faces meet, and each face needs a different normal (it points a different way) and usually a different UV. Same position + different normal = a different render vertex. Three faces per corner × 8 corners = 24. The index buffer keeps the connectivity cheap (36 small ints) even though the vertices can't be shared across faces.

interactive cube vertex & index buffer explorer
Toggle “by shared corner” and pick (+1,+1,+1) to see one point stored 3×. Switch hard/smooth to watch the count collapse to 8.
§ 09

Face vs triangle — and why triangles win

A cube has 6 square faces conceptually. Each square is triangulated into 2 triangles → the GPU renders 12 triangles. The GPU doesn't inherently know two triangles were once one quad unless tooling preserves that grouping.

Why the hardware bets everything on triangles

One-liner Quads are artist-friendly; triangles are rasterizer-friendly. The GPU is built around the triangle.

§ 10

UVs & normals — the two riders on every vertex

Position decides where a corner lands on screen. But two more attributes ride along and are interpolated across every triangle.

AttributeIsUsed for
UVa 2D texture coordinatewhich part of a texture maps onto the surface
Normala surface direction (not a position)lighting — how bright the surface faces a light

Flow: each triangle has 3 vertices carrying position/UV/normal → the rasterizer interpolates UV and normal across the face → the fragment shader gets a per-fragment UV and normal → it samples the texture by UV and computes lighting with the normal.

UV details

Normal details

§ 11

Matrices & the MVP chain

A matrix is a machine that moves a position from one coordinate space into another. Rendering is just a relay of these conversions until a vertex lands in clip space.

Object / Local Space vertex as authored in the model × Model World Space where it sits in the scene × View View / Camera Space relative to the camera at origin × Projection Clip Space float4(x,y,z,w) — VS output ends here ÷ w NDC tidy [-1,1] cube · perspective applied viewport Screen Space actual pixel coordinates vertex shader fixed-function
Fig 5. The relay. Your vertex shader does the top three multiplies; the GPU does the divide + viewport.
MatrixConvertsComes from
ModelObject → Worldthe object's transform (pos/rot/scale)
ViewWorld → Camerathe camera's transform (its inverse)
ProjectionCamera → ClipFOV, aspect, near/far, ortho settings
clipPos = Projection · View · Model · localPos   =  MVP · localPos

The CPU/engine builds and binds these matrices before the draw. The vertex shader applies them per vertex and outputs SV_POSITION; the GPU handles the rest of the relay.

Why 4×4 matrices and the w component

Homogeneous coordinates

Rotation and scale are linear and fit in a 3×3 matrix, but translation (moving) does not — a pure 3×3 can't add an offset. Bumping up to 4×4 with a w coordinate lets one matrix express translation and rotation/scale and perspective together. That's the whole trick.

  • Positions use w = 1 → translation affects them (a point can move).
  • Directions/normals use w = 0 → translation is ignored (a direction has no location, only orientation).

The normal-transform catch

Positions go through the model matrix directly. Normals are transformed as directions — and under non-uniform scale, naively applying the model matrix skews them off the surface. The fix is the inverse-transpose of the model matrix. Unity hands you UnityObjectToWorldNormal so you rarely write it by hand, but know why it exists.

interactive MVP transform tracer
Drag the sliders; trace one corner from local space to screen. Switch to orthographic to see w stay 1 and the perspective divide do nothing.
§ 12

Rasterization & barycentric interpolation

The vertex shader handed three clip-space corners to the fixed-function stages, which divided by w and mapped them to screen pixels. The rasterizer now answers two questions for every pixel: is it inside the triangle? and what are its interpolated attributes? Remarkably, one piece of math answers both.

Barycentric coordinates — what they are

For a triangle A, B, C, every point P in the plane can be written uniquely as a weighted blend of the corners, with the weights summing to one:

P = α·A + β·B + γ·C    with   α + β + γ = 1

(α, β, γ) are P's barycentric coordinates — how much each vertex contributes. At A they are (1,0,0), at B (0,1,0), at C (0,0,1). P is inside the triangle exactly when all three are ≥ 0. A negative weight means P is outside — that is the coverage test.

α β γ A B C P
Fig 6. Each weight is an area ratio: α = area(PBC)/area(ABC), β = area(APC)/area(ABC), γ = area(ABP)/area(ABC). As P → A, the opposite sub-triangle fills everything → α → 1.

How they're computed

The 2D cross product cross(u,v) = u.x·v.y − u.y·v.x gives twice a triangle's signed area. With Total = cross(B−A, C−A):

α = cross(B−P, C−P) / Total  ·  β = cross(C−P, A−P) / Total  ·  γ = 1 − α − β

This is the edge function, and it is exactly what hardware rasterizers evaluate per pixel: the sign gives the inside/outside test, the magnitude gives the interpolation weight. Coverage and weights fall out of one cheap, incremental computation.

Interpolating attributes

Once you have the weights, every per-vertex attribute — uv, normal, color, anything the vertex carried — is blended with the same weights. The fragment shader then receives these interpolated values.

Affine vs perspective-correct

Affine (screen-linear) blends directly: uv = α·uvA + β·uvB + γ·uvC. Cheap, but wrong under perspective — after projection, equal screen steps are not equal surface steps, so the texture visibly slides (the PlayStation-1 wobble). It is exact only when all w are equal.

Perspective-correct blends attr/w and 1/w linearly, then divides — recovering the value that is linear along the real 3D surface:

uv = ( α·uvA/wA + β·uvB/wB + γ·uvC/wC ) / ( α/wA + β/wB + γ/wC )

The GPU does this automatically for all interpolators (unless you mark one noperspective).

The depth value

Meaning: how far the fragment is along the view direction — written per-pixel to the depth (z) buffer and used by the depth test to resolve occlusion. Value: the post-divide NDC z (mapped to [0,1] in the buffer). Computed: NDC z is itself screen-linear over a planar triangle, so it interpolates with plain barycentric weights — no 1/w correction needed:

depth = α·zA + β·zB + γ·zC
Why depth precision is uneven

NDC depth is not linear in real-world distance — it is hyperbolic (1/z-like), packing most precision near the camera. That is why distant surfaces z-fight and why the near/far choice matters so much.

interactive rasterizer & barycentric interpolation
Drag A / B / C, click a pixel to read its α/β/γ weights, and toggle affine vs perspective-correct.
§ 13

Inside the fragment shader — texturing & lighting

The rasterizer delivers, per fragment, an interpolated uv and normal. The fragment shader's job is to turn those into a final color. Two operations dominate: sample a texture with the uv, and apply lighting with the normal.

// runs once per fragment float4 frag (v2f IN) : SV_Target { float2 uv = IN.uv * _Tiling; // scale / tile float3 tex = SAMPLE(_MainTex, uv); // wrap + filter happen in the sampler float3 N = normalize(IN.normalWS); // re-normalize the interpolated normal float3 L = normalize(_LightDir); float diff = max(0, dot(N, L)); // Lambert / cosine law float3 col = tex * (_Ambient + (1 - _Ambient) * diff); return float4(col, 1); }

Texture sampling

A texel is one stored color in the texture grid. Sampling maps a continuous uv ∈ [0,1] into texel space (uv × textureSize) and reads a color there. Two settings govern it.

Wrap (address) mode — what happens when uv leaves [0,1]:

ModeBehavior
repeatfrac(uv) — the texture tiles seamlessly.
clampuv is clamped to [0,1] — the edge texels stretch outward.
mirroreach successive tile is flipped — mirrored repeat.

Filtering — what happens between texel centers:

ModeBehavior
nearestpick the closest texel — blocky, pixelated.
bilinearblend the 4 nearest texels by fractional position — smooth.

For minification, GPUs add mipmaps (pre-shrunk copies) with trilinear blending, and anisotropic filtering for grazing angles.

Lighting (Lambert diffuse)

The normal N is the direction the surface faces; L points toward the light. Their dot product is the cosine of the angle between them:

brightness = max( 0, dot(N, L) )

Facing the light → 1 (bright); perpendicular → 0 (dark); facing away → negative, clamped to 0. This is Lambert's cosine law. ambient is a small floor so unlit areas are not pure black; the final color is texColor × (ambient + (1−ambient)·diff).

The renormalize trap

A weighted average of two unit vectors is generally shorter than 1, so the interpolated normal is not unit-length. The fragment shader must normalize() it before use, or lighting comes out subtly wrong.

interactive fragment shader — texturing & lighting
Lower tiling below 1 to expose nearest vs bilinear; raise it to compare wrap modes; rotate the light to move the highlight.
§ 14

Post-process & blit

Effects like tone-mapping or bloom still ride the graphics pipeline — they just draw a single fullscreen triangle/quad and run all their logic in the fragment shader.

So "blit" = draw a fullscreen quad that reads texture A and writes target B. Same pipeline, trivial geometry, all the work in the pixel shader.

§ 15

The compute pipeline — the other road

Not every GPU job is about triangles. The compute pipeline runs general-purpose GPU programs over raw data.

Graphics pipelineCompute pipeline
fired byDraw callDispatch
hasvertex shader, rasterizer, fragment shader, depth/blendone compute shader, run over thread groups
producespixels in a render targetdata in buffers/textures

Used for image processing, simulations, particles, GPU culling, and buffer/texture transforms — no rasterization anywhere. This is the road CUDA / TensorRT-style workloads conceptually live on.

§ 16

The 30-second master answer

Say this and you've got it

A 3D engine prepares visible work on the CPU — culls, sorts, batches — then binds GPU resources + pipeline state and submits draw commands. The GPU runs the raster pipeline: input assembly builds triangles from vertex/index buffers, the vertex shader transforms them with MVP matrices, the rasterizer turns triangles into fragments and interpolates attributes, the fragment shader computes color, depth/blend decide visibility and composition, and the result is written to a render target. Compute dispatch is a separate road that runs compute shaders over buffers — no rasterization.


Confusions this note deliberately corrected

WrongRight
CPU draws pixelsCPU writes commands; GPU draws pixels
bind = copy databind = point at existing data
1 GameObject = 1 draw calldraws ≈ batches × materials × passes × cameras
clip space = NDCNDC is clip space after ÷w
a cube has 8 vertices8 positions, 24 render vertices, 36 indices
render pass = a thread runrender pass = a logical stage with a target
SRP Batcher cuts draw countit cuts per-call CPU state cost