-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathglass.shader
113 lines (96 loc) · 3.68 KB
/
glass.shader
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
Shader "LX/glass"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
_BumpMap ("BumpMap", 2D) = "white" {}
_CubeMap ("CubeMap", Cube) = "_Skybox"
_RefractionScale("RefractionScale",float)=-1
_BumpScale("Bump Scale",float)=-1
_RefractionAmount("RefractionAmount",float)=0.5
_TexColorAmount("TexColorAmount",float)=0.1
}
SubShader
{
Tags
{
"Queue"="Transparent"
"RenderType"="Opaque"
}
GrabPass
{
"_RefractionTex"
}
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
float4 tangent:TANGENT;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
float3 worldPos : TEXCOORD1;
float4 tangent:TEXCOORD2;
float3 normal:TEXCOORD3;
float4 scrPos:TEXCOORD4;
};
sampler2D _MainTex;
float4 _MainTex_ST;
sampler2D _BumpMap;
samplerCUBE _CubeMap;
sampler2D _RefractionTex;
float4 _RefractionTex_TexelSize;
float _RefractionScale;
float _RefractionAmount;
float _BumpScale;
float _TexColorAmount;
v2f vert(appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
o.worldPos = mul(unity_ObjectToWorld, v.vertex);
o.tangent = v.tangent;
o.scrPos = ComputeGrabScreenPos(o.vertex);
return o;
}
fixed4 frag(v2f i) : SV_Target
{
fixed3 worldViewDir = UnityWorldSpaceViewDir(i.worldPos);
fixed3 col = tex2D(_MainTex, i.uv).rgb;
//从法线贴图中获取法线方向,此时在切线空间下
fixed3 normal = UnpackNormal(tex2D(_BumpMap, i.uv));
//使用Bumpscale控制凹凸程度 因为(0,0,1)表示原法线,因为在法线的xy上乘上某个倍数就代表在原偏移方向更加偏移
normal.xy *= _BumpScale;
normal.z = sqrt(1 - saturate(dot(normal.xy, normal.xy)));
//折射
float2 offset = normal.xy * _RefractionScale;
i.scrPos.xy = offset + i.scrPos.xy;
fixed3 refractionCol = tex2D(_RefractionTex, i.scrPos.xy / i.scrPos.w).rgb;
//转换到模型空间的矩阵
float3x3 tangent2Object =
{
i.tangent.xyz * i.tangent.w,
cross(i.tangent * i.tangent.w, i.normal),
i.normal
};
tangent2Object = transpose(tangent2Object);
fixed3 worldNormal = UnityObjectToWorldNormal(mul(tangent2Object, normal));
//反射
float3 reflectionDir = normalize(reflect(-worldViewDir, worldNormal));
float3 reflectionColor = texCUBE(_CubeMap, reflectionDir);
//混合反射和折射
return fixed4((refractionCol*_RefractionAmount + (1-_RefractionAmount)*reflectionColor)*(1-_TexColorAmount)+col*_TexColorAmount, 1);
}
ENDCG
}
}
}