首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >Swizzling in GLSL

Swizzling in GLSL

原创
作者头像
xosg
发布2025-09-16 15:27:34
发布2025-09-16 15:27:34
7200
代码可运行
举报
文章被收录于专栏:Web行业观察Web行业观察
运行总次数:0
代码可运行
Swizzling

You can access the components of vectors using the following syntax:

代码语言:javascript
代码运行次数:0
运行
复制
vec4 someVec;
someVec.x + someVec.y;

This is called swizzling. You can use x, y, z, or w, referring to the first, second, third, and fourth components, respectively.

The reason it has that name "swizzling" is because the following syntax is entirely valid:

代码语言:javascript
代码运行次数:0
运行
复制
vec2 someVec;
vec4 otherVec = someVec.xyxx;
vec3 thirdVec = otherVec.zyy;

You can use any combination of up to 4 of the letters to create a vector (of the same basic type) of that length. So otherVec.zyy is a vec3, which is how we can initialize a vec3 value with it. Any combination of up to 4 letters is acceptable, so long as the source vector actually has those components. Attempting to access the 'w' component of a vec3 for example is a compile-time error.

Swizzling also works on l-values:

代码语言:javascript
代码运行次数:0
运行
复制
vec4 someVec;
someVec.wzyx = vec4(1.0, 2.0, 3.0, 4.0); // Reverses the order.
someVec.zx = vec2(3.0, 5.0); // Sets the 3rd component of someVec to 3.0 and the 1st component to 5.0

However, when you use a swizzle as a way of setting component values, you cannot use the same swizzle component twice. So someVec.xx = vec2(4.0, 4.0); is not allowed.

Additionally, there are 3 sets of swizzle masks. You can use xyzw, rgba (for colors), or stpq (for texture coordinates). These three sets have no actual difference; they're just syntactic sugar. You cannot combine names from different sets in a single swizzle operation. So ".xrs" is not a valid swizzle mask.

In OpenGL 4.2 or ARB_shading_language_420pack, scalars can be swizzled as well. They obviously only have one source component, but it is legal to do this:

代码语言:javascript
代码运行次数:0
运行
复制
float aFloat;
vec4 someVec = aFloat.xxxx;

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Swizzling
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档