Swizzling is accessing the values within vector types (Real2, Integer3, etc.) in any order. The term swizzling originated as the name for a technique used for doing the same thing, but within shaders.
Understanding a Swizzle
To swizzle a vector, refer to its values as if they were data members, using the letters X
, Y
, Z
, and W
for the corresponding elements. These can be combined in any permutation or combination.
var a = Real3(0,1,2);
Console.WriteLine("Example 1: a.X: `a.X`");
Console.WriteLine("Example 2: a.XYZ: `a.XYZ`");
Console.WriteLine("Example 3: a.XY: `a.XY`");
Console.WriteLine("Example 4: a.YX: `a.YX`");
Console.WriteLine("Example 5: a.XXY: `a.XXY`");
Console.WriteLine("Example 6: a.ZYXZ: `a.ZYXZ`");
Example 1: a.X: 0
Example 2: a.XYZ: (0, 1, 2)
Example 3: a.XY: (0, 1)
Example 4: a.YX: (1, 0)
Example 5: a.XXY: (0, 0, 1)
Example 6: a.ZYXZ: (2, 1, 0, 2)
In this example a
is a simple real3:
- Example 1 constructs a Real containing the value of
a.X
- Example 2 constructs a by-value copy of
a
. - Example 3 constructs a real2 containing the
X
andY
values ofa
. - Example 4 constructs a real2 with
X
as the value ofa.Y
, andY
as the value ofa.X
. - Example 5 constructs a real3 where the
X
andY
are set to the value ofa.X
andZ
is set to the value ofa.Y
. - Example 6 constructs a real4 with the same
X
,Y
, andZ
values as the original vectora
, but whoseW
value is the value ofa.Z
.
Assigning With Swizzles
Extracting portions of a vector as seen above is a fairly common operation even outside of shader development. An example may be centering the camera object while not affecting its zoom in a 2D game.
//0 out the XY axis and maintain the Z axis values
var cameraOffset = this.Camera.Transform.LocalTranslation;
cameraOffset.XY = Real2.Zero;
this.Camera.Transform.LocalTranslation = cameraOffset;
If we tried to assign into the swizzle constructed by-value from the member variable, however, it would not work:
this.Camera.Transform.LocalTranslation.XY = Real2();
In this example .XY
returns a by-value copy of the LocalTranslation
's X
and Y
values as a Real2. So in this example when we assign the Real2()
into it we are assigning into a copy instead of the member variable itself.
Related Materials
Manual
Reference
Task
- T950