Swizzling - Built-in functions - Shader Learning

Built-in functions

Swizzling

Task

Using swizzle reorder pixel's color components from rgba to bgra.

Theory

Swizzling refers to the technique of selecting and rearranging components of a vector to create a new vector. It allows you to access and manipulate individual components of a vector in a concise and flexible manner. Swizzling is achieved by using a combination of component names x, y, z, w, referring to the first, second, third, and fourth components, respectively.


Also you can use the r, g, b and a swizzle mask instead of the x, y, z, w to access components of a vector. The rgba mask is commonly used when working with colors or texture data, as it corresponds to the red, green, blue, and alpha components typically associated with color information.


Here are some examples of swizzling in GLSL:

Swizzling Color Components:

vec4 color = vec4(1.0, 0.5, 0.2, 1.0);

// creates a vec3 with the red, green, and blue components
vec3 rgb  = color.rgb;

// reorders the components using rgba swizzle
vec4 rgba = color.bgra;

Combining Color Swizzle and Operations:

vec3 baseColor = vec3(0.5, 0.3, 0.8);
float alpha = 0.7;

// creates a new color with specified RGB components and alpha
vec4 finalColor = vec4(baseColor.rgb, alpha);

HLSL


In HLSL, swizzling works in a very similar way. You can access and rearrange vector components using the same .xyzw or .rgba notation. This makes it easy to manipulate colors, positions, normals, and other multi-component data.


Examples of swizzling in HLSL:

Swizzling Color Components:

float4 color = float4(1.0, 0.5, 0.2, 1.0);

// creates a float3 with the red, green, and blue components
float3 rgb  = color.rgb;

// reorders the components using rgba swizzle
float4 rgba = color.bgra;

Combining Color Swizzle and Operations:

float3 baseColor = float3(0.5, 0.3, 0.8);
float alpha = 0.7;

// creates a new color with specified RGB components and alpha
float4 finalColor = float4(baseColor.rgb, alpha);