Search code examples
c++glm-math

Why does glm::vec represent vec values as unions?


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?


Solution

  • Because a vec4 is commonly used for:

    • Space coordinates x, y, z, w
    • Colour components r, g, b, a
    • Texture coordinates 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.