GLSL Learning

GLSL built-in function

min()

Returns the smaller of x and y. With vectors, each component is compared separately.

Syntax

float min(float x, float y)
vec2 min(vec2 x, vec2 y)
vec2 min(vec2 x, float y)
vec3 min(vec3 x, vec3 y)
vec3 min(vec3 x, float y)

Parameters

x
The first value.
y
The second value. Can be a float even when x is a vector.

Return value

The smaller value, with the same type as x.

Live example

Edit the code and the preview updates as you type.

How it works

min(x, y) simply returns whichever value is smaller. min(0.3, 0.8) is 0.3.

It becomes powerful with signed distance fields (SDFs), where a value below 0 means "inside a shape". Taking min of two distances keeps a pixel inside if it is inside either shape, so the example draws the union of two circles. Watch the right circle slide in and out: wherever they overlap, they merge into one silhouette.

float d = min(da, db); // union of two shapes

Typical uses

  • Combining shapes: min(sdfA, sdfB) is the union of A and B.
  • Capping a value: min(brightness, 1.0) stops a value from going above 1.0.
  • Nearest of several points: looping over points and keeping min(d, distance(p, point)) finds the closest one, the core of Voronoi patterns.

Common mistakes

  • Using min to keep a value inside a range from both sides. That needs clamp(x, lo, hi), which is min(max(x, lo), hi).
  • Expecting a vector min to pick the "smaller vector". min(vec2(1.0, 0.0), vec2(0.0, 1.0)) is vec2(0.0, 0.0), because each component is compared on its own.

Related functions

Tutorials that use min()