GLSL Learning

GLSL built-in function

refract()

Returns the direction a ray takes after passing into a different material, like light bending as it enters glass or water.

Syntax

vec2 refract(vec2 I, vec2 N, float eta)
vec3 refract(vec3 I, vec3 N, float eta)

Parameters

I
The incoming direction, normalized, pointing toward the surface.
N
The surface normal, normalized.
eta
The ratio of refractive indices, outside / inside. Air into glass is 1.0 / 1.5.

Return value

The refracted direction, or a zero vector when total internal reflection happens.

Live example

Edit the code and the preview updates as you type.

How it works

When light crosses from one material into another it changes direction. How much depends on the ratio of the two refractive indices, eta:

from / toeta
air into water1.0 / 1.33
air into glass1.0 / 1.5
glass into air1.5 / 1.0

refract(I, N, eta) returns that new direction. In the example the view ray enters a glass sphere, bends toward the center, and the bent direction is used to offset where the checkerboard background is sampled. That is why the board looks magnified and flipped inside the ball.

Typical uses

  • Glass, water and lenses: offset a background lookup by the refracted direction.
  • Raytracing transparent objects: continue the ray inside the object along the refracted direction.

Common mistakes

  • Not normalizing I and N. The formula assumes unit vectors.
  • Inverting eta. Going from air into glass is 1.0 / 1.5, not 1.5.
  • Ignoring total internal reflection. When light leaves a dense material at a shallow angle, refract returns vec3(0.0). Check for it and fall back to reflect.

Related functions