GLSL Learning

GLSL built-in function

normalize()

Returns a vector pointing in the same direction as x but with length 1.0. Keeps the direction, drops the size.

Syntax

vec2 normalize(vec2 x)
vec3 normalize(vec3 x)
vec4 normalize(vec4 x)

Parameters

x
The vector to normalize. Must not be a zero vector.

Return value

x / length(x), a unit vector with the same type as x.

Live example

Edit the code and the preview updates as you type.

How it works

A vector has a direction and a length. normalize keeps the direction and sets the length to exactly 1:

normalize(vec2(3.0, 4.0)) // vec2(0.6, 0.8), length 1.0

The example colors each pixel by a vector from the center. On the left the raw vector is used, so colors fade toward gray near the middle where the vector is short. On the right the same vectors are normalized: every pixel has full-strength color and only the direction matters, which gives clean color sectors.

Typical uses

  • Lighting directions: light and view directions must be unit vectors for dot to give a proper 0..1 brightness.
  • Surface normals: after computing or interpolating a normal, normalize it before using it.
  • Ray directions: normalize(vec3(p, -1.0)) builds a camera ray in a raymarcher.

Common mistakes

  • Normalizing a zero vector. normalize(vec2(0.0)) divides by zero and returns NaN, typically a black pixel at the exact center. Add a tiny offset or check the length first.
  • Normalizing colors. normalize(color) changes brightness in a way that rarely looks right; it is meant for directions.
  • Forgetting to re-normalize after adding two unit vectors. normalize(lightDir + viewDir) is the half vector; the sum alone is too long.

Related functions

Tutorials that use normalize()