GLSL Learning

GLSL built-in function

dot()

Returns the dot product of two vectors. For unit vectors it measures how much they point the same way: 1.0 same direction, 0.0 perpendicular, -1.0 opposite.

Syntax

float dot(vec2 x, vec2 y)
float dot(vec3 x, vec3 y)
float dot(vec4 x, vec4 y)

Parameters

x
The first vector.
y
The second vector, with the same size as x.

Return value

A single float: x.x * y.x + x.y * y.y (+ x.z * y.z ...).

Live example

Edit the code and the preview updates as you type.

How it works

The formula is simple: multiply matching components and add them up.

dot(vec2(1.0, 2.0), vec2(3.0, 4.0)) // 1*3 + 2*4 = 11.0

The useful part is what it means. When both vectors have length 1, dot is the cosine of the angle between them:

directionsdot
the same1.0
60 degrees apart0.5
perpendicular0.0
opposite-1.0

That is exactly what diffuse lighting needs. In the example, dot(normal, light) is 1.0 where the sphere faces the light, falls toward 0 at the edge of the lit side, and goes negative on the far side, which max clamps to 0.

Typical uses

  • Diffuse (Lambert) lighting: max(dot(normal, lightDir), 0.0).
  • Squared length: dot(v, v) is length(v) * length(v) without the square root.
  • Projecting onto a direction: dot(p, dir) is how far p goes along dir, useful for gradients at any angle.
  • Hash functions: dot(p, vec2(12.9898, 78.233)) mixes two coordinates into one number before fract(sin(...)).

Common mistakes

  • Forgetting to normalize. With vectors longer than 1, the result is no longer between -1 and 1, and lighting becomes too bright or too dark.
  • Not clamping negative values in lighting, which darkens surfaces facing away from the light below the ambient level.
  • Passing vectors of different sizes. dot(vec3, vec2) does not compile.

Related functions

Tutorials that use dot()