Motivation
A graphics equation becomes useful software only when its inputs reach the intended stage with the intended meaning. A correct projection matrix attached to the wrong uniform, or a correct normal stored at the wrong byte offset, produces an incorrect image. This note builds a small complete example and explains the contracts between its stages. It draws two opaque triangles, rotates their object frame, shades their vertex colors, and uses a depth buffer to resolve their overlap.
The code uses WebGL 2, a browser interface with an OpenGL ES 3.0 style programmable pipeline, rather than pretending to be a desktop OpenGL context-creation example. The API relationship and webgl2 context are documented by the Khronos WebGL 2 specification. The page is self-contained and uses no libraries, network assets or installation. A supporting browser and graphics context are still execution prerequisites. No captured rendering is shown, so the image described below is a mathematical expectation, not a measured result.
The aim is a comprehensible first pipeline, not a production renderer. It deliberately uses fixed geometry, a rigid model rotation, one directional lighting approximation and a fixed drawing-buffer size. These choices let us prove why its normal transformation is valid and explain exactly where a later extension would require a different equation.
Definitions
Definition 10.1.1
(The stage contracts)
A vertex attribute varies between supplied vertices; a uniform is supplied by the host for a draw; a vertex-shader output becomes an input to rasterization and fragment processing. The vertex shader writes homogeneous clip position. A fragment shader computes candidate output values, after which depth and other enabled tests decide what updates the framebuffer. The example uses matching floating-point vertex outputs and fragment inputs with ordinary smooth interpolation.
The shader declarations use GLSL ES 3.00 syntax, including explicit attribute locations and an explicit fragment output. These language choices are checked against the Khronos GLSL ES 3.00 revision 6 specification, especially the input/output, layout, interpolation and built-in-variable sections. WebGL 2 has restrictions beyond native OpenGL ES, so desktop shader source should not be pasted into this example without checking its version and interface.
Definition 10.1.2
(Coordinate and data conventions)
Positions are column vectors, the camera looks down negative , and each vertex record stores nine 32-bit floats: position, RGB color, and normal. Each group has three entries. The model matrix is a rotation about ; the view matrix translates the world by ; the projection has vertical field of view degrees, near distance and far distance ten. The shader computes , with the rightmost operation first.
The browser host uploads matrix entries in column order with the transpose argument false. Vertex-array and buffer associations, byte offsets, draw counts and depth state are separate from these algebraic conventions; their underlying operations are described in the OpenGL ES 3.0.6 core specification, particularly vertex arrays, buffer objects, shaders, clipping and per-fragment operations. Our declarations choose one concrete compatible layout rather than relying on default guesses.
Concept lensStructural
A draw is a chain of contracts
The buffer describes where numbers live; the vertex interface describes what those numbers mean; the matrix chain describes their coordinate changes; interpolation describes the chosen surface field; depth state describes which opaque candidate survives. A failure at one contract can resemble a failure at another. Debugging is more effective when one checks an expected vertex, one expected attribute address and one overlap sample separately, rather than changing several matrices until the picture looks plausible.
Theorem / proposition
Theorem 10.1.3
(The example's normal formula is valid under its rigid model)
Let have linear part
For the example's vertex normal , multiplying by the upper-left model block gives the correct transformed unit normal . The interpolated normal on either triangle is that same nonzero vector at every covered sample. Nonuniform scaling is outside this assertion.
Theorem 10.1.4
(The chosen color and shading model stays in range)
Assume clipped visible geometry has positive homogeneous denominators, each vertex color component lies in , and normals and light direction are unit. Perspective-correct interpolation gives color components in . Multiplying by leaves every component in .
The range theorem concerns numerical shader values. It does not establish a calibrated display appearance or an energy-conserving material model: the constant floor is an explicit artistic ambient approximation. The page omits a full color-management pipeline. Such distinctions matter before interpreting its displayed RGB as measured radiance.
Proof sketch or proof idea
Proof
(A rotation is its own inverse transpose)
The columns of are orthonormal, so . The normal theorem from the geometry note therefore reduces to the ordinary rotation used in the shader. Multiplying its third column by one gives the displayed normal, whose length is one. Every vertex on both triangles starts with the same normal and receives the same rotation. Any normalized barycentric combination of identical vectors reproduces that vector, so no cancellation to zero occurs in this particular example. If a future mesh contains opposing vertex normals, that guarantee disappears and a separate convention is needed at zero.
Proof
(Convex combinations and the clamped diffuse factor)
For color, perspective correction produces original weights . At an interior covered point the screen weights are nonnegative and sum to one, while , so the original weights are nonnegative and sum to one too. Each interpolated component is a convex combination of its vertex components. Cauchy–Schwarz bounds by one; clamping gives a number in , hence . Multiplying a nonnegative color component by this factor preserves the stated range.
Proof X-ray
Where each hypothesis of the range proof is used
The range theorem is a chain of closure properties. Positive homogeneous denominators are what make the perspective-corrected weights nonnegative; a vertex with would produce negative weights and colors outside the vertex range, which is why the theorem considers only clipped visible geometry. The corrected weights sum to one directly from the normalization in their definition, so for color nothing further is needed beyond vertex components lying in .
The factor uses a different hypothesis. Unit length of and bounds the dot product by one through Cauchy–Schwarz, and the maximum with zero removes the negative side, so . The two chains are independent and meet only in the final product of two numbers in . If the interpolated normal were not renormalized, the unit-length hypothesis could fail; the fragment shader calls normalize(vNormal) to restore it, provided vNormal is nonzero.
Worked examples
Worked example 10.1.5
(Check the matrix chain at zero angle)
At , the front triangle vertex becomes in camera coordinates. With , its clip denominator is three and its normalized vertical coordinate is . Its horizontal coordinate is zero. The point is above image center and inside the vertical clip range. This simple prediction checks the matrix layout, camera sign and perspective division together.
Concept lensAlgorithmic
The matrix chain as a cost decision
In exact arithmetic, , so the product may be formed once per draw on the host. A matrix–vector product costs multiplications and a matrix–matrix product . Per vertex, a precomputed matrix costs , right-to-left evaluation , and the grouping P * V * M * v as written, which associates left to right, . All three agree mathematically; they differ in work and rounding.
Worked example 10.1.6
(Verify every byte of a vertex record)
Nine floats occupy bytes. Position starts at offset zero, color at twelve and normal at twenty-four. Vertex number five, the final zero-based vertex, begins at byte ; its normal occupies bytes through . Six records occupy bytes, so a draw of six vertices ends exactly at the buffer boundary. Asking for seven would require data that the uploaded array does not contain. Float counts and byte counts must not be interchanged.
Worked example 10.1.7
(Predict one lighting value and one overlap)
At zero angle, the normal is and the normalized light is . The diffuse cosine is , so the shading factor is approximately . At a front-triangle sample with color weights , the shader value is approximately . In the overlap, its plane has camera distance three while the yellow triangle has distance , so the monotone depth mapping selects the front triangle. The draw submits front first and back second; enabled depth testing prevents the later back fragment from overwriting it.
Complete instructional page
Save the following as an HTML file and open it in a supporting browser. The range control accepts ordinary pointer or keyboard input; moving it disables automatic motion. The animation uses elapsed time in milliseconds, not a count of rendered frames. Compiler and linker logs are shown when initialization fails.
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Two triangles: a programmable graphics pipeline</title>
<style>
body { max-width: 48rem; margin: 2rem auto; padding: 0 1rem;
font: 1rem/1.5 system-ui, sans-serif; }
canvas { display: block; width: 100%; height: auto; background: #111; }
label { display: inline-block; margin: 1rem 1rem 1rem 0; }
output { display: block; white-space: pre-wrap; }
</style>
<h1>Two triangles and a rotating coordinate frame</h1>
<p>The front triangle has vertex colors; the back triangle is yellow.
Depth testing chooses the nearer sample. This is a small WebGL 2 example.</p>
<canvas id="view" width="640" height="480" role="img"
aria-label="Two opaque triangles under a rotating model transform">
A WebGL 2 capable browser is required.
</canvas>
<label>Angle in radians
<input id="angle" type="range" min="-0.8" max="0.8" step="0.01" value="0">
</label>
<label><input id="animate" type="checkbox" checked> Animate</label>
<output id="status" aria-live="polite"></output>
<script type="module">
const canvas = document.querySelector('#view');
const angle = document.querySelector('#angle');
const animate = document.querySelector('#animate');
const status = document.querySelector('#status');
try {
const gl = canvas.getContext('webgl2', {alpha: false, depth: true, antialias: false});
if (!gl) throw new Error('WebGL 2 context creation failed.');
const vertexSource = `#version 300 es
precision highp float;
layout(location = 0) in vec3 aPosition;
layout(location = 1) in vec3 aColor;
layout(location = 2) in vec3 aNormal;
uniform mat4 uModel;
uniform mat4 uView;
uniform mat4 uProjection;
out vec3 vColor;
out vec3 vNormal;
void main() {
gl_Position = uProjection * uView * uModel * vec4(aPosition, 1.0);
vColor = aColor;
vNormal = mat3(uModel) * aNormal;
}`;
const fragmentSource = `#version 300 es
precision highp float;
in vec3 vColor;
in vec3 vNormal;
out vec4 fragmentColor;
void main() {
vec3 n = normalize(vNormal);
vec3 light = normalize(vec3(0.4, 0.6, 1.0));
float shade = 0.2 + 0.8 * max(dot(n, light), 0.0);
fragmentColor = vec4(vColor * shade, 1.0);
}`;
function shader(type, source) {
const handle = gl.createShader(type);
if (!handle) throw new Error('Shader allocation failed.');
gl.shaderSource(handle, source);
gl.compileShader(handle);
if (!gl.getShaderParameter(handle, gl.COMPILE_STATUS)) {
const log = gl.getShaderInfoLog(handle);
gl.deleteShader(handle);
throw new Error(log || 'Shader compilation failed.');
}
return handle;
}
const vs = shader(gl.VERTEX_SHADER, vertexSource);
const fs = shader(gl.FRAGMENT_SHADER, fragmentSource);
const program = gl.createProgram();
if (!program) throw new Error('Program allocation failed.');
gl.attachShader(program, vs);
gl.attachShader(program, fs);
gl.linkProgram(program);
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
throw new Error(gl.getProgramInfoLog(program) || 'Program linking failed.');
}
gl.deleteShader(vs);
gl.deleteShader(fs);
const data = new Float32Array([
-0.8, -0.6, 0.0, 1, 0, 0, 0, 0, 1,
0.8, -0.6, 0.0, 0, 1, 0, 0, 0, 1,
0.0, 0.8, 0.0, 0, 0, 1, 0, 0, 1,
-0.9, 0.5, -0.6, 0.7, 0.7, 0.1, 0, 0, 1,
0.0, -0.9, -0.6, 0.7, 0.7, 0.1, 0, 0, 1,
0.9, 0.5, -0.6, 0.7, 0.7, 0.1, 0, 0, 1
]);
const vao = gl.createVertexArray();
const buffer = gl.createBuffer();
if (!vao || !buffer) throw new Error('Geometry allocation failed.');
gl.bindVertexArray(vao);
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);
for (let attribute = 0; attribute < 3; ++attribute) {
gl.enableVertexAttribArray(attribute);
gl.vertexAttribPointer(attribute, 3, gl.FLOAT, false, 36, 12 * attribute);
}
gl.useProgram(program);
const modelLocation = gl.getUniformLocation(program, 'uModel');
const viewLocation = gl.getUniformLocation(program, 'uView');
const projectionLocation = gl.getUniformLocation(program, 'uProjection');
gl.uniformMatrix4fv(viewLocation, false, new Float32Array([
1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,-3,1
]));
const near = 0.1, far = 10, aspect = canvas.width / canvas.height;
const q = 1 / Math.tan(Math.PI / 6);
gl.uniformMatrix4fv(projectionLocation, false, new Float32Array([
q/aspect,0,0,0, 0,q,0,0,
0,0,-(far+near)/(far-near),-1, 0,0,-2*far*near/(far-near),0
]));
gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.LESS);
gl.depthMask(true);
gl.clearDepth(1);
gl.disable(gl.BLEND);
gl.disable(gl.CULL_FACE);
gl.clearColor(0.04, 0.04, 0.06, 1);
angle.addEventListener('input', () => { animate.checked = false; });
function frame(milliseconds) {
if (gl.isContextLost()) {
status.textContent = 'Graphics context lost; reload to initialize again.';
return;
}
const theta = animate.checked ? 0.65 * Math.sin(milliseconds / 1800)
: Number(angle.value);
const c = Math.cos(theta), s = Math.sin(theta);
gl.uniformMatrix4fv(modelLocation, false, new Float32Array([
c,0,-s,0, 0,1,0,0, s,0,c,0, 0,0,0,1
]));
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.drawArrays(gl.TRIANGLES, 0, 6);
requestAnimationFrame(frame);
}
status.textContent = 'Initialized. Move the angle control to pause automatic motion.';
requestAnimationFrame(frame);
} catch (error) {
status.textContent = String(error);
}
</script>
</html>
Reading the program as mathematics
The two triangles have different constant object-space depths. Rotation changes both position and normal in world space; the view translation affects positions but not directions. Since the light is expressed in world coordinates, the fragment normal must be expressed there too. If a later version rotates the camera, one can either retain this world-space lighting convention or transform both normal and light to camera space. Combining one in each space is meaningless even when their arrays have equal length.
The shader writes homogeneous clip coordinates and lets the pipeline perform clipping, division, rasterization and interpolation. It does not divide gl_Position by its fourth component itself. The host clears both color and depth each frame because each frame describes a newly evaluated scene. Retaining the previous depth buffer would compare the new geometry with stale samples and can reject valid fragments. The strict depth test also means a fragment exactly at the cleared maximum depth needs a deliberate far-boundary policy.
The code requests a depth buffer and enables writes and less-than comparison. Blending and culling are disabled for the two opaque, explicitly shaded triangles. Enabling blending alone would not make a correct transparent renderer; the compositing note explains why order and background contributions matter. Enabling culling requires a consistent winding/material convention, especially after reflections. Changing one state flag is not a replacement for changing the underlying model.
The fixed buffer is by , and the projection aspect ratio matches it. CSS scales the canvas while preserving that ratio. A resizable high-density application should update drawing-buffer dimensions, viewport and projection together, and may need a device-pixel policy. This small page does not claim native-resolution rendering on every screen. Context creation and shader compilation can fail on an actual device; the visible status is an execution report from that device, not a guarantee supplied by this prose.
Common mistakes
Counterexample mode
The normal shortcut fails after nonuniform scale
Replace the model rotation by and consider tangent with normal . Direct multiplication produces tangent and alleged normal , whose dot product is three. The correct inverse-transpose normal is proportional to , perpendicular to that tangent. Thus extending the program to scaled meshes requires a normal matrix and a nonzero normalization condition; merely keeping the existing mat3(uModel) expression is wrong.
Common mistake
(Counting offsets in floats instead of bytes)
The vertex record has a stride of bytes, with color at byte and normal at byte . Offsets are measured in bytes. Passing the float counts and is wrong: an offset of is not even a multiple of the four-byte float size, and an aligned wrong value such as starts the color attribute inside the position record.
Common mistake
(Treating a successful compilation as a correct pipeline)
Swapping the color and normal locations, renaming a shader variable without changing the host uniform, or reversing the matrix multiplication order can all compile. A successful shader compilation proves language and interface acceptance at that stage, not that its geometry or lighting is correct.
Summary
The complete page connects one explicit buffer layout to a vertex shader, a coordinate chain, smooth attributes, fragment shading and depth state. The normal shortcut is justified by the rigid model and identical nonzero normals; it is not a general normal transform. Mathematical predictions at a vertex, a byte address and an overlap sample provide concrete debugging evidence. Native desktop setup, textures, general meshes and calibrated display output remain separate extensions.
Exercises
Quick check
(Change each vertex record to position, color, normal and a two-component texture coordinate, all 32-bit floats. Find the stride and four attribute offsets. How many bytes hold six vertices?)
Count floats, then multiply by four bytes.
Solution · Answer
There are eleven floats, giving a stride of bytes. Offsets are zero, twelve, twenty-four and thirty-six bytes. Six vertices require bytes. The texture attribute has two components, so its final record ends at byte , exactly within that array.
Quick check
(At zero angle, compute the camera coordinates and divided horizontal position of front vertex for aspect ratio . Use .)
Apply the view translation, then the projection entries.
Solution · Answer
Camera coordinates are . The clip horizontal component is , and division by three gives . Omitting the aspect factor would stretch the image horizontally relative to the chosen viewport.
Quick check
(Disable depth testing while retaining the current draw order and no blending. Which triangle's color wins where both cover a sample, and why is that different from nearest-surface visibility?)
Think about which fragment is written last.
Solution · Answer
The yellow back triangle is submitted second and its fragments overwrite the front color where both are covered. This is draw-order visibility, not distance-based visibility. Reversing submission could make this specific scene look correct while still failing for intersecting triangles with no single global order.
Quick check
(A new model is . For normal , compute the correct unit normal and compare its direction with the direct-transform result.)
Use the inverse transpose of the model block.
Solution · Answer
The inverse transpose gives , so a unit choice is . Direct transformation gives , a different direction. Testing the original tangent after transformation gives ; its dot product with the correct normal is zero, whereas with the direct normal it is .