uniform vec4 u_lightCol;
uniform float u_multiplier;
uniform vec2 u_occlusionUVSize;
uniform float u_occlusionVOffset;
varying vec2 v_texCoord;
varying vec4 v_vertexPos;
varying vec2 v_normTexCoord;

#define PI 3.1415926535897932384626433832795
#define PI2 6.28318530717959
#define COEFF_1 0.78539816339745 //PI / 4.0
#define COEFF_2 2.35619449019235 //3.0 * COEFF_1

float fastAtan(float y, float x) {
    float abs_y = abs(y);
    float angle;
    
    if (x >= 0.0) {
        float r = (x - abs_y) / (x + abs_y);
        angle = COEFF_1 - COEFF_1 * r;
        
    } else {
        float r = (x + abs_y) / (abs_y - x);
        angle = COEFF_2 - COEFF_1 * r;
    }
    
    return y < 0.0 ? -angle : angle;
}

//sample from the 1D distance map
float sample(vec2 coord, float r) {
    return step(r, texture2D(CC_Texture2, coord).r);
    //return step(r, texture2D(CC_Texture2, coord).r);
    //return texture2D(CC_Texture2, coord).r;
}

void main()
{
    vec4 light = texture2D(CC_Texture1, v_texCoord);
    
    float off= u_occlusionUVSize.x / 128.0 * 0.5;
    
    //rectangular to polar
    //float theta = fastAtan(v_normTexCoord.y, v_normTexCoord.x);
    float theta = fastAtan(v_normTexCoord.y, v_normTexCoord.x);
    float r = length(v_normTexCoord);
    float coord = (theta + PI ) / PI2;
    //coord = mod(coord + off, 1.0);
    //sampling the 1D lookup texture
    //vec2 tc = vec2((1.0 - coord) * u_occlusionUVSize.x, u_occlusionVOffset);
    vec2 tc = vec2(coord * u_occlusionUVSize.x, u_occlusionVOffset);
    
    
    //the center tex coord, which gives us hard shadows
    float center = sample(tc, r);
    
 
    
    gl_FragColor = vec4(light.rgb * u_lightCol.rgb * center * u_multiplier, 1.0) ;
    
    //gl_FragColor = vec4(light.rgb  * u_lightCol.rgb, light.r) * 10.0;
    
    
    
    //gl_FragColor = vec4(light.rgb * u_lightCol.rgb * shadow * u_multiplier, 1.0) * 10.0;
}
