Lux URP Water.shader 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  1. // NOTE: Based on URP Lighting.hlsl which replaced some half3 with floats to avoid lighting artifacts on mobile
  2. Shader "Lux URP/Water"
  3. {
  4. Properties
  5. {
  6. [HeaderHelpLuxURP_URL(pwa0yoxc3z5m)]
  7. [Header(Surface Options)]
  8. [Space(8)]
  9. [Enum(Off,0,On,1)]_ZWrite ("ZWrite", Float) = 1.0
  10. [Enum(UnityEngine.Rendering.CompareFunction)] _ZTest("ZTest", Float) = 4 // "LessEqual"
  11. // [Enum(UnityEngine.Rendering.CullMode)] _Culling ("Culling", Float) = 0
  12. [Enum(UnityEngine.Rendering.BlendMode)] _DstBlend("Dest BlendMode", Float) = 0
  13. [ToggleOff(_RECEIVE_SHADOWS_OFF)]
  14. _ReceiveShadows ("Receive Shadows", Float) = 1.0
  15. [Toggle(ORTHO_SUPPORT)]
  16. _OrthoSpport ("Enable Orthographic Support", Float) = 0
  17. [Header(Surface Inputs)]
  18. [Space(8)]
  19. _BumpMap ("Water Normal Map", 2D) = "bump" {}
  20. _BumpScale ("Normal Scale", Float) = 1.0
  21. [LuxURPVectorTwoDrawer]
  22. _Speed ("Speed (UV)", Vector) = (0.1, 0, 0, 0)
  23. [LuxURPVectorFourDrawer]
  24. _SecondaryTilingSpeedRefractBump("Secondary Bump", Vector) = (2, 2.3, 0.1, 1)
  25. [LuxURPHelpDrawer] _Help ("Tiling (X) Speed (Y) Refraction (Z) Bump Scale (W)", Float) = 1
  26. [Space(5)]
  27. _Smoothness ("Smoothness", Range(0.0, 1.0)) = 0.5
  28. _SpecColor ("Specular", Color) = (0.2, 0.2, 0.2)
  29. [Space(5)]
  30. _EdgeBlend ("Edge Blending", Range(0.1, 10.0)) = 2.0
  31. [Space(5)]
  32. [Toggle(_REFRACTION)]
  33. _EnableRefraction ("Enable Refraction", Float) = 1
  34. _Refraction (" Refraction", Range(0, 1)) = .25
  35. _ReflectionBumpScale ("Reflection Bump Scale", Range(0.1, 1.0)) = 0.3
  36. [Header(Underwater Fog)]
  37. [Space(8)]
  38. _Color ("Fog Color", Color) = (.2,.8,.9,1)
  39. _Density ("Density", Float) = 1.0
  40. [Header(Foam)]
  41. [Space(8)]
  42. [Toggle(_FOAM)] _Foam ("Enable Foam", Float) = 1.0
  43. [NoScaleOffset] _FoamMap ("Foam Albedo (RGB) Mask (A)", 2D) = "bump" {}
  44. _FoamTiling ("Foam Tiling", Float) = 2
  45. [LuxURPVectorTwoDrawer]
  46. _FoamSpeed ("Foam Speed (UV)", Vector) = (0.1, 0, 0, 0)
  47. _FoamScale ("Foam Scale", Float) = 4
  48. _FoamSoftIntersectionFactor ("Foam Edge Blending", Range(0.1, 3.0)) = 0.5
  49. _FoamSlopStrength ("Foam Slope Strength", Range(0.0, 1.0)) = 0.85
  50. _FoamSmoothness ("Foam Smoothness", Range(0.0, 1.0)) = 0.3
  51. [Header(Advanced)]
  52. [Space(8)]
  53. [ToggleOff] _SpecularHighlights ("Enable Specular Highlights", Float) = 1.0
  54. [ToggleOff]
  55. _EnvironmentReflections ("Environment Reflections", Float) = 1.0
  56. // As URP 10.1 complains about it?!:
  57. [HideInInspector] _Alpha ("Dummy", Float) = 1
  58. [HideInInspector] _FresnelPower ("Dummy", Float) = 1
  59. }
  60. SubShader
  61. {
  62. Tags
  63. {
  64. "RenderPipeline" = "UniversalPipeline"
  65. "RenderType"="Transparent"
  66. "Queue"="Transparent"
  67. }
  68. LOD 300
  69. Pass
  70. {
  71. Tags {"LightMode" = "UniversalForward"}
  72. // Blend SrcAlpha OneMinusSrcAlpha
  73. Blend One [_DstBlend]
  74. Cull Back
  75. ZTest [_ZTest]
  76. ZWrite [_ZWrite]
  77. HLSLPROGRAM
  78. // Required to compile gles 2.0 with standard srp library
  79. #pragma prefer_hlslcc gles
  80. #pragma exclude_renderers d3d11_9x
  81. #pragma target 2.0
  82. // -------------------------------------
  83. // Universal Pipeline keywords
  84. #pragma multi_compile _ _MAIN_LIGHT_SHADOWS
  85. #pragma multi_compile _ _MAIN_LIGHT_SHADOWS_CASCADE
  86. #pragma multi_compile _ _ADDITIONAL_LIGHTS_VERTEX _ADDITIONAL_LIGHTS
  87. #pragma multi_compile_fragment _ _ADDITIONAL_LIGHT_SHADOWS
  88. #pragma multi_compile_fragment _ _SHADOWS_SOFT
  89. #pragma multi_compile _ LIGHTMAP_SHADOW_MIXING
  90. #pragma multi_compile _ SHADOWS_SHADOWMASK
  91. #pragma shader_feature_local_fragment _SPECULARHIGHLIGHTS_OFF
  92. #pragma shader_feature_local_fragment _ENVIRONMENTREFLECTIONS_OFF
  93. #pragma shader_feature_local _RECEIVE_SHADOWS_OFF
  94. #pragma shader_feature_local_fragment _FOAM
  95. #pragma shader_feature_local_fragment ORTHO_SUPPORT
  96. #pragma shader_feature_local_fragment _REFRACTION
  97. // #define _ADDITIONAL_LIGHTS_VERTEX
  98. // -------------------------------------
  99. // Unity defined keywords
  100. #pragma multi_compile _ DIRLIGHTMAP_COMBINED
  101. #pragma multi_compile _ LIGHTMAP_ON
  102. #pragma multi_compile_fog
  103. //--------------------------------------
  104. // GPU Instancing
  105. #pragma multi_compile_instancing
  106. // #pragma multi_compile _ DOTS_INSTANCING_ON // needs shader target 4.5
  107. #define _SPECULAR_SETUP 1
  108. #define _NORMALMAP 1
  109. #pragma vertex vert
  110. #pragma fragment frag
  111. #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
  112. // defines a bunch of helper functions (like lerpwhiteto)
  113. #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/CommonMaterial.hlsl"
  114. // defines SurfaceData, textures and the functions Alpha, SampleAlbedoAlpha, SampleNormal, SampleEmission
  115. #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/SurfaceInput.hlsl"
  116. #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"
  117. #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Color.hlsl"
  118. #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/UnityInstancing.hlsl"
  119. struct VertexInput
  120. {
  121. float4 positionOS : POSITION;
  122. float3 normalOS : NORMAL;
  123. float4 tangentOS : TANGENT;
  124. float2 texcoord : TEXCOORD0;
  125. float2 lightmapUV : TEXCOORD1;
  126. UNITY_VERTEX_INPUT_INSTANCE_ID
  127. };
  128. struct VertexOutput
  129. {
  130. float4 positionCS : SV_POSITION;
  131. float4 uv : TEXCOORD0; // xy textccord, zw water
  132. DECLARE_LIGHTMAP_OR_SH(lightmapUV, vertexSH, 1);
  133. float3 positionWS : TEXCOORD2;
  134. #ifdef _NORMALMAP
  135. half4 normalWS : TEXCOORD3; // xyz: normal, w: viewDir.x
  136. half4 tangentWS : TEXCOORD4; // xyz: tangent, w: viewDir.y
  137. half4 bitangentWS : TEXCOORD5; // xyz: bitangent, w: viewDir.z
  138. #else
  139. half3 normalWS : TEXCOORD3;
  140. half3 viewDirWS : TEXCOORD4;
  141. #endif
  142. half4 fogFactorAndVertexLight : TEXCOORD6; // x: fogFactor, yzw: vertex light
  143. #if defined(REQUIRES_VERTEX_SHADOW_COORD_INTERPOLATOR)
  144. float4 shadowCoord : TEXCOORD7;
  145. #endif
  146. UNITY_VERTEX_INPUT_INSTANCE_ID
  147. UNITY_VERTEX_OUTPUT_STEREO
  148. };
  149. CBUFFER_START(UnityPerMaterial)
  150. float _Alpha;
  151. half4 _SpecColor;
  152. half _Smoothness;
  153. half _EdgeBlend;
  154. float2 _Speed;
  155. half _BumpScale;
  156. float4 _SecondaryTilingSpeedRefractBump;
  157. half4 _Color;
  158. half _Density;
  159. half _FresnelPower;
  160. half _Refraction;
  161. half _ReflectionBumpScale;
  162. half _FoamScale;
  163. half _FoamTiling;
  164. half2 _FoamSpeed;
  165. half _FoamSoftIntersectionFactor;
  166. half _FoamSlopStrength;
  167. half _FoamSmoothness;
  168. float4 _BumpMap_ST;
  169. CBUFFER_END
  170. // Defined in SurfaceInput.hlsl
  171. // TEXTURE2D(_BaseMap); SAMPLER(sampler_BaseMap);
  172. #if defined(SHADER_API_GLES)
  173. TEXTURE2D(_CameraDepthTexture); SAMPLER(sampler_CameraDepthTexture);
  174. //TEXTURE2D(_CameraOpaqueTexture); SAMPLER(sampler_CameraOpaqueTexture);
  175. #else
  176. // URP 7.1.5.
  177. TEXTURE2D_X_FLOAT(_CameraDepthTexture);
  178. //SAMPLER(sampler_PointClamp); // Using Load means no sampling or filtering anyway
  179. #endif
  180. TEXTURE2D_X(_CameraOpaqueTexture);
  181. SAMPLER(sampler_LinearClamp);
  182. SAMPLER(sampler_PointClamp);
  183. float4 _CameraDepthTexture_TexelSize;
  184. float4 _CameraOpaqueTexture_TexelSize;
  185. float4 _CameraOpaqueTexture_ST;
  186. TEXTURE2D(_FoamMap); SAMPLER(sampler_FoamMap); float4 _FoamMap_TexelSize;
  187. VertexOutput vert (VertexInput input)
  188. {
  189. VertexOutput output = (VertexOutput)0;
  190. UNITY_SETUP_INSTANCE_ID(input);
  191. UNITY_TRANSFER_INSTANCE_ID(input, output);
  192. UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(output);
  193. //o.positionWS = TransformObjectToWorld(input.positionOS.xyz); // mul(UNITY_MATRIX_M, input.vertex).xyz;
  194. //o.positionCS = TransformWorldToHClip(o.positionWS.xyz); // TransformObjectToHClip(input.positionOS.xyz);
  195. VertexPositionInputs vertexInput = GetVertexPositionInputs(input.positionOS.xyz);
  196. output.positionWS = vertexInput.positionWS;
  197. output.positionCS = vertexInput.positionCS;
  198. VertexNormalInputs normalInput = GetVertexNormalInputs(input.normalOS, input.tangentOS);
  199. #if defined(REQUIRES_VERTEX_SHADOW_COORD_INTERPOLATOR)
  200. output.shadowCoord = GetShadowCoord(vertexInput);
  201. #endif
  202. #ifdef _NORMALMAP
  203. float3 viewDirWS = GetCameraPositionWS() - output.positionWS;
  204. output.normalWS = half4(normalInput.normalWS, viewDirWS.x);
  205. output.tangentWS = half4(normalInput.tangentWS, viewDirWS.y);
  206. output.bitangentWS = half4(normalInput.bitangentWS, viewDirWS.z);
  207. #else
  208. output.normalWS.xyz = NormalizeNormalPerVertex(normalInput.normalWS);
  209. output.viewDirWS = GetCameraPositionWS() - o.positionWS;
  210. #endif
  211. half fogFactor = ComputeFogFactor(output.positionCS.z);
  212. half3 vertexLight = VertexLighting(output.positionWS, output.normalWS.xyz);
  213. OUTPUT_LIGHTMAP_UV(input.lightmapUV, unity_LightmapST, output.lightmapUV);
  214. OUTPUT_SH(output.normalWS.xyz, output.vertexSH);
  215. output.fogFactorAndVertexLight = half4(fogFactor, vertexLight);
  216. output.uv.xy = TRANSFORM_TEX(input.texcoord, _BumpMap) + _Time.xx * _Speed;
  217. // Water
  218. // see: ComputeGrabScreenPos
  219. float4 screenUV = ComputeScreenPos(output.positionCS);
  220. output.uv.zw = screenUV.xy; //waterDepth.xx;
  221. return output;
  222. }
  223. // ------------------------------------------------------------------
  224. // Helper functions to handle orthographic / perspective projection
  225. inline float GetOrthoDepthFromZBuffer (float rawDepth) {
  226. #if defined(UNITY_REVERSED_Z)
  227. // Needed to handle openGL
  228. #if UNITY_REVERSED_Z == 1
  229. rawDepth = 1.0f - rawDepth;
  230. #endif
  231. #endif
  232. return lerp(_ProjectionParams.y, _ProjectionParams.z, rawDepth);
  233. }
  234. inline float GetProperEyeDepth (float rawDepth) {
  235. #if defined(ORTHO_SUPPORT)
  236. float perspectiveSceneDepth = LinearEyeDepth(rawDepth, _ZBufferParams);
  237. float orthoSceneDepth = GetOrthoDepthFromZBuffer(rawDepth);
  238. return lerp(perspectiveSceneDepth, orthoSceneDepth, unity_OrthoParams.w);
  239. #else
  240. return LinearEyeDepth(rawDepth, _ZBufferParams);
  241. #endif
  242. }
  243. half4 frag (VertexOutput input) : SV_Target
  244. {
  245. UNITY_SETUP_INSTANCE_ID(input);
  246. UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(input);
  247. //half3 albedo = 0;
  248. //half metallic = 0;
  249. half3 specular = _SpecColor.rgb;
  250. half smoothness = _Smoothness;
  251. half occlusion = 1;
  252. half emission = 0;
  253. half alpha = 1;
  254. half3 normalTS = half3(0,0,1);
  255. half3 refraction = 0;
  256. #if defined(ORTHO_SUPPORT)
  257. float surfaceEyeDepth = GetProperEyeDepth(input.positionCS.z); // LinearEyeDepth(input.positionCS.z, _ZBufferParams);
  258. #else
  259. float surfaceEyeDepth = input.positionCS.w;
  260. #endif
  261. // We have to reset i.grabUV.w as otherwise texture projection does not work
  262. #if defined(ORTHO_SUPPORT)
  263. input.positionCS.w = lerp(input.positionCS.w, 1.0f, unity_OrthoParams.w);
  264. #endif
  265. float2 screenUV = input.uv.zw / input.positionCS.w;
  266. // Fix screenUV for Single Pass Stereo Rendering
  267. #if defined(UNITY_SINGLE_PASS_STEREO)
  268. screenUV.xy = UnityStereoTransformScreenSpaceTex(screenUV.xy);
  269. #endif
  270. half4 normalSample = SAMPLE_TEXTURE2D(_BumpMap, sampler_BumpMap, input.uv.xy);
  271. // ////////////
  272. // Get the normals
  273. #if BUMP_SCALE_NOT_SUPPORTED
  274. normalTS = UnpackNormal(normalSample);
  275. normalSample = SAMPLE_TEXTURE2D(_BumpMap, sampler_BumpMap, input.uv.xy * _SecondaryTilingSpeedRefractBump.x + _Time.xx * _Speed * _SecondaryTilingSpeedRefractBump.y + normalTS.xz * _SecondaryTilingSpeedRefractBump.z );
  276. half3 detailNormal = UnpackNormal(normalSample);
  277. normalTS = normalize(half3(normalTS.xy + detailNormal.xy, normalTS.z * detailNormal.z));
  278. #else
  279. normalTS = UnpackNormalScale(normalSample, _BumpScale);
  280. normalSample = SAMPLE_TEXTURE2D(_BumpMap, sampler_BumpMap, input.uv.xy * _SecondaryTilingSpeedRefractBump.x + _Time.xx * _Speed * _SecondaryTilingSpeedRefractBump.y + normalTS.xz * _SecondaryTilingSpeedRefractBump.z );
  281. half3 detailNormal = UnpackNormalScale(normalSample, _SecondaryTilingSpeedRefractBump.w);
  282. normalTS = normalize(half3(normalTS.xy + detailNormal.xy, normalTS.z * detailNormal.z));
  283. #endif
  284. // World space normal - as we need it for view space normal (skipped)
  285. half3 normalWS = TransformTangentToWorld(normalTS, half3x3(input.tangentWS.xyz, input.bitangentWS.xyz, input.normalWS.xyz));
  286. normalWS = NormalizeNormalPerPixel(normalWS);
  287. // ////////////
  288. // Refraction
  289. // Skipped view space normal and went with tangent space instead
  290. //half3 viewNormal = mul((float3x3)GetWorldToHClipMatrix(), -normalWS).xyz;
  291. //float2 offset = viewNormal.xz * _Refraction;
  292. float distanceFadeFactor = input.positionCS.z * _ZBufferParams.z;
  293. // OpenGL Core
  294. #if UNITY_REVERSED_Z != 1
  295. distanceFadeFactor = input.positionCS.z / input.positionCS.w;
  296. #endif
  297. // Somehow handle orthographic projection
  298. #if defined(ORTHO_SUPPORT)
  299. distanceFadeFactor = (unity_OrthoParams.w) ? 1.0f / unity_OrthoParams.x : distanceFadeFactor;
  300. #endif
  301. #if defined(_REFRACTION)
  302. float2 offset = normalTS.xy * _Refraction * distanceFadeFactor;
  303. #else
  304. float2 offset = 0;
  305. #endif
  306. // URP 7.1.5.: We have to use saturate(screenUV + offset) and saturate(offset)
  307. // GLES 2.0 does not support LOAD_TEXTURE2D_X. LOAD_TEXTURE2D_X does not clamp even if we use saturate? * 0.9999f solves this.
  308. #if defined(SHADER_API_GLES)
  309. float refractedSceneDepth = SAMPLE_DEPTH_TEXTURE_LOD(_CameraDepthTexture, sampler_CameraDepthTexture, screenUV + offset, 0);
  310. #else
  311. float refractedSceneDepth = LOAD_TEXTURE2D_X(_CameraDepthTexture, _CameraDepthTexture_TexelSize.zw * saturate(screenUV + offset) * 0.9999f ).x;
  312. //float refractedSceneDepth = SAMPLE_TEXTURE2D_X(_CameraDepthTexture, sampler_PointClamp, saturate(screenUV + offset)).x;
  313. #endif
  314. refractedSceneDepth = GetProperEyeDepth(refractedSceneDepth);
  315. float viewDepth = refractedSceneDepth - surfaceEyeDepth;
  316. // Do not refract pixel of the foreground
  317. #if defined(_REFRACTION)
  318. offset = screenUV + offset * saturate(viewDepth);
  319. #if defined(SHADER_API_GLES)
  320. refractedSceneDepth = SAMPLE_DEPTH_TEXTURE_LOD(_CameraDepthTexture, sampler_CameraDepthTexture, offset, 0);
  321. #else
  322. refractedSceneDepth = LOAD_TEXTURE2D_X(_CameraDepthTexture, (_CameraDepthTexture_TexelSize.zw * saturate(offset) * 0.9999f )).x;
  323. //refractedSceneDepth = SAMPLE_TEXTURE2D_X(_CameraDepthTexture, sampler_PointClamp, saturate(offset)).x;
  324. #endif
  325. refractedSceneDepth = GetProperEyeDepth(refractedSceneDepth);
  326. refraction = SAMPLE_TEXTURE2D_X(_CameraOpaqueTexture, sampler_LinearClamp, saturate(offset)).rgb;
  327. viewDepth = refractedSceneDepth - surfaceEyeDepth;
  328. // In case we use HDR refraction may get way too bright.
  329. refraction = saturate(refraction);
  330. #endif
  331. // Final blend value
  332. alpha = saturate ( _EdgeBlend * viewDepth );
  333. // ////////////
  334. // Underwater fog
  335. // Calculate Attenuation along viewDirection
  336. float viewAtten = saturate( 1.0 - exp( -viewDepth * _Density) );
  337. float underwaterFogDensity = viewAtten;
  338. // ////////////
  339. // Foam
  340. #if defined(_FOAM)
  341. /*
  342. // We might do a 3rd unrefracted sample here - but it indroduces some kind of ghosting.
  343. #if defined(SHADER_API_GLES)
  344. refractedSceneDepth = SAMPLE_DEPTH_TEXTURE_LOD(_CameraDepthTexture, sampler_CameraDepthTexture, screenUV, 0);
  345. #else
  346. refractedSceneDepth = LOAD_TEXTURE2D_X(_CameraDepthTexture, _CameraDepthTexture_TexelSize.zw * screenUV).x;
  347. #endif
  348. refractedSceneDepth = GetProperEyeDepth(refractedSceneDepth);
  349. viewDepth = refractedSceneDepth - surfaceEyeDepth;
  350. */
  351. half FoamSoftIntersection = saturate( _FoamSoftIntersectionFactor * (viewDepth ));
  352. half FoamThreshold = normalTS.z * 2 - 1;
  353. // Get shoreline foam mask
  354. float shorelineFoam = saturate(-FoamSoftIntersection * (1 + FoamThreshold) + 1 );
  355. shorelineFoam = shorelineFoam * saturate(1 * FoamSoftIntersection - FoamSoftIntersection * FoamSoftIntersection );
  356. half4 rawFoamSample = SAMPLE_TEXTURE2D(_FoamMap, sampler_FoamMap, input.uv.xy * _FoamTiling + normalTS.xy * 0.02 + _Time.xx * _FoamSpeed);
  357. // Add foam on slopes
  358. shorelineFoam += saturate(1 - input.normalWS.y) * _FoamSlopStrength;
  359. // Combine sample and distribution(shorelineFoam)
  360. rawFoamSample.a = saturate(rawFoamSample.a * shorelineFoam * _FoamScale * ( 1 - (normalTS.x + normalTS.y) * 4) );
  361. // Errode foam
  362. rawFoamSample.a = rawFoamSample.a * smoothstep( 0.8 - rawFoamSample.a, 1.6 - rawFoamSample.a, rawFoamSample.a );
  363. // Adjust smoothess to foam
  364. smoothness = lerp(smoothness, _FoamSmoothness, rawFoamSample.a);
  365. #endif
  366. // ////////////
  367. // Transfer all to world space and prepare inputData (for convenience)
  368. InputData inputData = (InputData)0;
  369. inputData.positionWS = input.positionWS;
  370. #ifdef _NORMALMAP
  371. inputData.normalWS = normalWS;
  372. inputData.viewDirectionWS = SafeNormalize( float3(input.normalWS.w, input.tangentWS.w, input.bitangentWS.w) );
  373. #else
  374. inputData.normalWS = input.normalWS.xyz; // no normal map
  375. inputData.viewDirectionWS = SafeNormalize(input.viewDirWS);
  376. #endif
  377. // Refract shadows / * input.positionCS.w because unity will divide
  378. /*
  379. #if defined(_MAIN_LIGHT_SHADOWS)
  380. #if SHADOWS_SCREEN
  381. #if defined(_REFRACTION)
  382. inputData.shadowCoord = float4(offset * input.positionCS.w, input.shadowCoord.zw);
  383. #else
  384. inputData.shadowCoord = float4(screenUV * input.positionCS.w, input.shadowCoord.zw);
  385. #endif
  386. #else
  387. inputData.shadowCoord = input.shadowCoord;
  388. #endif
  389. #else
  390. inputData.shadowCoord = float4(0, 0, 0, 0);
  391. #endif
  392. */
  393. // No refracted shadows any more...
  394. #if defined(REQUIRES_VERTEX_SHADOW_COORD_INTERPOLATOR)
  395. inputData.shadowCoord = input.shadowCoord;
  396. #elif defined(MAIN_LIGHT_CALCULATE_SHADOWS)
  397. inputData.shadowCoord = TransformWorldToShadowCoord(inputData.positionWS);
  398. #else
  399. inputData.shadowCoord = float4(0, 0, 0, 0);
  400. #endif
  401. // Fix shadowCoord for Single Pass Stereo Rendering
  402. #if defined(UNITY_SINGLE_PASS_STEREO)
  403. #if SHADOWS_SCREEN
  404. // Shadows perform : UnityStereoTransformScreenSpaceTex(shadowCoord.xy) after perspective division;
  405. // We do it manually:
  406. inputData.shadowCoord.xy = inputData.shadowCoord.xy / inputData.shadowCoord.w;
  407. inputData.shadowCoord.w = 1.0f;
  408. // inputData.shadowCoord.x = screenUV.x;
  409. // Then we reset shadowCoord.w and unity_StereoScaleOffset so it does not get applied twice
  410. unity_StereoScaleOffset[0] = float4(1,1,0,0);
  411. unity_StereoScaleOffset[1] = float4(1,1,0,0);
  412. #endif
  413. #endif
  414. inputData.fogCoord = input.fogFactorAndVertexLight.x;
  415. inputData.vertexLighting = input.fogFactorAndVertexLight.yzw;
  416. inputData.bakedGI = SAMPLE_GI(input.lightmapUV, input.vertexSH, inputData.normalWS);
  417. inputData.shadowMask = SAMPLE_SHADOWMASK(input.lightmapUV);
  418. // /////////
  419. // Apply lighting
  420. half4 color = 1;
  421. half3 origRefraction = refraction;
  422. // Get fog
  423. real fogFactor = input.fogFactorAndVertexLight.x;
  424. #if defined(FOG_LINEAR) || defined(FOG_EXP) || defined(FOG_EXP2)
  425. #if defined(FOG_EXP)
  426. fogFactor = saturate(exp2(-fogFactor));
  427. #elif defined(FOG_EXP2)
  428. fogFactor = saturate(exp2(-fogFactor*fogFactor));
  429. #endif
  430. #endif
  431. // Prepare missing Inputs
  432. half reflectivity = ReflectivitySpecular(specular);
  433. half oneMinusReflectivity = 1.0 - reflectivity;
  434. half perceptualRoughness = PerceptualSmoothnessToPerceptualRoughness(smoothness);
  435. half roughness = PerceptualRoughnessToRoughness(perceptualRoughness);
  436. half roughness2 = roughness * roughness;
  437. half normalizationTerm = roughness * 4.0h + 2.0h;
  438. // ShadowMask: To ensure backward compatibility we have to avoid using shadowMask input, as it is not present in older shaders
  439. #if defined(SHADOWS_SHADOWMASK) && defined(LIGHTMAP_ON)
  440. half4 shadowMask = inputData.shadowMask;
  441. #elif !defined (LIGHTMAP_ON)
  442. half4 shadowMask = unity_ProbesOcclusion;
  443. #else
  444. half4 shadowMask = half4(1, 1, 1, 1);
  445. #endif
  446. // Get light
  447. //Light mainLight = GetMainLight(inputData.shadowCoord);
  448. Light mainLight = GetMainLight(inputData.shadowCoord, inputData.positionWS, shadowMask);
  449. half3 lightColorAndAttenuation = mainLight.color * (mainLight.distanceAttenuation * mainLight.shadowAttenuation);
  450. half3 shad = lightColorAndAttenuation;
  451. MixRealtimeAndBakedGI(mainLight, inputData.normalWS, inputData.bakedGI, half4(0, 0, 0, 0));
  452. #ifdef _ADDITIONAL_LIGHTS
  453. int pixelLightCount = GetAdditionalLightsCount();
  454. #endif
  455. half NdotL = saturate(dot( inputData.normalWS, mainLight.direction));
  456. half3 VertexAndGILighting = input.fogFactorAndVertexLight.yzw + inputData.bakedGI;
  457. // Diffuse underwater lighting
  458. half diffuse_nl = saturate(dot(half3(0,1,0), mainLight.direction));
  459. //half3 diffuseUnderwaterLighting = _Color * (lightColorAndAttenuation * diffuse_nl + VertexAndGILighting);
  460. // Shadows are sampled at the bottom surface. So we attenuate them by underwaterFogDensity. Just a hack but it looks better than not doing anything here.
  461. half3 diffuseUnderwaterLighting = _Color.rgb * (VertexAndGILighting + (diffuse_nl *
  462. mainLight.color * mainLight.distanceAttenuation *
  463. lerp( mainLight.shadowAttenuation, 1 , underwaterFogDensity )
  464. )
  465. );
  466. // Add foam
  467. #if defined(_FOAM)
  468. half3 foamLighting = rawFoamSample.rgb * (lightColorAndAttenuation * NdotL + VertexAndGILighting);
  469. #endif
  470. // Specular Lighting
  471. half3 specularLighting = 0;
  472. #if !defined(_SPECULARHIGHLIGHTS_OFF)
  473. float3 halfDir = SafeNormalize(float3(mainLight.direction) + float3(inputData.viewDirectionWS));
  474. float NoH = saturate(dot(inputData.normalWS, halfDir));
  475. half LoH = saturate(dot(mainLight.direction, halfDir));
  476. float d = NoH * NoH * (roughness2 - 1.h) + 1.0001f;
  477. half LoH2 = LoH * LoH;
  478. half specularTerm = roughness2 / ((d * d) * max(0.1h, LoH2) * normalizationTerm );
  479. #if defined (SHADER_API_MOBILE)
  480. specularTerm = specularTerm - HALF_MIN;
  481. specularTerm = clamp(specularTerm, 0.0, 100.0); // Prevent FP16 overflow on mobiles
  482. #endif
  483. specularLighting = specularTerm * specular * lightColorAndAttenuation;
  484. specularLighting *= NdotL;
  485. #endif
  486. #ifdef _ADDITIONAL_LIGHTS
  487. for (int i = 0; i < pixelLightCount; ++i) {
  488. Light light = GetAdditionalLight(i, inputData.positionWS);
  489. NdotL = saturate(dot(inputData.normalWS, light.direction));
  490. diffuse_nl = saturate(dot(half3(0,1,0), light.direction));
  491. half3 addLightColorAndAttenuation = light.color * light.distanceAttenuation * light.shadowAttenuation;
  492. diffuseUnderwaterLighting += _Color.rgb * addLightColorAndAttenuation * diffuse_nl;
  493. #if defined(_FOAM)
  494. foamLighting += rawFoamSample.rgb * addLightColorAndAttenuation * NdotL;
  495. #endif
  496. #if !defined(_SPECULARHIGHLIGHTS_OFF)
  497. halfDir = SafeNormalize(float3(light.direction) + float3(inputData.viewDirectionWS));
  498. NoH = saturate(dot(inputData.normalWS, halfDir));
  499. LoH = saturate(dot(light.direction, halfDir));
  500. d = NoH * NoH * (roughness2 - 1.h) + 1.0001f;
  501. LoH2 = LoH * LoH;
  502. specularTerm = roughness2 / ((d * d) * max(0.1h, LoH2) * normalizationTerm );
  503. #if defined (SHADER_API_MOBILE)
  504. specularTerm = specularTerm - HALF_MIN;
  505. specularTerm = clamp(specularTerm, 0.0, 100.0); // Prevent FP16 overflow on mobiles
  506. #endif
  507. specularLighting += specularTerm * specular * addLightColorAndAttenuation;
  508. #endif
  509. }
  510. #endif
  511. // Fog - diffuseUnderwaterLighting
  512. #if defined(FOG_LINEAR) || defined(FOG_EXP) || defined(FOG_EXP2)
  513. #if defined(_REFRACTION)
  514. diffuseUnderwaterLighting = lerp(unity_FogColor.rgb, diffuseUnderwaterLighting, fogFactor);
  515. #endif
  516. #endif
  517. // Add underwater fog
  518. #if defined(_REFRACTION)
  519. refraction.rgb = lerp(refraction.rgb, diffuseUnderwaterLighting, underwaterFogDensity);
  520. #else
  521. // Handle transparent mode
  522. refraction.rgb = diffuseUnderwaterLighting * underwaterFogDensity; // premul
  523. #endif
  524. // Fog – foam
  525. #if defined(_FOAM) && defined(_REFRACTION)
  526. #if defined(FOG_LINEAR) || defined(FOG_EXP) || defined(FOG_EXP2)
  527. foamLighting = lerp(unity_FogColor.rgb, foamLighting, fogFactor);
  528. #endif
  529. #endif
  530. // Reflections
  531. #if !defined(_ENVIRONMENTREFLECTIONS_OFF)
  532. // Calculate smoothedReflectionNormal
  533. half3 reflectionNormal = lerp( input.normalWS.xyz, inputData.normalWS, _ReflectionBumpScale);
  534. half3 reflectionVector = reflect(-inputData.viewDirectionWS, reflectionNormal);
  535. half fresnelTerm = Pow4(1.0 - saturate(dot(inputData.normalWS, inputData.viewDirectionWS)));
  536. half3 reflections = GlossyEnvironmentReflection(reflectionVector, perceptualRoughness, occlusion);
  537. float surfaceReduction = 1.0 / (roughness2 + 1.0);
  538. half grazingTerm = saturate(smoothness + reflectivity);
  539. reflections = reflections * surfaceReduction * lerp(specular, grazingTerm, fresnelTerm);
  540. // Combine specular lighting and reflections
  541. specularLighting += reflections;
  542. #endif
  543. #if !defined(_SPECULARHIGHLIGHTS_OFF) || !defined(_ENVIRONMENTREFLECTIONS_OFF)
  544. #if defined(FOG_LINEAR) || defined(FOG_EXP) || defined(FOG_EXP2)
  545. // "Apply" fog
  546. #if defined(_REFRACTION)
  547. specularLighting *= fogFactor;
  548. #endif
  549. #endif
  550. #endif
  551. // Combine all
  552. color.rgb = refraction.rgb;
  553. #if defined(_FOAM)
  554. color.rgb = lerp(color.rgb, foamLighting, rawFoamSample.a );
  555. #endif
  556. #if !defined(_SPECULARHIGHLIGHTS_OFF) || !defined(_ENVIRONMENTREFLECTIONS_OFF)
  557. color.rgb += specularLighting;
  558. #endif
  559. // Soft edge blending
  560. #if defined(_REFRACTION)
  561. color.rgb = lerp(origRefraction, color.rgb, alpha.xxx );
  562. #else
  563. // Transparent mode
  564. #if defined(_FOAM)
  565. float visibility = saturate(underwaterFogDensity + rawFoamSample.a) * oneMinusReflectivity + reflectivity;
  566. #else
  567. float visibility = underwaterFogDensity * oneMinusReflectivity + reflectivity;
  568. #endif
  569. #if defined(FOG_LINEAR) || defined(FOG_EXP) || defined(FOG_EXP2)
  570. color.rgb = lerp(unity_FogColor.rgb * visibility, color.rgb, fogFactor );
  571. #endif
  572. color.rgb *= alpha;
  573. color.a = alpha * visibility;
  574. #endif
  575. //color.rgb = shad;
  576. //color.rgb = refractedSceneDepth;
  577. //color.rgb = surfaceEyeDepth;
  578. //color.rgb = viewDepth;
  579. return color;
  580. }
  581. ENDHLSL
  582. }
  583. }
  584. }