I was looking at vec4
glm's source code implementation, and I was wondering why they represent vector values with a union, instead of primitive data types like float
or int
?
This is the code I found in vec4
implementation:
union { T x, r, s; };
union { T y, g, t; };
union { T z, b, p; };
union { T w, a, q; };
What is the difference if we just write T x
, T y
, T z
, T w
?
Because a vec4
is commonly used for:
x
, y
, z
, w
r
, g
, b
, a
s
, t
, p
, q
(although these are less standardised, and I've also seen r
and u
used in different contexts)Using unions allows use to access the e.g. second data member as either .y
or .g
, depending on your preference & semantics.