Intrinsics1 min read

ddy

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

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

Test ddy in a live shader

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

Open Playground

Live Demo

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

Signature

bwsl
ddy :: (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 vertical direction.

Example

bwsl
pipeline FlatNormals {
@fragment_only
fragment {
// Calculate face normal from world position derivatives
float3 dPdx = ddx(input.worldPos);
float3 dPdy = ddy(input.worldPos);
float3 flatNormal = normalize(cross(dPdx, dPdy));
// Use flat normal for faceted look
float3 lightDir = normalize(lightPos - input.worldPos);
float diffuse = max(dot(flatNormal, lightDir), 0.0);
output.color = float4(baseColor * diffuse, 1.0);
}
}

Common Use Cases

Face Normal Calculation

bwsl
// Flat shading from interpolated positions
float3 dPdx = ddx(worldPos);
float3 dPdy = ddy(worldPos);
float3 geometryNormal = normalize(cross(dPdx, dPdy));

Mipmap Selection

bwsl
// Calculate optimal mip level
float2 dUVdx = ddx(texCoord);
float2 dUVdy = ddy(texCoord);
float delta = max(dot(dUVdx, dUVdx), dot(dUVdy, dUVdy));
float mip = 0.5 * log2(delta);

Gradient Calculation

bwsl
// Get screen-space gradient direction
float2 gradient = float2(ddx(value), ddy(value));
float gradientMagnitude = length(gradient);

Normal Map Detail

bwsl
// Blend normal map based on view angle
float3 dTdx = ddx(tangent);
float3 dTdy = ddy(tangent);
float detailFade = saturate(1.0 / (1.0 + length(dTdx) + length(dTdy)));

Depth Gradient

bwsl
// Calculate depth slope for shadow bias
float depthDx = ddx(depth);
float depthDy = ddy(depth);
float slopeBias = max(abs(depthDx), abs(depthDy)) * biasScale;

Y Direction

Note that the y direction in screen space typically points downward (increasing y = lower on screen), though this can vary by API and framebuffer configuration.

Fragment Shader Only

Derivative functions are only available in fragment shaders. Using them elsewhere will cause a compilation error.

Compiled Output

When compiled to GLSL:

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

When compiled to HLSL:

hlsl
ddy(x)

When compiled to SPIR-V:

Uses OpDPdy instruction.

See Also

  • ddx - Derivative in x
  • ddy_fine - Fine derivative in y
  • fwidth - Sum of absolute derivatives