GLSL Learning

GLSL built-in function

clamp()

Limits x to the range between minVal and maxVal, computed as min(max(x, minVal), maxVal).

Syntax

float clamp(float x, float minVal, float maxVal)
vec2 clamp(vec2 x, float minVal, float maxVal)
vec3 clamp(vec3 x, float minVal, float maxVal)
vec3 clamp(vec3 x, vec3 minVal, vec3 maxVal)

Parameters

x
The value to limit.
minVal
The lower bound. Values below it become minVal.
maxVal
The upper bound. Values above it become maxVal. Must be greater than or equal to minVal.

Return value

x if it is inside the range, otherwise the nearest bound.

Live example

Edit the code and the preview updates as you type.

How it works

clamp(x, minVal, maxVal) keeps x inside a range:

  • below minVal: returns minVal
  • above maxVal: returns maxVal
  • in between: returns x unchanged

In the example the gray diagonal line is the raw value. The green line follows it in the middle and goes flat at the top and bottom, where the value hits the limits. The limits breathe with u_time.

Typical uses

  • Keeping colors valid: clamp(color, 0.0, 1.0) before writing to gl_FragColor.
  • Safe input to other functions: sqrt(clamp(x, 0.0, 1.0)) or acos(clamp(d, -1.0, 1.0)) avoid undefined results from out-of-range input.
  • Hard-edged progress bars: clamp((u_time - start) / duration, 0.0, 1.0) goes from 0 to 1 and then stays at 1.

Common mistakes

  • Swapping the bounds. If minVal is greater than maxVal the result is undefined in GLSL and differs between GPUs.
  • Expecting a smooth transition. clamp has sharp corners at both ends; use smoothstep when you want an eased curve.

Related functions

Tutorials that use clamp()