Advertisement
Guest User

Untitled

a guest
Aug 30th, 2016
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
XBasic 102.78 KB | None | 0 0
  1. #version 120
  2.  
  3. /*
  4.  _______ _________ _______  _______  _
  5. (  ____ \\__   __/(  ___  )(  ____ )( )
  6. | (    \/   ) (   | (   ) || (    )|| |
  7. | (_____    | |   | |   | || (____)|| |
  8. (_____  )   | |   | |   | ||  _____)| |
  9.       ) |   | |   | |   | || (      (_)
  10. /\____) |   | |   | (___) || )       _
  11. \_______)   )_(   (_______)|/       (_)
  12.  
  13. Do not modify this code until you have read the LICENSE.txt contained in the root directory of this shaderpack!
  14.  
  15. */
  16.  
  17.  
  18. #define SHADOW_MAP_BIAS 0.90
  19.  
  20.  
  21. /////////ADJUSTABLE VARIABLES//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  22. /////////ADJUSTABLE VARIABLES//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  23.  
  24.  
  25. //Only enable one of these.
  26. //#define ENABLE_SOFT_SHADOWS       // Simple soft shadows
  27. #define VARIABLE_PENUMBRA_SHADOWS   // Contact-hardening (area) shadows
  28.  
  29. #define COLORED_SHADOWS // Tinted shadows from stained glass
  30.  
  31.  
  32. //#define PIXEL_SHADOWS // Pixel-locked shadows
  33. #define TEXTURE_RESOLUTION 128 // Resolution of current resource pack. This needs to be set properly for POM! [16 32 64 128 256 512]
  34.  
  35.  
  36.  
  37. #define VOLUMETRIC_CLOUDS // Volumetric clouds
  38. #define HQ_VOLUMETRIC_CLOUDS // High-quality volumetric clouds. Volumetric Clouds must be enabled!
  39. #define CREPUSCULAR_RAYS // Light rays from sunlight
  40. #define ATMOSPHERIC_SCATTERING // Blue tint of distant objects to simulate atmospheric scattering
  41. #define RAYLEIGH_AMOUNT 1.0 // Strength of atmospheric scattering (atmospheric density). [0.5 1.0 1.5 2.0]
  42.  
  43. //#define BASIC_AMBIENT
  44.  
  45. #define GI_RENDER_RESOLUTION 0 // Render resolution of GI. 0 = High. 1 = Low. Set to 1 for faster but blurrier GI. [0 1]
  46.  
  47. #define WATER_CAUSTICS
  48.  
  49. #define TORCHLIGHT_BRIGHTNESS 0.5 // How bright is light from torches, fire, etc. [0.25 0.5 0.75 1.0 1.5 2.0]
  50.  
  51. /////////INTERNAL VARIABLES////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  52. /////////INTERNAL VARIABLES////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  53. //Do not change the name of these variables or their type. The Shaders Mod reads these lines and determines values to send to the inner-workings
  54. //of the shaders mod. The shaders mod only reads these lines and doesn't actually know the real value assigned to these variables in GLSL.
  55. //Some of these variables are critical for proper operation. Change at your own risk.
  56.  
  57.  
  58. const int       shadowMapResolution     = 2048; // Shadowmap resolution [1024 2048 4096]
  59. const float     shadowDistance          = 120.0; // Shadow distance. Set lower if you prefer nicer close shadows. Set higher if you prefer nicer distant shadows. [80.0 120.0 180.0 240.0]
  60. const float     shadowIntervalSize      = 4.0f;
  61. const bool      shadowHardwareFiltering0 = true;
  62.  
  63. const bool      shadowtex1Mipmap = true;
  64. const bool      shadowtex1Nearest = false;
  65. const bool      shadowcolor0Mipmap = true;
  66. const bool      shadowcolor0Nearest = false;
  67. const bool      shadowcolor1Mipmap = true;
  68. const bool      shadowcolor1Nearest = false;
  69.  
  70. const int       R8                      = 0;
  71. const int       RG8                     = 0;
  72. const int       RGB8                    = 1;
  73. const int       RGB16                   = 2;
  74. const int       gcolorFormat            = RGB16;
  75. const int       gdepthFormat            = RGB8;
  76. const int       gnormalFormat           = RGB16;
  77. const int       compositeFormat         = RGB8;
  78.  
  79. const float     eyeBrightnessHalflife   = 10.0f;
  80. const float     wetnessHalflife         = 300.0f;
  81. const float     drynessHalflife         = 40.0f;
  82.  
  83. const int       superSamplingLevel      = 0;
  84.  
  85. const float     sunPathRotation         = -40.0f;
  86. const float     ambientOcclusionLevel   = 0.01f;
  87.  
  88. const int       noiseTextureResolution  = 64;
  89.  
  90.  
  91. //END OF INTERNAL VARIABLES//
  92.  
  93. /* DRAWBUFFERS:0135 */
  94.  
  95. const bool gaux1MipmapEnabled = true;
  96.  
  97. #define BANDING_FIX_FACTOR 1.0f
  98.  
  99. uniform sampler2D gcolor;
  100. uniform sampler2D gdepth;
  101. uniform sampler2D gdepthtex;
  102. uniform sampler2D gnormal;
  103. uniform sampler2D composite;
  104. uniform sampler2D shadowtex1;
  105. uniform sampler2DShadow shadow;
  106. uniform sampler2D shadowcolor;
  107. uniform sampler2D shadowcolor1;
  108. uniform sampler2D noisetex;
  109. uniform sampler2D gaux1;
  110. uniform sampler2D gaux2;
  111. uniform sampler2D gaux3;
  112. uniform sampler2D depthtex1;
  113.  
  114. varying vec4 texcoord;
  115. varying vec3 lightVector;
  116. varying vec3 upVector;
  117.  
  118. uniform int worldTime;
  119.  
  120. uniform mat4 gbufferProjection;
  121. uniform mat4 gbufferProjectionInverse;
  122. uniform mat4 gbufferModelViewInverse;
  123. uniform mat4 gbufferModelView;
  124. uniform mat4 shadowProjectionInverse;
  125. uniform mat4 shadowProjection;
  126. uniform mat4 shadowModelView;
  127. uniform mat4 shadowModelViewInverse;
  128. uniform vec3 sunPosition;
  129. uniform vec3 cameraPosition;
  130. uniform vec3 upPosition;
  131.  
  132. uniform float near;
  133. uniform float far;
  134. uniform float viewWidth;
  135. uniform float viewHeight;
  136. uniform float rainStrength;
  137. uniform float wetness;
  138. uniform float aspectRatio;
  139. uniform float frameTimeCounter;
  140. uniform float sunAngle;
  141. uniform vec3 skyColor;
  142.  
  143. uniform int   isEyeInWater;
  144. uniform float eyeAltitude;
  145. uniform ivec2 eyeBrightness;
  146. uniform ivec2 eyeBrightnessSmooth;
  147. uniform int   fogMode;
  148.  
  149.  
  150. varying float timeSunriseSunset;
  151. varying float timeNoon;
  152. varying float timeMidnight;
  153. varying float timeSkyDark;
  154.  
  155. varying vec3 colorSunlight;
  156. varying vec3 colorSkylight;
  157. varying vec3 colorSunglow;
  158. varying vec3 colorBouncedSunlight;
  159. varying vec3 colorScatteredSunlight;
  160. varying vec3 colorTorchlight;
  161. varying vec3 colorWaterMurk;
  162. varying vec3 colorWaterBlue;
  163. varying vec3 colorSkyTint;
  164.  
  165. uniform int heldBlockLightValue;
  166.  
  167.  
  168.  
  169.  
  170.  
  171. /////////////////////////FUNCTIONS/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  172. /////////////////////////FUNCTIONS/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  173.  
  174. float saturate(float x)
  175. {
  176.     return clamp(x, 0.0, 1.0);
  177. }
  178.  
  179. //Get gbuffer textures
  180. vec3    GetAlbedoLinear(in vec2 coord) {            //Function that retrieves the diffuse texture and convert it into linear space.
  181.     return pow(texture2D(gcolor, coord).rgb, vec3(2.2f));
  182. }
  183.  
  184. vec3    GetAlbedoGamma(in vec2 coord) {         //Function that retrieves the diffuse texture and leaves it in gamma space.
  185.     return texture2D(gcolor, coord).rgb;
  186. }
  187.  
  188. vec3    GetWaterNormals(in vec2 coord) {                //Function that retrieves the screen space surface normals. Used for lighting calculations
  189.     return normalize(texture2DLod(gnormal, coord.st, 0).rgb * 2.0f - 1.0f);
  190. }
  191.  
  192.  
  193. vec3    GetNormals(in vec2 coord) {             //Function that retrieves the screen space surface normals. Used for lighting calculations
  194.     return normalize(texture2DLod(gaux2, coord.st, 0).rgb * 2.0f - 1.0f);
  195. }
  196.  
  197. float   GetDepth(in vec2 coord) {                   //Function that retrieves the scene depth. 0 - 1, higher values meaning farther away
  198.     return texture2D(depthtex1, coord).r;
  199. }
  200.  
  201. float   GetDepthLinear(in vec2 coord) {                 //Function that retrieves the scene depth. 0 - 1, higher values meaning farther away
  202.     //return 2.0f * near * far / (far + near - (2.0f * texture2D(depthtex1, coord).x - 1.0f) * (far - near));
  203.     return (near * far) / (texture2D(depthtex1, coord).x * (near - far) + far);
  204. }
  205.  
  206. float   ExpToLinearDepth(in float depth)
  207. {
  208.     //return 2.0f * near * far / (far + near - (2.0f * depth - 1.0f) * (far - near));
  209.     return (near*far)/(depth*(near-far)+far);
  210. }
  211.  
  212. float GetParallaxShadow(in vec2 coord)
  213. {
  214.     return 1.0 - texture2D(composite, coord).b;
  215. }
  216.  
  217.  
  218. //Lightmaps
  219. float   GetLightmapTorch(in vec2 coord) {           //Function that retrieves the lightmap of light emitted by emissive blocks like torches and lava
  220.     float lightmap = texture2D(gdepth, coord).g;
  221.  
  222.     //Apply inverse square law and normalize for natural light falloff
  223.     lightmap        = clamp(lightmap * 1.22f, 0.0f, 1.0f);
  224.     lightmap        = 1.0f - lightmap;
  225.     lightmap        *= 5.6f;
  226.     lightmap        = 1.0f / pow((lightmap + 0.8f), 2.0f);
  227.     lightmap        -= 0.02435f;
  228.  
  229.     // if (lightmap <= 0.0f)
  230.         // lightmap = 1.0f;
  231.  
  232.     lightmap        = max(0.0f, lightmap);
  233.     lightmap        *= 0.008f;
  234.     lightmap        = clamp(lightmap, 0.0f, 1.0f);
  235.     lightmap        = pow(lightmap, 0.9f);
  236.     return lightmap * 1.0;
  237.  
  238.  
  239. }
  240.  
  241. float   GetLightmapSky(in vec2 coord) {         //Function that retrieves the lightmap of light emitted by the sky. This is a raw value from 0 (fully dark) to 1 (fully lit) regardless of time of day
  242.     //return pow(texture2D(gdepth, coord).b, 8.3f);
  243.  
  244.     float light = texture2D(gdepth, coord).b;
  245.  
  246.     light = 1.0 - light * 0.834;
  247.     light = 1.0 / light - 1;
  248.     light = light / 5.0;
  249.  
  250.     light = max(0.0, light * 1.05 - 0.05);
  251.  
  252.     return pow(light, 2.0);
  253. }
  254.  
  255. float GetTransparentLightmapSky(in vec2 coord)
  256. {
  257.     return pow(texture2D(gaux3, coord).b, 8.3f);
  258. }
  259.  
  260. float   GetUnderwaterLightmapSky(in vec2 coord) {
  261.     return texture2D(composite, coord).r;
  262. }
  263.  
  264.  
  265. //Specularity
  266. float   GetSpecularity(in vec2 coord) {         //Function that retrieves how reflective any surface/pixel is in the scene. Used for reflections and specularity
  267.     return texture2D(composite, texcoord.st).r;
  268. }
  269.  
  270. float   GetGlossiness(in vec2 coord) {          //Function that retrieves how reflective any surface/pixel is in the scene. Used for reflections and specularity
  271.     return texture2D(composite, texcoord.st).g;
  272. }
  273.  
  274.  
  275.  
  276. //Material IDs
  277. float   GetMaterialIDs(in vec2 coord) {         //Function that retrieves the texture that has all material IDs stored in it
  278.     return texture2D(gdepth, coord).r;
  279. }
  280.  
  281. float   GetTransparentID(in vec2 coord)
  282. {
  283.     return texture2D(gaux3, coord).a;
  284. }
  285.  
  286.  
  287. bool    GetSky(in vec2 coord) {                 //Function that returns true for any pixel that is part of the sky, and false for any pixel that isn't part of the sky
  288.     float matID = GetMaterialIDs(coord);        //Gets texture that has all material IDs stored in it
  289.           matID = floor(matID * 255.0f);        //Scale texture from 0-1 float to 0-255 integer format
  290.  
  291.     if (matID == 0.0f) {                        //Checks to see if the current pixel's material ID is 0 = the sky
  292.         return true;                            //If the current pixel has the material ID of 0 (sky material ID), Return "this pixel is part of the sky"
  293.     } else {
  294.         return false;                           //Return "this pixel is not part of the sky"
  295.     }
  296. }
  297.  
  298. float   GetMaterialMask(in vec2 coord ,const in int ID, in float matID) {
  299.     matID = (matID * 255.0f);
  300.  
  301.     //Catch last part of sky
  302.     if (matID > 254.0f) {
  303.         matID = 0.0f;
  304.     }
  305.  
  306.     if (matID == ID) {
  307.         return 1.0f;
  308.     } else {
  309.         return 0.0f;
  310.     }
  311. }
  312.  
  313. float   GetWaterMask(in vec2 coord, in float matID) {                   //Function that returns "true" if a pixel is water, and "false" if a pixel is not water.
  314.     matID = (matID * 255.0f);
  315.  
  316.     if (matID >= 35.0f && matID <= 51) {
  317.         return 1.0f;
  318.     } else {
  319.         return 0.0f;
  320.     }
  321. }
  322.  
  323. float   GetStainedGlassMask(in vec2 coord, in float matID) {                    //Function that returns "true" if a pixel is water, and "false" if a pixel is not water.
  324.     matID = (matID * 255.0f);
  325.  
  326.     if (matID >= 55.0f && matID <= 70.0f) {
  327.         return 1.0f;
  328.     } else {
  329.         return 0.0f;
  330.     }
  331. }
  332.  
  333. float   GetIceMask(in vec2 coord, in float matID) {                 //Function that returns "true" if a pixel is water, and "false" if a pixel is not water.
  334.     matID = (matID * 255.0f);
  335.  
  336.     if (matID == 4.0f) {
  337.         return 1.0f;
  338.     } else {
  339.         return 0.0f;
  340.     }
  341. }
  342.  
  343.  
  344.  
  345.  
  346. //Surface calculations
  347. vec4    GetScreenSpacePosition(in vec2 coord) { //Function that calculates the screen-space position of the objects in the scene using the depth texture and the texture coordinates of the full-screen quad
  348.     float depth = GetDepth(coord);
  349.           depth += float(GetMaterialMask(coord, 5, GetMaterialIDs(coord))) * 0.38f;
  350.           //float handMask = float(GetMaterialMask(coord, 5, GetMaterialIDs(coord)));
  351.     vec4 fragposition = gbufferProjectionInverse * vec4(coord.s * 2.0f - 1.0f, coord.t * 2.0f - 1.0f, 2.0f * depth - 1.0f, 1.0f);
  352.          fragposition /= fragposition.w;
  353.  
  354.          //fragposition.xyz *= mix(1.0f, 15.0f, handMask);
  355.  
  356.     return fragposition;
  357. }
  358.  
  359. vec4    GetScreenSpacePosition(in vec2 coord, in float depth) { //Function that calculates the screen-space position of the objects in the scene using the depth texture and the texture coordinates of the full-screen quad
  360.           //depth += float(GetMaterialMask(coord, 5)) * 0.38f;
  361.     vec4 fragposition = gbufferProjectionInverse * vec4(coord.s * 2.0f - 1.0f, coord.t * 2.0f - 1.0f, 2.0f * depth - 1.0f, 1.0f);
  362.          fragposition /= fragposition.w;
  363.  
  364.     return fragposition;
  365. }
  366.  
  367. vec4    GetWorldSpacePosition(in vec2 coord, in float depth)
  368. {
  369.     vec4 pos = GetScreenSpacePosition(coord, depth);
  370.     pos = gbufferModelViewInverse * pos;
  371.     pos.xyz += cameraPosition.xyz;
  372.  
  373.     return pos;
  374. }
  375.  
  376. vec4    GetCloudSpacePosition(in vec2 coord, in float depth, in float distanceMult)
  377. {
  378.     // depth *= 30.0f;
  379.  
  380.     float linDepth = depth;
  381.  
  382.     float expDepth = (far * (linDepth - near)) / (linDepth * (far - near));
  383.  
  384.     //Convert texture coordinates and depth into view space
  385.     vec4 viewPos = gbufferProjectionInverse * vec4(coord.s * 2.0f - 1.0f, coord.t * 2.0f - 1.0f, 2.0f * expDepth - 1.0f, 1.0f);
  386.          viewPos /= viewPos.w;
  387.  
  388.     //Convert from view space to world space
  389.     vec4 worldPos = gbufferModelViewInverse * viewPos;
  390.  
  391.     worldPos.xyz *= distanceMult;
  392.     worldPos.xyz += cameraPosition.xyz;
  393.  
  394.     return worldPos;
  395. }
  396.  
  397. vec4    ScreenSpaceFromWorldSpace(in vec4 worldPosition)
  398. {
  399.     worldPosition.xyz -= cameraPosition;
  400.     worldPosition = gbufferModelView * worldPosition;
  401.     return worldPosition;
  402. }
  403.  
  404.  
  405.  
  406. void    DoNightEye(inout vec3 color) {          //Desaturates any color input at night, simulating the rods in the human eye
  407.  
  408.     float amount = 0.8f;                        //How much will the new desaturated and tinted image be mixed with the original image
  409.     vec3 rodColor = vec3(0.2f, 0.4f, 1.0f);     //Cyan color that humans percieve when viewing extremely low light levels via rod cells in the eye
  410.     float colorDesat = dot(color, vec3(1.0f));  //Desaturated color
  411.  
  412.     color = mix(color, vec3(colorDesat) * rodColor, timeMidnight * amount);
  413.     //color.rgb = color.rgb;
  414. }
  415.  
  416.  
  417. float   ExponentialToLinearDepth(in float depth)
  418. {
  419.     vec4 worldposition = vec4(depth);
  420.     worldposition = gbufferProjection * worldposition;
  421.     return worldposition.z;
  422. }
  423.  
  424. float   LinearToExponentialDepth(in float linDepth)
  425. {
  426.     float expDepth = (far * (linDepth - near)) / (linDepth * (far - near));
  427.     return expDepth;
  428. }
  429.  
  430. void    DoLowlightEye(inout vec3 color) {           //Desaturates any color input at night, simulating the rods in the human eye
  431.  
  432.     float amount = 0.8f;                        //How much will the new desaturated and tinted image be mixed with the original image
  433.     vec3 rodColor = vec3(0.2f, 0.4f, 1.0f);     //Cyan color that humans percieve when viewing extremely low light levels via rod cells in the eye
  434.     float colorDesat = dot(color, vec3(1.0f));  //Desaturated color
  435.  
  436.     color = mix(color, vec3(colorDesat) * rodColor, amount);
  437.     // color.rgb = color.rgb;
  438. }
  439.  
  440. void    FixLightFalloff(inout float lightmap) { //Fixes the ugly lightmap falloff and creates a nice linear one
  441.     float additive = 5.35f;
  442.     float exponent = 40.0f;
  443.  
  444.     lightmap += additive;                           //Prevent ugly fast falloff
  445.     lightmap = pow(lightmap, exponent);         //Curve light falloff
  446.     lightmap = max(0.0f, lightmap);     //Make sure light properly falls off to zero
  447.     lightmap /= pow(1.0f + additive, exponent);
  448. }
  449.  
  450.  
  451. float   CalculateLuminance(in vec3 color) {
  452.     return (color.r * 0.2126f + color.g * 0.7152f + color.b * 0.0722f);
  453. }
  454.  
  455. vec3    Glowmap(in vec3 albedo, in float mask, in float curve, in vec3 emissiveColor) {
  456.     vec3 color = albedo * (mask);
  457.          color = pow(color, vec3(curve));
  458.          color = vec3(CalculateLuminance(color));
  459.          color *= emissiveColor;
  460.  
  461.     return color;
  462. }
  463.  
  464.  
  465. float   ChebyshevUpperBound(in vec2 moments, in float distance) {
  466.     if (distance <= moments.x)
  467.         return 1.0f;
  468.  
  469.     float variance = moments.y - (moments.x * moments.x);
  470.           variance = max(variance, 0.000002f);
  471.  
  472.     float d = distance - moments.x;
  473.     float pMax = variance / (variance + d*d);
  474.  
  475.     return pMax;
  476. }
  477.  
  478. float   CalculateDitherPattern() {
  479.     const int[4] ditherPattern = int[4] (0, 2, 1, 4);
  480.  
  481.     vec2 count = vec2(0.0f);
  482.          count.x = floor(mod(texcoord.s * viewWidth, 2.0f));
  483.          count.y = floor(mod(texcoord.t * viewHeight, 2.0f));
  484.  
  485.     int dither = ditherPattern[int(count.x) + int(count.y) * 2];
  486.  
  487.     return float(dither) / 4.0f;
  488. }
  489.  
  490.  
  491. float   CalculateDitherPattern1() {
  492.     const int[16] ditherPattern = int[16] (0 , 8 , 2 , 10,
  493.                                            12, 4 , 14, 6 ,
  494.                                            3 , 11, 1,  9 ,
  495.                                            15, 7 , 13, 5 );
  496.  
  497.     vec2 count = vec2(0.0f);
  498.          count.x = floor(mod(texcoord.s * viewWidth, 4.0f));
  499.          count.y = floor(mod(texcoord.t * viewHeight, 4.0f));
  500.  
  501.     int dither = ditherPattern[int(count.x) + int(count.y) * 4];
  502.  
  503.     return float(dither) / 16.0f;
  504. }
  505.  
  506. float   CalculateDitherPattern2() {
  507.     const int[64] ditherPattern = int[64] ( 1, 49, 13, 61,  4, 52, 16, 64,
  508.                                            33, 17, 45, 29, 36, 20, 48, 32,
  509.                                             9, 57,  5, 53, 12, 60,  8, 56,
  510.                                            41, 25, 37, 21, 44, 28, 40, 24,
  511.                                             3, 51, 15, 63,  2, 50, 14, 62,
  512.                                            35, 19, 47, 31, 34, 18, 46, 30,
  513.                                            11, 59,  7, 55, 10, 58,  6, 54,
  514.                                            43, 27, 39, 23, 42, 26, 38, 22);
  515.  
  516.     vec2 count = vec2(0.0f);
  517.          count.x = floor(mod(texcoord.s * viewWidth, 8.0f));
  518.          count.y = floor(mod(texcoord.t * viewHeight, 8.0f));
  519.  
  520.     int dither = ditherPattern[int(count.x) + int(count.y) * 8];
  521.  
  522.     return float(dither) / 64.0f;
  523. }
  524.  
  525. vec3    CalculateNoisePattern1(vec2 offset, float size) {
  526.     vec2 coord = texcoord.st;
  527.  
  528.     coord *= vec2(viewWidth, viewHeight);
  529.     coord = mod(coord + offset, vec2(size));
  530.     coord /= noiseTextureResolution;
  531.  
  532.     return texture2D(noisetex, coord).xyz;
  533. }
  534.  
  535.  
  536. void DrawDebugSquare(inout vec3 color) {
  537.  
  538.     vec2 pix = vec2(1.0f / viewWidth, 1.0f / viewHeight);
  539.  
  540.     vec2 offset = vec2(0.5f);
  541.     vec2 size = vec2(0.0f);
  542.          size.x = 1.0f / 2.0f;
  543.          size.y = 1.0f / 2.0f;
  544.  
  545.     vec2 padding = pix * 0.0f;
  546.          size += padding;
  547.  
  548.     if ( texcoord.s + offset.s / 2.0f + padding.x / 2.0f > offset.s &&
  549.          texcoord.s + offset.s / 2.0f + padding.x / 2.0f < offset.s + size.x &&
  550.          texcoord.t + offset.t / 2.0f + padding.y / 2.0f > offset.t &&
  551.          texcoord.t + offset.t / 2.0f + padding.y / 2.0f < offset.t + size.y
  552.         )
  553.     {
  554.  
  555.         int[16] ditherPattern = int[16] (0, 3, 0, 3,
  556.                                          2, 1, 2, 1,
  557.                                          0, 3, 0, 3,
  558.                                          2, 1, 2, 1);
  559.  
  560.         vec2 count = vec2(0.0f);
  561.              count.x = floor(mod(texcoord.s * viewWidth, 4.0f));
  562.              count.y = floor(mod(texcoord.t * viewHeight, 4.0f));
  563.  
  564.         int dither = ditherPattern[int(count.x) + int(count.y) * 4];
  565.         color.rgb = vec3(float(dither) / 3.0f);
  566.  
  567.  
  568.     }
  569.  
  570. }
  571.  
  572. /////////////////////////STRUCTS///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  573. /////////////////////////STRUCTS///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  574.  
  575. struct MCLightmapStruct {       //Lightmaps directly from MC engine
  576.     float torch;                //Light emitted from torches and other emissive blocks
  577.     float sky;                  //Light coming from the sky
  578.     float lightning;            //Light coming from lightning
  579.  
  580.     vec3 torchVector;           //Vector in screen space that represents the direction of average light transfered
  581.     vec3 skyVector;
  582. } mcLightmap;
  583.  
  584.  
  585.  
  586. struct DiffuseAttributesStruct {            //Diffuse surface shading attributes
  587.     float roughness;            //Roughness of surface. More roughness will use Oren Nayar reflectance.
  588.     float translucency;         //How translucent the surface is. Translucency represents how much energy will be transfered through the surface
  589.     vec3  translucencyColor;    //Color that will be multiplied with sunlight for backsides of translucent materials.
  590. };
  591.  
  592. struct SpecularAttributesStruct {           //Specular surface shading attributes
  593.     float specularity;          //How reflective a surface is
  594.     float extraSpecularity;     //Additional reflectance for specular reflections from sun only
  595.     float glossiness;           //How smooth or rough a specular surface is
  596.     float metallic;             //from 0 - 1. 0 representing non-metallic, 1 representing fully metallic.
  597.     float gain;                 //Adjust specularity further
  598.     float base;                 //Reflectance when the camera is facing directly at the surface normal. 0 allows only the fresnel effect to add specularity
  599.     float fresnelPower;         //Curve of fresnel effect. Higher values mean the surface has to be viewed at more extreme angles to see reflectance
  600. };
  601.  
  602. struct SkyStruct {              //All sky shading attributes
  603.     vec3    albedo;             //Diffuse texture aka "color texture" of the sky
  604.     vec3    tintColor;          //Color that will be multiplied with the sky to tint it
  605.     vec3    sunglow;            //Color that will be added to the sky simulating scattered light arond the sun/moon
  606.     vec3    sunSpot;            //Actual sun surface
  607. };
  608.  
  609. struct WaterStruct {
  610.     vec3 albedo;
  611. };
  612.  
  613. struct MaskStruct {
  614.  
  615.     float matIDs;
  616.  
  617.     float sky;
  618.     float land;
  619.     float grass;
  620.     float leaves;
  621.     float ice;
  622.     float hand;
  623.     float translucent;
  624.     float glow;
  625.     float sunspot;
  626.     float goldBlock;
  627.     float ironBlock;
  628.     float diamondBlock;
  629.     float emeraldBlock;
  630.     float sand;
  631.     float sandstone;
  632.     float stone;
  633.     float cobblestone;
  634.     float wool;
  635.     float clouds;
  636.  
  637.     float torch;
  638.     float lava;
  639.     float glowstone;
  640.     float fire;
  641.  
  642.     float water;
  643.  
  644.     float volumeCloud;
  645.  
  646.     float stainedGlass;
  647.  
  648. };
  649.  
  650. struct CloudsStruct {
  651.     vec3 albedo;
  652. };
  653.  
  654. struct AOStruct {
  655.     float skylight;
  656.     float scatteredUpLight;
  657.     float bouncedSunlight;
  658.     float scatteredSunlight;
  659.     float constant;
  660. };
  661.  
  662. struct Ray {
  663.     vec3 dir;
  664.     vec3 origin;
  665. };
  666.  
  667. struct Plane {
  668.     vec3 normal;
  669.     vec3 origin;
  670. };
  671.  
  672. struct SurfaceStruct {          //Surface shading properties, attributes, and functions
  673.  
  674.     //Attributes that change how shading is applied to each pixel
  675.         DiffuseAttributesStruct  diffuse;           //Contains all diffuse surface attributes
  676.         SpecularAttributesStruct specular;          //Contains all specular surface attributes
  677.  
  678.     SkyStruct       sky;            //Sky shading attributes and properties
  679.     WaterStruct     water;          //Water shading attributes and properties
  680.     MaskStruct      mask;           //Material ID Masks
  681.     CloudsStruct    clouds;
  682.     AOStruct        ao;             //ambient occlusion
  683.  
  684.     //Properties that are required for lighting calculation
  685.         vec3    albedo;                 //Diffuse texture aka "color texture"
  686.         vec3    normal;                 //Screen-space surface normals
  687.         float   depth;                  //Scene depth
  688.         float   linearDepth;            //Linear depth
  689.  
  690.         vec4    screenSpacePosition;    //Vector representing the screen-space position of the surface
  691.         vec4    worldSpacePosition;
  692.         vec3    viewVector;             //Vector representing the viewing direction
  693.         vec3    lightVector;            //Vector representing sunlight direction
  694.         Ray     viewRay;
  695.         vec3    worldLightVector;
  696.         vec3    upVector;               //Vector representing "up" direction
  697.         float   NdotL;                  //dot(normal, lightVector). used for direct lighting calculation
  698.         vec3    debug;
  699.  
  700.         float   shadow;
  701.         float   cloudShadow;
  702.  
  703.         float   cloudAlpha;
  704. } surface;
  705.  
  706. struct LightmapStruct {         //Lighting information to light the scene. These are untextured colored lightmaps to be multiplied with albedo to get the final lit and textured image.
  707.     vec3 sunlight;              //Direct light from the sun
  708.     vec3 skylight;              //Ambient light from the sky
  709.     vec3 bouncedSunlight;       //Fake bounced light, coming from opposite of sun direction and adding to ambient light
  710.     vec3 scatteredSunlight;     //Fake scattered sunlight, coming from same direction as sun and adding to ambient light
  711.     vec3 scatteredUpLight;      //Fake GI from ground
  712.     vec3 torchlight;            //Light emitted from torches and other emissive blocks
  713.     vec3 lightning;             //Light caused by lightning
  714.     vec3 nolight;               //Base ambient light added to everything. For lighting caves so that the player can barely see even when no lights are present
  715.     vec3 specular;              //Reflected direct light from sun
  716.     vec3 translucent;           //Light on the backside of objects representing thin translucent materials
  717.     vec3 sky;                   //Color and brightness of the sky itself
  718.     vec3 underwater;            //underwater lightmap
  719.     vec3 heldLight;
  720. } lightmap;
  721.  
  722. struct ShadingStruct {          //Shading calculation variables
  723.     float   direct;
  724.     float   waterDirect;
  725.     float   bounced;            //Fake bounced sunlight
  726.     float   skylight;           //Light coming from sky
  727.     float   scattered;          //Fake scattered sunlight
  728.     float   scatteredUp;        //Fake GI from ground
  729.     float   specular;           //Reflected direct light
  730.     float   translucent;        //Backside of objects lit up from the sun via thin translucent materials
  731.     vec3    sunlightVisibility; //Shadows
  732.     float   heldLight;
  733. } shading;
  734.  
  735. struct GlowStruct {
  736.     vec3 torch;
  737.     vec3 lava;
  738.     vec3 glowstone;
  739.     vec3 fire;
  740. };
  741.  
  742. struct FinalStruct {            //Final textured and lit images sorted by what is illuminating them.
  743.  
  744.     GlowStruct      glow;       //Struct containing emissive material final images
  745.  
  746.     vec3 sunlight;              //Direct light from the sun
  747.     vec3 skylight;              //Ambient light from the sky
  748.     vec3 bouncedSunlight;       //Fake bounced light, coming from opposite of sun direction and adding to ambient light
  749.     vec3 scatteredSunlight;     //Fake scattered sunlight, coming from same direction as sun and adding to ambient light
  750.     vec3 scatteredUpLight;      //Fake GI from ground
  751.     vec3 torchlight;            //Light emitted from torches and other emissive blocks
  752.     vec3 lightning;             //Light caused by lightning
  753.     vec3 nolight;               //Base ambient light added to everything. For lighting caves so that the player can barely see even when no lights are present
  754.     vec3 translucent;           //Light on the backside of objects representing thin translucent materials
  755.     vec3 sky;                   //Color and brightness of the sky itself
  756.     vec3 underwater;            //underwater colors
  757.     vec3 heldLight;
  758.  
  759.  
  760. } final;
  761.  
  762. struct Intersection {
  763.     vec3 pos;
  764.     float distance;
  765.     float angle;
  766. };
  767.  
  768.  
  769.  
  770.  
  771. /////////////////////////STRUCT FUNCTIONS//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  772. /////////////////////////STRUCT FUNCTIONS//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  773.  
  774. //Mask
  775. void    CalculateMasks(inout MaskStruct mask) {
  776.         if (isEyeInWater > 0)
  777.             mask.sky = 0.0f;
  778.         else
  779.             mask.sky            = GetMaterialMask(texcoord.st, 0, mask.matIDs);
  780.  
  781.         mask.land           = GetMaterialMask(texcoord.st, 1, mask.matIDs);
  782.         mask.grass          = GetMaterialMask(texcoord.st, 2, mask.matIDs);
  783.         mask.leaves         = GetMaterialMask(texcoord.st, 3, mask.matIDs);
  784.         mask.hand           = GetMaterialMask(texcoord.st, 5, mask.matIDs);
  785.         mask.translucent    = GetMaterialMask(texcoord.st, 6, mask.matIDs);
  786.  
  787.         mask.glow           = GetMaterialMask(texcoord.st, 10, mask.matIDs);
  788.         mask.sunspot        = GetMaterialMask(texcoord.st, 11, mask.matIDs);
  789.  
  790.         mask.goldBlock      = GetMaterialMask(texcoord.st, 20, mask.matIDs);
  791.         mask.ironBlock      = GetMaterialMask(texcoord.st, 21, mask.matIDs);
  792.         mask.diamondBlock   = GetMaterialMask(texcoord.st, 22, mask.matIDs);
  793.         mask.emeraldBlock   = GetMaterialMask(texcoord.st, 23, mask.matIDs);
  794.         mask.sand           = GetMaterialMask(texcoord.st, 24, mask.matIDs);
  795.         mask.sandstone      = GetMaterialMask(texcoord.st, 25, mask.matIDs);
  796.         mask.stone          = GetMaterialMask(texcoord.st, 26, mask.matIDs);
  797.         mask.cobblestone    = GetMaterialMask(texcoord.st, 27, mask.matIDs);
  798.         mask.wool           = GetMaterialMask(texcoord.st, 28, mask.matIDs);
  799.         mask.clouds         = GetMaterialMask(texcoord.st, 29, mask.matIDs);
  800.  
  801.         mask.torch          = GetMaterialMask(texcoord.st, 30, mask.matIDs);
  802.         mask.lava           = GetMaterialMask(texcoord.st, 31, mask.matIDs);
  803.         mask.glowstone      = GetMaterialMask(texcoord.st, 32, mask.matIDs);
  804.         mask.fire           = GetMaterialMask(texcoord.st, 33, mask.matIDs);
  805.  
  806.         float transparentID = GetTransparentID(texcoord.st);
  807.  
  808.         mask.water          = GetWaterMask(texcoord.st, transparentID);
  809.         mask.stainedGlass   = GetStainedGlassMask(texcoord.st, transparentID);
  810.         mask.ice            = GetIceMask(texcoord.st, transparentID);
  811.  
  812.         mask.volumeCloud    = 0.0f;
  813. }
  814.  
  815. //Surface
  816. void    CalculateNdotL(inout SurfaceStruct surface) {       //Calculates direct sunlight without visibility check
  817.     float direct = dot(surface.normal.rgb, surface.lightVector);
  818.           direct = direct * 1.0f + 0.0f;
  819.           //direct = clamp(direct, 0.0f, 1.0f);
  820.  
  821.     surface.NdotL = direct;
  822. }
  823.  
  824. float   CalculateDirectLighting(in SurfaceStruct surface) {
  825.  
  826.     //Tall grass translucent shading
  827.     if (surface.mask.grass > 0.5f) {
  828.  
  829.         return clamp(dot(surface.lightVector, surface.upVector) * 0.8 + 0.2, 0.0, 1.0);
  830.  
  831.  
  832.     //Leaves
  833.     } else if (surface.mask.leaves > 0.5f) {
  834.  
  835.         // if (surface.NdotL > -0.01f) {
  836.         //  return surface.NdotL * 0.99f + 0.01f;
  837.         // } else {
  838.         //  return abs(surface.NdotL) * 0.25f;
  839.         // }
  840.  
  841.         return 0.5f;
  842.  
  843.  
  844.     //clouds
  845.     } else if (surface.mask.clouds > 0.5f) {
  846.  
  847.         return 0.5f;
  848.  
  849.  
  850.     } else if (surface.mask.ice > 0.5f) {
  851.  
  852.         return pow(surface.NdotL * 0.5 + 0.5, 2.0f);
  853.  
  854.     //Default lambert shading
  855.     } else {
  856.         const float PI = 3.14159;
  857.         const float roughness = 0.95;
  858.  
  859.         // interpolating normals will change the length of the normal, so renormalize the normal.
  860.         vec3 normal = normalize(surface.normal.xyz);
  861.  
  862.  
  863.         vec3 eyeDir = normalize(-surface.screenSpacePosition.xyz);
  864.  
  865.         // normal = normalize(normal + surface.lightVector * pow(clamp(dot(eyeDir, surface.lightVector), 0.0, 1.0), 5.0) * 0.5);
  866.  
  867.         // normal = normalize(normal + eyeDir * clamp(dot(normal, eyeDir), 0.0f, 1.0f));
  868.  
  869.         // calculate intermediary values
  870.         float NdotL = dot(normal, surface.lightVector.xyz);
  871.         float NdotV = dot(normal, eyeDir);
  872.  
  873.         float angleVN = acos(NdotV);
  874.         float angleLN = acos(NdotL);
  875.  
  876.         float alpha = max(angleVN, angleLN);
  877.         float beta = min(angleVN, angleLN);
  878.         float gamma = dot(eyeDir - normal * dot(eyeDir, normal), surface.lightVector - normal * dot(surface.lightVector, normal));
  879.  
  880.         float roughnessSquared = roughness * roughness;
  881.  
  882.         // calculate A and B
  883.         float A = 1.0 - 0.5 * (roughnessSquared / (roughnessSquared + 0.57));
  884.  
  885.         float B = 0.45 * (roughnessSquared / (roughnessSquared + 0.09));
  886.  
  887.         float C = sin(alpha) * tan(beta);
  888.  
  889.         // put it all together
  890.         float L1 = max(0.0, NdotL) * (A + B * max(0.0, gamma) * C);
  891.  
  892.         //return max(0.0f, surface.NdotL * 0.99f + 0.01f);
  893.         return clamp(L1, 0.0f, 1.0f);
  894.     }
  895. }
  896.  
  897. vec3    CalculateSunlightVisibility(inout SurfaceStruct surface, in ShadingStruct shadingStruct) {              //Calculates shadows
  898.     if (rainStrength >= 0.99f)
  899.         return vec3(1.0f);
  900.  
  901.  
  902.     if (shadingStruct.direct > 0.0f) {
  903.         float distance = sqrt(  surface.screenSpacePosition.x * surface.screenSpacePosition.x   //Get surface distance in meters
  904.                               + surface.screenSpacePosition.y * surface.screenSpacePosition.y
  905.                               + surface.screenSpacePosition.z * surface.screenSpacePosition.z);
  906.  
  907.         vec4 ssp = surface.screenSpacePosition;
  908.  
  909.         if (isEyeInWater > 0.5)
  910.         {
  911.             ssp.xy *= 0.8;
  912.         }
  913.  
  914.         vec4 worldposition = vec4(0.0f);
  915.              worldposition = gbufferModelViewInverse * ssp;     //Transform from screen space to world space
  916.  
  917.  
  918.         #if defined PIXEL_SHADOWS
  919.             worldposition.xyz += cameraPosition.xyz + 0.001;
  920.             worldposition.xyz = floor(worldposition.xyz * TEXTURE_RESOLUTION) / TEXTURE_RESOLUTION;
  921.             worldposition.xyz -= cameraPosition.xyz;
  922.         #endif
  923.  
  924.         float yDistanceSquared  = worldposition.y * worldposition.y;
  925.  
  926.         worldposition = shadowModelView * worldposition;    //Transform from world space to shadow space
  927.         float comparedepth = -worldposition.z;              //Surface distance from sun to be compared to the shadow map
  928.  
  929.         worldposition = shadowProjection * worldposition;
  930.         worldposition /= worldposition.w;
  931.  
  932.         float dist = sqrt(worldposition.x * worldposition.x + worldposition.y * worldposition.y);
  933.         float distortFactor = (1.0f - SHADOW_MAP_BIAS) + dist * SHADOW_MAP_BIAS;
  934.         worldposition.xy *= 0.95f / distortFactor;
  935.         worldposition.z = mix(worldposition.z, 0.5, 0.8);
  936.         worldposition = worldposition * 0.5f + 0.5f;        //Transform from shadow space to shadow map coordinates
  937.  
  938.         float shadowMult = 0.0f;                                                                            //Multiplier used to fade out shadows at distance
  939.         float shading = 0.0f;
  940.  
  941.         float fademult = 0.15f;
  942.             shadowMult = clamp((shadowDistance * 41.4f * fademult) - (distance * fademult), 0.0f, 1.0f);    //Calculate shadowMult to fade shadows out
  943.  
  944.         if (shadowMult > 0.0)
  945.         {
  946.  
  947.             float diffthresh = dist * 1.0f + 0.10f;
  948.                   diffthresh *= 1.0f / (shadowMapResolution / 2048.0f);
  949.                   //diffthresh /= shadingStruct.direct + 0.1f;
  950.  
  951.  
  952.             #ifdef PIXEL_SHADOWS
  953.                   //diffthresh += 1.5;
  954.             #endif
  955.  
  956.  
  957.             #ifdef ENABLE_SOFT_SHADOWS
  958.             #ifndef VARIABLE_PENUMBRA_SHADOWS
  959.  
  960.                 int count = 0;
  961.                 float spread = 1.0f / shadowMapResolution;
  962.  
  963.                 vec3 noise = CalculateNoisePattern1(vec2(0.0), 64.0);
  964.  
  965.                 for (float i = -0.5f; i <= 0.5f; i += 1.0f)
  966.                 {
  967.                     for (float j = -0.5f; j <= 0.5f; j += 1.0f)
  968.                     {
  969.                         float angle = noise.x * 3.14159 * 2.0;
  970.  
  971.                         mat2 rot = mat2(cos(angle), -sin(angle), sin(angle), cos(angle));
  972.  
  973.                         vec2 coord = vec2(i, j) * rot;
  974.  
  975.                         shading += shadow2D(shadow, vec3(worldposition.st + coord * spread, worldposition.z - 0.0008f * diffthresh)).x;
  976.                         count += 1;
  977.                     }
  978.                 }
  979.                 shading /= count;
  980.  
  981.             #endif
  982.             #endif
  983.  
  984.             #ifdef VARIABLE_PENUMBRA_SHADOWS
  985.  
  986.                 float vpsSpread = 0.125 / distortFactor;
  987.  
  988.                 float avgDepth = 0.0;
  989.                 float minDepth = 11.0;
  990.                 int c;
  991.  
  992.                 for (int i = -1; i <= 1; i++)
  993.                 {
  994.                     for (int j = -1; j <= 1; j++)
  995.                     {
  996.                         vec2 lookupCoord = worldposition.xy + (vec2(i, j) / shadowMapResolution) * 8.0 * vpsSpread;
  997.                         //avgDepth += pow(texture2DLod(shadowtex1, lookupCoord, 2).x, 4.1);
  998.                         float depthSample = texture2DLod(shadowtex1, lookupCoord, 2).x;
  999.                         minDepth = min(minDepth, texture2DLod(shadowtex1, lookupCoord, 2).x);
  1000.                         avgDepth += pow(min(max(0.0, worldposition.z - depthSample) * 1.0, 0.15), 2.0);
  1001.                         c++;
  1002.                     }
  1003.                 }
  1004.  
  1005.                 avgDepth /= c;
  1006.                 avgDepth = pow(avgDepth, 1.0 / 2.0);
  1007.  
  1008.                 // float penumbraSize = min(abs(worldposition.z - minDepth), 0.15);
  1009.                 float penumbraSize = avgDepth;
  1010.  
  1011.                 int count = 0;
  1012.                 float spread = penumbraSize * 0.0125 * vpsSpread + 0.5 / shadowMapResolution;
  1013.  
  1014.                 vec3 noise = CalculateNoisePattern1(vec2(0.0), 64.0);
  1015.  
  1016.                 diffthresh *= 0.5 + avgDepth * 50.0;
  1017.  
  1018.                 for (float i = -2.0f; i <= 2.0f; i += 1.0f)
  1019.                 {
  1020.                     for (float j = -2.0f; j <= 2.0f; j += 1.0f)
  1021.                     {
  1022.                         float angle = noise.x * 3.14159 * 2.0;
  1023.  
  1024.                         mat2 rot = mat2(cos(angle), -sin(angle), sin(angle), cos(angle));
  1025.  
  1026.                         vec2 coord = vec2(i, j) * rot;
  1027.  
  1028.                         shading += shadow2D(shadow, vec3(worldposition.st + coord * spread, worldposition.z - 0.0012f * diffthresh)).x;
  1029.                         count += 1;
  1030.                     }
  1031.                 }
  1032.                 shading /= count;
  1033.  
  1034.             #endif
  1035.  
  1036.             #ifndef VARIABLE_PENUMBRA_SHADOWS
  1037.             #ifndef ENABLE_SOFT_SHADOWS
  1038.                 //diffthresh *= 2.0f;
  1039.                 shading = shadow2DLod(shadow, vec3(worldposition.st, worldposition.z - 0.0006f * diffthresh), 0).x;
  1040.             #endif
  1041.             #endif
  1042.  
  1043.         }
  1044.  
  1045.         //shading = mix(1.0f, shading, shadowMult);
  1046.  
  1047.         surface.shadow = shading;
  1048.  
  1049.         vec3 result = vec3(shading);
  1050.  
  1051.  
  1052.         ///*
  1053.         #ifdef COLORED_SHADOWS
  1054.         float shadowNormalAlpha = texture2DLod(shadowcolor1, worldposition.st, 0).a;
  1055.  
  1056.         vec3 noise2 = CalculateNoisePattern1(vec2(0.0), 64.0);
  1057.  
  1058.         //worldposition.st += (noise2.xy * 2.0 - 1.0) / shadowMapResolution;
  1059.  
  1060.         if (shadowNormalAlpha < 0.5)
  1061.         {
  1062.             result = mix(vec3(1.0), pow(texture2DLod(shadowcolor, worldposition.st, 0).rgb, vec3(1.6)), vec3(1.0 - shading));
  1063.             float solidDepth = texture2DLod(shadowtex1, worldposition.st, 0).x;
  1064.             float solidShadow = 1.0 - clamp((worldposition.z - solidDepth) * 1200.0, 0.0, 1.0);
  1065.             result *= solidShadow;
  1066.         }
  1067.         #endif
  1068.         //*/
  1069.  
  1070.         result = mix(vec3(1.0), result, shadowMult);
  1071.  
  1072.         return result;
  1073.     } else {
  1074.         return vec3(0.0f);
  1075.     }
  1076. }
  1077.  
  1078. float   CalculateBouncedSunlight(in SurfaceStruct surface) {
  1079.  
  1080.     float NdotL = surface.NdotL;
  1081.     float bounced = clamp(-NdotL + 0.95f, 0.0f, 1.95f) / 1.95f;
  1082.           bounced = bounced * bounced * bounced;
  1083.  
  1084.     return bounced;
  1085. }
  1086.  
  1087. float   CalculateScatteredSunlight(in SurfaceStruct surface) {
  1088.  
  1089.     float NdotL = surface.NdotL;
  1090.     float scattered = clamp(NdotL * 0.75f + 0.25f, 0.0f, 1.0f);
  1091.           //scattered *= scattered * scattered;
  1092.  
  1093.     return scattered;
  1094. }
  1095.  
  1096. float   CalculateSkylight(in SurfaceStruct surface) {
  1097.  
  1098.     if (surface.mask.clouds > 0.5f) {
  1099.         return 1.0f;
  1100.  
  1101.     } else if (surface.mask.leaves > 0.5) {
  1102.  
  1103.         return dot(surface.normal, surface.upVector) * 0.35 + 0.65;
  1104.  
  1105.     } else if (surface.mask.grass > 0.5f) {
  1106.  
  1107.         return 1.6f;
  1108.  
  1109.     } else {
  1110.  
  1111.         float skylight = dot(surface.normal, surface.upVector);
  1112.               skylight = skylight * 0.4f + 0.6f;
  1113.  
  1114.         return skylight;
  1115.     }
  1116. }
  1117.  
  1118. float   CalculateScatteredUpLight(in SurfaceStruct surface) {
  1119.     float scattered = dot(surface.normal, surface.upVector);
  1120.           scattered = scattered * 0.5f + 0.5f;
  1121.           scattered = 1.0f - scattered;
  1122.  
  1123.     return scattered;
  1124. }
  1125.  
  1126. float CalculateHeldLightShading(in SurfaceStruct surface)
  1127. {
  1128.     vec3 lightPos = vec3(0.0f);
  1129.     vec3 lightVector = normalize(lightPos - surface.screenSpacePosition.xyz);
  1130.     float lightDist = length(lightPos.xyz - surface.screenSpacePosition.xyz);
  1131.  
  1132.     float atten = 1.0f / (pow(lightDist, 2.0f) + 0.5f);
  1133.     float NdotL = 1.0f;
  1134.  
  1135.     return atten * NdotL;
  1136. }
  1137.  
  1138. float   CalculateSunglow(in SurfaceStruct surface) {
  1139.  
  1140.     float curve = 4.0f;
  1141.  
  1142.     vec3 npos = normalize(surface.screenSpacePosition.xyz);
  1143.     vec3 halfVector2 = normalize(-surface.lightVector + npos);
  1144.     float factor = 1.0f - dot(halfVector2, npos);
  1145.  
  1146.     return factor * factor * factor * factor;
  1147. }
  1148.  
  1149. float   CalculateAntiSunglow(in SurfaceStruct surface) {
  1150.  
  1151.     float curve = 4.0f;
  1152.  
  1153.     vec3 npos = normalize(surface.screenSpacePosition.xyz);
  1154.     vec3 halfVector2 = normalize(surface.lightVector + npos);
  1155.     float factor = 1.0f - dot(halfVector2, npos);
  1156.  
  1157.     return factor * factor * factor * factor;
  1158. }
  1159.  
  1160. bool   CalculateSunspot(in SurfaceStruct surface) {
  1161.  
  1162.     //circular sun
  1163.     float curve = 1.0f;
  1164.  
  1165.     vec3 npos = normalize(surface.screenSpacePosition.xyz);
  1166.     vec3 halfVector2 = normalize(-surface.lightVector + npos);
  1167.  
  1168.     float sunProximity = 1.0f - dot(halfVector2, npos);
  1169.  
  1170.     if (sunProximity > 0.96f && sunAngle > 0.0f && sunAngle < 0.5f) {
  1171.         return true;
  1172.     } else {
  1173.         return false;
  1174.     }
  1175.  
  1176.     //Sun based on matID
  1177.  
  1178.     // if (surface.mask.sunspot)
  1179.     //  return true;
  1180.     // else
  1181.     //  return false;
  1182. }
  1183.  
  1184. void    GetLightVectors(inout MCLightmapStruct mcLightmap, in SurfaceStruct surface) {
  1185.  
  1186.     vec2 torchDiff = vec2(0.0f);
  1187.          torchDiff.x = GetLightmapTorch(texcoord.st) - GetLightmapTorch(texcoord.st + vec2(1.0f / viewWidth, 0.0f));
  1188.          torchDiff.y = GetLightmapTorch(texcoord.st) - GetLightmapTorch(texcoord.st + vec2(0.0f, 1.0f / viewWidth));
  1189.  
  1190.          //torchDiff /= GetDepthLinear(texcoord.st);
  1191.  
  1192.     mcLightmap.torchVector.x = torchDiff.x * 200.0f;
  1193.     //mcLightmap.torchVector.x *= 1.0f - surface.viewVector.x;
  1194.  
  1195.     mcLightmap.torchVector.y = torchDiff.y * 200.0f;
  1196.  
  1197.     mcLightmap.torchVector.x = 1.0f;
  1198.     mcLightmap.torchVector.y = 0.0f;
  1199.     mcLightmap.torchVector.z = sqrt(1.0f - mcLightmap.torchVector.x * mcLightmap.torchVector.x + mcLightmap.torchVector.y + mcLightmap.torchVector.y);
  1200.  
  1201.  
  1202.  
  1203.  
  1204.     float torchNormal = dot(surface.normal.rgb, mcLightmap.torchVector.rgb);
  1205.  
  1206.     mcLightmap.torchVector.x = torchNormal;
  1207.  
  1208.  
  1209.     //mcLightmap.torchVector = mcLightmap.torchVector * 0.5f + 0.5f;
  1210. }
  1211.  
  1212. void    AddSkyGradient(inout SurfaceStruct surface) {
  1213.     float curve = 5.0f;
  1214.     vec3 npos = normalize(surface.screenSpacePosition.xyz);
  1215.     vec3 halfVector2 = normalize(-surface.upVector + npos);
  1216.     float skyGradientFactor = dot(halfVector2, npos);
  1217.     float skyDirectionGradient = skyGradientFactor;
  1218.  
  1219.     if (dot(halfVector2, npos) > 0.75)
  1220.         skyGradientFactor = 1.5f - skyGradientFactor;
  1221.  
  1222.     skyGradientFactor = pow(skyGradientFactor, curve);
  1223.  
  1224.     surface.sky.albedo = CalculateLuminance(surface.sky.albedo) * colorSkylight;
  1225.  
  1226.     surface.sky.albedo *= mix(skyGradientFactor, 1.0f, clamp((0.12f - (timeNoon * 0.1f)) + rainStrength, 0.0f, 1.0f));
  1227.     surface.sky.albedo *= pow(skyGradientFactor, 2.5f) + 0.2f;
  1228.     surface.sky.albedo *= (pow(skyGradientFactor, 1.1f) + 0.425f) * 0.5f;
  1229.     surface.sky.albedo.g *= skyGradientFactor * 1.0f + 1.0f;
  1230.  
  1231.  
  1232.     vec3 linFogColor = pow(gl_Fog.color.rgb, vec3(2.2f));
  1233.  
  1234.     float fogLum = max(max(linFogColor.r, linFogColor.g), linFogColor.b);
  1235.  
  1236.  
  1237.     float fade1 = clamp(skyGradientFactor - 0.05f, 0.0f, 0.2f) / 0.2f;
  1238.           fade1 = fade1 * fade1 * (3.0f - 2.0f * fade1);
  1239.     vec3 color1 = vec3(12.0f, 8.0, 4.7f) * 0.15f;
  1240.          color1 = mix(color1, vec3(2.0f, 0.55f, 0.2f), vec3(timeSunriseSunset));
  1241.  
  1242.     surface.sky.albedo *= mix(vec3(1.0f), color1, vec3(fade1));
  1243.  
  1244.     float fade2 = clamp(skyGradientFactor - 0.11f, 0.0f, 0.2f) / 0.2f;
  1245.     vec3 color2 = vec3(2.7f, 1.0f, 2.8f) / 20.0f;
  1246.          color2 = mix(color2, vec3(1.0f, 0.15f, 0.5f), vec3(timeSunriseSunset));
  1247.  
  1248.     surface.sky.albedo *= mix(vec3(1.0f), color2, vec3(fade2 * 0.5f));
  1249.  
  1250.  
  1251.  
  1252.     float horizonGradient = 1.0f - distance(skyDirectionGradient, 0.72f) / 0.72f;
  1253.           horizonGradient = pow(horizonGradient, 10.0f);
  1254.           horizonGradient = max(0.0f, horizonGradient);
  1255.  
  1256.     float sunglow = CalculateSunglow(surface);
  1257.           horizonGradient *= sunglow * 2.0f + (0.65f - timeSunriseSunset * 0.55f);
  1258.  
  1259.     vec3 horizonColor1 = vec3(1.5f, 1.5f, 1.5f);
  1260.          horizonColor1 = mix(horizonColor1, vec3(1.5f, 1.95f, 1.5f) * 2.0f, vec3(timeSunriseSunset));
  1261.     vec3 horizonColor2 = vec3(1.5f, 1.2f, 0.8f) * 1.0f;
  1262.          horizonColor2 = mix(horizonColor2, vec3(1.9f, 0.6f, 0.4f) * 2.0f, vec3(timeSunriseSunset));
  1263.  
  1264.     surface.sky.albedo *= mix(vec3(1.0f), horizonColor1, vec3(horizonGradient) * (1.0f - timeMidnight));
  1265.     surface.sky.albedo *= mix(vec3(1.0f), horizonColor2, vec3(pow(horizonGradient, 2.0f)) * (1.0f - timeMidnight));
  1266.  
  1267.     float grayscale = fogLum / 10.0f;
  1268.           grayscale /= 3.0f;
  1269.  
  1270.     surface.sky.albedo = mix(surface.sky.albedo, vec3(grayscale * colorSkylight.r) * 0.06f * vec3(0.85f, 0.85f, 1.0f), vec3(rainStrength));
  1271.  
  1272.  
  1273.     surface.sky.albedo /= fogLum;
  1274.  
  1275.  
  1276.     surface.sky.albedo *= mix(1.0f, 4.5f, timeNoon);
  1277.  
  1278.  
  1279.  
  1280.     // //Fake land
  1281.     // vec3 fakeLandColor = vec3(0.2f, 0.5f, 1.0f) * 0.006f;
  1282.     // surface.sky.albedo = mix(surface.sky.albedo, fakeLandColor, vec3(clamp(skyGradientFactor * 8.0f - 0.7f, 0.0f, 1.0f)));
  1283.  
  1284.  
  1285.     surface.sky.albedo *= (surface.mask.sky);
  1286. }
  1287.  
  1288. void    AddSunglow(inout SurfaceStruct surface) {
  1289.     float sunglowFactor = CalculateSunglow(surface);
  1290.     float antiSunglowFactor = CalculateAntiSunglow(surface);
  1291.  
  1292.     surface.sky.albedo *= 1.0f + pow(sunglowFactor, 1.1f) * (7.0f + timeNoon * 1.0f) * (1.0f - rainStrength) * 0.4;
  1293.     surface.sky.albedo *= mix(vec3(1.0f), colorSunlight * 11.0f, pow(clamp(vec3(sunglowFactor) * (1.0f - timeMidnight) * (1.0f - rainStrength), vec3(0.0f), vec3(1.0f)), vec3(2.0f)));
  1294.     surface.sky.albedo = mix(surface.sky.albedo, colorSunlight * surface.mask.sky * (0.25 + timeSunriseSunset * 0.25), pow(clamp(vec3(sunglowFactor) * (1.0f - timeMidnight) * (1.0f - rainStrength), vec3(0.0f), vec3(1.0f)), vec3(5.0f)));
  1295.  
  1296.     surface.sky.albedo *= 1.0f + antiSunglowFactor * 2.0f * (1.0f - rainStrength);
  1297.     //surface.sky.albedo *= mix(vec3(1.0f), colorSunlight, antiSunglowFactor);
  1298. }
  1299.  
  1300.  
  1301. void    AddCloudGlow(inout vec3 color, in SurfaceStruct surface) {
  1302.     float glow = CalculateSunglow(surface);
  1303.           glow = pow(glow, 1.0f);
  1304.  
  1305.     float mult = mix(50.0f, 800.0f, timeSkyDark);
  1306.  
  1307.     color.rgb *= 1.0f + glow * mult * (surface.mask.clouds);
  1308. }
  1309.  
  1310.  
  1311. void    CalculateUnderwaterFog(in SurfaceStruct surface, inout vec3 finalComposite) {
  1312.     vec3 fogColor = colorWaterMurk * vec3(colorSkylight.b);
  1313.     // float fogDensity = 0.045f;
  1314.     // float fogFactor = exp(GetDepthLinear(texcoord.st) * fogDensity) - 1.0f;
  1315.     //    fogFactor = min(fogFactor, 1.0f);
  1316.     float fogFactor = GetDepthLinear(texcoord.st) / 100.0f;
  1317.           fogFactor = min(fogFactor, 0.7f);
  1318.           fogFactor = sin(fogFactor * 3.1415 / 2.0f);
  1319.           fogFactor = pow(fogFactor, 0.5f);
  1320.  
  1321.  
  1322.     finalComposite.rgb = mix(finalComposite.rgb, fogColor * 0.002f, vec3(fogFactor));
  1323.     finalComposite.rgb *= mix(vec3(1.0f), colorWaterBlue * colorWaterBlue * colorWaterBlue * colorWaterBlue, vec3(fogFactor));
  1324.     //finalComposite.rgb = vec3(0.1f);
  1325. }
  1326.  
  1327. void    TestRaymarch(inout vec3 color, in SurfaceStruct surface)
  1328. {
  1329.  
  1330.     //visualize march steps
  1331.     float rayDepth = 0.0f;
  1332.     float rayIncrement = 0.05f;
  1333.     float fogFactor = 0.0f;
  1334.  
  1335.     while (rayDepth < 1.0f)
  1336.     {
  1337.         vec4 rayPosition = GetScreenSpacePosition(texcoord.st, pow(rayDepth, 0.002f));
  1338.  
  1339.  
  1340.  
  1341.         if (abs(rayPosition.z - surface.screenSpacePosition.z) < 0.025f)
  1342.         {
  1343.             color.rgb = vec3(0.01f, 0.0f, 0.0f);
  1344.         }
  1345.  
  1346.         // if (SphereTestDistance(vec3(surface.screenSpacePosition.x, surface.screenSpacePosition.y, surface.screenSpacePosition.z)) <= 0.001f)
  1347.         //  fogFactor += 0.001f;
  1348.  
  1349.         rayDepth += rayIncrement;
  1350.  
  1351.     }
  1352.  
  1353.     // color.rgb = mix(color.rgb, vec3(1.0f) * 0.01f, fogFactor);
  1354.  
  1355.     // vec4 newPosition = surface.screenSpacePosition;
  1356.  
  1357.     // color.rgb = vec3(distance(newPosition.rgb, vec3(0.0f, 0.0f, 0.0f)) * 0.00001f);
  1358.  
  1359. }
  1360.  
  1361. void InitializeAO(inout SurfaceStruct surface)
  1362. {
  1363.     surface.ao.skylight = 1.0f;
  1364.     surface.ao.bouncedSunlight = 1.0f;
  1365.     surface.ao.scatteredUpLight = 1.0f;
  1366.     surface.ao.constant = 1.0f;
  1367. }
  1368.  
  1369. void CalculateAO(inout SurfaceStruct surface)
  1370. {
  1371.     const int numSamples = 20;
  1372.     vec3[numSamples] kernel;
  1373.  
  1374.     vec3 stochastic = texture2D(noisetex, texcoord.st * vec2(viewWidth, viewHeight) / noiseTextureResolution).rgb;
  1375.  
  1376.     //Generate positions for sample points in hemisphere
  1377.     for (int i = 0; i < numSamples; i++)
  1378.     {
  1379.         //Random direction
  1380.         kernel[i] = vec3(texture2D(noisetex, vec2(0.0f + (i * 1.0f) / noiseTextureResolution)).r * 2.0f - 1.0f,
  1381.                          texture2D(noisetex, vec2(0.0f + (i * 1.0f) / noiseTextureResolution)).g * 2.0f - 1.0f,
  1382.                          texture2D(noisetex, vec2(0.0f + (i * 1.0f) / noiseTextureResolution)).b * 2.0f - 1.0f);
  1383.         //kernel[i] += (stochastic * vec3(2.0f, 2.0f, 1.0f) - vec3(1.0f, 1.0f, 0.0f)) * 0.0f;
  1384.         kernel[i] = normalize(kernel[i]);
  1385.  
  1386.         //scale randomly to distribute within hemisphere;
  1387.         kernel[i] *= pow(texture2D(noisetex, vec2(0.3f + (i * 1.0f) / noiseTextureResolution)).r * CalculateNoisePattern1(vec2(43.0f), 64.0f).x * 1.0f, 1.2f);
  1388.     }
  1389.  
  1390.     //Determine origin position and normal
  1391.     vec3 origin = surface.screenSpacePosition.xyz;
  1392.     vec3 normal = surface.normal.xyz;
  1393.          //normal = lightVector;
  1394.  
  1395.     //Create matrix to orient hemisphere according to surface normal
  1396.     //vec3 randomRotation = texture2D(noisetex, texcoord.st * vec2(viewWidth / noiseTextureResolution, viewHeight / noiseTextureResolution)).rgb * 2.0f - 1.0f;
  1397.         //float dither1 = CalculateDitherPattern1() * 2.0f - 1.0f;
  1398.         //randomRotation = vec3(dither1, mod(dither1 + 0.5f, 2.0f), mod(dither1 + 1.0f, 2.0f));
  1399.     vec3    randomRotation = CalculateNoisePattern1(vec2(0.0f), 64.0f).xyz * 2.0f - 1.0f;
  1400.     //vec3  randomRotation = vec3(1.0f, 0.0f, 0.0f);
  1401.  
  1402.  
  1403.     vec3 tangent = normalize(randomRotation - upVector * dot(randomRotation, upVector));
  1404.     vec3 bitangent = cross(upVector, tangent);
  1405.     mat3 tbn = mat3(tangent, bitangent, upVector);
  1406.  
  1407.     float ao = 0.0f;
  1408.     float aoSkylight    = 0.0f;
  1409.     float aoUp          = 0.0f;
  1410.     float aoBounced     = 0.0f;
  1411.     float aoScattered   = 0.0f;
  1412.  
  1413.  
  1414.     float aoRadius   = 0.35f * -surface.screenSpacePosition.z;
  1415.           //aoRadius   = 3.0f;
  1416.     float zThickness = 0.35f * -surface.screenSpacePosition.z;
  1417.           zThickness = 6.0f;
  1418.  
  1419.  
  1420.     vec3    samplePosition      = vec3(0.0f);
  1421.     float   intersect           = 0.0f;
  1422.     vec4    sampleScreenSpace   = vec4(0.0f);
  1423.     float   sampleDepth         = 0.0f;
  1424.     float   distanceWeight      = 0.0f;
  1425.     float   finalRadius         = 0.0f;
  1426.  
  1427.     float skylightWeight = 0.0f;
  1428.     float bouncedWeight  = 0.0f;
  1429.     float scatteredUpWeight = 0.0f;
  1430.     float scatteredSunWeight = 0.0f;
  1431.     vec3 bentNormal = vec3(0.0f);
  1432.  
  1433.     for (int i = 0; i < numSamples; i++)
  1434.     {
  1435.         samplePosition = tbn * kernel[i];
  1436.         samplePosition = samplePosition * aoRadius + origin;
  1437.  
  1438.         intersect = dot(normalize(samplePosition - origin), surface.normal);
  1439.  
  1440.         if (intersect > 0.2f) {
  1441.             //Convert camera space to screen space
  1442.             sampleScreenSpace = gbufferProjection * vec4(samplePosition, 1.0f);
  1443.             sampleScreenSpace.xyz /= sampleScreenSpace.w;
  1444.             sampleScreenSpace.xyz = sampleScreenSpace.xyz * 0.5f + 0.5f;
  1445.  
  1446.             //Check depth at sample point
  1447.             sampleDepth = GetScreenSpacePosition(sampleScreenSpace.xy).z;
  1448.  
  1449.             //If point is behind geometry, buildup AO
  1450.             if (sampleDepth >= samplePosition.z && surface.mask.sky < 0.5f)
  1451.             {
  1452.                 //Reduce halo
  1453.                 float sampleLength = length(samplePosition - origin) * 4.0f;
  1454.                 //distanceWeight = 1.0f - clamp(distance(sampleDepth, origin.z) - (sampleLength * 0.5f), 0.0f, sampleLength * 0.5f) / (sampleLength * 0.5f);
  1455.                 distanceWeight = 1.0f - step(sampleLength, distance(sampleDepth, origin.z));
  1456.  
  1457.                 //Weigh samples based on light direction
  1458.                 skylightWeight          = clamp(dot(normalize(samplePosition - origin), upVector)       * 1.0f - 0.0f , 0.0f, 0.01f) / 0.01f;
  1459.                 //skylightWeight           += clamp(dot(normalize(samplePosition - origin), upVector), 0.0f, 1.0f);
  1460.                 bouncedWeight           = clamp(dot(normalize(samplePosition - origin), -lightVector)   * 1.0f - 0.0f , 0.0f, 0.51f) / 0.51f;
  1461.                 scatteredUpWeight       = clamp(dot(normalize(samplePosition - origin), -upVector)      * 1.0f - 0.0f , 0.0f, 0.51f) / 0.51f;
  1462.                 scatteredSunWeight      = clamp(dot(normalize(samplePosition - origin), lightVector)    * 1.0f - 0.25f, 0.0f, 0.51f) / 0.51f;
  1463.  
  1464.                       //buildup occlusion more for further facing surfaces
  1465.                       skylightWeight            /= clamp(dot(normal, upVector)          * 0.5f + 0.501f, 0.01f, 1.0f);
  1466.                       bouncedWeight             /= clamp(dot(normal, -lightVector)      * 0.5f + 0.501f, 0.01f, 1.0f);
  1467.                       scatteredUpWeight         /= clamp(dot(normal, -upVector)         * 0.5f + 0.501f, 0.01f, 1.0f);
  1468.                       scatteredSunWeight        /= clamp(dot(normal, lightVector)       * 0.75f + 0.25f, 0.01f, 1.0f);
  1469.  
  1470.  
  1471.                 //Accumulate ao
  1472.                 ao          += 2.0f * distanceWeight;
  1473.                 aoSkylight  += 2.0f * distanceWeight * skylightWeight       ;
  1474.                 aoUp        += 2.0f * distanceWeight * scatteredUpWeight    ;
  1475.                 aoBounced   += 2.0f * distanceWeight * bouncedWeight        ;
  1476.                 aoScattered += 2.0f * distanceWeight * scatteredSunWeight   ;
  1477.             } else {
  1478.                 bentNormal.rgb += normalize(samplePosition - origin);
  1479.             }
  1480.         }
  1481.     }
  1482.  
  1483.     bentNormal.rgb /= numSamples;
  1484.  
  1485.     ao          /= numSamples;
  1486.     aoSkylight  /= numSamples;
  1487.     aoUp        /= numSamples;
  1488.     aoBounced   /= numSamples;
  1489.     aoScattered /= numSamples;
  1490.  
  1491.     ao          = 1.0f - ao;
  1492.     aoSkylight  = 1.0f - aoSkylight;
  1493.     aoUp        = 1.0f - aoUp;
  1494.     aoBounced   = 1.0f - aoBounced;
  1495.     aoScattered = 1.0f - aoScattered;
  1496.  
  1497.     ao          = clamp(ao,             0.0f, 1.0f);
  1498.     aoSkylight  = clamp(aoSkylight,     0.0f, 1.0f);
  1499.     aoUp        = clamp(aoUp,           0.0f, 1.0f);
  1500.     aoBounced   = clamp(aoBounced,      0.0f, 1.0f);
  1501.     aoScattered = clamp(aoScattered,    0.0f, 1.0f);
  1502.  
  1503.     surface.ao.constant                 = pow(ao,           1.0f);
  1504.     surface.ao.skylight                 = pow(aoSkylight,   3.0f);
  1505.     surface.ao.bouncedSunlight          = pow(aoBounced,    6.0f);
  1506.     surface.ao.scatteredUpLight         = pow(aoUp,         6.0f);
  1507.     surface.ao.scatteredSunlight        = pow(aoScattered,  1.0f);
  1508.  
  1509.     surface.debug = vec3(pow(aoSkylight, 2.0f) * clamp((dot(surface.normal, upVector) * 0.75f + 0.25f), 0.0f, 1.0f));
  1510.     //surface.debug = vec3(dot(normalize(bentNormal), upVector));
  1511. }
  1512.  
  1513.  
  1514. void    CalculateRainFog(inout vec3 color, in SurfaceStruct surface)
  1515. {
  1516.     vec3 fogColor = colorSkylight * 0.055f;
  1517.  
  1518.     float fogDensity = 0.00018f * rainStrength;
  1519.           fogDensity *= mix(0.0f, 1.0f, pow(eyeBrightnessSmooth.y / 240.0f, 6.0f));
  1520.     float visibility = 1.0f / (pow(exp(distance(surface.screenSpacePosition.xyz, vec3(0.0f)) * fogDensity), 1.0f));
  1521.     float fogFactor = 1.0f - visibility;
  1522.           fogFactor = clamp(fogFactor, 0.0f, 1.0f);
  1523.           fogFactor = mix(fogFactor, 1.0f, (surface.mask.sky) * 0.8f * rainStrength);
  1524.           fogFactor = mix(fogFactor, 1.0f, (surface.mask.clouds) * 0.8f * rainStrength);
  1525.           fogFactor *= mix(1.0f, 0.0f, (surface.mask.sky));
  1526.  
  1527.     color = mix(color, fogColor, vec3(fogFactor));
  1528. }
  1529.  
  1530. void    CalculateAtmosphericScattering(inout vec3 color, in SurfaceStruct surface)
  1531. {
  1532.     // vec3 fogColor = mix(colorSkylight, colorSunlight, vec3(0.05f)) * 0.11f;
  1533.  
  1534.     // float sat = 0.1f;
  1535.     //   fogColor.r = fogColor.r * (1.0f + sat) - (fogColor.g + fogColor.b) * 0.5f * sat;
  1536.     //   fogColor.g = fogColor.g * (1.0f + sat) - (fogColor.r + fogColor.b) * 0.5f * sat;
  1537.     //   fogColor.b = fogColor.b * (1.0f + sat) - (fogColor.r + fogColor.g) * 0.5f * sat;
  1538.  
  1539.     vec3 fogColor = pow(colorSkylight, vec3(1.55f));
  1540.  
  1541.     float sunglow = pow(CalculateSunglow(surface), 2.0f);
  1542.  
  1543.     fogColor *= 1.0 + sunglow;
  1544.  
  1545.     //vec3 sunColor = colorSunlight;
  1546.  
  1547.     //fogColor += mix(vec3(0.0f), sunColor * 10.0f, sunglow * 0.8f);
  1548.  
  1549.     //float fogFactor = pow(surface.linearDepth / 1500.0f, 2.0f);
  1550.     //float fogFactor = 1.0 - exp(-length(surface.screenSpacePosition) * 0.0001);
  1551.     float fogFactor = 1.0 - exp(-pow(length(surface.screenSpacePosition), 2.0) * 0.000001);
  1552.           //fogFactor = mix(fogFactor, 1.0f, float(surface.mask.sky) * 0.8f * rainStrength);
  1553.           //fogFactor = mix(fogFactor, 1.0f, float(surface.mask.clouds) * 0.8f * rainStrength);
  1554.  
  1555.     fogFactor = mix(fogFactor, 0.0f, min(1.0f, surface.sky.sunSpot.r));
  1556.     fogFactor *= mix(1.0f, 0.0f, (surface.mask.sky));
  1557.     fogFactor *= mix(1.0f, 0.75f, (surface.mask.clouds));
  1558.  
  1559.     fogFactor *= pow(eyeBrightnessSmooth.y / 240.0f, 1.0f);
  1560.  
  1561.     // float redshift = 100.5f * (1.0f - rainStrength);
  1562.     //    redshift *= float(!surface.mask.sky);
  1563.  
  1564.     // //scatter away high frequency light
  1565.     // color.b *= 1.0f - clamp(fogFactor * 1.65 * redshift, 0.0f, 0.75f);
  1566.     // color.g *= 1.0f - fogFactor * 0.8* redshift;
  1567.     // color.g *= 1.0f - clamp(fogFactor - 0.26f, 0.0f, 1.0f) * 0.5* redshift;
  1568.  
  1569.     //add scattered low frequency light
  1570.     color += fogColor * fogFactor * 0.00015f * RAYLEIGH_AMOUNT;
  1571.  
  1572. }
  1573.  
  1574.  
  1575. Intersection    RayPlaneIntersectionWorld(in Ray ray, in Plane plane)
  1576. {
  1577.     float rayPlaneAngle = dot(ray.dir, plane.normal);
  1578.  
  1579.     float planeRayDist = 100000000.0f;
  1580.     vec3 intersectionPos = ray.dir * planeRayDist;
  1581.  
  1582.     if (rayPlaneAngle > 0.0001f || rayPlaneAngle < -0.0001f)
  1583.     {
  1584.         planeRayDist = dot((plane.origin), plane.normal) / rayPlaneAngle;
  1585.         intersectionPos = ray.dir * planeRayDist;
  1586.         intersectionPos = -intersectionPos;
  1587.  
  1588.         intersectionPos += cameraPosition.xyz;
  1589.     }
  1590.  
  1591.     Intersection i;
  1592.  
  1593.     i.pos = intersectionPos;
  1594.     i.distance = planeRayDist;
  1595.     i.angle = rayPlaneAngle;
  1596.  
  1597.     return i;
  1598. }
  1599.  
  1600. Intersection    RayPlaneIntersection(in Ray ray, in Plane plane)
  1601. {
  1602.     float rayPlaneAngle = dot(ray.dir, plane.normal);
  1603.  
  1604.     float planeRayDist = 100000000.0f;
  1605.     vec3 intersectionPos = ray.dir * planeRayDist;
  1606.  
  1607.     if (rayPlaneAngle > 0.0001f || rayPlaneAngle < -0.0001f)
  1608.     {
  1609.         planeRayDist = dot((plane.origin - ray.origin), plane.normal) / rayPlaneAngle;
  1610.         intersectionPos = ray.origin + ray.dir * planeRayDist;
  1611.         // intersectionPos = -intersectionPos;
  1612.  
  1613.         // intersectionPos += cameraPosition.xyz;
  1614.     }
  1615.  
  1616.     Intersection i;
  1617.  
  1618.     i.pos = intersectionPos;
  1619.     i.distance = planeRayDist;
  1620.     i.angle = rayPlaneAngle;
  1621.  
  1622.     return i;
  1623. }
  1624.  
  1625. float CubicSmooth(float x)
  1626. {
  1627.     return x * x * (3.0 - 2.0 * x);
  1628. }
  1629.  
  1630. float Get3DNoise(in vec3 pos)
  1631. {
  1632.     pos.z += 0.0f;
  1633.  
  1634.     pos.xyz += 0.5f;
  1635.  
  1636.     vec3 p = floor(pos);
  1637.     vec3 f = fract(pos);
  1638.  
  1639.     // f.x = f.x * f.x * (3.0f - 2.0f * f.x);
  1640.     // f.y = f.y * f.y * (3.0f - 2.0f * f.y);
  1641.     // f.z = f.z * f.z * (3.0f - 2.0f * f.z);
  1642.  
  1643.     vec2 uv =  (p.xy + p.z * vec2(17.0f)) + f.xy;
  1644.     vec2 uv2 = (p.xy + (p.z + 1.0f) * vec2(17.0f)) + f.xy;
  1645.  
  1646.     // uv -= 0.5f;
  1647.     // uv2 -= 0.5f;
  1648.  
  1649.     vec2 coord =  (uv  + 0.5f) / noiseTextureResolution;
  1650.     vec2 coord2 = (uv2 + 0.5f) / noiseTextureResolution;
  1651.     float xy1 = texture2D(noisetex, coord).x;
  1652.     float xy2 = texture2D(noisetex, coord2).x;
  1653.     return mix(xy1, xy2, f.z);
  1654. }
  1655.  
  1656. float GetCoverage(in float coverage, in float density, in float clouds)
  1657. {
  1658.     clouds = clamp(clouds - (1.0f - coverage), 0.0f, 1.0f -density) / (1.0f - density);
  1659.         clouds = max(0.0f, clouds * 1.1f - 0.1f);
  1660.      clouds = clouds = clouds * clouds * (3.0f - 2.0f * clouds);
  1661.      // clouds = pow(clouds, 1.0f);
  1662.     return clouds;
  1663. }
  1664.  
  1665.  
  1666. vec4 CloudColor(in vec4 worldPosition, in float sunglow, in vec3 worldLightVector, in float altitude, in float thickness, const bool isShadowPass)
  1667. {
  1668.  
  1669.     float cloudHeight = altitude;
  1670.     float cloudDepth  = thickness;
  1671.     float cloudUpperHeight = cloudHeight + (cloudDepth / 2.0f);
  1672.     float cloudLowerHeight = cloudHeight - (cloudDepth / 2.0f);
  1673.  
  1674.     //worldPosition.xz /= 1.0f + max(0.0f, length(worldPosition.xz - cameraPosition.xz) / 5000.0f);
  1675.  
  1676.     vec3 p = worldPosition.xyz / 150.0f;
  1677.  
  1678.  
  1679.  
  1680.     float t = frameTimeCounter * 1.0f;
  1681.           t *= 0.5;
  1682.  
  1683.  
  1684.      p += (Get3DNoise(p * 2.0f + vec3(0.0f, t * 0.00f, 0.0f)) * 2.0f - 1.0f) * 0.10f;
  1685.      p.z -= (Get3DNoise(p * 0.25f + vec3(0.0f, t * 0.00f, 0.0f)) * 2.0f - 1.0f) * 0.45f;
  1686.      p.x -= (Get3DNoise(p * 0.125f + vec3(0.0f, t * 0.00f, 0.0f)) * 2.0f - 1.0f) * 3.2f;
  1687.     p.xz -= (Get3DNoise(p * 0.0525f + vec3(0.0f, t * 0.00f, 0.0f)) * 2.0f - 1.0f) * 2.7f;
  1688.  
  1689.  
  1690.     p.x *= 0.5f;
  1691.     p.x -= t * 0.01f;
  1692.  
  1693.     vec3 p1 = p * vec3(1.0f, 0.5f, 1.0f)  + vec3(0.0f, t * 0.01f, 0.0f);
  1694.     float noise  =  Get3DNoise(p * vec3(1.0f, 0.5f, 1.0f) + vec3(0.0f, t * 0.01f, 0.0f));   p *= 2.0f;  p.x -= t * 0.057f;  vec3 p2 = p;
  1695.           noise += (2.0f - abs(Get3DNoise(p) * 2.0f - 0.0f)) * (0.25f);                     p *= 3.0f;  p.xz -= t * 0.035f; p.x *= 2.0f;    vec3 p3 = p;
  1696.           noise += (3.0f - abs(Get3DNoise(p) * 3.0f - 0.0f)) * (0.085f);                        p *= 3.0f;  p.xz -= t * 0.035f; vec3 p4 = p;
  1697.           noise += (3.0f - abs(Get3DNoise(p) * 3.0f - 0.0f)) * (0.035f);                        p *= 3.0f;  p.xz -= t * 0.035f;
  1698.           if (!isShadowPass)
  1699.           {
  1700.                 noise += ((Get3DNoise(p))) * (0.039f);                                              p *= 3.0f;
  1701.                 noise += ((Get3DNoise(p))) * (0.014f);
  1702.           }
  1703.           noise /= 1.575f;
  1704.  
  1705.     //cloud edge
  1706.     float coverage = 0.67f;
  1707.           coverage = mix(coverage, 0.87f, rainStrength);
  1708.  
  1709.           float dist = length(worldPosition.xz - cameraPosition.xz * 0.5);
  1710.           coverage *= max(0.0f, 1.0f - dist / 4000.0f);
  1711.     float density = 0.1f - rainStrength * 0.3;
  1712.  
  1713.     if (isShadowPass)
  1714.     {
  1715.         return vec4(GetCoverage(0.4f, 0.4f, noise));
  1716.     }
  1717.  
  1718.     noise = GetCoverage(coverage, density, noise);
  1719.  
  1720.     const float lightOffset = 0.2f;
  1721.  
  1722.  
  1723.  
  1724.     float sundiff = Get3DNoise(p1 + worldLightVector.xyz * lightOffset);
  1725.           sundiff += (2.0f - abs(Get3DNoise(p2 + worldLightVector.xyz * lightOffset / 2.0f) * 2.0f - 0.0f)) * (0.55f);
  1726.                         float largeSundiff = sundiff;
  1727.                               largeSundiff = -GetCoverage(coverage, 0.0f, largeSundiff * 1.3f);
  1728.           sundiff += (3.0f - abs(Get3DNoise(p3 + worldLightVector.xyz * lightOffset / 5.0f) * 3.0f - 0.0f)) * (0.045f);
  1729.           sundiff += (3.0f - abs(Get3DNoise(p4 + worldLightVector.xyz * lightOffset / 8.0f) * 3.0f - 0.0f)) * (0.015f);
  1730.           sundiff /= 1.5f;
  1731.           sundiff = -GetCoverage(coverage * 1.0f, 0.0f, sundiff);
  1732.     float secondOrder   = pow(clamp(sundiff * 1.1f + 1.45f, 0.0f, 1.0f), 7.0f);
  1733.     float firstOrder    = pow(clamp(largeSundiff * 1.1f + 1.66f, 0.0f, 1.0f), 3.0f);
  1734.  
  1735.  
  1736.  
  1737.     float directLightFalloff = firstOrder * secondOrder;
  1738.     float anisoBackFactor = mix(clamp(pow(noise, 1.6f) * 2.5f, 0.0f, 1.0f), 1.0f, pow(sunglow, 1.0f));
  1739.  
  1740.           directLightFalloff *= anisoBackFactor;
  1741.           directLightFalloff *= mix(11.5f, 1.0f, pow(sunglow, 0.5f));
  1742.  
  1743.  
  1744.  
  1745.     vec3 colorDirect = colorSunlight * 0.215f;
  1746.          colorDirect = mix(colorDirect, colorDirect * vec3(0.2f, 0.5f, 1.0f), timeMidnight);
  1747.          colorDirect *= 1.0f + pow(sunglow, 2.0f) * 600.0f * pow(directLightFalloff, 1.1f) * (1.0f - rainStrength);
  1748.          colorDirect *= 1.0f + rainStrength * 3.25;
  1749.  
  1750.  
  1751.     vec3 colorAmbient = mix(colorSkylight, colorSunlight * 2.0f, vec3(0.15f)) * 0.03f;
  1752.          colorAmbient *= mix(1.0f, 0.3f, timeMidnight);
  1753.          colorAmbient = mix(colorAmbient, colorAmbient * 3.0f + colorSunlight * 0.05f, vec3(clamp(pow(1.0f - noise, 12.0f) * 1.0f, 0.0f, 1.0f)));
  1754.  
  1755.  
  1756.     directLightFalloff *= 2.0f;
  1757.  
  1758.     directLightFalloff *= mix(1.0, 0.125, rainStrength);
  1759.  
  1760.     //directLightFalloff += (pow(Get3DNoise(p3), 2.0f) * 0.5f + pow(Get3DNoise(p3 * 1.5f), 2.0f) * 0.25f) * 0.02f;
  1761.     //directLightFalloff *= Get3DNoise(p2);
  1762.  
  1763.     vec3 color = mix(colorAmbient, colorDirect, vec3(min(1.0f, directLightFalloff)));
  1764.  
  1765.     color *= 1.0f;
  1766.  
  1767.     color = mix(color, color * 0.9, rainStrength);
  1768.  
  1769.  
  1770.     vec4 result = vec4(color.rgb, noise);
  1771.  
  1772.     return result;
  1773.  
  1774. }
  1775.  
  1776. float pcurve(float x, float a, float b)
  1777. {
  1778.     float k = pow(a+b, a+b) / (pow(a,a)*pow(b,b));
  1779.     return k * pow(x, a) * pow(1.0 - x, b);
  1780. }
  1781.  
  1782. vec4 CloudColor2(in vec4 worldPosition, in float sunglow, in vec3 worldLightVector, in float altitude, in float heightFactor, const bool isShadowPass)
  1783. {
  1784.  
  1785.     //worldPosition.xz /= 1.0f + max(0.0f, length(worldPosition.xz - cameraPosition.xz) / 5000.0f);
  1786.  
  1787.     vec3 p = worldPosition.xyz / 130.0f;
  1788.  
  1789.  
  1790.     float t = frameTimeCounter * 1.0f;
  1791.           t *= 0.05;
  1792.           //t *= 0.00;
  1793.  
  1794.  
  1795.     //  p += (Get3DNoise(p * 2.0f + vec3(0.0f, t * 0.01f, 0.0f)) * 2.0f - 1.0f) * 0.1f;
  1796.     //  p.z -= (Get3DNoise(p * 0.25f + vec3(0.0f, t * 0.01f, 0.0f)) * 2.0f - 1.0f) * 0.5f;
  1797.     //  p.x -= (Get3DNoise(p * 0.125f + vec3(0.0f, t * 0.01f, 0.0f)) * 2.0f - 1.0f) * 1.2f;
  1798.     // p.xz -= (Get3DNoise(p * 0.0525f + vec3(0.0f, t * 0.01f, 0.0f)) * 2.0f - 1.0f) * 1.7f;
  1799.  
  1800.  
  1801.     p.x *= 0.5f;
  1802.     p.x -= t * 0.01f;
  1803.  
  1804.     vec3 p1 = p * vec3(1.0f, 0.5f, 1.0f)  + vec3(0.0f, t * 0.01f, 0.0f);
  1805.  
  1806.     float noise  =  Get3DNoise(p * vec3(1.0f, 0.5f, 1.0f) + vec3(0.0f, t * 0.01f, 0.0f)) * 1.3;     p *= 2.0f;  p.x -= t * 0.557f;  vec3 p2 = p;   
  1807.           noise += (2.0f - abs(Get3DNoise(p) * 2.0f - 0.0f)) * (0.35f);                             p *= 3.0f;  p.xz -= t * 0.905f; p.x *= 2.0f;    vec3 p3 = p;    float largeNoise = noise;
  1808.           noise += (3.0f - abs(Get3DNoise(p) * 3.0f - 0.0f)) * (0.085f);                            p *= 3.0f;  p.xz -= t * 3.905f; vec3 p4 = p;
  1809.           noise += (3.0f - abs(Get3DNoise(p) * 3.0f - 0.0f)) * (0.035f);                            p *= 3.0f;  p.xz -= t * 3.905f;
  1810.           noise += ((Get3DNoise(p))) * (0.04f);                                             p *= 3.0f;
  1811.           noise /= 2.375f;
  1812.  
  1813. //WEIFUIWEF
  1814.     //cloud height coverage falloff
  1815.  
  1816.     //cloud edge
  1817.     float coverage = 0.5f;
  1818.           coverage = mix(coverage, 0.87f, rainStrength);
  1819.  
  1820.           float dist = length(worldPosition.xz - cameraPosition.xz * 0.5) * 0.5;
  1821.           coverage *= max(0.0f, 1.0f - dist / 4000.0f);
  1822.     float density = 0.71f - rainStrength * 0.3;
  1823.  
  1824.     noise = GetCoverage(coverage, density, noise);
  1825.  
  1826.     const float lightOffset = 0.2f;
  1827.  
  1828.     noise *= pcurve(heightFactor, 0.5, 2.5) * saturate(heightFactor * 8.0 - 1.0);
  1829.     //noise *= heightFactor;
  1830.  
  1831.     if (noise < 0.0001)
  1832.     {
  1833.         return vec4(0.0, 0.0, 0.0, 0.0);
  1834.     }
  1835.  
  1836.  
  1837.     float sundiff = Get3DNoise(p1 + worldLightVector.xyz * lightOffset) * 1.3;
  1838.           sundiff += (2.0f - abs(Get3DNoise(p2 + worldLightVector.xyz * lightOffset / 2.0f) * 2.0f - 0.0f)) * (0.35f);
  1839.                         float largeSundiff = sundiff;
  1840.                               largeSundiff = -GetCoverage(coverage, 0.0f, largeSundiff * 1.3f);
  1841.           // sundiff += (3.0f - abs(Get3DNoise(p3 + worldLightVector.xyz * lightOffset / 5.0f) * 3.0f - 0.0f)) * (0.035f);
  1842.           // sundiff += (3.0f - abs(Get3DNoise(p4 + worldLightVector.xyz * lightOffset / 8.0f) * 3.0f - 0.0f)) * (0.015f);
  1843.           sundiff /= 1.1f;
  1844.           sundiff *= max(0.0f, 1.0f - dist / 10000.0f);
  1845.           sundiff = -GetCoverage(coverage * 1.1f, -0.2f, sundiff);
  1846.           //sundiff *= pow(cos((heightFactor * 2.0 - 1.0) * 3.14159265 * 0.5) * 0.5 + 0.5, 0.8);
  1847.           //sundiff *= pcurve(max(0.0, heightFactor - worldLightVector.y * 0.1 - 0.05) * 0.5, 0.5, 1.5);
  1848.           sundiff *= pow(saturate(heightFactor * 1.5), 1.0);
  1849.           sundiff *= mix(1.0, pow(saturate((1.0 - heightFactor) * (1.0 + largeNoise * 1.0)), 1.0), 0.6);
  1850.     float secondOrder   = pow(clamp(sundiff * 1.0f + 1.2f, 0.0f, 1.0f), 2.7f);
  1851.     float firstOrder    = pow(clamp(sundiff * 0.9f + 1.1f, 0.0f, 1.0f), 13.0f);
  1852.     float thirdOrder    = pow(clamp(-largeNoise * 1.0 + 2.0, 0.0, 3.0), 1.0);
  1853.  
  1854.  
  1855.  
  1856.     float directLightFalloff = mix(firstOrder * 2.0, secondOrder * 3.0, 0.15);
  1857.     float anisoBackFactor = mix(clamp(pow(noise, 1.3f) * 7.5f, 0.0f, 2.0f), 1.0f, pow(sunglow, 1.0f));
  1858.  
  1859.           directLightFalloff *= anisoBackFactor * 0.8 + 0.2;
  1860.           //directLightFalloff *= mix(11.5f, 1.0f, pow(sunglow, 0.5f));
  1861.  
  1862.          //directLightFalloff *= 0.5 + pow(1.0 - noise, 18.0) * 0.9;
  1863.  
  1864.  
  1865.  
  1866.     vec3 colorDirect = colorSunlight * 0.215f;
  1867.          colorDirect = mix(colorDirect, colorDirect * vec3(0.2f, 0.5f, 1.0f), timeMidnight);
  1868.          //colorDirect *= 1.0f + pow(sunglow, 2.0f) * 300.0f * pow(directLightFalloff, 1.1f) * (1.0f - rainStrength);
  1869.          //colorDirect *= 1.0f + rainStrength * 3.25;
  1870.          colorDirect *= 1.0 + 115.0 * pow((1.0 - noise), 5.0) * firstOrder * firstOrder * pow(sunglow, 1.0) * (1.0 - rainStrength);
  1871.  
  1872.  
  1873.     vec3 colorAmbient = mix(colorSkylight, colorSunlight * 2.0f, vec3(0.15f)) * 0.03f;
  1874.          colorAmbient *= mix(1.0f, 0.3f, timeMidnight);
  1875.          colorAmbient *= mix(1.0, 0.1, heightFactor);
  1876.          //colorAmbient = mix(colorAmbient, colorAmbient * 8.0f + colorSunlight * 0.0f, vec3(clamp(pow(1.0f - noise, 12.0f) * 1.0f, 0.0f, 1.0f)));
  1877.          //colorAmbient *= thirdOrder;
  1878.          //colorAmbient *= 0.0;
  1879.          //colorAmbient += colorSunlight * pow(thirdOrder, 3.0) * 0.02;
  1880.  
  1881.     //directLightFalloff *= 1.0f;
  1882.  
  1883.     directLightFalloff *= mix(1.0, 0.175, rainStrength);
  1884.  
  1885.     //directLightFalloff += (pow(Get3DNoise(p3), 2.0f) * 0.5f + pow(Get3DNoise(p3 * 1.5f), 2.0f) * 0.25f) * 0.02f;
  1886.     //directLightFalloff *= Get3DNoise(p2);
  1887.  
  1888.     vec3 color = mix(colorAmbient, colorDirect, vec3(min(1.0f, directLightFalloff)));
  1889.  
  1890.     //color = colorAmbient;
  1891.  
  1892.     color *= 1.0f;
  1893.  
  1894.     color = mix(color, color * 0.9, rainStrength);
  1895.  
  1896.     vec4 result = vec4(color.rgb, noise);
  1897.  
  1898.     return result;
  1899.  
  1900. }
  1901.  
  1902. void CloudPlane(SurfaceStruct surface, inout vec3 color)
  1903. {
  1904.     //Initialize view ray
  1905.     vec4 worldVector = gbufferModelViewInverse * (vec4(-GetScreenSpacePosition(texcoord.st).xyz, 0.0));
  1906.  
  1907.     surface.viewRay.dir = normalize(worldVector.xyz);
  1908.     surface.viewRay.origin = vec3(0.0f);
  1909.  
  1910.     float sunglow = CalculateSunglow(surface);
  1911.  
  1912.  
  1913.  
  1914.     float cloudsAltitude = 540.0f;
  1915.     float cloudsThickness = 150.0f;
  1916.  
  1917.     float cloudsUpperLimit = cloudsAltitude + cloudsThickness * 0.5f;
  1918.     float cloudsLowerLimit = cloudsAltitude - cloudsThickness * 0.5f;
  1919.  
  1920.     float density = 1.0f;
  1921.  
  1922.     float planeHeight = cloudsUpperLimit;
  1923.     float stepSize = 25.5f;
  1924.     planeHeight -= cloudsThickness * 0.85f;
  1925.  
  1926.  
  1927.     Plane pl;
  1928.     pl.origin = vec3(0.0f, cameraPosition.y - planeHeight, 0.0f);
  1929.     pl.normal = vec3(0.0f, 1.0f, 0.0f);
  1930.  
  1931.     Intersection i = RayPlaneIntersectionWorld(surface.viewRay, pl);
  1932.  
  1933.     vec3 original = color.rgb;
  1934.  
  1935.     if (i.angle < 0.0f)
  1936.     {
  1937.         if (i.distance < surface.linearDepth || surface.mask.sky > 0.5)
  1938.         {
  1939.             vec4 cloudSample = CloudColor(vec4(i.pos.xyz * 0.5f + vec3(30.0f) + vec3(1000.0, 0.0, 0.0), 1.0f), sunglow, surface.worldLightVector, cloudsAltitude, cloudsThickness, false);
  1940.                  cloudSample.a = min(1.0f, cloudSample.a * density);
  1941.  
  1942.  
  1943.             color.rgb = mix(color.rgb, cloudSample.rgb * 1.0f, cloudSample.a);
  1944.  
  1945.         }
  1946.     }
  1947. }
  1948.  
  1949. void VolumeClouds(inout SurfaceStruct surface, inout vec3 color)
  1950. {
  1951.     //Initialize view ray
  1952.     vec4 worldVector = gbufferModelViewInverse * (vec4(-GetScreenSpacePosition(texcoord.st).xyz, 0.0));
  1953.  
  1954.     surface.viewRay.dir = normalize(worldVector.xyz);
  1955.     surface.viewRay.origin = vec3(0.0f);
  1956.  
  1957.     float sunglow = CalculateSunglow(surface);
  1958.  
  1959.  
  1960.  
  1961.     float cloudsAltitude = 540.0f;
  1962.  
  1963.     #ifdef HQ_VOLUMETRIC_CLOUDS
  1964.     float cloudsThickness = 120.0f;
  1965.     #else
  1966.     float cloudsThickness = 120.0f;
  1967.     #endif
  1968.  
  1969.     float cloudsUpperLimit = cloudsAltitude + cloudsThickness * 0.5f;
  1970.     float cloudsLowerLimit = cloudsAltitude - cloudsThickness * 0.5f;
  1971.  
  1972.     float density = 3.0f;
  1973.  
  1974.     float planeHeight = cloudsAltitude;
  1975.     //float stepSize = 25.5f;
  1976.     //planeHeight -= cloudsThickness * 0.85f;
  1977.  
  1978.  
  1979.     float alphaAccum = 1.0;
  1980.  
  1981.  
  1982.     vec3 original = color.rgb;
  1983.  
  1984.     #ifdef HQ_VOLUMETRIC_CLOUDS
  1985.     const int numSamples = 20;
  1986.     #else
  1987.     const int numSamples = 10;
  1988.     #endif
  1989.  
  1990.     float dither = CalculateDitherPattern1();
  1991.  
  1992.     planeHeight -= dither * (cloudsThickness / numSamples);
  1993.  
  1994.     float heightFactor = 0.0 + dither / numSamples;
  1995.  
  1996.     for (int j = 0; j < numSamples; j++)
  1997.     {
  1998.         Plane pl;
  1999.         pl.origin = vec3(0.0f, cameraPosition.y - planeHeight, 0.0f);
  2000.         pl.normal = vec3(0.0f, 1.0f, 0.0f);
  2001.  
  2002.         Intersection i = RayPlaneIntersectionWorld(surface.viewRay, pl);
  2003.  
  2004.         if (i.angle < 0.0f)
  2005.         {
  2006.             if (i.distance < surface.linearDepth || surface.mask.sky > 0.5)
  2007.             {
  2008.                 vec4 cloudSample = CloudColor2(vec4(i.pos.xyz * 0.5f + vec3(30.0f), 1.0f), sunglow, surface.worldLightVector, cloudsAltitude, heightFactor, false);
  2009.                      cloudSample.a = min(1.0f, cloudSample.a * density);
  2010.  
  2011.                 alphaAccum *= cloudSample.a;
  2012.  
  2013.                 color.rgb = mix(color.rgb, cloudSample.rgb * 1.0f, cloudSample.a);
  2014.  
  2015.                 // cloudSample = CloudColor2(vec4(i.pos.xyz * 0.65f + vec3(10.0f) + vec3(i.pos.z * 0.5f, 0.0f, 330.0f), 1.0f), sunglow, surface.worldLightVector, cloudsAltitude, cloudsThickness, false);
  2016.                 // cloudSample.a = min(1.0f, cloudSample.a * density);
  2017.  
  2018.                 // surface.color.rgb = mix(surface.color.rgb, cloudSample.rgb * 0.001f, cloudSample.a);
  2019.  
  2020.             }
  2021.         }
  2022.  
  2023.         planeHeight -= cloudsThickness / numSamples;
  2024.         heightFactor += 1.0 / numSamples;
  2025.     }
  2026.  
  2027.     surface.cloudAlpha = 1.0 - alphaAccum;
  2028.  
  2029.     //color.rgb = mix(color.rgb, original, surface.cloudAlpha);
  2030. }
  2031.  
  2032. float CloudShadow(in SurfaceStruct surface)
  2033. {
  2034.     float cloudsAltitude = 540.0f;
  2035.     float cloudsThickness = 150.0f;
  2036.  
  2037.     float cloudsUpperLimit = cloudsAltitude + cloudsThickness * 0.5f;
  2038.     float cloudsLowerLimit = cloudsAltitude - cloudsThickness * 0.5f;
  2039.  
  2040.     float planeHeight = cloudsUpperLimit;
  2041.  
  2042.     planeHeight -= cloudsThickness * 0.85f;
  2043.  
  2044.     Plane pl;
  2045.     pl.origin = vec3(0.0f, planeHeight, 0.0f);
  2046.     pl.normal = vec3(0.0f, 1.0f, 0.0f);
  2047.  
  2048.     //Cloud shadow
  2049.     Ray surfaceToSun;
  2050.     vec4 sunDir = gbufferModelViewInverse * vec4(surface.lightVector, 0.0f);
  2051.     surfaceToSun.dir = normalize(sunDir.xyz);
  2052.     vec4 surfacePos = gbufferModelViewInverse * surface.screenSpacePosition;
  2053.     surfaceToSun.origin = surfacePos.xyz + cameraPosition.xyz;
  2054.  
  2055.     Intersection i = RayPlaneIntersection(surfaceToSun, pl);
  2056.  
  2057.     float cloudShadow = CloudColor2(vec4(i.pos.xyz * 0.5f + vec3(30.0f), 1.0f), 0.0f, vec3(1.0f), cloudsAltitude, cloudsThickness, true).x;
  2058.           cloudShadow += CloudColor2(vec4(i.pos.xyz * 0.65f + vec3(10.0f) + vec3(i.pos.z * 0.5f, 0.0f, 0.0f), 1.0f), 0.0f, vec3(1.0f), cloudsAltitude, cloudsThickness, true).x;
  2059.  
  2060.           cloudShadow = min(cloudShadow, 1.0f);
  2061.           cloudShadow = 1.0f - cloudShadow;
  2062.  
  2063.     return cloudShadow;
  2064.     // return 1.0f;
  2065. }
  2066.  
  2067.  
  2068.  
  2069. void    SnowShader(inout SurfaceStruct surface)
  2070. {
  2071.     float snowFactor = dot(surface.normal, upVector);
  2072.           snowFactor = clamp(snowFactor - 0.1f, 0.0f, 0.05f) / 0.05f;
  2073.     surface.albedo = mix(surface.albedo.rgb, vec3(1.0f), vec3(snowFactor));
  2074. }
  2075.  
  2076. void    Test(inout vec3 color, inout SurfaceStruct surface)
  2077. {
  2078.     vec4 rayScreenSpace = GetScreenSpacePosition(texcoord.st, 1.0f);
  2079.          rayScreenSpace = -rayScreenSpace;
  2080.          rayScreenSpace = gbufferModelViewInverse * rayScreenSpace;
  2081.  
  2082.     float planeAltitude = 100.0f;
  2083.  
  2084.     vec3 rayDir = normalize(rayScreenSpace.xyz);
  2085.     vec3 planeOrigin = vec3(0.0f, 1.0f, 0.0f);
  2086.     vec3 planeNormal = vec3(0.0f, 1.0f, 0.0f);
  2087.     vec3 rayOrigin = vec3(0.0f);
  2088.  
  2089.     float denom = dot(rayDir, planeNormal);
  2090.  
  2091.     vec3 intersectionPos = vec3(0.0f);
  2092.  
  2093.     if (denom > 0.0001f || denom < -0.0001f)
  2094.     {
  2095.         float planeRayDist = dot((planeOrigin - rayOrigin), planeNormal) / denom;   //How far along the ray that the ray intersected with the plane
  2096.  
  2097.         //if (planeRayDist > 0.0f)
  2098.         intersectionPos = rayDir * planeRayDist;
  2099.         intersectionPos = -intersectionPos;
  2100.  
  2101.         intersectionPos.xz *= cameraPosition.y - 100.0f;
  2102.  
  2103.         intersectionPos += cameraPosition.xyz;
  2104.  
  2105.         intersectionPos.x = mod(intersectionPos.x, 1.0f);
  2106.         intersectionPos.y = mod(intersectionPos.y, 1.0f);
  2107.         intersectionPos.z = mod(intersectionPos.z, 1.0f);
  2108.     }
  2109.  
  2110.  
  2111.     color += intersectionPos.xyz * 0.1f;
  2112. }
  2113.  
  2114. vec3 Contrast(in vec3 color, in float contrast)
  2115. {
  2116.     float colorLength = length(color);
  2117.     vec3 nColor = color / colorLength;
  2118.  
  2119.     colorLength = pow(colorLength, contrast);
  2120.  
  2121.     return nColor * colorLength;
  2122. }
  2123.  
  2124. float GetAO(in vec4 screenSpacePosition, in vec3 normal, in vec2 coord, in vec3 dither)
  2125. {
  2126.     //Determine origin position
  2127.     vec3 origin = screenSpacePosition.xyz;
  2128.  
  2129.     vec3 randomRotation = normalize(dither.xyz * vec3(2.0f, 2.0f, 1.0f) - vec3(1.0f, 1.0f, 0.0f));
  2130.  
  2131.     vec3 tangent = normalize(randomRotation - normal * dot(randomRotation, normal));
  2132.     vec3 bitangent = cross(normal, tangent);
  2133.     mat3 tbn = mat3(tangent, bitangent, normal);
  2134.  
  2135.     float aoRadius   = 0.15f * -screenSpacePosition.z;
  2136.           //aoRadius   = 0.8f;
  2137.     float zThickness = 0.15f * -screenSpacePosition.z;
  2138.           //zThickness = 2.2f;
  2139.  
  2140.     vec3    samplePosition      = vec3(0.0f);
  2141.     float   intersect           = 0.0f;
  2142.     vec4    sampleScreenSpace   = vec4(0.0f);
  2143.     float   sampleDepth         = 0.0f;
  2144.     float   distanceWeight      = 0.0f;
  2145.     float   finalRadius         = 0.0f;
  2146.  
  2147.     int numRaysPassed = 0;
  2148.  
  2149.     float ao = 0.0f;
  2150.  
  2151.     for (int i = 0; i < 4; i++)
  2152.     {
  2153.         vec3 kernel = vec3(texture2D(noisetex, vec2(0.1f + (i * 1.0f) / 64.0f)).r * 2.0f - 1.0f,
  2154.                          texture2D(noisetex, vec2(0.1f + (i * 1.0f) / 64.0f)).g * 2.0f - 1.0f,
  2155.                          texture2D(noisetex, vec2(0.1f + (i * 1.0f) / 64.0f)).b * 1.0f);
  2156.              kernel = normalize(kernel);
  2157.              kernel *= pow(dither.x + 0.01f, 1.0f);
  2158.  
  2159.         samplePosition = tbn * kernel;
  2160.         samplePosition = samplePosition * aoRadius + origin;
  2161.  
  2162.             sampleScreenSpace = gbufferProjection * vec4(samplePosition, 0.0f);
  2163.             sampleScreenSpace.xyz /= sampleScreenSpace.w;
  2164.             sampleScreenSpace.xyz = sampleScreenSpace.xyz * 0.5f + 0.5f;
  2165.  
  2166.             //Check depth at sample point
  2167.             sampleDepth = GetScreenSpacePosition(sampleScreenSpace.xy).z;
  2168.  
  2169.             //If point is behind geometry, buildup AO
  2170.             if (sampleDepth >= samplePosition.z && sampleDepth - samplePosition.z < zThickness)
  2171.             {
  2172.                 ao += 1.0f;
  2173.             } else {
  2174.  
  2175.             }
  2176.     }
  2177.     ao /= 4;
  2178.     ao = 1.0f - ao;
  2179.     ao = pow(ao, 2.1f);
  2180.  
  2181.     return ao;
  2182. }
  2183.  
  2184. vec4 BilateralUpsample(const in float scale, in vec2 offset, in float depth, in vec3 normal)
  2185. {
  2186.     vec2 recipres = vec2(1.0f / viewWidth, 1.0f / viewHeight);
  2187.  
  2188.     vec4 light = vec4(0.0f);
  2189.     float weights = 0.0f;
  2190.  
  2191.     for (float i = -0.5f; i <= 0.5f; i += 1.0f)
  2192.     {
  2193.         for (float j = -0.5f; j <= 0.5f; j += 1.0f)
  2194.         {
  2195.             vec2 coord = vec2(i, j) * recipres * 2.0f;
  2196.  
  2197.             float sampleDepth = GetDepthLinear(texcoord.st + coord * 2.0f * (exp2(scale)));
  2198.             vec3 sampleNormal = GetNormals(texcoord.st + coord * 2.0f * (exp2(scale)));
  2199.             //float weight = 1.0f / (pow(abs(sampleDepth - depth) * 1000.0f, 2.0f) + 0.001f);
  2200.             float weight = clamp(1.0f - abs(sampleDepth - depth) / 2.0f, 0.0f, 1.0f);
  2201.                   weight *= max(0.0f, dot(sampleNormal, normal) * 2.0f - 1.0f);
  2202.             //weight = 1.0f;
  2203.  
  2204.             light +=    pow(texture2DLod(gaux1, (texcoord.st) * (1.0f / exp2(scale )) +     offset + coord, 1), vec4(2.2f, 2.2f, 2.2f, 1.0f)) * weight;
  2205.  
  2206.             weights += weight;
  2207.         }
  2208.     }
  2209.  
  2210.  
  2211.     light /= max(0.00001f, weights);
  2212.  
  2213.     if (weights < 0.01f)
  2214.     {
  2215.         light = pow(texture2DLod(gaux1, (texcoord.st) * (1.0f / exp2(scale  )) +    offset, 2), vec4(2.2f, 2.2f, 2.2f, 1.0f));
  2216.     }
  2217.  
  2218.  
  2219.     // vec3 light = texture2DLod(gcolor, (texcoord.st) * (1.0f / pow(2.0f,  scale   )) +    offset, 2).rgb;
  2220.  
  2221.  
  2222.     return light;
  2223. }
  2224.  
  2225. vec4 Delta(vec3 albedo, vec3 normal, float skylight)
  2226. {
  2227.     float depth = GetDepthLinear(texcoord.st);
  2228.  
  2229.     vec4 delta = BilateralUpsample(GI_RENDER_RESOLUTION, vec2(0.0f, 0.0f),      depth, normal);
  2230.  
  2231.     delta.rgb = delta.rgb * albedo * colorSunlight;
  2232.  
  2233.     delta.rgb *= 1.0f;
  2234.  
  2235.     delta.rgb *= 3.0f * delta.a * (1.0 - rainStrength) * pow(skylight, 0.05);
  2236.  
  2237.     // delta.rgb *= sin(frameTimeCounter) > 0.6 ? 0.0 : 1.0;
  2238.  
  2239.     return delta;
  2240. }
  2241.  
  2242. vec4 textureSmooth(in sampler2D tex, in vec2 coord)
  2243. {
  2244.     vec2 res = vec2(64.0f, 64.0f);
  2245.  
  2246.     coord *= res;
  2247.     coord += 0.5f;
  2248.  
  2249.     vec2 whole = floor(coord);
  2250.     vec2 part  = fract(coord);
  2251.  
  2252.     part.x = part.x * part.x * (3.0f - 2.0f * part.x);
  2253.     part.y = part.y * part.y * (3.0f - 2.0f * part.y);
  2254.     // part.x = 1.0f - (cos(part.x * 3.1415f) * 0.5f + 0.5f);
  2255.     // part.y = 1.0f - (cos(part.y * 3.1415f) * 0.5f + 0.5f);
  2256.  
  2257.     coord = whole + part;
  2258.  
  2259.     coord -= 0.5f;
  2260.     coord /= res;
  2261.  
  2262.     return texture2D(tex, coord);
  2263. }
  2264.  
  2265. float AlmostIdentity(in float x, in float m, in float n)
  2266. {
  2267.     if (x > m) return x;
  2268.  
  2269.     float a = 2.0f * n - m;
  2270.     float b = 2.0f * m - 3.0f * n;
  2271.     float t = x / m;
  2272.  
  2273.     return (a * t + b) * t * t + n;
  2274. }
  2275.  
  2276.  
  2277. float GetWaves(vec3 position) {
  2278.     float speed = 0.9f;
  2279.  
  2280.   vec2 p = position.xz / 20.0f;
  2281.  
  2282.   p.xy -= position.y / 20.0f;
  2283.  
  2284.   p.x = -p.x;
  2285.  
  2286.   p.x += (frameTimeCounter / 40.0f) * speed;
  2287.   p.y -= (frameTimeCounter / 40.0f) * speed;
  2288.  
  2289.   float weight = 1.0f;
  2290.   float weights = weight;
  2291.  
  2292.   float allwaves = 0.0f;
  2293.  
  2294.   float wave = 0.0;
  2295.     //wave = textureSmooth(noisetex, (p * vec2(2.0f, 1.2f))  + vec2(0.0f,  p.x * 2.1f) ).x;
  2296.     p /= 2.1f;  /*p *= pow(2.0f, 1.0f);*/   p.y -= (frameTimeCounter / 20.0f) * speed; p.x -= (frameTimeCounter / 30.0f) * speed;
  2297.   //allwaves += wave;
  2298.  
  2299.   weight = 4.1f;
  2300.   weights += weight;
  2301.       wave = textureSmooth(noisetex, (p * vec2(2.0f, 1.4f))  + vec2(0.0f,  -p.x * 2.1f) ).x;
  2302.             p /= 1.5f;/*p *= pow(2.0f, 2.0f);*/     p.x += (frameTimeCounter / 20.0f) * speed;
  2303.       wave *= weight;
  2304.   allwaves += wave;
  2305.  
  2306.   weight = 17.25f;
  2307.   weights += weight;
  2308.       wave = (textureSmooth(noisetex, (p * vec2(1.0f, 0.75f))  + vec2(0.0f,  p.x * 1.1f) ).x);      p /= 1.5f;  p.x -= (frameTimeCounter / 55.0f) * speed;
  2309.       wave *= weight;
  2310.   allwaves += wave;
  2311.  
  2312.   weight = 15.25f;
  2313.   weights += weight;
  2314.       wave = (textureSmooth(noisetex, (p * vec2(1.0f, 0.75f))  + vec2(0.0f,  -p.x * 1.7f) ).x);     p /= 1.9f;  p.x += (frameTimeCounter / 155.0f) * speed;
  2315.       wave *= weight;
  2316.   allwaves += wave;
  2317.  
  2318.   weight = 29.25f;
  2319.   weights += weight;
  2320.       wave = abs(textureSmooth(noisetex, (p * vec2(1.0f, 0.8f))  + vec2(0.0f,  -p.x * 1.7f) ).x * 2.0f - 1.0f);     p /= 2.0f;  p.x += (frameTimeCounter / 155.0f) * speed;
  2321.       wave = 1.0f - AlmostIdentity(wave, 0.2f, 0.1f);
  2322.       wave *= weight;
  2323.   allwaves += wave;
  2324.  
  2325.   weight = 15.25f;
  2326.   weights += weight;
  2327.       wave = abs(textureSmooth(noisetex, (p * vec2(1.0f, 0.8f))  + vec2(0.0f,  p.x * 1.7f) ).x * 2.0f - 1.0f);
  2328.       wave = 1.0f - AlmostIdentity(wave, 0.2f, 0.1f);
  2329.       wave *= weight;
  2330.   allwaves += wave;
  2331.  
  2332.   allwaves /= weights;
  2333.  
  2334.   return allwaves;
  2335. }
  2336.  
  2337.  
  2338. vec3 GetWavesNormal(vec3 position) {
  2339.  
  2340.     vec2 coord = position.xz / 50.0;
  2341.     coord.xy -= position.y / 50.0;
  2342.     coord -= floor(coord);
  2343.  
  2344.     vec3 normal;
  2345.     normal.xy = texture2DLod(gaux3, coord, 1).xy * 2.0 - 1.0;
  2346.     normal.z = sqrt(1.0 - dot(normal.xy, normal.xy));
  2347.  
  2348.     return normal;
  2349.  
  2350. /*
  2351.     float WAVE_HEIGHT = 1.5;
  2352.  
  2353.     const float sampleDistance = 3.0f;
  2354.  
  2355.     position -= vec3(0.005f, 0.0f, 0.005f) * sampleDistance;
  2356.  
  2357.     float wavesCenter = GetWaves(position);
  2358.     float wavesLeft = GetWaves(position + vec3(0.01f * sampleDistance, 0.0f, 0.0f));
  2359.     float wavesUp   = GetWaves(position + vec3(0.0f, 0.0f, 0.01f * sampleDistance));
  2360.  
  2361.     vec3 wavesNormal;
  2362.          wavesNormal.r = wavesCenter - wavesLeft;
  2363.          wavesNormal.g = wavesCenter - wavesUp;
  2364.  
  2365.          wavesNormal.r *= 30.0f * WAVE_HEIGHT / sampleDistance;
  2366.          wavesNormal.g *= 30.0f * WAVE_HEIGHT / sampleDistance;
  2367.  
  2368.         //  wavesNormal.b = sqrt(1.0f - wavesNormal.r * wavesNormal.r - wavesNormal.g * wavesNormal.g);
  2369.          wavesNormal.b = 1.0;
  2370.          wavesNormal.rgb = normalize(wavesNormal.rgb);
  2371.  
  2372.  
  2373.  
  2374.     return wavesNormal.rgb;
  2375.     */
  2376. }
  2377.  
  2378.  
  2379. vec3 FakeRefract(vec3 vector, vec3 normal, float ior)
  2380. {
  2381.     return refract(vector, normal, ior);
  2382.     //return vector + normal * 0.5;
  2383. }
  2384.  
  2385.  
  2386. float CalculateWaterCaustics(SurfaceStruct surface, ShadingStruct shading)
  2387. {
  2388.     //if (shading.direct <= 0.0)
  2389.     //{
  2390.     //  return 0.0;
  2391.     //}
  2392.     if (isEyeInWater == 1)
  2393.     {
  2394.         if (surface.mask.water > 0.5)
  2395.         {
  2396.             return 1.0;
  2397.         }
  2398.     }
  2399.     vec4 worldPos = gbufferModelViewInverse * surface.screenSpacePosition;
  2400.     worldPos.xyz += cameraPosition.xyz;
  2401.  
  2402.     vec2 dither = CalculateNoisePattern1(vec2(0.0), 2.0).xy;
  2403.     // float waterPlaneHeight = worldPos.y + 8.0;
  2404.     float waterPlaneHeight = 63.0;
  2405.  
  2406.     // vec4 wlv = shadowModelViewInverse * vec4(0.0, 0.0, 1.0, 0.0);
  2407.     vec4 wlv = gbufferModelViewInverse * vec4(lightVector.xyz, 0.0);
  2408.     vec3 worldLightVector = -normalize(wlv.xyz);
  2409.     // worldLightVector = normalize(vec3(-1.0, 1.0, 0.0));
  2410.  
  2411.     float pointToWaterVerticalLength = min(abs(worldPos.y - waterPlaneHeight), 2.0);
  2412.     vec3 flatRefractVector = FakeRefract(worldLightVector, vec3(0.0, 1.0, 0.0), 1.0 / 1.3333);
  2413.     float pointToWaterLength = pointToWaterVerticalLength / -flatRefractVector.y;
  2414.     vec3 lookupCenter = worldPos.xyz - flatRefractVector * pointToWaterLength;
  2415.  
  2416.  
  2417.     const float distanceThreshold = 0.15;
  2418.  
  2419.     const int numSamples = 1;
  2420.     int c = 0;
  2421.  
  2422.     float caustics = 0.0;
  2423.  
  2424.     for (int i = -numSamples; i <= numSamples; i++)
  2425.     {
  2426.         for (int j = -numSamples; j <= numSamples; j++)
  2427.         {
  2428.             vec2 offset = vec2(i + dither.x, j + dither.y) * 0.2;
  2429.             vec3 lookupPoint = lookupCenter + vec3(offset.x, 0.0, offset.y);
  2430.             // vec3 wavesNormal = normalize(GetWavesNormal(lookupPoint).xzy + vec3(0.0, 1.0, 0.0) * 100.0);
  2431.             vec3 wavesNormal = GetWavesNormal(lookupPoint).xzy;
  2432.             vec3 refractVector = FakeRefract(worldLightVector.xyz, wavesNormal.xyz, 1.0 / 1.3333);
  2433.             float rayLength = pointToWaterVerticalLength / refractVector.y;
  2434.             vec3 collisionPoint = lookupPoint - refractVector * rayLength;
  2435.  
  2436.             float dist = distance(collisionPoint, worldPos.xyz);
  2437.  
  2438.             caustics += 1.0 - saturate(dist / distanceThreshold);
  2439.  
  2440.             c++;
  2441.         }
  2442.     }
  2443.  
  2444.     caustics /= c;
  2445.  
  2446.     caustics /= distanceThreshold;
  2447.  
  2448.  
  2449.     return pow(caustics, 2.0) * 3.0;
  2450. }
  2451.  
  2452. void WaterFog(inout vec3 color, in SurfaceStruct surface, in MCLightmapStruct mcLightmap)
  2453. {
  2454.     // return;
  2455.     if (surface.mask.water > 0.5 || isEyeInWater > 0)
  2456.     {
  2457.         float depth = texture2D(depthtex1, texcoord.st).x;
  2458.         float depthSolid = texture2D(gdepthtex, texcoord.st).x;
  2459.  
  2460.         vec4 viewSpacePosition = GetScreenSpacePosition(texcoord.st, depth);
  2461.         vec4 viewSpacePositionSolid = GetScreenSpacePosition(texcoord.st, depthSolid);
  2462.  
  2463.         vec3 viewVector = normalize(viewSpacePosition.xyz);
  2464.  
  2465.  
  2466.         float waterDepth = distance(viewSpacePosition.xyz, viewSpacePositionSolid.xyz);
  2467.         if (isEyeInWater > 0)
  2468.         {
  2469.             waterDepth = length(viewSpacePosition.xyz) * 0.5;      
  2470.             if (surface.mask.water > 0.5)
  2471.             {
  2472.                 waterDepth = length(viewSpacePositionSolid.xyz) * 0.5;     
  2473.             }  
  2474.         }
  2475.  
  2476.  
  2477.         float fogDensity = 0.20;
  2478.         float visibility = 1.0f / (pow(exp(waterDepth * fogDensity), 1.0f));
  2479.         float visibility2 = 1.0f / (pow(exp(waterDepth * fogDensity), 1.0f));
  2480.  
  2481.         vec3 waterNormal = normalize(GetWaterNormals(texcoord.st));
  2482.  
  2483.         // vec3 waterFogColor = vec3(1.0, 1.0, 0.1);    //murky water
  2484.         // vec3 waterFogColor = vec3(0.2, 0.95, 0.0) * 1.0; //green water
  2485.         // vec3 waterFogColor = vec3(0.4, 0.95, 0.05) * 2.0; //green water
  2486.         // vec3 waterFogColor = vec3(0.7, 0.95, 0.00) * 0.75; //green water
  2487.         // vec3 waterFogColor = vec3(0.2, 0.95, 0.4) * 5.0; //green water
  2488.         // vec3 waterFogColor = vec3(0.2, 0.95, 1.0) * 1.0; //clear water
  2489.         vec3 waterFogColor = vec3(0.2, 0.85, 1.0) * 0.75; //clear water
  2490.               waterFogColor *= 0.01 * dot(vec3(0.33333), colorSunlight);
  2491.               waterFogColor *= (1.0 - rainStrength * 0.95);
  2492.               waterFogColor *= isEyeInWater * 2.0 + 1.0;
  2493.  
  2494.         if (isEyeInWater == 0)
  2495.         {
  2496.             waterFogColor *= mcLightmap.sky;
  2497.         }
  2498.         else
  2499.         {
  2500.             waterFogColor *= pow(eyeBrightnessSmooth.y / 240.0f, 6.0f);
  2501.         }
  2502.  
  2503.         // float scatter = CalculateSunglow(surface);
  2504.  
  2505.         vec3 viewVectorRefracted = refract(viewVector, waterNormal, 1.0 / 1.3333);
  2506.         float scatter = 1.0 / (pow(saturate(dot(-lightVector, viewVectorRefracted) * 0.5 + 0.5) * 20.0, 2.0) + 0.1);
  2507.         //vec3 reflectedLightVector = reflect(lightVector, upVector);
  2508.               //scatter += (1.0 / (pow(saturate(dot(-reflectedLightVector, viewVectorRefracted) * 0.5 + 0.5) * 30.0, 2.0) + 0.1)) * saturate(1.0 - dot(lightVector, upVector) * 1.4);
  2509.  
  2510.         // scatter += pow(saturate(dot(-lightVector, viewVectorRefracted) * 0.5 + 0.5), 3.0) * 0.02;
  2511.         if (isEyeInWater < 1)
  2512.         {
  2513.             waterFogColor = mix(waterFogColor, colorSunlight * 21.0 * waterFogColor, vec3(scatter * (1.0 - rainStrength)));
  2514.         }
  2515.  
  2516.         // color *= pow(vec3(0.7, 0.88, 1.0) * 0.99, vec3(waterDepth * 0.45 + 0.2));
  2517.         // color *= pow(vec3(0.7, 0.88, 1.0) * 0.99, vec3(waterDepth * 0.45 + 1.0));
  2518.         color *= pow(vec3(0.4, 0.72, 1.0) * 0.99, vec3(waterDepth * 0.25 + 0.25));
  2519.         // color *= pow(vec3(0.7, 1.0, 0.2) * 0.8, vec3(waterDepth * 0.15 + 0.1));
  2520.         color = mix(waterFogColor, color, saturate(visibility));
  2521.  
  2522.  
  2523.  
  2524.     }
  2525. }
  2526.  
  2527. void IceFog(inout vec3 color, in SurfaceStruct surface, in MCLightmapStruct mcLightmap)
  2528. {
  2529.     // return;
  2530.     if (surface.mask.ice > 0.5)
  2531.     {
  2532.         float depth = texture2D(depthtex1, texcoord.st).x;
  2533.         float depthSolid = texture2D(gdepthtex, texcoord.st).x;
  2534.  
  2535.         vec4 viewSpacePosition = GetScreenSpacePosition(texcoord.st, depth);
  2536.         vec4 viewSpacePositionSolid = GetScreenSpacePosition(texcoord.st, depthSolid);
  2537.  
  2538.         vec3 viewVector = normalize(viewSpacePosition.xyz);
  2539.  
  2540.  
  2541.         float waterDepth = distance(viewSpacePosition.xyz, viewSpacePositionSolid.xyz);
  2542.  
  2543.  
  2544.         float fogDensity = 0.41;
  2545.         float visibility = 1.0f / (pow(exp(waterDepth * fogDensity), 1.0f));
  2546.         float visibility2 = 1.0f / (pow(exp(waterDepth * fogDensity), 1.0f));
  2547.  
  2548.         vec3 waterNormal = normalize(GetWaterNormals(texcoord.st));
  2549.  
  2550.         // vec3 waterFogColor = vec3(1.0, 1.0, 0.1);    //murky water
  2551.         // vec3 waterFogColor = vec3(0.2, 0.95, 0.0) * 1.0; //green water
  2552.         // vec3 waterFogColor = vec3(0.4, 0.95, 0.05) * 2.0; //green water
  2553.         // vec3 waterFogColor = vec3(0.7, 0.95, 0.00) * 0.75; //green water
  2554.         // vec3 waterFogColor = vec3(0.2, 0.95, 0.4) * 5.0; //green water
  2555.         // vec3 waterFogColor = vec3(0.2, 0.95, 1.0) * 1.0; //clear water
  2556.         vec3 waterFogColor = vec3(0.2, 0.45, 1.0) * 0.75; //clear water
  2557.               waterFogColor *= 0.01 * dot(vec3(0.33333), colorSunlight);
  2558.               waterFogColor *= (1.0 - rainStrength * 0.95);
  2559.  
  2560.  
  2561.             waterFogColor *= mcLightmap.sky;
  2562.  
  2563.  
  2564.         // float scatter = CalculateSunglow(surface);
  2565.  
  2566.         vec3 viewVectorRefracted = refract(viewVector, waterNormal, 1.0 / 1.3333);
  2567.         float scatter = 1.0 / (pow(saturate(dot(-lightVector, viewVectorRefracted) * 0.5 + 0.5) * 10.0, 2.0) + 0.1);
  2568.         //vec3 reflectedLightVector = reflect(lightVector, upVector);
  2569.               //scatter += (1.0 / (pow(saturate(dot(-reflectedLightVector, viewVectorRefracted) * 0.5 + 0.5) * 30.0, 2.0) + 0.1)) * saturate(1.0 - dot(lightVector, upVector) * 1.4);
  2570.  
  2571.         // scatter += pow(saturate(dot(-lightVector, viewVectorRefracted) * 0.5 + 0.5), 3.0) * 0.02;
  2572.             waterFogColor = mix(waterFogColor, colorSunlight * 21.0 * waterFogColor, vec3(scatter * (1.0 - rainStrength)));
  2573.  
  2574.         // color *= pow(vec3(0.7, 0.88, 1.0) * 0.99, vec3(waterDepth * 0.45 + 0.2));
  2575.         // color *= pow(vec3(0.7, 0.88, 1.0) * 0.99, vec3(waterDepth * 0.45 + 1.0));
  2576.         color *= pow(vec3(0.4, 0.72, 1.0) * 0.99, vec3(waterDepth * 0.25 + 0.25));
  2577.         // color *= pow(vec3(0.7, 1.0, 0.2) * 0.8, vec3(waterDepth * 0.15 + 0.1));
  2578.         color = mix(waterFogColor, color, saturate(visibility));
  2579.  
  2580.  
  2581.  
  2582.     }
  2583. }
  2584.  
  2585. void CrepuscularRays(inout float color, in SurfaceStruct surface)
  2586. {
  2587.     if (rainStrength == 1.0)
  2588.         return;
  2589.  
  2590.  
  2591.     float rayDepth = 0.02f;
  2592.     float increment = 5.0f;
  2593.  
  2594.     const float rayLimit = 280.0f;
  2595.  
  2596.     float dither = CalculateDitherPattern1();
  2597.  
  2598.     //rayDepth += dither * increment;
  2599.  
  2600.     float lightAccumulation = 0.0f;
  2601.     //float mistLight = 0.0f;
  2602.     float ambientFogAccumulation = 0.0f;
  2603.  
  2604.     float numSteps = rayLimit / increment;
  2605.  
  2606.     int count = 0;
  2607.  
  2608.     while (rayDepth < rayLimit)
  2609.     {
  2610.         if (surface.linearDepth < rayDepth + dither * increment)
  2611.         {
  2612.             break;
  2613.         }
  2614.         vec4 rayPosition = GetScreenSpacePosition(texcoord.st, LinearToExponentialDepth(rayDepth + dither * increment));
  2615.         rayPosition = gbufferModelViewInverse * rayPosition;
  2616.         //vec4 rayWorldPosition = rayPosition + vec4(cameraPosition.xyz, 0.0f);
  2617.  
  2618.         rayPosition = shadowModelView * rayPosition;
  2619.         rayPosition = shadowProjection * rayPosition;
  2620.         rayPosition /= rayPosition.w;
  2621.  
  2622.         float dist = sqrt(dot(rayPosition.xy, rayPosition.xy));
  2623.         float distortFactor = (1.0f - SHADOW_MAP_BIAS) + dist * SHADOW_MAP_BIAS;
  2624.         rayPosition.xy *= 0.95f / distortFactor;
  2625.         rayPosition.z = mix(rayPosition.z, 0.5, 0.8);
  2626.         rayPosition = rayPosition * 0.5f + 0.5f;
  2627.  
  2628.         float shadowSample = shadow2DLod(shadow, vec3(rayPosition.st, rayPosition.z + 0.0018f), 4).x;
  2629.  
  2630.         //if (count < 1)
  2631.         //{
  2632.         //  lightAccumulation += shadowSample;
  2633.         //}
  2634.         //else
  2635.         //{
  2636.             lightAccumulation += shadowSample * increment;
  2637.         //}
  2638.         //mistLight += shadowSample * Get3DNoise(rayWorldPosition.xyz * 0.5f);
  2639.  
  2640.  
  2641.         ambientFogAccumulation += 1.0f;
  2642.  
  2643.         rayDepth += increment;
  2644.         count++;
  2645.         increment *= 1.0f;
  2646.     }
  2647.  
  2648.     //lightAccumulation -= 1.0f;
  2649.     lightAccumulation /= numSteps;
  2650.     ambientFogAccumulation /= numSteps;
  2651.  
  2652.     //lightAccumulation *= 0.25;
  2653.     //mistLight /= numSteps;
  2654.  
  2655.     color = lightAccumulation * 0.3 * (1.0 - rainStrength);
  2656.  
  2657.     return;
  2658.  
  2659. /*
  2660.     float sunglow = CalculateSunglow(surface);
  2661.     float antiSunglow = CalculateAntiSunglow(surface);
  2662.  
  2663.     //float anisoHighlight = max(0.0f, pow(sunglow, 1.0f)) * 0.0f + max(pow(antiSunglow, 2.0f), 0.0f) * 0.05f;
  2664.          // anisoHighlight += pow(sunglow, 4.0f) * 5.0f;
  2665.  
  2666.     float anisoHighlight = pow(1.0f / (pow((1.0f - sunglow) * 3.0f, 2.0f) + 0.0001f) * 1.5f, 1.5f) + 0.5f;
  2667.           anisoHighlight *= sunglow + 0.0f;
  2668.           anisoHighlight += antiSunglow * 0.05f;
  2669.  
  2670.     //lightAccumulation *= 1.0f + anisoHighlight * 300.0f;
  2671.  
  2672.  
  2673.  
  2674.     //lightAccumulation = mix(1.0f, 10.0f, float(surface.mask.sky));
  2675.  
  2676.     vec3 rays = vec3(lightAccumulation);
  2677.  
  2678.     vec3 rayColor = colorSunlight * 0.5f + colorSkylight * 1.0f + colorSunlight * (anisoHighlight * 120.0f);
  2679.  
  2680.     rays *= rayColor;
  2681.  
  2682.     //vec3 mist = vec3(mistLight);
  2683.  
  2684.     color.rgb += rays * (0.0025f + float(isEyeInWater) * 0.0001f);
  2685.     //color.rgb += mist * 0.0001f;
  2686.     //color.rgb += vec3(ambientFogAccumulation) * colorScatteredSunlight * 0.00001f;
  2687.     */
  2688. }
  2689.  
  2690.  
  2691.  
  2692. ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  2693. ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  2694. /////////////////////////////////////////////////////////////MAIN//////////////////////////////////////////////////////////////////////////////
  2695. ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  2696. ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  2697. void main() {
  2698.  
  2699.     //Initialize surface properties required for lighting calculation for any surface that is not part of the sky
  2700.     surface.albedo              = GetAlbedoLinear(texcoord.st);                 //Gets the albedo texture
  2701.     surface.albedo              = pow(surface.albedo, vec3(1.0f));
  2702.  
  2703.     // surface.albedo = Contrast(surface.albedo, 1.1f);
  2704.  
  2705.     //surface.albedo = normalize(surface.albedo) * (pow(length(surface.albedo), 1.2f));
  2706.  
  2707.     //surface.albedo                = vec3(0.8f);
  2708.     surface.normal              = GetNormals(texcoord.st);                      //Gets the screen-space normals
  2709.     surface.depth               = GetDepth(texcoord.st);                        //Gets the scene depth
  2710.     surface.linearDepth         = ExpToLinearDepth(surface.depth);              //Get linear scene depth
  2711.     surface.screenSpacePosition = GetScreenSpacePosition(texcoord.st);          //Gets the screen-space position
  2712.     surface.worldSpacePosition  = gbufferModelViewInverse * surface.screenSpacePosition;
  2713.     surface.viewVector          = normalize(surface.screenSpacePosition.rgb);   //Gets the view vector
  2714.     surface.lightVector         = lightVector;                                  //Gets the sunlight vector
  2715.     //vec4 wlv                  = gbufferModelViewInverse * vec4(surface.lightVector, 1.0f);
  2716.     vec4 wlv                    = shadowModelViewInverse * vec4(0.0f, 0.0f, 1.0f, 0.0f);
  2717.     surface.worldLightVector    = normalize(wlv.xyz);
  2718.     surface.upVector            = upVector;                                     //Store the up vector
  2719.  
  2720.  
  2721.  
  2722.  
  2723.  
  2724.     surface.mask.matIDs         = GetMaterialIDs(texcoord.st);                  //Gets material ids
  2725.     CalculateMasks(surface.mask);
  2726.  
  2727.     if (surface.mask.water > 0.5)
  2728.     {
  2729.         surface.albedo *= 1.9;
  2730.         //surface.albedo = mix(surface.albedo, vec3(0.5, 0.9, 0.1) * 0.15, vec3(0.5));
  2731.         //surface.albedo = mix(surface.albedo, vec3(0.5, 0.9, 0.1) * 0.15, vec3(saturate(dot(surface.normal, upVector) * 0.5 + 0.5)));
  2732.     }
  2733.  
  2734.     surface.albedo *= 1.0f - (surface.mask.sky);                        //Remove the sky from surface albedo, because sky will be handled separately
  2735.  
  2736.     //surface.water.albedo = surface.albedo * float(surface.mask.water);        //Store underwater albedo
  2737.     //surface.albedo *= 1.0f - float(surface.mask.water);                       //Remove water from surface albedo to handle water separately
  2738.  
  2739.  
  2740.  
  2741.     //Initialize sky surface properties
  2742.     surface.sky.albedo      = GetAlbedoLinear(texcoord.st) * (min(1.0f, (surface.mask.sky) + (surface.mask.sunspot)));                          //Gets the albedo texture for the sky
  2743.  
  2744.     surface.sky.tintColor   = vec3(1.0f);
  2745.     //surface.sky.tintColor     = mix(colorSunlight, vec3(colorSunlight.r), vec3(0.8f));                                    //Initializes the defualt tint color for the sky
  2746.     //surface.sky.tintColor     *= mix(1.0f, 500.0f, timeSkyDark);                                                  //Boost sky color at night                                                                      //Scale sunglow back to be less intense
  2747.  
  2748.     surface.sky.sunSpot     = vec3(float(CalculateSunspot(surface))) * vec3((min(1.0f, (surface.mask.sky) + (surface.mask.sunspot)))) * colorSunlight;
  2749.     surface.sky.sunSpot     *= 1.0f - timeMidnight;
  2750.     surface.sky.sunSpot     *= 300.0f;
  2751.     surface.sky.sunSpot     *= 1.0f - rainStrength;
  2752.     //surface.sky.sunSpot     *= 1.0f - timeMidnight;
  2753.  
  2754.     AddSkyGradient(surface);
  2755.     AddSunglow(surface);
  2756.  
  2757.  
  2758.  
  2759.     //Initialize MCLightmap values
  2760.     mcLightmap.torch        = GetLightmapTorch(texcoord.st);    //Gets the lightmap for light coming from emissive blocks
  2761.  
  2762.  
  2763.     mcLightmap.sky          = GetLightmapSky(texcoord.st);      //Gets the lightmap for light coming from the sky
  2764.  
  2765.     // mcLightmap.sky       = 1.0f / pow((1.0f - mcLightmap.sky + 0.00001f), 2.0f);
  2766.     // mcLightmap.sky       -= 1.0f;
  2767.     // mcLightmap.sky       = max(0.0f, mcLightmap.sky);
  2768.  
  2769.     mcLightmap.lightning    = 0.0f;                             //gets the lightmap for light coming from lightning
  2770.     if (surface.mask.water > 0.5 || surface.mask.ice > 0.5)
  2771.     {
  2772.         mcLightmap.sky      = GetTransparentLightmapSky(texcoord.st);
  2773.     }
  2774.  
  2775.     //Initialize default surface shading attributes
  2776.     surface.diffuse.roughness           = 0.0f;                 //Default surface roughness
  2777.     surface.diffuse.translucency        = 0.0f;                 //Default surface translucency
  2778.     surface.diffuse.translucencyColor   = vec3(1.0f);           //Default translucency color
  2779.  
  2780.     surface.specular.specularity        = GetSpecularity(texcoord.st)//Gets the reflectance/specularity of the surface
  2781.     surface.specular.extraSpecularity   = 0.0f;                         //Default value for extra specularity
  2782.     surface.specular.glossiness         = GetGlossiness(texcoord.st);
  2783.     surface.specular.metallic           = 0.0f;                         //Default value of how metallic the surface is
  2784.     surface.specular.gain               = 1.0f;                         //Default surface specular gain
  2785.     surface.specular.base               = 0.0f;                         //Default reflectance when the surface normal and viewing normal are aligned
  2786.     surface.specular.fresnelPower       = 5.0f;                         //Default surface fresnel power
  2787.  
  2788.  
  2789.  
  2790.  
  2791.     //Calculate surface shading
  2792.     CalculateNdotL(surface);
  2793.     shading.direct              = CalculateDirectLighting(surface);             //Calculate direct sunlight without visibility check (shadows)
  2794.     shading.sunlightVisibility  = CalculateSunlightVisibility(surface, shading);                    //Calculate shadows and apply them to direct lighting
  2795.     shading.direct              *= mix(1.0f, 0.0f, rainStrength);
  2796.     float caustics = 1.0;
  2797.     #ifdef WATER_CAUSTICS
  2798.     if (surface.mask.water > 0.5 || isEyeInWater > 0)
  2799.         caustics = CalculateWaterCaustics(surface, shading);
  2800.     #endif
  2801.     shading.direct *= caustics;
  2802.     shading.waterDirect         = shading.direct;
  2803.     shading.direct              *= pow(mcLightmap.sky, 0.1f);
  2804.     // shading.bounced  = CalculateBouncedSunlight(surface);            //Calculate fake bounced sunlight
  2805.     shading.scattered   = CalculateScatteredSunlight(surface);          //Calculate fake scattered sunlight
  2806.     shading.skylight    = CalculateSkylight(surface);                   //Calculate scattered light from sky
  2807.     shading.skylight    *= pow(caustics, 0.5) * 0.4 + 0.6;
  2808.     // shading.scatteredUp = CalculateScatteredUpLight(surface);
  2809.     shading.heldLight   = CalculateHeldLightShading(surface);
  2810.     shading.heldLight   *= pow(caustics, 0.5) * 0.4 + 0.6;
  2811.  
  2812.  
  2813.     InitializeAO(surface);
  2814.     //if (texcoord.s < 0.5f && texcoord.t < 0.5f)
  2815.     //CalculateAO(surface);
  2816.  
  2817.     float ao = 1.0;
  2818.  
  2819.     vec4 delta = vec4(0.0);
  2820.     delta.a = 1.0;
  2821.  
  2822.     #ifndef BASIC_AMBIENT
  2823.         if (isEyeInWater < 1)
  2824.         {
  2825.             delta = Delta(surface.albedo.rgb, surface.normal.xyz, mcLightmap.sky);
  2826.         }
  2827.  
  2828.         ao = delta.a;
  2829.     #endif
  2830.  
  2831.     //Colorize surface shading and store in lightmaps
  2832.     lightmap.sunlight           = vec3(shading.direct) * colorSunlight;
  2833.     lightmap.sunlight           *= shading.sunlightVisibility;
  2834.     lightmap.sunlight           *= GetParallaxShadow(texcoord.st);
  2835.     AddCloudGlow(lightmap.sunlight, surface);
  2836.     //lightmap.sunlight             *= 2.0f - AO;
  2837.  
  2838.     lightmap.skylight           = vec3(mcLightmap.sky);
  2839.     lightmap.skylight           *= mix(colorSkylight, colorBouncedSunlight, vec3(max(0.2f, (1.0f - pow(mcLightmap.sky + 0.13f, 1.0f) * 1.0f)))) + colorBouncedSunlight * (mix(0.3f, 2.8f, 0.0)) * (1.0f - rainStrength);
  2840.     //lightmap.skylight             *= mix(colorSkylight, colorBouncedSunlight, vec3(0.2f));
  2841.     lightmap.skylight           *= shading.skylight;
  2842.     lightmap.skylight           *= mix(1.0f, 5.0f, (surface.mask.clouds));
  2843.     lightmap.skylight           *= mix(1.0f, 50.0f, (surface.mask.clouds) * timeSkyDark);
  2844.     // lightmap.skylight            += vec3(0.5, 0.8, 1.0) * surface.mask.water * mcLightmap.sky * dot(vec3(0.3333), colorSunlight * colorSunlight) * 1.0//water ambient
  2845.     lightmap.skylight           *= surface.ao.skylight;
  2846.     //lightmap.skylight             *= surface.ao.constant * 0.5f + 0.5f;
  2847.     lightmap.skylight           += mix(colorSkylight, colorSunlight, vec3(0.2f)) * vec3(mcLightmap.sky) * surface.ao.constant * 0.05f;
  2848.     lightmap.skylight           *= mix(1.0f, 0.4f, rainStrength);
  2849.     lightmap.skylight           *= ao;
  2850.  
  2851.  
  2852.  
  2853.     lightmap.scatteredSunlight  = vec3(shading.scattered) * colorSunlight * (1.0f - rainStrength);
  2854.     lightmap.scatteredSunlight  *= pow(vec3(mcLightmap.sky), vec3(1.0f));
  2855.     lightmap.scatteredSunlight  *= ao;
  2856.  
  2857.     lightmap.underwater         = vec3(mcLightmap.sky) * colorSkylight;
  2858.  
  2859.     lightmap.torchlight         = mcLightmap.torch * colorTorchlight;
  2860.     lightmap.torchlight         *= ao;
  2861.     lightmap.torchlight         *= pow(caustics, 0.5) * 0.4 + 0.6;
  2862.  
  2863.     lightmap.nolight            = vec3(0.05f);
  2864.     lightmap.nolight            *= surface.ao.constant;
  2865.     lightmap.nolight            *= ao;
  2866.  
  2867.     // lightmap.scatteredUpLight    = vec3(shading.scatteredUp) * mix(colorSunlight, colorSkylight, vec3(0.3f));
  2868.     // lightmap.scatteredUpLight   *= pow(mcLightmap.sky, 0.5f);
  2869.     // lightmap.scatteredUpLight    *= surface.ao.scatteredUpLight;
  2870.     // lightmap.scatteredUpLight    *= mix(1.0f, 0.1f, rainStrength);
  2871.     // lightmap.scatteredUpLight    *= ao;
  2872.     //lightmap.scatteredUpLight   *= surface.ao.constant * 0.5f + 0.5f;
  2873.  
  2874.     lightmap.heldLight          = vec3(shading.heldLight);
  2875.     lightmap.heldLight          *= colorTorchlight;
  2876.     lightmap.heldLight          *= ao;
  2877.     lightmap.heldLight          *= heldBlockLightValue / 16.0f;
  2878.  
  2879.  
  2880.  
  2881.  
  2882.     //If eye is in water
  2883.     if (isEyeInWater > 0) {
  2884.         vec3 halfColor = mix(colorWaterMurk, vec3(1.0f), vec3(0.5f));
  2885.         lightmap.sunlight *= mcLightmap.sky * halfColor;
  2886.         lightmap.skylight *= halfColor;
  2887.         lightmap.bouncedSunlight *= 0.0f;
  2888.         lightmap.scatteredSunlight *= halfColor;
  2889.         lightmap.nolight *= halfColor;
  2890.         lightmap.scatteredUpLight *= halfColor;
  2891.     }
  2892.  
  2893.     surface.albedo.rgb = mix(surface.albedo.rgb, pow(surface.albedo.rgb, vec3(2.0f)), vec3((surface.mask.fire)));
  2894.  
  2895.  
  2896.     //Apply lightmaps to albedo and generate final shaded surface
  2897.     final.nolight           = surface.albedo * lightmap.nolight;
  2898.     final.sunlight          = surface.albedo * lightmap.sunlight;
  2899.     final.skylight          = surface.albedo * lightmap.skylight;
  2900.     final.bouncedSunlight   = surface.albedo * lightmap.bouncedSunlight;
  2901.     final.scatteredSunlight = surface.albedo * lightmap.scatteredSunlight;
  2902.     final.scatteredUpLight  = surface.albedo * lightmap.scatteredUpLight;
  2903.     final.torchlight        = surface.albedo * lightmap.torchlight;
  2904.     final.underwater        = surface.water.albedo * colorWaterBlue;
  2905.     // final.underwater         *= GetUnderwaterLightmapSky(texcoord.st);
  2906.     // final.underwater         += vec3(0.9f, 1.00f, 0.35f) * float(surface.mask.water) * 0.065f;
  2907.      final.underwater       *= (lightmap.sunlight * 0.3f) + (lightmap.skylight * 0.06f) + (lightmap.torchlight * 0.0165) + (lightmap.nolight * 0.002f);
  2908.  
  2909.  
  2910.     //final.glow.torch              = pow(surface.albedo, vec3(4.0f)) * float(surface.mask.torch);
  2911.     final.glow.lava                 = Glowmap(surface.albedo, surface.mask.lava,      4.0f, vec3(1.0f, 0.05f, 0.001f));
  2912.  
  2913.     final.glow.glowstone            = Glowmap(surface.albedo, surface.mask.glowstone, 2.0f, colorTorchlight);
  2914.     //final.glow.glowstone         *= (sin(frameTimeCounter * 3.1415f / 3.0f) * 0.5f + 0.5f) * 3.0f + 1.0f;
  2915.     final.torchlight               *= 1.0f - (surface.mask.glowstone);
  2916.  
  2917.     final.glow.fire                 = surface.albedo * (surface.mask.fire);
  2918.     final.glow.fire                 = pow(final.glow.fire, vec3(1.0f));
  2919.  
  2920.     //final.glow.torch              = Glowmap(surface.albedo, surface.mask.torch,    16.0f, vec3(1.0f, 0.07f, 0.001f));
  2921.  
  2922.     //final.glow.torch              = surface.albedo * float(surface.mask.torch);
  2923.     //final.glow.torch              *= pow(vec3(CalculateLuminance(final.glow.torch)), vec3(6.0f));
  2924.     //final.glow.torch              = pow(final.glow.torch, vec3(1.4f));
  2925.  
  2926.  
  2927.     final.glow.torch                = pow(surface.albedo * (surface.mask.torch), vec3(4.4f));
  2928.  
  2929.  
  2930.  
  2931.     //Remove glow items from torchlight to keep control
  2932.     final.torchlight *= 1.0f - (surface.mask.lava);
  2933.  
  2934.     final.heldLight = lightmap.heldLight * surface.albedo;
  2935.  
  2936.  
  2937.     //Do night eye effect on outdoor lighting and sky
  2938.     DoNightEye(final.sunlight);
  2939.     DoNightEye(final.skylight);
  2940.     DoNightEye(final.bouncedSunlight);
  2941.     DoNightEye(final.scatteredSunlight);
  2942.     DoNightEye(surface.sky.albedo);
  2943.     DoNightEye(final.underwater);
  2944.     DoNightEye(delta.rgb);
  2945.  
  2946.     DoLowlightEye(final.nolight);
  2947.  
  2948.  
  2949.  
  2950.     surface.cloudShadow = 1.0f;
  2951.     const float sunlightMult = 0.21f;
  2952.  
  2953.     //Apply lightmaps to albedo and generate final shaded surface
  2954.     vec3 finalComposite = final.sunlight            * 0.9f  * 1.5f * sunlightMult               //Add direct sunlight
  2955.                         + final.skylight            * 0.03f             //Add ambient skylight
  2956.                         + final.nolight             * 0.00003f          //Add base ambient light
  2957.                         //+ final.bouncedSunlight   * 0.005f    * sunlightMult              //Add fake bounced sunlight
  2958.                         + final.scatteredSunlight   * 0.02f     * (1.0f - sunlightMult)                 //Add fake scattered sunlight
  2959.                         //+ final.scatteredUpLight  * 0.0015f   * sunlightMult
  2960.                         + final.torchlight          * 2.0f      * TORCHLIGHT_BRIGHTNESS //Add light coming from emissive blocks
  2961.                         + final.glow.lava           * 1.6f      * TORCHLIGHT_BRIGHTNESS
  2962.                         + final.glow.glowstone      * 1.1f      * TORCHLIGHT_BRIGHTNESS
  2963.                         + final.glow.fire           * 0.025f    * TORCHLIGHT_BRIGHTNESS
  2964.                         + final.glow.torch          * 0.15f     * TORCHLIGHT_BRIGHTNESS
  2965.                         + final.heldLight           * 0.05f     * TORCHLIGHT_BRIGHTNESS
  2966.                         ;
  2967.  
  2968.     delta.rgb *= mix(vec3(1.0), vec3(0.1, 0.3, 1.0) * 1.0, surface.mask.water);
  2969.  
  2970.     //Apply sky to final composite
  2971.          surface.sky.albedo *= 6.0f;
  2972.          surface.sky.albedo = surface.sky.albedo * surface.sky.tintColor + surface.sky.sunglow + surface.sky.sunSpot;
  2973.          //DoNightEye(surface.sky.albedo);
  2974.          finalComposite     += surface.sky.albedo;      //Add sky to final image
  2975.          finalComposite     += delta.rgb * sunlightMult * 1.4;
  2976.  
  2977.  
  2978.  
  2979.     //if eye is in water, do underwater fog
  2980.     if (isEyeInWater > 0) {
  2981.         finalComposite *= 9.0;
  2982.         //CalculateUnderwaterFog(surface, finalComposite);
  2983.     }
  2984.  
  2985.     CloudPlane(surface, finalComposite);
  2986.  
  2987.     #ifdef VOLUMETRIC_CLOUDS
  2988.     VolumeClouds(surface, finalComposite);
  2989.     #endif
  2990.  
  2991.     WaterFog(finalComposite, surface, mcLightmap);
  2992.     IceFog(finalComposite, surface, mcLightmap);
  2993.  
  2994.    
  2995.     if (surface.mask.stainedGlass > 0.5)
  2996.     {
  2997.         finalComposite *= 1.5;
  2998.     }
  2999.  
  3000.  
  3001.  
  3002.     finalComposite *= 0.001f;                                               //Scale image down for HDR
  3003.     finalComposite.b *= 1.0f;
  3004.  
  3005.     #ifdef ATMOSPHERIC_SCATTERING
  3006.     CalculateAtmosphericScattering(finalComposite.rgb, surface);
  3007.     #endif
  3008.  
  3009.  
  3010.     float crepuscularRays = 0.0f;
  3011.     #ifdef CREPUSCULAR_RAYS
  3012.     CrepuscularRays(crepuscularRays, surface);
  3013.     #endif
  3014.  
  3015.     //finalComposite.rgb += crepuscularRays.rgb * 0.0022;
  3016.  
  3017.      finalComposite = pow(finalComposite, vec3(1.0f / 2.2f));                   //Convert final image into gamma 0.45 space to compensate for gamma 2.2 on displays
  3018.      finalComposite = pow(finalComposite, vec3(1.0f / BANDING_FIX_FACTOR));     //Convert final image into banding fix space to help reduce color banding
  3019.  
  3020.  
  3021.     if (finalComposite.r > 1.0f) {
  3022.         finalComposite.r = 0.0f;
  3023.     }
  3024.  
  3025.     if (finalComposite.g > 1.0f) {
  3026.         finalComposite.g = 0.0f;
  3027.     }
  3028.  
  3029.     if (finalComposite.b > 1.0f) {
  3030.         finalComposite.b = 0.0f;
  3031.     }
  3032.  
  3033.     //finalComposite *= ao;
  3034.  
  3035.  
  3036.     finalComposite += CalculateNoisePattern1(vec2(0.0), 64.0) * (1.0 / 65535.0);
  3037.  
  3038.  
  3039.     gl_FragData[0] = vec4(finalComposite, 1.0f);
  3040.     gl_FragData[1] = vec4(surface.mask.matIDs, crepuscularRays, mcLightmap.sky, 1.0f);
  3041.     gl_FragData[2] = vec4(surface.specular.specularity, surface.cloudAlpha, surface.specular.glossiness, 1.0f);
  3042.     gl_FragData[3] = vec4(shading.sunlightVisibility, 1.0f);
  3043.     // gl_FragData[4] = vec4(pow(surface.albedo.rgb, vec3(1.0f / 2.2f)), 1.0f);
  3044.     // gl_FragData[5] = vec4(surface.normal.rgb * 0.5f + 0.5f, 1.0f);
  3045.  
  3046. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement