GLSL Learning

GLSL built-in function

mod()

Returns x modulo y, computed as x - y * floor(x / y): the remainder after dividing x by y.

Syntax

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

Parameters

x
The value to wrap.
y
The period. The result repeats every y units. Must not be 0.

Return value

A value of the same type as x. For positive y the result is in [0, y).

Live example

Edit the code and the preview updates as you type.

How it works

mod(x, y) wraps x into a repeating range of length y:

  • mod(7.0, 3.0) is 1.0
  • mod(6.0, 3.0) is 0.0
  • mod(-1.0, 3.0) is 2.0

It is defined as x - y * floor(x / y), so mod(x, 1.0) is exactly fract(x). The difference is that mod lets you choose the period.

The checkerboard in the example adds the column and row index of each cell. Neighboring cells always differ by 1, so mod(sum, 2.0) alternates between 0 and 1.

Typical uses

  • Checkerboards and alternating stripes: mod(floor(uv.x * n), 2.0).
  • Keeping time small: mod(u_time, 6.2831) keeps the input to sin from growing forever, which avoids precision loss on mobile GPUs.
  • Repeating space: mod(p, 2.0) - 1.0 repeats an object every 2 units in a raymarcher.

Common mistakes

  • Expecting C-style % for negative numbers. In GLSL mod(-1.0, 3.0) is 2.0, not -1.0. This is usually what you want for tiling.
  • Using % on floats. GLSL ES 1.0 has no % operator; always call mod.
  • Passing integers: write mod(x, 2.0), not mod(x, 2).

Related functions

Tutorials that use mod()