Intrinsics1 min read

step

Generates a step function by comparing two values.

Reading Time
1 min
Word Count
143
Sections
11
Try It Live

Test step in a live shader

Open the playground, start from a visual preset, and wire step into the fragment stage to see how it behaves with real values.

Open Playground

Live Demo

The step function returns 0 if x < edge, otherwise it returns 1. This creates a hard threshold or step transition at the edge value.

Signature

bwsl
step :: (T edge, T x) -> T {...}

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

Parameters

ParameterTypeDescription
edgeTThreshold value
xTValue to test

Return Value

Returns 0.0 if x < edge, otherwise returns 1.0.

Example

bwsl
pipeline ThresholdEffect {
fragment {
// Convert grayscale to black and white
float4 texColor = sample(inputTex, input.uv);
float gray = dot(texColor.rgb, float3(0.299, 0.587, 0.114));
// Hard threshold at 0.5
float bw = step(0.5, gray);
output.color = float4(float3(bw), 1.0);
}
}

Common Use Cases

Cel Shading Bands

bwsl
// Create distinct lighting bands
float NdotL = dot(normal, lightDir);
float band1 = step(0.0, NdotL);
float band2 = step(0.5, NdotL);
float lighting = 0.3 + 0.35 * band1 + 0.35 * band2;

Sharp Cutoff

bwsl
// Clip pixels below alpha threshold
float visible = step(0.5, texColor.a);
if (visible < 0.5) discard;

Grid Lines

bwsl
// Draw grid lines
float2 grid = abs(fract(input.uv * 10.0) - 0.5);
float line = 1.0 - step(0.45, min(grid.x, grid.y));

Distance Field Shapes

bwsl
// Hard-edged circle from distance field
float dist = length(input.uv - 0.5);
float circle = 1.0 - step(0.25, dist);

Branchless Selection

The step function is useful for branchless conditional selection: a * step(threshold, x) + b * (1.0 - step(threshold, x)) selects a when x >= threshold, otherwise b.

Parameter Order

Note that the parameter order is step(edge, x), not step(x, edge). The edge comes first, then the value being tested.

Compiled Output

When compiled to GLSL:

glsl
step(edge, x)

When compiled to HLSL:

hlsl
step(edge, x)

See Also