ShaderToy内的效果图如下:
ShaderToy内的源码如下:
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec2 q = 0.6 * (2.0*fragCoord.xy-iResolution.xy)/min(iResolution.y,iResolution.x);
float leaves = 4.0;
float pointyness = 0.13;
float a = atan(q.x,q.y);
float r = length(q);
float s = 0.5 + 0.5*sin(leaves*a + iTime);
float g = sin(1.57+leaves*a+iTime);
float d = 0.15 + 0.3*sqrt(s) + pointyness*g*g;
float h = r/d;
float f = 1.0-smoothstep( 0.95, 1.0, h );
h *= 1.0-0.5*(1.0-h)*smoothstep(0.95+0.05*h,1.0,sin(leaves*a+iTime));
vec3 bcol = vec3(0.9+0.1*q.y,1.0,0.9-0.1*q.y);
bcol *= 1.0 - 0.5*r;
h = 0.1 + h;
vec3 col = mix( bcol, 1.2*vec3(0.6*h,0.2+0.5*h,0.0), f );
fragColor = vec4( col, 1.0 );
}
下面是在Unity内的效果展示:
下面是转译后的UnityShaderLab代码:
Shader"Leaf"
{
Properties
{
}
SubShader
{
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma fragmentoption ARB_precision_hint_fastest
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
float4 screenCoord : TEXCOORD1;
};
v2f vert(appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
o.screenCoord.xy = ComputeScreenPos(o.vertex);
return o;
}
fixed4 frag(v2f i) : SV_Target
{
fixed2 q = 0.6 * (2.0*i.uv-1)/min(1,1);
fixed a = atan2( q.y , q.x);
fixed r = length( q );
fixed s = 0.50001 + 0.5*sin( 6.0*a + _Time.y*3 );
fixed g = sin( 1.57+6.0*a+_Time.y*3 );
fixed d = 0.15 + 0.3*sqrt(s) + 0.15*g*g;
fixed h = clamp( r/d, 0.0, 1.0 );
fixed f = 1.0-smoothstep( 0.95, 1.0, h );
h *= 1.0-0.5*(1.0-h)*smoothstep( 0.95+0.05*h, 1.0, sin(6.0*a+_Time.y*3) );
fixed3 bcol = fixed3(0.9+0.1*q.y, 1.0, 0.9-0.1*q.y);
bcol *= 1.0 - 0.5*r;
fixed3 col = lerp( bcol, 1.2*fixed3(0.65*h, 0.25+0.5*h, 0.0), f );
return fixed4( col, 1.0 );
}
ENDCG
}
}
}
代码详解:
"fixed a = atan2( q.y , q.x);"//计算的是下面这样的效果,(在片段着色器中的“a”的值):
fixed r = length( q );//计算的是下面这样的效果,(在片段着色器中的“r”的值):
fixed s = 0.50001 + 0.5*sin( 6.0*a + _Time.y*3 );//计算的是下面这样的效果,(在片段着色器中的“s”的值):
fixed g = sin( 1.57+6.0*a+_Time.y*3 );//g 和 s 的算法都带有"sin(x)"公式,变量参数同样是 a 的值。
fixed d = 0.15 + 0.3*sqrt(s) + 0.15*g*g; // 通过sqrt和g*g 计算出的d值,效果如下图
fixed h = clamp( r/d, 0.0, 1.0 ); // 通过clamp 计算出的h值,效果如下图
到这一步,基本雏形初现了。
fixed f = 1.0-smoothstep( 0.95, 1.0, h ); //通过smoothstep 计算出的f值,效果如下图