unity shader 之 CG(C for graphics) 入门(2)——CG的Swizzle操作

参考资料: 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;

以上的拼凑的都是可以允许的,大家可以通过自己的方式尝试着拼凑数据,能通过编译就行了。







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值