Metal Shader Functions Cheat Sheet

Basic Math Functions

Trigonometric

sin(x)      // Sine wave: -1 to 1, period 2π
cos(x)      // Cosine wave: -1 to 1, period 2π
tan(x)      // Tangent: -∞ to ∞
asin(x)     // Arcsine: input -1 to 1, output -π/2 to π/2
acos(x)     // Arccosine: input -1 to 1, output 0 to π
atan(x)     // Arctangent: output -π/2 to π/2
atan2(y,x)  // Arctangent with quadrant: output -π to π

When to use: Creating waves, rotations, circular patterns

Power & Exponential

pow(x, y)   // x raised to power y
exp(x)      // e^x
exp2(x)     // 2^x
log(x)      // Natural logarithm
log2(x)     // Base-2 logarithm
sqrt(x)     // Square root
inversesqrt(x) // 1/sqrt(x) - faster than 1.0/sqrt(x)

When to use: Contrast adjustments, falloff curves, acceleration

Basic Operations

abs(x)      // Absolute value: |-5| = 5
sign(x)     // Extract sign: -1, 0, or 1
floor(x)    // Round down: floor(1.7) = 1
ceil(x)     // Round up: ceil(1.2) = 2
round(x)    // Round to nearest integer
trunc(x)    // Remove decimal part
fract(x)    // Decimal part only: fract(3.7) = 0.7
mod(x, y)   // Remainder: mod(7, 3) = 1

When to use: Pattern repetition, grid creation, value snapping

Interpolation & Smoothing

Linear Interpolation

mix(a, b, t)    // Blend between a and b by t (0-1)
                // Result: a*(1-t) + b*t

When to use: Blending colors, smooth transitions, animation

Step Functions

step(edge, x)   // 0 if x < edge, 1 if x >= edge
                // Hard cutoff/threshold

When to use: Sharp edges, binary decisions, masking

Smooth Step

smoothstep(a, b, x)  // Smooth transition from 0 to 1
                     // 0 when x <= a
                     // 0-1 when a < x < b  
                     // 1 when x >= b

When to use: Soft edges, antialiasing, gradual transitions

Value Manipulation

Clamping & Saturation

clamp(x, min, max)    // Constrain x between min and max
saturate(x)           // Clamp between 0 and 1 (same as clamp(x, 0, 1))
min(a, b)            // Smaller of two values
max(a, b)            // Larger of two values

When to use: Keeping values in valid ranges, combining shapes

Vector Operations

Length & Distance

length(v)           // Magnitude of vector: length(float2(3,4)) = 5
distance(a, b)      // Distance between points: length(a - b)
normalize(v)        // Unit vector (length = 1)

When to use: Radial patterns, circular gradients, direction vectors

Dot & Cross Product

dot(a, b)          // Dot product: a.x*b.x + a.y*b.y + ...
cross(a, b)        // Cross product (3D vectors only)

When to use: Angles between vectors, lighting calculations

Reflection

reflect(i, n)      // Reflect vector i around normal n
refract(i, n, eta) // Refract vector with index of refraction

When to use: Mirror effects, glass/water shaders

Common Patterns & Techniques

Creating Grids

float2 grid = fract(uv * gridSize);        // Repeat space
float2 cellIndex = floor(uv * gridSize);   // Which cell

Radial Patterns

float2 center = uv - 0.5;
float r = length(center);        // Distance from center
float angle = atan2(center.y, center.x);  // Angle

Rotating Coordinates

float s = sin(angle);
float c = cos(angle);
float2 rotated = float2(
    uv.x * c - uv.y * s,
    uv.x * s + uv.y * c
);

Wave Animation

sin(position * frequency + time * speed)

Random/Noise (Pseudo)

float random(float2 st) {
    return fract(sin(dot(st, float2(12.9898, 78.233))) * 43758.5453);
}

Shader-Specific Types

Precision Types

half    // 16-bit float (faster, less precise)
float   // 32-bit float (standard precision)
half4   // 4-component 16-bit vector (colors)
float2  // 2-component 32-bit vector (coordinates)

SwiftUI Shader Types

// colorEffect - modify colors
[[ stitchable ]] half4 shader(float2 position, half4 color, float2 size)

// distortionEffect - warp space
[[ stitchable ]] float2 shader(float2 position, float2 size)

// layerEffect - sample textures
[[ stitchable ]] half4 shader(float2 position, SwiftUI::Layer layer, float2 size)

Performance Tips

Prefer Built-in Functions

// GOOD: inversesqrt(x)
// BAD:  1.0 / sqrt(x)

// GOOD: saturate(x)
// BAD:  clamp(x, 0.0, 1.0)

Avoid Branching When Possible

// GOOD: mix(a, b, step(0.5, x))
// BAD:  if (x > 0.5) return b; else return a;

Use Vector Operations

// GOOD: v * 0.5
// BAD:  float3(v.x * 0.5, v.y * 0.5, v.z * 0.5)

Quick Reference Examples

Smooth Circle

float circle = 1.0 - smoothstep(radius - 0.01, radius + 0.01, length(uv - center));

Gradient Remap

float value = sin(x) * 0.5 + 0.5;  // Remap -1,1 to 0,1

Pulsing Animation

float pulse = sin(time * speed) * 0.5 + 0.5;
float size = baseSize + pulse * sizeVariation;

Edge Detection

float edge = length(fwidth(value));  // Derivative for antialiasing

Color Adjustment

// Brightness
color.rgb *= brightness;

// Contrast
color.rgb = (color.rgb - 0.5) * contrast + 0.5;

// Saturation
float gray = dot(color.rgb, float3(0.299, 0.587, 0.114));
color.rgb = mix(float3(gray), color.rgb, saturation);