GLSL Learning

GLSL built-in function

reflect()

Returns the direction a ray bounces to after hitting a surface: reflect(I, N) = I - 2.0 * dot(N, I) * N.

Syntax

vec2 reflect(vec2 I, vec2 N)
vec3 reflect(vec3 I, vec3 N)

Parameters

I
The incoming direction, pointing toward the surface.
N
The surface normal. Must be normalized.

Return value

The reflected direction, with the same length as I.

Live example

Edit the code and the preview updates as you type.

How it works

Throw a ball at a wall and it bounces off at the same angle it came in. reflect(I, N) computes that bounce for a direction I hitting a surface with normal N:

vec3 r = reflect(I, N); // I - 2.0 * dot(N, I) * N

The part of I that goes into the surface is flipped; the part that runs along the surface is kept.

In the example the camera looks straight into the screen. For each pixel on the sphere, the view direction bounces off the surface normal, and the bounced direction is used to look up a simple sky-and-floor environment. The result looks like a chrome ball.

Typical uses

  • Specular highlights (Phong): pow(max(dot(reflect(-lightDir, normal), viewDir), 0.0), shininess).
  • Environment reflections: look up a sky color or cube map with the reflected direction.
  • Bouncing particles: reflect the velocity when a particle hits a wall.

Common mistakes

  • Passing the direction the wrong way. I points toward the surface. For a light direction that points from the surface to the light, use reflect(-lightDir, normal).
  • Using an unnormalized normal, which makes the bounce angle wrong. Always normalize(N) first.
  • Swapping the arguments: the incoming direction comes first, the normal second.

Related functions

Tutorials that use reflect()