Created
March 11, 2020 01:55
-
-
Save stilllisisi/999338a9007a45a55babde58d2679283 to your computer and use it in GitHub Desktop.
【游戏-Shader】切线空间下的法线贴图
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//法线贴图有两种,一种是模型空间的贴图,也就是贴图中的法线信息是在模型空间下的;第二种是切线空间的贴图,也就是贴图中的法线信息是在切线空间下的。 | |
//由于后一种要比前一种好用,所以后面用的皆为切线空间中的法线贴图。 | |
Shader "Unlit/NormalTex" | |
{ | |
Properties | |
{ | |
_MainTex ("Texture", 2D) = "white" {} | |
_MainNormalTex("NormalTex",2D) = "white"{} | |
} | |
SubShader | |
{ | |
Tags { "RenderType"="Opaque" } | |
LOD 100 | |
Pass | |
{ | |
Tags{ | |
"LightMode"="ForwardBase" | |
} | |
CGPROGRAM | |
#pragma vertex vert | |
#pragma fragment frag | |
#include "UnityCG.cginc" | |
#include "Lighting.cginc" | |
struct a2v | |
{ | |
float4 vertex : POSITION; | |
float2 uv : TEXCOORD0; | |
float3 normal:NORMAL; | |
float4 tangent:TANGENT; | |
}; | |
struct v2f | |
{ | |
float4 uv : TEXCOORD0; | |
float4 vertex : SV_POSITION; | |
float3 lightDir : TEXCOORD1; | |
float3 viewDir : TEXCOORD2; | |
}; | |
sampler2D _MainTex; | |
float4 _MainTex_ST; | |
sampler2D _MainNormalTex; | |
float4 _MainNormalTex_ST; | |
v2f vert (a2v v) | |
{ | |
v2f o; | |
o.vertex = UnityObjectToClipPos(v.vertex); | |
// 缩放+偏移 | |
o.uv.xy = TRANSFORM_TEX(v.uv,_MainTex); | |
o.uv.zw = TRANSFORM_TEX(v.uv,_MainNormalTex); | |
// 构造切线空间,此处需要计算副切线才能使用float2x3矩阵构造 | |
// 新的切线空间名字是:rotation | |
TANGENT_SPACE_ROTATION; | |
o.lightDir = mul(rotation,ObjSpaceLightDir(v.vertex )); | |
o.viewDir = mul(rotation,ObjSpaceViewDir(v.vertex)); | |
return o; | |
} | |
fixed4 frag (v2f i) : SV_Target | |
{ | |
// L V | |
fixed3 tangentLightDir = normalize(i.lightDir); | |
fixed3 tangentViewDir = normalize(i.viewDir); | |
// N | |
fixed4 packedNormal = tex2D(_MainNormalTex,i.uv.zw); | |
fixed3 tangentNormal = UnpackNormal(packedNormal); | |
// tangentNormal.z = sqrt(1-saturate(dot(tangentNormal.xy,tangentNormal.xy))); | |
float3 albedo = tex2D(_MainTex,i.uv.xy).rgb; | |
fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT; | |
fixed3 diffuse = _LightColo-r0.rgb * albedo* max(0,dot(tangentNormal,tangentLightDir)); | |
fixed3 halfDir = normalize(tangentLightDir+tangentViewDir); | |
fixed3 specular = _LightColor0.rgb * pow(max(0,dot(tangentNormal,halfDir)),20); | |
return fixed4( diffuse+ambient+specular,1.0); | |
} | |
ENDCG | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://gameinstitute.qq.com/community/detail/128749