WebGPU From Zero · Episode 15
Loading Real Geometry
Loading Real Geometry is Episode 15 of WebGPU From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.
Part of the MasterAllArts Creative 3D Roadmap .
For fourteen episodes you have hand-coded every triangle: a cube from eight corners
you typed yourself, a sphere from two nested loops. That stops today. Real apps don't
generate their meshes — they load them. An artist sculpts a model in
Blender, exports a file, and your renderer turns that file into GPU buffers. The file
format that has survived since 1992, that every tool on earth can export, that is plain
enough to parse in thirty lines, is Wavefront .obj.
So we're going to write an OBJ parser from scratch, weld its weird split indices into
proper GPU vertices, upload the result, and light it — all from a tiny model
embedded as a string right inside this page. No fetch, no
server, no 404. By the end you'll have a parsed, lit, spinning gem assembled from inline
OBJ data, sitting inside a small scene graph with parented parts that orbit. Stop typing
cubes. Let's load a real one.
What you're looking at
One canvas, one parser, six stages of the same machine. Stage 1 shows why we bother
with an index buffer at all. Stage 2 reads the raw OBJ text into flat arrays.
Stage 3 welds those arrays into real vertices and draws the mesh. Stage 4 hangs the
mesh off a scene graph — a node with a parent whose transform it
inherits. Stage 5 stamps the same mesh out a dozen times with different transforms.
Stage 6 lights the whole little scene and lets it orbit. The model dropdown
swaps between two inline OBJ strings; the wireframe toggle strips the fill so
you can see the triangles the parser produced. Everything is in the page — open the
source and search for OBJ_GEM; that string is the entire asset.
Why OBJ — the format that refuses to die
Wavefront OBJ was designed for the Advanced Visualizer in 1992 and it is still the
lingua franca of 3D, for one reason: it is boring text. There is no compression,
no chunk table, no version field to get wrong — just lines like v 0 1 0 that
any human can read and any tool can write in an afternoon. That makes it the perfect
teaching format: you can see the whole asset, and the parser is small enough to fit on a
slide. The price is verbosity (a binary glTF is far smaller) and the welding dance we're
about to do. The mental model transfers directly, though — every loader, glTF and FBX
included, ends in the same place: interleaved vertices + an index buffer handed to the
GPU. Learn it once here on plain text, and the binary formats are just the same
destination reached faster.
| Format | Shape | Welding? | Good for |
|---|---|---|---|
| OBJ | text, split indices | you do it | learning, interchange |
| glTF / GLB | JSON + binary blob | pre-done by exporter | shipping to the web |
| FBX | binary, rich scene | pre-done | DCC pipelines (Maya etc.) |
Stage 1 — Indexed geometry: stop repeating vertices
A triangle list with no index buffer is wasteful. A cube has 6 faces × 2 triangles ×
3 vertices = 36 vertices, even though it only has 8 distinct corners.
Every shared corner is duplicated into the buffer again and again. Indexed drawing fixes
this: you store each unique vertex once in a vertex buffer, then store a list of
u32 indices that say "draw a triangle using vertices 0, 1, 2; then 0, 2,
3…". The GPU's post-transform vertex cache even reuses the shader result for a repeated
index, so it's faster too.
In WebGPU you bind both buffers and call drawIndexed instead of
draw. The demo's Stage 1 badge shows the vertex/index counts so you can
see the saving. Work the cube by hand: non-indexed needs 36 position+normal
vertices = 36 × 6 floats = 864 bytes. Indexed needs 8 unique vertices
(192 bytes) + 36 u32 indices (144 bytes) = 336 bytes — less
than half, and the gap only widens as meshes grow, because a vertex's cost stays fixed
while the number of triangles sharing it climbs.
| vertices stored | index data | total bytes | |
|---|---|---|---|
| non-indexed cube | 36 × 24B = 864 | — | 864 |
| indexed cube | 8 × 24B = 192 | 36 × 4B = 144 | 336 |
For a dense model the win is enormous: shared edges mean most vertices are touched by 4–6 triangles, so an indexed mesh stores roughly one vertex where a non-indexed one stores five or six copies. (Caveat from the next stage: a vertex is only "shared" if all its attributes match — two triangles meeting at a hard crease have the same position but different normals, so they cannot share a vertex. Welding handles exactly that.)
Stage 2 — Parse an inline OBJ
An OBJ file is a text file, one record per line. Four line types matter for a lit mesh:
| Line | Meaning | Example |
|---|---|---|
v | a vertex position (x y z) | v 0 1 0 |
vn | a vertex normal (x y z) | vn 0 1 0 |
vt | a texture coordinate (u v) | vt 0.5 0.5 |
f | a face: indices into the above | f 1//1 2//2 3//3 |
The face line is where OBJ gets strange. Each corner is written
position/texcoord/normal — and those are three separate
indices. 1//1 means "position #1, no texcoord, normal #1".
3/2/5 means "position #3, texcoord #2, normal #5". And every index is
1-based, because OBJ predates zero-based-everything by a decade. Our
parser splits the text into lines, switches on the first token, pushes
v/vn numbers into flat arrays, and records each face corner as
a little {p, t, n} triple (converted to 0-based):
// (a) The OBJ parser — split lines; v / vn → arrays; f corners → triples
function parseOBJ(text) {
const positions = []; // flat: x,y,z, x,y,z, … (from "v")
const normals = []; // flat: x,y,z, … (from "vn")
const faces = []; // array of [{p,t,n}, …] per face
for (const raw of text.split('\n')) {
const line = raw.trim();
if (!line || line[0] === '#') continue; // skip blanks + comments
const parts = line.split(/\s+/);
const tag = parts.shift();
if (tag === 'v') positions.push(+parts[0], +parts[1], +parts[2]);
else if (tag === 'vn') normals.push(+parts[0], +parts[1], +parts[2]);
else if (tag === 'f') {
const corners = parts.map(tok => {
const [p, t, n] = tok.split('/'); // "p/t/n", any may be empty
return {
p: (+p) - 1, // 1-based → 0-based!
t: t ? (+t) - 1 : -1,
n: n ? (+n) - 1 : -1,
};
});
faces.push(corners);
}
}
return { positions, normals, faces };
}
The demo's Stage 2 prints a live read-out of what the parser found:
N positions · M normals · F faces for whichever model is selected. Switch
models and watch the numbers change — that's the parser running on a different inline
string.
Stage 3 — Build buffers + draw: welding the split indices
Here's the catch that trips up everyone's first loader. A GPU vertex is one
bundle of attributes addressed by one index. But OBJ gave us a separate index
for position and normal. The face corner 3/_/5 wants position #3 paired with
normal #5 — and the corner 3/_/9 wants the same position #3 but a
different normal #9. Those are two different GPU vertices, even
though they share a position. You cannot just upload the position and normal arrays
side-by-side; the indices don't line up.
The fix is the classic weld: walk every face corner, build a string
key "p/t/n", and keep a map from that key to a GPU-vertex index. The first
time you see a unique combo, append an interleaved vertex (position + normal) to the
output and remember its index. Every later corner with the same key reuses it. Triangles
with more than three corners (quads, ngons) are fanned: (0,1,2), (0,2,3), …:
// (b) De-index / weld: a GPU vertex = unique (position, normal) pair
function buildMesh(parsed) {
const { positions, normals, faces } = parsed;
const verts = []; // interleaved: px,py,pz, nx,ny,nz, …
const indices = [];
const seen = new Map(); // "p/t/n" → gpu vertex index
const cornerIndex = (c) => {
const key = c.p + '/' + c.t + '/' + c.n;
let idx = seen.get(key);
if (idx !== undefined) return idx; // already welded → reuse
const px = positions[c.p*3], py = positions[c.p*3+1], pz = positions[c.p*3+2];
let nx = 0, ny = 0, nz = 0;
if (c.n >= 0) { nx = normals[c.n*3]; ny = normals[c.n*3+1]; nz = normals[c.n*3+2]; }
idx = verts.length / 6;
verts.push(px, py, pz, nx, ny, nz);
seen.set(key, idx);
return idx;
};
for (const face of faces) {
// triangle-fan any polygon with > 3 corners
for (let i = 1; i < face.length - 1; i++) {
indices.push(cornerIndex(face[0]), cornerIndex(face[i]), cornerIndex(face[i+1]));
}
}
return {
verts: new Float32Array(verts),
indices: new Uint32Array(indices),
};
}
Walk it concretely. Say two faces both reference position 5:
f 5//2 … and f 5//7 …. The keys are "4/-1/1" and
"4/-1/6" (0-based) — different strings, so the map mints two GPU
vertices that happen to share a position but carry different normals. That is exactly
right: it's a hard edge, and each side wants its own normal. Meanwhile a smooth surface
where every face at a vertex shares one vn produces the same key
every time, so the map returns the same index and the vertex is genuinely shared. The map
is doing the whole "is this the same vertex?" decision for you, attribute by attribute.
If a face corner has no normal at all (c.n < 0 — the OBJ omitted
vn lines), the welder here leaves the normal zero and then a small
post-pass computes a flat face normal per triangle so nothing renders unlit (the
house's roof exercises this path). Deriving those flat normals yourself is the first
exercise below. Stage 3 draws the welded mesh; flip on wireframe to see
the actual triangles the parser produced and confirm the fan triangulation is sane.
Stage 4 — A scene graph: nodes with parent transforms
One mesh, drawn once, at the origin, is boring. Real scenes are hierarchies: a turret bolted to a tank, a moon orbiting a planet orbiting a sun. Each object is a node with a local transform (its position/rotation/scale relative to its parent) and a computed world transform. The rule is one line and it is the whole of scene-graph math:
worldMatrix = parentWorldMatrix × localMatrix
A child sits in its parent's coordinate frame. Spin the parent and the child sweeps
around with it, for free, because the parent's rotation is baked into the product. Order
matters: it's parent × local, never the reverse — matrix multiplication
doesn't commute. With the column-major mat4.mul(a, b) from Episode 09, the
parent goes on the left:
// (c) The scene-graph node — worldMatrix = parent × local
class Node {
constructor(mesh = null) {
this.local = mat4.ident();
this.world = mat4.ident();
this.mesh = mesh; // optional GPU mesh to draw at this node
this.children = [];
}
add(child) { this.children.push(child); return child; }
// recompute world matrices top-down
updateWorld(parentWorld = mat4.ident()) {
this.world = mat4.mul(parentWorld, this.local); // ← parent FIRST
for (const c of this.children) c.updateWorld(this.world);
}
}
Why parent-first? Read the product right-to-left, the way a point flows through it. A
child vertex p is first placed by local (where the child sits in
its parent's frame), and that result is then re-placed by parentWorld (where
the parent sits in the world). So world · p = parentWorld · (local · p) —
local acts first because it's nearest the vector. Flip the order and you'd be saying "put
the parent inside the child's frame," which is nonsense for a hierarchy. The recursion in
updateWorld walks the tree top-down so every parent's world matrix is ready
before its children read it.
In Stage 4 the gem is the parent; two smaller gems are its children, parked off to the
side in local space (a translate then a scale). We spin only the parent's
local each frame — the children orbit it without any orbit code of their own,
because the parent's rotation is baked into their world matrix by the product. That is the
entire payoff of a scene graph: animate one node, and everything beneath it follows for
free. A solar system, a skeleton, a robot arm — all the same one-line rule, applied
recursively.
Stage 5 — Multiple instances / nodes
Once you have a node that carries a mesh and a world matrix, drawing the same mesh many
times is trivial: build many nodes that all point at the same GPU buffers but
each have a different local transform. The vertex/index buffers are uploaded
once; only a small per-node uniform (the world matrix and its normal matrix)
changes between draws. In the demo each node writes its 144 bytes into its own 256-byte
slot of one big uniform buffer, and the draw selects the slot with a dynamic
offset — a single bind group, re-pointed per node. That keeps twelve draws cheap:
no new buffers, no new bind groups, just twelve writeBuffers and twelve
drawIndexed calls into distinct windows.
Stage 5 lays out a ring of a dozen gems — one mesh, twelve nodes. This is the moment
instancing earns its keep: at twelve copies the per-draw overhead is invisible, but at
twelve thousand you'd want a single instanced draw reading transforms from a
storage buffer (the draw(indexCount, instanceCount) pattern). That collapse
is the headline of Episode 16; keeping the draws separate here keeps the scene-graph idea
— one node, one transform, one draw — front and center.
Stage 6 — The loaded model, lit and orbiting
Finally we put it together: the parsed mesh, a couple of parented satellites, simple
Lambert lighting from a fixed direction, and a camera that slowly orbits so the scene is
alive on the very first frame. A real solid mesh makes the depth buffer
non-negotiable — without it, whichever triangle is drawn last wins each pixel and the gem
turns inside-out as it spins. So the pass attaches a depth24plus texture with
depthCompare:'less', recreated whenever the canvas resizes. The drawing side
is otherwise the indexed render pass from Episode 09 — bind the vertex buffer, bind the
index buffer, set the per-node uniforms, drawIndexed:
// (d) Uploading + drawing one parsed mesh
function uploadMesh(device, mesh) {
const vbuf = device.createBuffer({
size: mesh.verts.byteLength,
usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
});
device.queue.writeBuffer(vbuf, 0, mesh.verts);
const ibuf = device.createBuffer({
size: mesh.indices.byteLength,
usage: GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST,
});
device.queue.writeBuffer(ibuf, 0, mesh.indices);
return { vbuf, ibuf, count: mesh.indices.length };
}
// per node, per frame: push world + normal matrix, then drawIndexed
function drawNode(pass, node, gpuMesh) {
device.queue.writeBuffer(nodeUBO, 0, new Float32Array([
...node.world, // mat4x4<f32> — column-major, maps 1:1
...mat3normal(node.world), // inverse-transpose for lighting
]));
pass.setBindGroup(1, nodeBind);
pass.setVertexBuffer(0, gpuMesh.vbuf);
pass.setIndexBuffer(gpuMesh.ibuf, 'uint32');
pass.drawIndexed(gpuMesh.count); // ← indexed draw, not draw()
}
And the WGSL is the same lit shader you've seen since Episode 10 — a vertex stage that
multiplies by view-projection and the node's world matrix, and a fragment stage that does
one dot(N, L):
struct Camera { viewProj: mat4x4<f32> };
struct NodeU { world: mat4x4<f32>, normalMat: mat4x4<f32> };
@group(0) @binding(0) var<uniform> cam: Camera;
@group(1) @binding(0) var<uniform> node: NodeU;
struct VSOut { @builtin(position) pos: vec4f, @location(0) nrm: vec3f };
@vertex fn vs(@location(0) p: vec3f, @location(1) n: vec3f) -> VSOut {
var o: VSOut;
let world = node.world * vec4f(p, 1.0);
o.pos = cam.viewProj * world;
o.nrm = (node.normalMat * vec4f(n, 0.0)).xyz; // rotate the normal
return o;
}
@fragment fn fs(i: VSOut) -> @location(0) vec4f {
let N = normalize(i.nrm);
let L = normalize(vec3f(0.4, 0.8, 0.5));
let diff = max(dot(N, L), 0.0) * 0.85 + 0.15; // Lambert + ambient
return vec4f(vec3f(0.55, 0.78, 0.95) * diff, 1.0);
}
That's the entire pipeline, from a string of text to a lit, spinning solid. The model lives in the page; nothing is fetched; it can never 404.
Common pitfalls
- Separate position/normal/uv indices. This is the OBJ
gotcha. You cannot upload the
varray and thevnarray side-by-side — their indices are independent. You must weld each unique"p/t/n"combination into one GPU vertex via a map, as in code block (b). Skip this and your normals will be scrambled onto the wrong positions. - 1-based indices. OBJ counts from 1. Subtract 1 the moment you read a face index, or every triangle references the wrong vertex (and index 0 becomes -1, reading garbage or crashing).
- Quads and ngons. A face line can have 4+ corners. If you assume
exactly 3 you'll silently drop geometry. Triangle-fan them
(
0,i,i+1) — correct for any convex polygon, which exported OBJ faces almost always are. - Winding order. OBJ faces are conventionally counter-clockwise. If
your model renders inside-out (you see the back faces), either your cull mode disagrees
with the winding or your fan reversed it — flip
frontFaceor the cull mode, don't reverse every triangle by hand. - The inline string — never fetch. The model is a JS string in the
page (
OBJ_GEM,OBJ_HOUSE). Nofetch, nofile://CORS surprise, no missing-asset 404. The parser runs on text you already have. (Loading a real external file is the third exercise — and it needs a file picker precisely becausefetchof a local path won't work.) - Scene-graph matrix order. It is
parent × local, in that order. Reverse it and children rotate about their own origin instead of the parent's — a classic "why is my moon spinning in place instead of orbiting?" bug. - Index buffer type.
setIndexBuffer(buf, 'uint32')must match yourUint32Array. A welded model can exceed 65 535 vertices, so reach foruint32rather thanuint16by default here.
Exercises
- Compute flat normals when the OBJ lacks them. Strip the
vnlines from the gem string. Now inbuildMesh, when a face has no normals, compute the face normal with a cross product (normalize(cross(b−a, c−a))) and assign it to all three of that triangle's vertices. You'll get faceted shading — exactly what a normal-less OBJ should look like. - A glTF-style JSON note. glTF is the modern format: instead of text
lines it ships a JSON manifest plus a binary blob of already-interleaved,
already-indexed vertices — no welding needed, because the exporter did it. As a
paper exercise, sketch how you'd map a glTF
accessor(offset, stride, count, componentType) straight onto adevice.createBuffer+writeBuffer. Notice the parser nearly vanishes. - Load a real file by drop. Add a
dragover/drophandler on the canvas, read the dropped.objwithfile.text(), run it through the sameparseOBJ+buildMesh, and re-upload. Suddenly the page loads any model you drag in — and you'll appreciate why a file picker is required: the browser can'tfetcha path off the user's disk.
What's next
Episode 16 — A Tiny Renderer, the Season 2 finale. We take everything
from this season — the matrix stack, depth, lighting, render-to-texture, the scene graph
and loaded meshes from today — and fold it into one small, reusable renderer: a material
abstraction, a draw queue, instanced draws to collapse Stage 5's dozen calls into one,
and a clean scene.add(node) API. The hand-written demos become a library.
See you there.