Created
July 12, 2025 15:43
-
-
Save olchyk98/68412332d6f3d3e341019847ff324a5f to your computer and use it in GitHub Desktop.
GLSL Vector Swizzling in Javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function vec(...args) { | |
| if (args.length > 4) { | |
| throw new Error('Only vectors with up to 4 elements are supported.') | |
| } | |
| const proxied = new Proxy(args, { | |
| get(t, p) { | |
| if (['x', 'r'].includes(p)) return t[0] | |
| if (['y', 'g'].includes(p)) return t[1] | |
| if (['z', 'b'].includes(p)) return t[2] | |
| if (['w', 'a'].includes(p)) return t[3] | |
| if (p.length <= 1) return t[p] | |
| const ingredients = p | |
| .split('') | |
| .map((i) => proxied[i]) | |
| if (ingredients.every(Boolean)) { | |
| return vec(...ingredients) | |
| } | |
| return t[p] | |
| }, | |
| set(t, p, v) { | |
| t[p] = v | |
| return true | |
| } | |
| }) | |
| return proxied | |
| } | |
| const vec4 = (a, b, c, d) => vec(a, b, c, d) | |
| const vec3 = (a, b, c) => vec(a, b, c) | |
| const vec2 = (a, b) => vec(a, b) | |
| const vec1 = (a) => vec(a) | |
| const v4 = vec4(1, 2, 3, 4) | |
| // Swizzling | |
| console.log(v4.rgba.abgr.xya.yx) // [3,4] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment