带法线贴图的高光着色
Posted cocotang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了带法线贴图的高光着色相关的知识,希望对你有一定的参考价值。
<1>效果
<2>代码
//blinn高光 带法线细节 //思路:使用切线空间下面的法线贴图(效率虽然低点,但是通用性好) //顶点函数计算切线空间转世界空间矩阵 //片元函数采样法线贴图 并且反隐射 再计算光照 Shader "Tang/617/BlinnTexNormal" Properties _Color("Tin Color",Color) = (1,1,1,1) _MainTex("漫反射贴图",2D) = "white" _BumpTex("法线贴图",2D) = "bump" _BumpScale("BumpScale",Range(1,8)) = 2 _Specular("Specular",Color) = (1,1,1,1) _Gloss("Gloss",Range(1,64)) = 8 SubShader Pass Tags "LightMode" = "ForwardBase" CGPROGRAM #pragma vertex vert #pragma fragment frag #include "Lighting.cginc" struct a2v float4 vertex:POSITION; float3 normal:NORMAL; float4 tangent:TANGENT; float4 texcoord:TEXCOORD0; ; struct v2f float4 pos:SV_POSITION; float4 uv:TEXCOORD0; //切线空间转世界空间矩阵 float4 TtoW0:TEXCOORD1; float4 TtoW1:TEXCOORD2; float4 TtoW2:TEXCOORD3; ; fixed4 _Color; fixed4 _Specular; fixed _Gloss; sampler2D _MainTex;float4 _MainTex_ST; sampler2D _BumpTex;float4 _BumpTex_ST; fixed _BumpScale; v2f vert(a2v v) v2f o; o.pos = UnityObjectToClipPos(v.vertex); fixed3 worldNormal = UnityObjectToWorldNormal(v.normal); fixed3 worldPos = mul(unity_ObjectToWorld,v.vertex).xyz; fixed3 worldTangent = UnityObjectToWorldDir(v.tangent.xyz); fixed3 worldBinormal = cross(worldNormal,worldTangent)*v.tangent.w;//保证副法线的方向正确*v.tangent.w? //uv o.uv.xy = TRANSFORM_TEX(v.texcoord,_MainTex); o.uv.zw = TRANSFORM_TEX(v.texcoord,_BumpTex); //切线到世界空间的矩阵 o.TtoW0 = float4(worldTangent.x,worldBinormal.x,worldNormal.x,worldPos.x); o.TtoW1 = float4(worldTangent.y,worldBinormal.y,worldNormal.y,worldPos.y); o.TtoW2 = float4(worldTangent.z,worldBinormal.z,worldNormal.z,worldPos.z); return o; fixed4 frag(v2f i):SV_Target //世界坐标 fixed3 worldPos = fixed3(i.TtoW0.w,i.TtoW1.w,i.TtoW2.w); //世界光线方向 fixed3 lightDir = UnityWorldSpaceLightDir(worldPos); //世界观察方向 fixed3 viewDir = UnityWorldSpaceViewDir(worldPos); //采样法线贴图 并反隐射到-1,1(像素只能是0-1 所以需要反隐射) fixed3 bump = UnpackNormal(tex2D(_BumpTex,i.uv.zw)); bump.xy *= _BumpScale; bump.z = sqrt(1-saturate(dot(bump.xy,bump.xy))); bump = normalize(half3(dot(i.TtoW0.xyz,bump),dot(i.TtoW1.xyz,bump),dot(i.TtoW2.xyz,bump))); //下面使用法线进行光照计算 fixed3 albedo = tex2D(_MainTex,i.uv.xy)*_Color.rgb; fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz*albedo; fixed3 diffuse = _LightColor0.rgb*albedo* saturate(dot(bump,lightDir)); //blinn fixed3 h = normalize(lightDir+viewDir); fixed3 specular = _LightColor0.rgb*_Specular.rgb* pow(saturate(dot(h,bump)),_Gloss); return fixed4(ambient+diffuse+specular,1); ENDCG FallBack "Diffuse"
以上是关于带法线贴图的高光着色的主要内容,如果未能解决你的问题,请参考以下文章