How Do GLSL Exponential Functions Work?

GLSL provides a dedicated suite of built-in exponential functions designed to handle powers, logarithms, roots, and base-\(e\) calculations efficiently on graphics hardware. This article explores how functions such as pow, exp, log, exp2, log2, sqrt, and inversesqrt operate under the hood, their component-wise vector handling, undefined domain constraints, and underlying GPU hardware considerations.

Core Exponential Functions in GLSL

The OpenGL Shading Language (GLSL) defines standard math functions across scalar floats and floating-point vectors (vec2, vec3, vec4). When applied to vectors, all operations execute component-wise.

Power and Roots

Natural Exponents and Logarithms

Base-2 Exponents and Logarithms

Vector Processing and Component-Wise Execution

GLSL exponential functions are overloaded across primitive types and vector sizes:

// Scalar computation
float intensity = pow(0.5, 2.2);

// Vector computation (applied per-component)
vec3 color = vec3(0.2, 0.4, 0.8);
vec3 gammaCorrected = pow(color, vec3(1.0 / 2.2));

// Vector normalization using inversesqrt
vec3 normal = vec3(1.0, 2.0, 3.0);
vec3 normalized = normal * inversesqrt(dot(normal, normal));

Because execution occurs on each vector component independently, passing mismatched vector dimensions causes compile-time errors unless combined with a matching scalar or vector overload.

GPU Hardware Architecture and Precision

GPUs execute exponential instructions using Special Function Units (SFUs) alongside standard Arithmetic Logic Units (ALUs).

  1. Base-2 Transformation: GPUs natively calculate log2 and exp2 via SFU lookup tables and interpolation. Functions like exp(x) or pow(x, y) are compiled into scaled base-2 instructions:

\[\text{exp}(x) = 2^{x \cdot \log_2(e)}\]

\[\text{pow}(x, y) = 2^{y \cdot \log_2(x)}\]

  1. Precision and Precision Qualifiers: In GLSL ES (OpenGL ES / WebGL), qualifiers like lowp, mediump, and highp determine the precision of SFU evaluations. mediump or lowp exponential functions can introduce noticeable color banding in operations like gamma correction or specular highlight attenuation.
  2. Handling Out-of-Range Inputs: Passing negative or zero values where strictly positive inputs are required leads to NaN (Not a Number) or Inf (Infinity), causing visual artifacts like black or white pixel dropouts. Clamping inputs via max(val, 0.0001) prevents domain violations before calling pow or log.