参考资料: http://http.developer.nvidia.com/Cg/Cg_language.html
从上面的链接中找到Swizzle的操作介绍如下:
- There is a built-in swizzle operator:
.xyzw
or.rgba
for vectors. This operator allows the components of a vector to be rearranged and also replicated. It also allows the creation of a vector from a scalar. - For an lvalue, the swizzle operator allows components of a vector or matrix to be selectively written.
简单来说,允许你通过拼凑的方式来组合
首先,先來一段简单的代码,作为用于学习Swizzle操作的基本结构。
Shader "Custom/SwizzleOperation"
{
SubShader
{
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
void vert(in float2 inPos : POSITION, out float4 outPos : POSITION)
{
outPos = fixed4(inPos, 0, 1);
}
void frag(inout float4 col : COLOR)
{
fixed r = 0;
fixed g = 1;
fixed b = 0;
fixed a = 1;
col = fixed4(r, g, b, a);
//数据维度最多为4.
float2 f2 = float2(1, 0);
float3 f3 = float3(0, 1, 1);
float4 f4 = float4(0, 0, 1, 1);
//继续添加代码
}
ENDCG
}
}
}
现在使用Swizzle操作来拼凑数据,有如下几种形式:
float4 fl4 = float4(f2, 0, 1);
//可以按正常顺序来取值,也可以反序来取值
fl4 = float4(f2.xy, 0, 1);
fl4 = float4(f2.yx, 0, 1);
fl4 = float4(f3.xyzz);
fl4 = float4(f3.xxxx);
fl4 = float4(f3.yyyy);
fl4 = float4(f4.wzyx);
fl4 = float4(f4.rgba);
fl4 = float4(f4.ab, f3.zy);
//这样的形式是不允许的。
//fl4 = float4(f4.rgzw);
col = fl4;
以上的拼凑的都是可以允许的,大家可以通过自己的方式尝试着拼凑数据,能通过编译就行了。