ConverterSplitPreview_Builtin.shader 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. // UNITY_SHADER_NO_UPGRADE
  2. //Mesh Terain Editor's terrain split preview shader for Builtin Pipeline
  3. //http://u3d.as/oWB
  4. //This is a modified shader from https://github.com/ColinLeung-NiloCat/UnityURPUnlitScreenSpaceDecalShader
  5. Shader "Hidden/MTE/ConverterSplitPreview/Builtin"
  6. {
  7. Properties
  8. {
  9. [Header(MTE Parameters)]
  10. _SplitNumber("Split Number", int) = 2
  11. _NormalizedLineWidth("Normalized Line Width", float) = 0.01
  12. [Header(Basic)]
  13. _MainTex("Texture", 2D) = "white" {}
  14. [HDR]_Color("_Color (default = 1,1,1,1)", color) = (1,1,1,1)
  15. [Header(Blending)]
  16. //https://docs.unity3d.com/ScriptReference/Rendering.BlendMode.html
  17. [Enum(UnityEngine.Rendering.BlendMode)]_SrcBlend("_SrcBlend (default = One)", Float) = 1 //1 = One
  18. [Enum(UnityEngine.Rendering.BlendMode)]_DstBlend("_DstBlend (default = One)", Float) = 1 //1 = One
  19. [Header(Alpha remap(extra alpha control))]
  20. _AlphaRemap("_AlphaRemap (default = 1,0,0,0) _____alpha will first mul x, then add y (zw unused)", vector) = (1,0,0,0)
  21. [Header(Prevent Side Stretching(Compare projection direction with scene normal and Discard if needed))]
  22. [Toggle(_ProjectionAngleDiscardEnable)] _ProjectionAngleDiscardEnable("_ProjectionAngleDiscardEnable (default = off)", float) = 0
  23. _ProjectionAngleDiscardThreshold("_ProjectionAngleDiscardThreshold (default = 0)", range(-1,1)) = 0
  24. [Header(Mul alpha to rgb)]
  25. [Toggle]_MulAlphaToRGB("_MulAlphaToRGB (default = off)", Float) = 0
  26. [Header(Ignore texture wrap mode setting)]
  27. [Toggle(_FracUVEnable)] _FracUVEnable("_FracUVEnable (default = off)", Float) = 0
  28. //====================================== below = usually can ignore in normal use case =====================================================================
  29. [Header(Stencil Masking)]
  30. //https://docs.unity3d.com/ScriptReference/Rendering.CompareFunction.html
  31. _StencilRef("_StencilRef", Float) = 0
  32. [Enum(UnityEngine.Rendering.CompareFunction)]_StencilComp("_StencilComp (default = Disable) _____Set to NotEqual if you want to mask by specific _StencilRef value, else set to Disable", Float) = 0 //0 = disable
  33. [Header(ZTest)]
  34. //https://docs.unity3d.com/ScriptReference/Rendering.CompareFunction.html
  35. //default need to be Disable, because we need to make sure decal render correctly even if camera goes into decal cube volume, although disable ZTest by default will prevent EarlyZ (bad for GPU performance)
  36. [Enum(UnityEngine.Rendering.CompareFunction)]_ZTest("_ZTest (default = Disable) _____to improve GPU performance, Set to LessEqual if camera never goes into cube volume, else set to Disable", Float) = 0 //0 = disable
  37. [Header(Cull)]
  38. //https://docs.unity3d.com/ScriptReference/Rendering.CullMode.html
  39. //default need to be Front, because we need to make sure decal render correctly even if camera goes into decal cube
  40. [Enum(UnityEngine.Rendering.CullMode)]_Cull("_Cull (default = Front) _____to improve GPU performance, Set to Back if camera never goes into cube volume, else set to Front", Float) = 1 //1 = Front
  41. }
  42. SubShader
  43. {
  44. //To avoid render order problems, Queue must >= 2501, which enters the transparent queue, in transparent queue Unity will always draw from back to front
  45. //https://github.com/ColinLeung-NiloCat/UnityURPUnlitScreenSpaceDecalShader/issues/6#issuecomment-615940985
  46. /*
  47. //https://docs.unity3d.com/Manual/SL-SubShaderTags.html
  48. Queues up to 2500 (“Geometry+500”) are consided “opaque” and optimize the drawing order of the objects for best performance.
  49. Higher rendering queues are considered for “transparent objects” and sort objects by distance, starting rendering from the furthest ones and ending with the closest ones.
  50. Skyboxes are drawn in between all opaque and all transparent objects.
  51. */
  52. Tags { "RenderType" = "Overlay" "Queue" = "Transparent-499" }
  53. Pass
  54. {
  55. Stencil
  56. {
  57. Ref[_StencilRef]
  58. Comp[_StencilComp]
  59. }
  60. Cull[_Cull]
  61. ZTest[_ZTest]
  62. ZWrite off
  63. Blend[_SrcBlend][_DstBlend]
  64. CGPROGRAM
  65. #pragma vertex vert
  66. #pragma fragment frag
  67. // make fog work
  68. #pragma multi_compile_fog
  69. //due to using ddx() & ddy()
  70. #pragma target 3.0
  71. #pragma shader_feature_local _ProjectionAngleDiscardEnable
  72. #pragma shader_feature_local _UnityFogEnable
  73. #pragma shader_feature_local _FracUVEnable
  74. // Required by all Builtin pipeline shaders.
  75. // It will include Unity built-in shader variables (except the lighting variables)
  76. // (https://docs.unity3d.com/Manual/SL-UnityShaderVariables.html
  77. // It will also include many utilitary functions.
  78. #include "UnityCG.cginc"
  79. // Return the PreTranslated ObjectToWorld Matrix (i.e matrix with _WorldSpaceCameraPos apply to it if we use camera relative rendering)
  80. float4x4 GetObjectToWorldMatrix()
  81. {
  82. return UNITY_MATRIX_M;
  83. }
  84. float4x4 GetWorldToViewMatrix()
  85. {
  86. return UNITY_MATRIX_V;
  87. }
  88. // Transform to homogenous clip space
  89. float4x4 GetWorldToHClipMatrix()
  90. {
  91. return UNITY_MATRIX_VP;
  92. }
  93. float3 TransformObjectToWorld(float3 positionOS)
  94. {
  95. return mul(GetObjectToWorldMatrix(), float4(positionOS, 1.0)).xyz;
  96. }
  97. // Transforms position from object space to homogenous space
  98. float4 TransformObjectToHClip(float3 positionOS)
  99. {
  100. // More efficient than computing M*VP matrix product
  101. return mul(GetWorldToHClipMatrix(), mul(GetObjectToWorldMatrix(), float4(positionOS, 1.0)));
  102. }
  103. float3 TransformWorldToView(float3 positionWS)
  104. {
  105. return mul(GetWorldToViewMatrix(), float4(positionWS, 1.0)).xyz;
  106. }
  107. float LinearEyeDepth(float depth, float4 zBufferParam)
  108. {
  109. return 1.0 / (zBufferParam.z * depth + zBufferParam.w);
  110. }
  111. struct appdata
  112. {
  113. float4 vertex : POSITION;
  114. };
  115. struct v2f
  116. {
  117. float4 vertex : SV_POSITION;
  118. float4 screenUV : TEXCOORD0;
  119. float4 viewRayOS : TEXCOORD1;
  120. float4 cameraPosOSAndFogFactor : TEXCOORD2;
  121. };
  122. sampler2D _MainTex;
  123. float4 _MainTex_ST;
  124. int _SplitNumber;
  125. float _NormalizedLineWidth;
  126. float _ProjectionAngleDiscardThreshold;
  127. half4 _Color;
  128. half2 _AlphaRemap;
  129. half _MulAlphaToRGB;
  130. sampler2D _CameraDepthTexture;
  131. v2f vert(appdata v)
  132. {
  133. v2f o;
  134. //regular MVP
  135. o.vertex = TransformObjectToHClip(v.vertex.xyz);
  136. //regular unity fog
  137. o.cameraPosOSAndFogFactor.a = 0;
  138. //prepare depth texture's screen space UV
  139. o.screenUV = ComputeScreenPos(o.vertex);
  140. //get "camera to vertex" ray in View space
  141. float3 viewRay = TransformWorldToView(TransformObjectToWorld(v.vertex.xyz));
  142. //***WARNING***
  143. //=========================================================
  144. //"viewRay z division" must do in the fragment shader, not vertex shader! (due to rasteriazation varying interpolation's perspective correction)
  145. //We skip the "viewRay z division" in vertex shader for now, and pass the division value to varying o.viewRayOS.w first, we will do the division later when we enter fragment shader
  146. //viewRay /= viewRay.z; //skip the "viewRay z division" in vertex shader for now
  147. o.viewRayOS.w = viewRay.z;//pass the division value to varying o.viewRayOS.w
  148. //=========================================================
  149. viewRay *= -1; //unity's camera space is right hand coord(negativeZ pointing into screen), we want positive z ray in fragment shader, so negate it
  150. //it is ok to write very expensive code in decal's vertex shader, it is just a unity cube(4*6 vertices) per decal only, won't affect GPU performance at all.
  151. float4x4 ViewToObjectMatrix = mul(unity_WorldToObject, UNITY_MATRIX_I_V);
  152. //transform everything to object space(decal space) in vertex shader first, so we can skip all matrix mul() in fragment shader
  153. o.viewRayOS.xyz = mul((float3x3)ViewToObjectMatrix, viewRay);
  154. o.cameraPosOSAndFogFactor.xyz = mul(ViewToObjectMatrix, float4(0,0,0,1)).xyz;
  155. return o;
  156. }
  157. half4 frag(v2f i) : SV_Target
  158. {
  159. //***WARNING***
  160. //=========================================================
  161. //now do "viewRay z division" that we skipped in vertex shader earlier.
  162. i.viewRayOS /= i.viewRayOS.w;
  163. //=========================================================
  164. float sceneCameraSpaceDepth = LinearEyeDepth(tex2Dproj(_CameraDepthTexture, i.screenUV).r, _ZBufferParams);
  165. //scene depth in any space = rayStartPos + rayDir * rayLength
  166. //here all data in ObjectSpace(OS) or DecalSpace
  167. float3 decalSpaceScenePos = i.cameraPosOSAndFogFactor.xyz + i.viewRayOS.xyz * sceneCameraSpaceDepth;
  168. //convert unity cube's [-0.5,0.5] vertex pos range to [0,1] uv. Only works if you use unity cube in mesh filter!
  169. float2 decalSpaceUV = decalSpaceScenePos.xy + 0.5;
  170. //discard logic
  171. //===================================================
  172. // discard "out of cube volume" pixels
  173. //2020-4-17: tried fix clip() bug by removing all possible bool
  174. //https://github.com/ColinLeung-NiloCat/UnityURPUnlitScreenSpaceDecalShader/issues/6#issuecomment-614633460
  175. float mask = (abs(decalSpaceScenePos.x) < 0.5 ? 1.0 : 0.0) * (abs(decalSpaceScenePos.y) < 0.5 ? 1.0 : 0.0) * (abs(decalSpaceScenePos.z) < 0.5 ? 1.0 : 0.0);
  176. //call discard
  177. clip(mask - 0.5);//if ZWrite is off, clip() is fast enough on mobile, because it won't write the DepthBuffer, so no pipeline stall(confirmed by ARM staff).
  178. //===================================================
  179. // sample the decal texture
  180. float2 uv = decalSpaceUV.xy * _MainTex_ST.xy + _MainTex_ST.zw;//Texture tiling & offset
  181. half4 col = tex2D(_MainTex, uv);
  182. col *= _Color;//tint color
  183. col.a = saturate(col.a * _AlphaRemap.x + _AlphaRemap.y);//alpha remap MAD
  184. col.rgb *= lerp(1, col.a, _MulAlphaToRGB);//extra multiply alpha to RGB
  185. float2 st = uv;
  186. st *= _SplitNumber;
  187. st = frac(st);
  188. float min = 0;
  189. float max = _NormalizedLineWidth;
  190. float c = smoothstep(min, max, st.x)*smoothstep(min, max, st.y);
  191. col = half4(1-c,1-c,1-c,0.5);
  192. return col;
  193. }
  194. ENDCG
  195. }
  196. }
  197. }