/* Butter - shadow_frag.glsl
Fragment shadow function.

Typon - GNU Lesser General Public License v3.0
*/

vec3 calcFinalShadow(vec3 the_shadow_pos, vec2 offset, float shadow_sample, float detect_sample) {
  	float shadow_detector = 1.0;
      float shadow_black = 1.0;
      vec4 shadow_color = vec4(1.0);
      float alpha_complement;
	  
      shadow_detector = detect_sample;
      if (shadow_detector < 1.0) {
        shadow_black = shadow_sample;
        if (shadow_black != shadow_detector) {
          #if !defined GBUFFER_HAND
          shadow_color = texture2D(shadowcolor0, the_shadow_pos.xy);
          alpha_complement = 1.15 - shadow_color.a;
          shadow_color.rgb = mix(shadow_color.rgb*3.0, vec3(1.0), alpha_complement);
          shadow_color.rgb *= shadow_color.a;
         #endif
        }
      }
      
      shadow_color.rgb *= shadow_black;
 
      shadow_color.rgb = mix(shadow_color.rgb, vec3(1.0), shadow_detector);
	
	return shadow_color.rgb;
}

vec3 get_shadow(vec3 the_shadow_pos) {
   float pass = eyeBrightnessSmooth.y / 234.0;
  
    #if AA_TYPE > 0
      float dither = shifted_unit_dither(gl_FragCoord.xy);
    #else
      float dither = unit_dither(gl_FragCoord.xy);
    #endif

    float new_z = the_shadow_pos.z - 0.00005 - (0.0006 * dither);
    
    float current_radius = dither;
    dither *= 6.283185307;

    vec2 offset = (vec2(cos(dither), sin(dither)) * current_radius * SHADOW_BLUR) / shadowMapResolution;

    vec2 packShadow = vec2(shadow2D(shadowtex1, vec3(the_shadow_pos.st + offset, new_z)).r +
    shadow2D(shadowtex1, vec3(the_shadow_pos.st - offset, new_z)).r,
    shadow2D(shadowtex0, vec3(the_shadow_pos.st + offset, new_z)).r +
    shadow2D(shadowtex0, vec3(the_shadow_pos.st - offset, new_z)).r);
	
    packShadow *= 0.5;
    
  return clamp(calcFinalShadow(the_shadow_pos, offset, packShadow.x, packShadow.y) * mix(2.0, 0.1, tNight), vec3(0.0), vec3(1.0)) * 5.0;
}
