Lighting Equation

The Ambient, Diffuse and Specular Lighting Equation

The classic model, from Bui Tuong Phong's 1975 paper, adds three terms for each light:

The unit vectors of the lighting equation at one point on a surface
The unit vectors of the lighting equation at one point on a surface

A fragment's color is the sum over lights, clamped by the framebuffer. Every vector must be unit length and in one space (world space here). Colors multiply per component, so a red cover under blue light comes out dark.

A globe lit by ambient, diffuse and specular terms separately, then all three summedHTMLLive
<!doctype html>
<style>
  body { margin: 0; font: 11px system-ui, sans-serif; background: #f7f4ee; color: #333; }
  canvas { display: block; width: 100%; max-width: 600px; }
  .names { display: flex; max-width: 600px; text-align: center; font-family: monospace; }
  .names div { flex: 1; padding: 4px 2px; }
</style>
<canvas id="c" width="600" height="160"></canvas>
<div class="names"><div>ambient</div><div>diffuse: max(N&middot;L, 0)</div><div>specular: max(R&middot;V, 0)^30</div><div>sum</div></div>
<script>
const m4 = {
  perspective(fovy, aspect, near, far) {
    const f = 1 / Math.tan(fovy * Math.PI / 360), d = near - far;
    return [f / aspect, 0, 0, 0, 0, f, 0, 0, 0, 0, (far + near) / d, -1, 0, 0, 2 * far * near / d, 0];
  },
  lookAt(eye, target, up = [0, 1, 0]) {
    const cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
    const unit = (v) => v.map((c) => c / Math.hypot(...v));
    const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
    const z = unit(eye.map((c, i) => c - target[i])), x = unit(cross(up, z)), y = cross(z, x);
    return [x[0], y[0], z[0], 0, x[1], y[1], z[1], 0, x[2], y[2], z[2], 0, -dot(x, eye), -dot(y, eye), -dot(z, eye), 1];
  },
  multiply(a, b) {
    const out = new Array(16).fill(0);
    for (let c = 0; c < 4; c++) for (let r = 0; r < 4; r++) for (let k = 0; k < 4; k++) out[c * 4 + r] += a[k * 4 + r] * b[c * 4 + k];
    return out;
  },
};
function sphere(rings, segments) {           // unit sphere: position = normal, indexed
  const vertices = [], indices = [];
  for (let i = 0; i <= rings; i++) for (let j = 0; j <= segments; j++) {
    const t = i / rings * Math.PI, p = j / segments * 2 * Math.PI;
    vertices.push(Math.sin(t) * Math.cos(p), Math.cos(t), -Math.sin(t) * Math.sin(p));
  }
  for (let i = 0; i < rings; i++) for (let j = 0; j < segments; j++) {
    const a = i * (segments + 1) + j, b = a + segments + 1;
    indices.push(a, b, a + 1, a + 1, b, b + 1);
  }
  return { vertices: new Float32Array(vertices), indices: new Uint16Array(indices) };
}
const gl = document.getElementById('c').getContext('webgl2');
const program = gl.createProgram();
for (const [type, src] of [[gl.VERTEX_SHADER, `#version 300 es
layout(location = 0) in vec3 aPosition;
uniform mat4 uViewProjection; out vec3 vPosition, vNormal;
void main() { vPosition = aPosition; vNormal = aPosition; gl_Position = uViewProjection * vec4(aPosition, 1.0); }`],
  [gl.FRAGMENT_SHADER, `#version 300 es
precision highp float;
in vec3 vPosition, vNormal;
uniform vec3 uToLight, uEye; uniform int uTerm;
out vec4 outColor;
void main() {
  vec3 base = vec3(0.12, 0.37, 0.55), lightColor = vec3(1.0, 0.95, 0.85);
  vec3 N = normalize(vNormal), L = uToLight, V = normalize(uEye - vPosition);
  vec3 R = reflect(-L, N);                                         // mirror direction
  vec3 ambient = vec3(0.25) * base;
  vec3 diffuse = lightColor * base * max(dot(N, L), 0.0);          // Lambert's law
  vec3 specular = lightColor * pow(max(dot(R, V), 0.0), 30.0);     // Phong's highlight
  vec3 terms[4] = vec3[](ambient, diffuse, specular, ambient + diffuse + specular);
  outColor = vec4(terms[uTerm], 1.0);
}`]]) {
  const s = gl.createShader(type); gl.shaderSource(s, src); gl.compileShader(s);
  if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(s));
  gl.attachShader(program, s);
}
gl.linkProgram(program); gl.useProgram(program);
const u = (n) => gl.getUniformLocation(program, n);
const globe = sphere(32, 48);
gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());
gl.bufferData(gl.ARRAY_BUFFER, globe.vertices, gl.STATIC_DRAW);
gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 0, 0); gl.enableVertexAttribArray(0);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, gl.createBuffer());
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, globe.indices, gl.STATIC_DRAW);
gl.enable(gl.DEPTH_TEST); gl.enable(gl.CULL_FACE); gl.enable(gl.SCISSOR_TEST);
const eye = [0, 0, 3.4];
gl.uniform3fv(u('uEye'), eye);
gl.uniformMatrix4fv(u('uViewProjection'), false, m4.multiply(m4.perspective(40, 150 / 160, 0.1, 10), m4.lookAt(eye, [0, 0, 0])));
function frame(ms) {
  const a = ms * 0.0008;
  const L = [Math.cos(a) * 0.7, 0.55, Math.sin(a) * 0.3 + 0.6], len = Math.hypot(...L);
  gl.uniform3fv(u('uToLight'), L.map(c => c / len));    // unit vector toward the light
  for (let i = 0; i < 4; i++) {
    gl.viewport(i * 150, 0, 150, 160); gl.scissor(i * 150 + 2, 0, 146, 160);
    gl.clearColor(0.93, 0.91, 0.87, 1);
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
    gl.uniform1i(u('uTerm'), i);
    gl.drawElements(gl.TRIANGLES, globe.indices.length, gl.UNSIGNED_SHORT, 0);
  }
  requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
</script>