ABS - Rhomb - Built-in functions - Shader Learning

Built-in functions

ABS - Rhomb

Task

Write a shader that draws the full screen rhombus.


Requirements


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

Theory

Mathematically, a rhombus can be represented as an area bounded by 4 straight lines:


Image 1 - Rombus Area


Let's focus on determining the equation of the top left border of the rhombus:


Image 2 - Rombus top-left border


In general, the equation of a straight line has the form:

$ y = k * x + b $

Where:

  • $k$ is the slope coefficient of the line, which determines the angle at which the line intersects the x-axis.
  • $b$ is the displacement of the line along the y-axis.

For the top-left border, we observe that the $y$ parameter increases at the same rate as $x$, indicating a slope coefficient of $1$. The displacement along the y-axis is $0.5$. Therefore, the equation of our boundary takes the form:

$ y = x + 0.5 $

Next, we aim to describe the area below this straight line:


Image 3 - Area below the line


To achieve this, we convert our equation into an inequality. Since we are concerned with the area under the line, we replace the equal sign with the less than sign:

$ y < x + 0.5 \ \text{or} \ y - x < 0.5 $

Similarly, we can determine the equations for the remaining three boundaries and find their intersection.

Final Formula

As a result, we obtain four inequalities, each corresponding to one of the possible sign combinations of the arguments $x$ and $y$. Together, they cover all possible cases of how absolute values are opened. This means they are equal to the condition:

$ |x| + |y| < 0.5 $