地址
https://en.wikibooks.org/wiki/Cg_Programming/Unity/RGB_Cube
重点
认识结构体、顶点输出语义
关键代码
Shader "Cg shader for RGB cube" {
SubShader {
Pass {
CGPROGRAM
#pragma vertex vert // vert function is the vertex shader
#pragma fragment frag // frag function is the fragment shader
// for multiple vertex output parameters an output structure
// is defined:
struct vertexOutput {
float4 pos : SV_POSITION;
float4 col : TEXCOORD0;
};
vertexOutput vert(float4 vertexPos : POSITION)
// vertex shader
{
vertexOutput output; // we don't need to type 'struct' here
output.pos = mul(UNITY_MATRIX_MVP, vertexPos);
output.col = vertexPos + float4(0.5, 0.5, 0.5, 0.0);
// Here the vertex shader writes output data
// to the output structure. We add 0.5 to the
// x, y, and z coordinates, because the
// coordinates of the cube are between -0.5 and
// 0.5 but we need them between 0.0 and 1.0.
return output;
}
float4 frag(vertexOutput input) : COLOR // fragment shader
{
return input.col;
// Here the fragment shader returns the "col" input
// parameter with semantic TEXCOORD0 as nameless
// output parameter with semantic COLOR.
}
ENDCG
}
}
}
在网页的最后有相关阅读,英文好的可以自己查阅,我再下面写出我自己的理解
解读
本次的shader和上次的差别不是很大,介绍不同的部分
struct vertexOutput { float4 pos : SV_POSITION; float4 col : TEXCOORD0; };在cg中支持结构体,这样你可以将一组数据放在一个里面,有点面向对象的赶脚,语义的形式很多种,详见参考书阳春白雪
SV_POSITION 表示位置的输出语义
TEXCOORDO 表示纹理的输出语义
大致有这几种语义:
在vert程序中将数据存入结构体
output.pos = mul(UNITY_MATRIX_MVP, vertexPos); 存入位置信息
output.col = vertexPos + float4(0.5, 0.5, 0.5, 0.0); 在默认颜色信息的基础上加
float4(0.5, 0.5, 0.5, 0.0)
默认的颜色值不是全部为0,默认的效果图:
在frag中把顶点处理得到的颜色信息直接返回,得到:
这个shader的作用相当于把默认的提亮了
疑惑
维基百科上说默认值在-0.5-0.5之间,可是具体多少呢,我本想打印出来,可是发现我不知道怎么调试