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:
| directions | dot |
|---|---|
| the same | 1.0 |
| 60 degrees apart | 0.5 |
| perpendicular | 0.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)islength(v) * length(v)without the square root. - Projecting onto a direction:
dot(p, dir)is how farpgoes alongdir, useful for gradients at any angle. - Hash functions:
dot(p, vec2(12.9898, 78.233))mixes two coordinates into one number beforefract(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
normalize()
Returns a vector pointing in the same direction as x but with length 1.0. Keeps the direction, drops the size.
acos()
Returns the angle in radians whose cosine is x. acos(dot(a, b)) gives the angle between two unit vectors.
reflect()
Returns the direction a ray bounces to after hitting a surface: reflect(I, N) = I - 2.0 * dot(N, I) * N.
Tutorials that use dot()
- Ambient + DiffuseLearn core lighting terms (diffuse/specular/rim) on a simple sphere.
- Hash Grid NoiseGenerate a random value per grid cell using a small hash function.
- Half-LambertLearn core lighting terms (diffuse/specular/rim) on a simple sphere.
- Rim LightLearn core lighting terms (diffuse/specular/rim) on a simple sphere.
- Fake ShadowLearn core lighting terms (diffuse/specular/rim) on a simple sphere.
- Toon LightingLearn core lighting terms (diffuse/specular/rim) on a simple sphere.