Intrinsics1 min read
tanh
Computes the hyperbolic tangent.
Reading Time
1 min
Word Count
127
Sections
12
Try It Live
Test tanh in a live shader
Open the playground, start from a visual preset, and wire tanh into the fragment stage to see how it behaves with real values.
Open PlaygroundThe tanh function returns the hyperbolic tangent of x, defined as sinh(x) / cosh(x).
Live Demo
Signature
bwsl
tanh :: (T x) -> T {...}
Where T can be float, float2, float3, or float4.
Parameters
| Parameter | Type | Description |
|---|---|---|
x | T | The input value |
Return Value
Returns the hyperbolic tangent of x, in the range [-1, 1].
Example
bwsl
pipeline SoftLimiter {
fragment {
float3 color = sample(hdrTex, input.uv).rgb;
// Compress high dynamic range values smoothly
float exposure = 1.4;
float3 mapped = tanh(color * exposure);
output.color = float4(mapped, 1.0);
}
}Common Use Cases
Smooth Limiting
bwsl
// Clamp large positive and negative values without a hard edge
float limited = tanh(value);Signed Mask Shaping
bwsl
// Convert a signed distance into a smooth -1..1 transition
float mask = tanh(signedDistance * sharpness);Tone Mapping
bwsl
// Simple HDR compression
float3 displayColor = tanh(hdrColor * exposure);Velocity Dampening
bwsl
// Limit extreme velocity values smoothly
float3 dampedVelocity = tanh(velocity * scale) / scale;Soft Saturation
tanh is useful when saturate or clamp would create a hard edge. It approaches -1 and 1 smoothly as the input magnitude grows.
Compiled Output
When compiled to GLSL:
glsl
tanh(x)
When compiled to HLSL:
hlsl
tanh(x)
When compiled to Metal:
metal
tanh(x)