If / Else - Shader Basics - Shader Learning

Shader Basics

If / Else

Task

The input color (HLSL: input.color) is a gradient: its red component grows from 0.0 at the left edge to 1.0 at the right edge.


Use if / else:

  • where color.r is less than 0.5, paint the pixel blue (0.0, 0.0, 1.0, 1.0);
  • everywhere else, paint it red (1.0, 0.0, 0.0, 1.0).
Hint 1

Which component of color tells how far to the right the pixel is? The left half is where it's small, the right half where it's big.

Hint 2

Create a result variable before the if. Set it in the branches, and write it to the output after them. The comparison table in the theory has the operator you need for "less than half".

Theory

So far every pixel did the same thing. A condition lets a pixel choose: if something is true, do one thing, otherwise do another.


Comparisons


A comparison checks two values and gives a bool: true or false.


Operator Meaning Example Result
< less than 0.3 < 0.5 true
> greater than 0.3 > 0.5 false
<= less than or equal 0.5 <= 0.5 true
>= greater than or equal 0.2 >= 0.5 false
== equal 1.0 == 1.0 true
!= not equal 1.0 != 2.0 true

Watch out: = puts a value into a variable, == compares.


if / else

vec3 result = vec3(0.0);

if (color.r > 0.5) {
    result = vec3(1.0); // runs only when the condition is true
} else {
    result = vec3(0.0); // runs only when it is false
}

The else part is optional. In HLSL it looks exactly the same.


When you use if, the editor warns that branching can slow down your program. For small shaders like these it's fine - you'll learn why later in the course.