GLSL Functions

Definition of Smoothstep Function

By taking \(x^2\) we have a function that starts smoothly at \(0\) but ends rather harsh at \(1\). When we take the same function, push it one to the right and flip it arund we get \(-(x-1)^2\). By adding 1 we move the parabola to \(1\) and have a function with smooth ending.

When we now interpolate both functions

\[\begin{array}{rl}f(x) &= x^2\\g(x) &= 1-(x-1)^2\end{array}\]

we get a smooth function

\[\sigma(x) = f(x) \cdot (1-x) + g(x) \cdot x = x^2(3-2x)\]

Since we want the function to operate in \([0,1]\), we clamp the input value of \(x\):

\[x'=\max(0, \min(1, x))\]

Since the smoothstep function in GLSL has two ramp parameters \(a\) and \(b\), we shift the curve by \(a\) first:

\[x'=\max(0, \min(1, x - a))\]

The second ramp parameter \(b\) depends on the slope of the ramp, so

\[x'=\max\left(0, \min\left(1, \frac{x - a}{b-a} \right)\right)\]

which finally leads to the smooth step function:

\[\sigma(x; a, b):= \sigma\left(\max\left(0, \min\left(1, \frac{x - a}{b-a} \right)\right)\right)\]

The good thing is, if \(b < a\), the function flips over, which is exactly the behavior of the GLSL implementation.

Definition of Mix Function

\[\text{mix}(\mathbf{a}, \mathbf{b}, p) := \mathbf{a} + p \cdot (\mathbf{b} - \mathbf{a})\]

Definition of Step Function

\[\text{step}(\mathbf{a}, \mathbf{b}) := \mathbf{b} < \mathbf{a}\text{ ? }\mathbf{0} : \mathbf{1}\]

Smooth Staircase

Let \(\sigma : [0, 1]\to[0,1]\) be a step function with \(\sigma(x)=0\) \(\forall x<\epsilon\) and \(\sigma(x)=1\) \(\forall x>1-\epsilon\). A smooth staircase with step size 1 is then

\[\Gamma(x) = \sigma(x - \left\lfloor x\right\rfloor) + \left\lfloor x\right\rfloor\]

If a given width and height of the steps is required, we can rescale \(\Gamma\) to get

\[\Gamma(x ; w, h) = h\cdot \Gamma\left(\frac{x}{w}\right) = h\cdot \left[\sigma\left(\frac{x}{w} - \left\lfloor \frac{x}{w}\right\rfloor\right) + \left\lfloor \frac{x}{w}\right\rfloor\right]\]

Derivation of logical float functions

\[\begin{array}{rl}\text{not}(x) &:= 1 - x\\\text{and} (x, y) &:= x y\\\text{or} (x, y) &:= \text{not}(\text{and}(\text{not}(x), \text{not}(y))) = x + y - x y\\\text{xor} (x, y) &:= \text{or}(\text{and}(x, \text{not}(y)), \text{and}(y, \text{not}(x))) = x + y - 2 x y\\\text{implies}(x, y) &:= \text{or}(\text{not}(x), y) = 1 - x + x y\\x\text{ ? } y : z &:= x y + (1 - x) z = z + x(y - z)\\\end{array}\]

« Back to Book Overview