Table of Contents

Math

The math class holds the shader math functions, with the same names and behavior as the HLSL functions, and the usual constants. Functions that take vectors work on each component separately, unless noted otherwise.

The functions take float values and vectors, and abs, sign, min, max, clamp and mad also take int and uint ones. There are no separate half versions: half values convert to float, so the result is a float. Cast it back where you need a half, as in OUT.albedo = (half3)math.saturate(color);.

Functions

Group Functions
Trigonometry (radians) sin, cos, tan, asin, acos, atan, atan2, sinh, cosh, tanh, sincos
Exponents and logarithms exp, exp2, log, log2, log10, pow, sqrt, rsqrt, rcp
Rounding floor, ceil, round, trunc, frac, fmod, modf
Sign and range abs, sign, min, max, clamp, saturate
Interpolation lerp, step, smoothstep
Vectors dot, cross, length, lengthsq, distance, distancesq, normalize, reflect, refract
Matrices mul, transpose, determinant
Angles degrees, radians
Comparison equal, notequal, lessthan, greaterthan, lessthanequal, greaterthanequal, all, any
Special values isnan, isinf, isfinite
Bits countbits, reversebits, firstbithigh, firstbitlow, asfloat, asint, asuint, f16tof32, f32tof16
Other mad (a * b + c in one instruction)

A few behaviors worth knowing:

  • lerp(a, b, t) doesn't clamp t: values outside 0 to 1 extrapolate.
  • saturate(x) clamps to 0 to 1, and is usually free on the GPU.
  • frac(x) is x - floor(x), so frac(-0.25) is 0.75.
  • pow(x, y) with a negative x gives NaN on the GPU.
  • normalize of a zero vector gives NaN.
  • round rounds halfway values, such as 2.5, to the nearest even number on the GPU.

The screen-space derivatives ddx, ddy and fwidth aren't in math, because they depend on the pixel being rendered rather than only on their arguments. They're in ShaderApi. See Built-in variables and functions.

Constants

Constant Value
PI, TAU (same as TWO_PI), FOUR_PI π, 2π, 4π
HALF_PI, PI_DIV_FOUR π/2, π/4
INV_PI, INV_TWO_PI, INV_FOUR_PI, INV_HALF_PI 1/π, 1/(2π), 1/(4π), 2/π
E, LOG2_E, SQRT2 e, log₂ e, √2
FLT_MAX, FLT_MIN, FLT_EPS The largest float, the smallest normalized float, and the float epsilon (2⁻²⁴).
HALF_MAX, HALF_MIN, HALF_MIN_SQRT, HALF_EPS The same for half.
UINT_MAX The largest uint.

The constants are replaced by their values in the generated code, so using them costs nothing.

float angle = uv.x * math.TAU;
float2 circle = new float2(math.cos(angle), math.sin(angle));