ddx
Computes the partial derivative with respect to screen-space x.
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 PlaygroundLive 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
ddx :: (T x) -> T {...}
Where T can be float, float2, float3, or float4.
Parameters
| Parameter | Type | Description |
|---|---|---|
x | T | The value to differentiate |
Return Value
Returns the rate of change of x per screen pixel in the horizontal direction.
Example
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
// 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
// Smooth edge using screen-space derivative
float edge = smoothstep(-ddx(sdf), ddx(sdf), sdf);Flat Shading
// Calculate face normal from position derivatives
float3 dPdx = ddx(input.worldPos);
float3 dPdy = ddy(input.worldPos);
float3 faceNormal = normalize(cross(dPdx, dPdy));Texture Filtering
// Calculate anisotropic filter parameters
float2 ddxUV = ddx(uv * textureSize);
float2 ddyUV = ddy(uv * textureSize);
float majorAxis = max(length(ddxUV), length(ddyUV));Curvature Estimation
// 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:
ddx(x)
When compiled to SPIR-V:
Uses OpDPdx instruction.