Intrinsics1 min read

ddx

Computes the partial derivative with respect to screen-space x.

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

Test ddx in a live shader

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

Open Playground

Live Demo

The ddx function computes the partial derivative of a value with respect to the screen-space x coordinate. This is only available in fragment shaders.

Signature

bwsl
ddx :: (T x) -> T {...}

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

Parameters

ParameterTypeDescription
xTThe value to differentiate

Return Value

Returns the rate of change of x per screen pixel in the horizontal direction.

Example

bwsl
pipeline AntialiasedLine {
@fragment_only
fragment {
// Distance from line
float dist = abs(input.uv.y - 0.5);
// Compute pixel width of line edge using derivatives
float pixelWidth = fwidth(input.uv.y);
// Anti-aliased line
float line = 1.0 - smoothstep(lineWidth - pixelWidth, lineWidth + pixelWidth, dist);
output.color = float4(float3(line), 1.0);
}
}

Common Use Cases

Mipmap Level Calculation

bwsl
// Calculate LOD from UV derivatives
float2 dx = ddx(uv);
float2 dy = ddy(uv);
float maxDeriv = max(dot(dx, dx), dot(dy, dy));
float mipLevel = 0.5 * log2(maxDeriv);

Anti-aliased Edges

bwsl
// Smooth edge using screen-space derivative
float edge = smoothstep(-ddx(sdf), ddx(sdf), sdf);

Flat Shading

bwsl
// Calculate face normal from position derivatives
float3 dPdx = ddx(input.worldPos);
float3 dPdy = ddy(input.worldPos);
float3 faceNormal = normalize(cross(dPdx, dPdy));

Texture Filtering

bwsl
// Calculate anisotropic filter parameters
float2 ddxUV = ddx(uv * textureSize);
float2 ddyUV = ddy(uv * textureSize);
float majorAxis = max(length(ddxUV), length(ddyUV));

Curvature Estimation

bwsl
// Estimate surface curvature
float3 dNdx = ddx(normal);
float3 dNdy = ddy(normal);
float curvature = length(dNdx) + length(dNdy);

Fragment Shader Only

Derivative functions are only available in fragment shaders. They rely on neighboring fragment values computed in parallel.

2x2 Quad

GPUs compute derivatives using 2x2 fragment quads. This means derivatives are constant across each 2x2 block. For finer control, use ddx_fine.

Compiled Output

When compiled to GLSL:

Uses the target backend's native x-derivative operation.

When compiled to HLSL:

hlsl
ddx(x)

When compiled to SPIR-V:

Uses OpDPdx instruction.

See Also

  • ddy - Derivative in y
  • ddx_fine - Fine derivative in x
  • fwidth - Sum of absolute derivatives