Intrinsics1 min read

mod

Computes the floating-point remainder of division.

Reading Time
1 min
Word Count
140
Sections
12
Try It Live

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 Playground

Live Demo

The mod function returns the floating-point remainder of x / y. The result has the same sign as x and magnitude less than y.

Signature

bwsl
mod :: (T x, T y) -> T {...}

Where T can be float, float2, float3, or float4.

Parameters

ParameterTypeDescription
xTThe dividend
yTThe divisor

Return Value

Returns x - y * floor(x / y).

Example

bwsl
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

bwsl
// Wrap scrolling UVs
float2 scrolledUV = mod(input.uv + velocity * time, float2(1.0));

Repeating Patterns

bwsl
// Create repeating distance field
float repeatDist = mod(distance, cellSize);
float pattern = smoothstep(0.0, 0.1, repeatDist);

Circular Values

bwsl
// Keep angle in [0, 2*PI] range
float wrappedAngle = mod(angle, 6.28318);

Ping-Pong Animation

bwsl
// Create back-and-forth motion
float cycle = mod(time, 2.0);
float pingPong = 1.0 - abs(cycle - 1.0); // 0->1->0

Stripe Patterns

bwsl
// Alternating stripes
float stripe = step(0.5, mod(input.uv.x * stripeCount, 1.0));

Difference from HLSL fmod

BWSL's mod matches GLSL behavior: the result has the same sign as the dividend. HLSL's fmod can give different results for negative numbers. BWSL uses x - y * floor(x/y) semantics.

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:

glsl
mod(x, y)

When compiled to HLSL:

hlsl
x - y * floor(x / y)

When compiled to Metal:

metal
fmod(x, y)

See Also