Skip to content
Tutorials Center
My learning

Topics

Lesson 43 of 50 ยท WebGL and Real-Time Graphics

A Rotating 3D Cube in WebGL

Build a lit, rotating 3D cube in WebGL: model, view and projection matrices as uniforms, indexed drawing, the depth test, and Lambert lighting in the shader.

A triangle on screen proves that the pipeline works, but a rotating cube is where WebGL starts to feel like real 3D. To get there you need four ideas that you already know from the earlier chapters: transformation matrices, the perspective projection, hidden-surface removal and a simple lighting model. WebGL does not give you any of them for free. It gives you a vertex shader, a fragment shader and a depth buffer, and you supply the math.

In this lesson you will pass a model-view-projection matrix to the vertex shader as a uniform, describe the cube with an index buffer so shared corners are not repeated unnecessarily, switch on the depth test, and compute Lambert diffuse lighting in the shader. If the shader vocabulary is new, read Shaders and GLSL Basics first, and WebGL Overview for the buffer and draw-call setup.

The plan for one frame

Every frame follows the same recipe. The CPU (your JavaScript) builds the matrices and sends them to the GPU as uniforms. One drawElements call then runs the vertex shader once per vertex and the fragment shader once per covered pixel.

flowchart LR
  A["JavaScript<br/>build model, view,<br/>projection matrices"] --> B["Uniforms<br/>uMVP, uModel"]
  B --> C["Vertex shader<br/>gl_Position = uMVP * position"]
  C --> D["Rasterizer<br/>covered pixels,<br/>interpolated varyings"]
  D --> E["Fragment shader<br/>Lambert lighting"]
  E --> F["Depth test<br/>nearest wins"]
  F --> G["Framebuffer"]

The CPU prepares the matrices; the GPU runs the per-vertex and per-pixel work.

Matrices as uniforms

You met the three transformations in 3D Points and Transformation Matrices, The Camera and View Transformation and Orthographic and Perspective Projection. A vertex goes through them in this order:

TEXT
clip position = Projection * View * Model * vertex

Since the product is the same for every vertex of the cube, multiply the three matrices once per frame in JavaScript and upload the result as a single mat4 uniform called uMVP. The vertex shader then needs only one multiplication.

There is one trap: WebGL expects matrices in column-major order. A Float32Array of 16 numbers is read column by column, so the translation part of a 4 by 4 matrix lives in elements 12, 13 and 14, not in elements 3, 7 and 11. Many beginner bugs (a cube that shears, or never appears) come from writing matrices in the row-major layout used in textbooks and uploading them unchanged. WebGL 1 also forces the transpose argument of uniformMatrix4fv to be false, so you must lay the numbers out correctly yourself.

Why a second matrix, uModel?

For lighting you need each normal in a space where the light direction is known. We keep the light fixed in world space, so the shader also receives the model matrix alone (uModel) and rotates every normal with it. This is correct as long as the model matrix contains only rotations and translations. With non-uniform scaling you would need the inverse transpose of the matrix instead.

The cube as an indexed mesh

A cube has 8 corners but 6 faces, and each face needs its own normal for crisp lighting. A corner is shared by three faces that each want a different normal, so the usual solution is to give every face its own 4 vertices: 24 vertices in total, each carrying a position, a normal and a color. Each face is two triangles, so we list six indices per face: 0 1 2 and 0 2 3 (offset by 4 for each next face). The result is 36 indices in a Uint16Array.

Why bother with indices instead of listing 36 full vertices? A quad needs 6 triangle corners but only 4 distinct vertices, so indices save a third of the vertex data, and on real meshes that share most corners among 4 to 6 triangles the saving is far larger. The GPU can also reuse a transformed vertex that it has seen recently.

All triangles are listed counter-clockwise when seen from outside. That is the default front-face rule in WebGL, and it is what makes back-face culling possible: the same idea as in Back-Face Culling and the Painter's Algorithm, executed by the GPU.

The depth test

For a closed convex object such as a cube, culling the back faces already removes all hidden surfaces. But the depth test is the general tool, and it is the thing you really need once there are two objects, so the demo below lets you turn each feature off separately. Enable it with gl.enable(gl.DEPTH_TEST), ask the context for a depth buffer when it is created (the default is depth: true), and clear both buffers at the start of every frame:

JavaScript
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

Forgetting to clear the depth buffer is the classic bug: last frame's nearer pixels survive and parts of the cube vanish. The depth test itself is the z-buffer algorithm in hardware.

Lighting in the shader

The fragment shader receives the interpolated normal, normalizes it (interpolation shortens vectors) and computes the diffuse term from the Lambert model: the brightness is the cosine between the normal and the direction to the light, clamped at zero, plus a little constant ambient light so shadowed faces are not pitch black.

GLSL
float diffuse = max(dot(normalize(vNormal), uLightDir), 0.0);
float brightness = 0.25 + 0.75 * diffuse;
gl_FragColor = vec4(vColor * brightness, 1.0);

Here is the whole program. The checkboxes switch the depth test, the back-face culling and the lighting on and off, so you can see what each one contributes. Turn off both the depth test and culling and the faces are drawn in index order, which produces an obviously wrong cube.

A lit, rotating WebGL cube

With everything on you see a solid, shaded cube. With culling off but the depth test on, the picture is still correct (the hidden faces are drawn and then rejected by depth). With both off, the six faces are painted in the order of the index buffer and the cube looks inside out.

What the matrix really does

The second example runs in plain JavaScript and prints the journey of one cube corner through the same matrices, without a GPU. It also shows the column-major layout: the translation sits at the end of the array.

JS One vertex through the MVP matrix

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that w equals 4 (the corner is 4 units in front of the camera), and that the combined matrix gives exactly the same clip coordinates. The GPU performs the division by w itself after the vertex shader, which is why gl_Position is a four-component value.

Common mistakes

  • Row-major matrices. Upload column-major data, or build your matrix library accordingly.
  • Wrong multiplication order. With column vectors the order is P * V * M * v: the matrix nearest the vertex acts first.
  • Not clearing the depth buffer, or drawing with a near plane of 0 (a perspective matrix with near = 0 collapses depth precision).
  • Inconsistent winding. If one face is listed clockwise, culling removes it and you see a hole.
  • Unnormalized normals in the fragment shader; interpolation does not preserve length.
  • Using uModel for normals with non-uniform scale. Use the inverse transpose.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In which layout does WebGL expect a 4x4 matrix stored in a Float32Array?

    WebGL reads the 16 numbers column by column. The translation column is the last one, which is why x, y and z sit at indices 12 to 14.
  2. 2. Why does the cube in the demo use 24 vertices instead of 8?

    A corner belongs to three faces that need three different normals, so each face gets four vertices of its own. The index buffer still avoids repeating vertices within a face.
  3. 3. What is the order of the product that turns a model-space vertex into clip space?

    With column vectors the matrix closest to the vertex is applied first: model, then view, then projection.
  4. 4. A rotating cube loses random faces after the first frames when the depth test is on. What is the most likely bug?

    Without gl.DEPTH_BUFFER_BIT in gl.clear, depths from previous frames remain and reject new fragments that are farther away.
  5. 5. Why does the fragment shader call normalize on the varying normal?

    The interpolated normal between two different unit vectors is shorter than a unit vector, so it is re-normalized before the dot product.

Summary

  • Build the model, view and projection matrices in JavaScript, multiply them once per frame and upload the result as a mat4 uniform; WebGL needs column-major order.
  • An index buffer lists triangles by vertex number; a cube with per-face normals uses 24 vertices and 36 indices.
  • Enable DEPTH_TEST, clear the depth buffer every frame and keep the winding counter-clockwise so back-face culling works.
  • The vertex shader outputs gl_Position; the GPU divides by w, rasterizes and interpolates the varyings (normal, color) for the fragment shader.
  • A Lambert term (max(dot(n, l), 0)) plus an ambient part gives convincing diffuse lighting in a few lines of GLSL.

You now have every piece of a real-time renderer. The next chapter puts them together without a GPU, in Project: A Software 3D Engine.