//precision highp float;

uniform vec2 u_lightDirection;
//Size of the oclussion map
uniform vec2 u_occlusionMapUVSize;
uniform vec2 u_shadowMapUVSize;
uniform float u_verticalPixelUVSize;
//This should be max when the emissor is vertical
uniform float u_shadowStr;
uniform vec2 u_gridHalf;

//actual tex coord (taking in account the POT factor)
varying vec2 v_texCoord;
varying vec2 v_gridTexCoord;

#define RAY_LENGTH 1.41

//vec2 clampToPixels(vec2 coords){



//}

void main(void) {

    //clamped grid coords
    vec2 cCoords = floor(v_gridTexCoord * u_gridHalf * 2.0) / 2.0 / u_gridHalf;
    
     //Obtain the shadow map sample point
    //CC_TEXTURE1 vertical and horizontal shadow maps
    //CC_TEXTURE2 original texture
    vec2 invLightDir = -u_lightDirection;
//    float fromLeft = u_lightDirection.x >0.0? 0.0 :1.0;
    float fromLeft = 1.0 - step(0.0, u_lightDirection.x);

    vec2 x0Top = vec2 (0.0,1.0);
    vec2 rhsTop = vec2 (x0Top.x - cCoords.x, x0Top.y - cCoords.y);
    
    //t2
    float XrayDistance=0.0;
    float YrayDistance=0.0;
    
    float occluderDist;
    float light = 0.0;
    vec2 shadowMapCoord = vec2(0.0,0.0);
    
    //Check if collides on top
    //t1 > 0 ?
     float xRayOrigin = (rhsTop.x * invLightDir.y - rhsTop.y * invLightDir.x)/(-invLightDir.y);// * u_occlusionMapUVSize.x;
    
    if(xRayOrigin>=0.0 && xRayOrigin<1.0){ //ray from top
        XrayDistance = rhsTop.y / invLightDir.y;
        shadowMapCoord = vec2(clamp(xRayOrigin * u_shadowMapUVSize.x,0.0,u_occlusionMapUVSize.x * 0.99) , 0.0 );
        occluderDist = texture2D(CC_Texture1,shadowMapCoord).r * RAY_LENGTH ;
        light = step( XrayDistance, occluderDist) *u_shadowStr + 0.5;
    
    }else{ //ray from side
        vec2 x0Side = mix(vec2(0.0,0.0), vec2(1.0,0.0), fromLeft);
        vec2 rhsSide = vec2 (x0Side.x - cCoords.x, x0Side.y - cCoords.y);
        
        float yRayOrigin = (rhsSide.x * invLightDir.y - rhsSide.y * invLightDir.x) / (invLightDir.x);// * u_occlusionMapUVSize.y;
        YrayDistance = rhsSide.x / invLightDir.x	;
        shadowMapCoord = vec2(clamp(yRayOrigin * u_shadowMapUVSize.y *0.5,0.0,u_shadowMapUVSize.y *0.5 * 0.99), u_verticalPixelUVSize);
        occluderDist = texture2D(CC_Texture1,shadowMapCoord).r * RAY_LENGTH;
        light = step(YrayDistance,occluderDist ) *u_shadowStr + 0.5;

    }
    gl_FragColor = light*texture2D(CC_Texture2, v_texCoord);

}
