mod
Computes the floored floating-point remainder; the result takes the sign of the divisor.
Test mod in a live shader
Open the playground, start from a visual preset, and wire mod into the fragment stage to see how it behaves with real values.
Open PlaygroundLive Demo
The mod function returns the floating-point remainder of x / y, using a floored quotient. The result has the same sign as y (the divisor) and magnitude less than |y|, so for a positive y it always lies in [0, y). For the sign-of-dividend remainder, use fmod.
Signature
mod :: (T x, T y) -> T {...}
Where T can be float, float2, float3, or float4.
Parameters
| Parameter | Type | Description |
|---|---|---|
x | T | The dividend |
y | T | The divisor |
Return Value
Returns x - y * floor(x / y).
Example
pipeline WavingFlag {
fragment {
float2 uv = input.uv;
// Create horizontal wave animation
float wave = sin(uv.x * 10.0 + time * 2.0) * 0.05;
uv.y += wave;
// Wrap UV coordinates using mod
uv = mod(uv, float2(1.0));
float4 color = sample(flagTex, uv);
output.color = color;
}
}Common Use Cases
UV Wrapping
// Wrap scrolling UVs
float2 scrolledUV = mod(input.uv + velocity * time, float2(1.0));Repeating Patterns
// Create repeating distance field
float repeatDist = mod(distance, cellSize);
float pattern = smoothstep(0.0, 0.1, repeatDist);Circular Values
// Keep angle in [0, 2*PI] range
float wrappedAngle = mod(angle, 6.28318);Ping-Pong Animation
// Create back-and-forth motion
float cycle = mod(time, 2.0);
float pingPong = 1.0 - abs(cycle - 1.0); // 0->1->0Stripe Patterns
// Alternating stripes
float stripe = step(0.5, mod(input.uv.x * stripeCount, 1.0));Difference from HLSL fmod
BWSL's mod matches GLSL mod: x - y * floor(x / y), so the result takes the sign of the divisor. mod(-0.5, 2.0) is 1.5. HLSL and Metal fmod truncate instead and take the sign of the dividend; BWSL exposes that as fmod.
Use fract for [0,1]
When dividing by 1.0, prefer fract(x) over mod(x, 1.0) for cleaner code.
Compiled Output
When compiled to GLSL:
mod(x, y)
When compiled to HLSL:
x - y * floor(x / y)
When compiled to Metal, a mod helper with the same formula is emitted:
mod(x, y) // x - y * floor(x / y)