ABS - Built-in functions - Shader Learning

Built-in functions

ABS

Task

Create a gradient that linearly transitions from 0.0 (black) at the center to 1.0 (red) at the edges.


Requirements


The shader should avoid using branching or conditional statements in its code, and instead rely on the abs function to determine the color of each pixel.

Theory

The abs function is used to calculate the absolute value of a scalar or vector input. The absolute value of a number is its magnitude without regard to its sign. The abs function can be applied to scalar values (e.g., floats) as well as vector values (e.g., vec2, vec3, vec4).


Function Signature

float abs(float x);

How It Works


The abs function operates by:

  • Returning the input value if it is positive or zero.
  • Returning the negation of the input value if it is negative.

This ensures that the output of the abs function is always positive or zero.


Example

float number = -5.0;
float absValue = abs(number); // will be 5.0

Practical Applications


By using the abs function in GLSL/HLSL, you can easily mirror functions with respect to the zero value by leveraging the symmetry provided by absolute values. This technique is particularly useful for creating symmetrical effects or transformations in shaders.