Intrinsics1 min read
sign
Returns the sign of a value.
Reading Time
1 min
Word Count
150
Sections
12
Try It Live
Test sign in a live shader
Open the playground, start from a visual preset, and wire sign into the fragment stage to see how it behaves with real values.
Open PlaygroundLive Demo
The sign function returns -1 if the value is negative, 0 if the value is zero, and 1 if the value is positive.
Signature
bwsl
sign :: (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 -1.0, 0.0, or 1.0 (for floats) or -1, 0, 1 (for integers) based on the sign of x.
Example
bwsl
pipeline DirectionIndicator {
fragment {
// Visualize velocity direction
float2 velocity = float2(sin(time), cos(time * 1.3));
// Get direction signs
float2 dir = sign(velocity);
// Map to color (-1,1) -> (0,1)
float2 colorRG = dir * 0.5 + 0.5;
output.color = float4(colorRG.x, colorRG.y, 0.5, 1.0);
}
}Common Use Cases
Direction Extraction
bwsl
// Get movement direction from velocity
float3 direction = sign(velocity);Mirroring Effects
bwsl
// Mirror UV based on position sign
float2 mirrorUV = input.uv * sign(input.position.xy);Conditional Logic Without Branching
bwsl
// Apply different factors based on sign
float factor = 1.0 + sign(value) * 0.5; // 0.5 if negative, 1.5 if positiveNormal Reconstruction
bwsl
// Reconstruct normal direction
float3 normal = normalize(rawNormal);
normal.z = sqrt(1.0 - dot(normal.xy, normal.xy)) * sign(rawNormal.z);Axis-Aligned Operations
bwsl
// Determine which face of a cube we're on
int3 dominantAxis = int3(0);
float maxComponent = 0.0;
for (int i = 0; i < 3; i++) {
if (abs(direction[i]) > maxComponent) {
maxComponent = abs(direction[i]);
dominantAxis = int3(0);
dominantAxis[i] = int(sign(direction[i]));
}
}Zero Handling
The sign function returns 0 when the input is exactly 0. This makes it useful for detecting zero crossings or distinguishing between positive, negative, and zero values.
Compiled Output
When compiled to GLSL (for floats):
glsl
sign(x)
When compiled to HLSL:
hlsl
sign(x)