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)is1.0mod(6.0, 3.0)is0.0mod(-1.0, 3.0)is2.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 tosinfrom growing forever, which avoids precision loss on mobile GPUs. - Repeating space:
mod(p, 2.0) - 1.0repeats an object every 2 units in a raymarcher.
Common mistakes
- Expecting C-style
%for negative numbers. In GLSLmod(-1.0, 3.0)is2.0, not-1.0. This is usually what you want for tiling. - Using
%on floats. GLSL ES 1.0 has no%operator; always callmod. - Passing integers: write
mod(x, 2.0), notmod(x, 2).
Related functions
Tutorials that use mod()
- Brick WallPractice building repeating patterns from UV coordinates.
- Checker 10x10Practice building repeating patterns from UV coordinates.
- Checkerboard PatternCombine the mod() function with floor() to generate a black and white checkerboard texture.
- Pattern RepetitionLearn how to create repetitive geometric patterns, including grid systems, random variations, and animation effects