Intrinsics1 min read
abs
Returns the absolute value.
Reading Time
1 min
Word Count
141
Sections
12
Try It Live
Test abs in a live shader
Open the playground, start from a visual preset, and wire abs into the fragment stage to see how it behaves with real values.
Open PlaygroundLive Demo
The abs function returns the absolute (non-negative) value of the input. For positive values, the input is returned unchanged; for negative values, the negation is returned.
Signature
bwsl
abs :: (T x) -> T {...}
Where T can be float, float2, float3, float4, int, int2, int3, or int4.
Parameters
| Parameter | Type | Description |
|---|---|---|
x | T | The input value |
Return Value
Returns the absolute value of x.
Example
bwsl
pipeline WavePattern {
fragment {
// Create symmetric wave pattern from center
float2 centered = input.uv - 0.5;
// Use abs to create symmetry
float wave = sin(abs(centered.x) * 20.0 + time);
wave *= sin(abs(centered.y) * 20.0 + time);
float3 color = float3(0.5 + 0.5 * wave);
output.color = float4(color, 1.0);
}
}Common Use Cases
Symmetric Patterns
bwsl
// Create pattern symmetric about center
float2 uv = abs(input.uv - 0.5) * 2.0; // Mirror coordinates
float pattern = sin(uv.x * 10.0) * sin(uv.y * 10.0);Distance from Axis
bwsl
// Distance from vertical center line
float distFromCenter = abs(input.uv.x - 0.5);Clamping to Positive
bwsl
// Ensure value is always positive
float positiveNoise = abs(noise);Fresnel Effect
bwsl
// View-angle dependent effect
float NdotV = dot(normal, viewDir);
float fresnel = pow(1.0 - abs(NdotV), 5.0);Box Distance Field
bwsl
// Signed distance to box
float3 d = abs(position) - boxSize;
float boxDist = length(max(d, float3(0.0))) + min(max(d.x, max(d.y, d.z)), 0.0);Performance
The abs function is extremely fast on GPUs - typically a single instruction or even free when combined with other operations through instruction modifiers.
Compiled Output
When compiled to GLSL:
glsl
abs(x)
When compiled to HLSL:
hlsl
abs(x)
When compiled to Metal:
metal
abs(x)