London Inverted

Functional Shaders: A Colorful Intro-Part3 Invert and Swizzle

Rupert
3 min readSep 22, 2020

--

Swizzling and invert time. No that’s not a hot new dance move or skate board trick. This article will show how to invert the image we added in part 2 and use that as a way to learn about swizzling. This will get a little technical. If your head starts to spin just do the practice examples.

Missed Part1?

Missed Part 2 — How to add an image

Invert Example Starting Point

As we learned in part 1 that colors and alpha should always be in the 0 to 1 range we can simply invert the colors by changing it to negative and subtracting from one.

Inverting Individual Channels:

texColor.r = 1.0 — texColor.r; 
texColor.g = 1.0 — texColor.g;
texColor.b = 1.0 — texColor.b;

Inverting Vector 3 — Swizzled

texColor.rgb = vec3(1.0) - texColor.rgb;

Inverting Vector 4 — Swizzled

texColor = vec4(1.0) - texColor;
// set alpha back to 1.0
// texColor.a = 1.0;

What is Swizzling

In part 1 we learned that we can change each color channel individually via the r, g and b components. A common feature of shader languages like GLSL is the swizzle operators. Those allow selecting multiple components of a vector and change their order. For example, “color.r”, “color.rbg” and “color.brgg” form respectively a scalar, a three components vector and a four components vector. With GLSL, swizzle operators can be both R-values and L-values.

An l-value refers to an object that persists beyond a single expression. An r-value is a temporary value that does not persist beyond the expression that uses it.).

This is called swizzling. You can use x, y, z, or w, referring to the first, second, third, and fourth components, respectively.

There are 3 sets of swizzle masks. You can use xyzw, rgba (for colors), or stpq (for texture coordinates). These three sets have no actual difference. You cannot combine names from different sets in a single swizzle operation. So “.xgp” is not a valid swizzle mask.

Why Swizzle

Swizzle can both make your shader faster, and make your code easier to read.

fragColor = texColor.rgba * vec4(vec3(color1.r), color1.g);

This could simply be syntactic shorthand for something like:

fragColor = Vec4(texColor.r, texColor.g, texColor.b, texColor.a)
* Vec4(color1.r, color1.r, color1.r, color1.g);

Swizzle masks are essentially free in hardware. Use them where possible.

Challenge

Try swizzling the inverted image to make this

Completed Invert Shader

Links

In part 4 we will learn how to convert an image to gray scale

--

--