Shader:三向貼圖(Tri-planar mapping)
1.背景:
在一般的貼圖方法中,模型頂點uv值傳入頂點着色器,進行插值后傳入片段着色器,在片段着色器內使用tex2D(texture,uv)對2D材質進行采樣即可。在World Space UV-mapping中,不使用uv值,而是使用當前像素的世界坐標的兩個分量來進行貼圖,例如tex2D(texture,worldPos_xy)。
由於tex2D會自動對第二個參數進行0-1取值范圍的限制,因此一般面積大於1的2D平面會出現一種repeat的效果,可以將uv值除以一個變量進行縮放。
2.shader方法:
Shader "Nie/03 TextureScale" { Properties { _DiffuseMap ("Texture ", 2D) = "white" {} _TextureScale ("Texture Scale",float) = 1 _TriplanarBlendSharpness ("Blend Sharpness",float) = 1 } SubShader { //定義Tags Tags { "RenderType"="Opaque" } LOD 100 Pass { CGPROGRAM #pragma vertex vert #pragma fragment frag // make fog work #pragma multi_compile_fog #include "UnityCG.cginc" struct appdata { float4 vertex : POSITION; float2 uv : TEXCOORD0; float3 normal:NORMAL; }; struct v2f { float2 uv : TEXCOORD0; UNITY_FOG_COORDS(1) float4 vertex : SV_POSITION; float3 normal:NORMAL; float4 wVertex : FLOAT; }; float _TextureScale; sampler2D _DiffuseMap; float4 _DiffuseMap_ST; float _TriplanarBlendSharpness; v2f vert (appdata v) { v2f o; o.vertex = UnityObjectToClipPos(v.vertex); o.uv = TRANSFORM_TEX(v.uv, _DiffuseMap); UNITY_TRANSFER_FOG(o,o.vertex); o.normal=mul(unity_ObjectToWorld,v.normal); o.wVertex=mul(unity_ObjectToWorld,v.vertex); return o; } fixed4 frag (v2f i) : SV_Target { // sample the texture float3 bWeight=(pow(abs(normalize(i.normal)),_TriplanarBlendSharpness)); //example: sharpness=2: 0,0.25,1--->0,0.0625,1 bWeight=bWeight/(bWeight.x+bWeight.y+bWeight.z); float4 xaxis_tex=tex2D(_DiffuseMap,i.wVertex.zy/_TextureScale); float4 yaxis_tex=tex2D(_DiffuseMap,i.wVertex.xz/_TextureScale); float4 zaxis_tex=tex2D(_DiffuseMap,i.wVertex.xy/_TextureScale); fixed4 tex=xaxis_tex*bWeight.x+yaxis_tex*bWeight.y+zaxis_tex*bWeight.z; // apply fog UNITY_APPLY_FOG(i.fogCoord, tex); return tex; } ENDCG } } }
3.參考文檔:
https://blog.csdn.net/liu_if_else/article/details/73833656
原文鏈接:https://blog.csdn.net/qq_40629631/article/details/105316518