What Does the Fract Function Do in GLSL?

The fract function in the OpenGL Shading Language (GLSL) computes the fractional part of a floating-point scalar or vector. Mathematically, it evaluates \(x - \lfloor x \rfloor\), where \(\lfloor x \rfloor\) represents the floor function. Because it relies on the floor operation rather than simple truncation, fract produces a strictly periodic sawtooth wave on the half-open interval \([0, 1)\) for any real input, making it essential for UV manipulation, repeating patterns, and procedural shaders.

Mathematical Definition

The OpenGL Shading Language specification explicitly defines the function as:

\[\operatorname{fract}(x) = x - \operatorname{floor}(x)\]

The floor function returns the greatest integer less than or equal to \(x\). Consequently, fract subtracts that base integer from the original value to isolate the remaining fraction.

Positive Values

For positive numbers, fract behaves identically to stripping away the whole number portion:

Negative Values

For negative inputs, the behavior differs from standard decimal truncation because \(\operatorname{floor}(x)\) rounds toward negative infinity rather than toward zero:

Because \(\operatorname{floor}(x)\) always satisfies \(\operatorname{floor}(x) \le x < \operatorname{floor}(x) + 1\), the result of \(\operatorname{fract}(x)\) is guaranteed to lie within the non-negative range:

\[0 \le \operatorname{fract}(x) < 1\]

Vector Support and Component-Wise Execution

GLSL implements fract as an overloaded intrinsic function supporting multiple floating-point types:

When applied to vector types (vec2, vec3, or vec4), the operation executes independently on each individual component:

vec2 uv = vec2(3.2, -1.7);
vec2 f = fract(uv); // f becomes vec2(0.2, 0.3)

Common Applications in Shaders

Texture Tiling and UV Grids

Multiplying UV coordinates by a scalar and passing the result to fract creates repeating coordinate spaces across a single surface, dividing geometry into localized \([0, 1)\) cells:

vec2 tiledUV = fract(v_uv * 4.0); // Creates a 4x4 repeating grid

Sawtooth Waveforms and Timers

Passing a linearly increasing time variable into fract generates a standard sawtooth wave oscillating between \(0.0\) and \(1.0\), commonly used for looped animations, blinking effects, and periodic visual transitions.