#version 430 core
// an attempt to test whether a geometry surface occludes the camera from a
// light source
layout (triangles) in;
layout (triangle_strip, max_vertices = 4) out;
layout (std140, binding = 0) uniform TheMat { mat4 theMat; } ;
uniform vec3 lightPos;
uniform vec2 camPos;
void main()
{
    vec3 p0 = gl_in[0].gl_Position.xyz ;
    vec3 p1 = gl_in[1].gl_Position.xyz ;
    vec3 p2 = gl_in[2].gl_Position.xyz ;
    
    // first determine intersection point (if any)

    vec3 u = p1 - p0 ;
    vec3 v = p2 - p0 ;
    vec3 n = cross (u,v) ;
    vec3 dir = vec3 (camPos, 100) - lightPos ;
    vec3 w0 = p0 - lightPos ;
    float a = dot(n, w0) ;
    float b = dot(n,dir) ;
    if (abs(b) < 0.00001) {}
    else {
        float r = a / b ;   
        if (r < 0.0) {}
        else {
            vec3 ip = lightPos + r * dir ;
            float uu, uv, vv, wu, wv, D;
            uu = dot(u,u);
            uv = dot(u,v);
            vv = dot(v,v);
            vec3 w = ip - p0;
            wu = dot (w,u);
            wv = dot (w,v);
            D = uv * uv - uu * vv;
            //get and test parametric coords
            float s, t;
            s = (uv * wv - vv * wu) / D;
            if (s < 0.0 || s > 1.0) {}
            else
            {
                t = (uv * wu - uu * wv) / D;
                if (t < 0.0 || (s + t) > 1.0) {}
                else
                {
                    gl_Position = vec4(-1,-1,50,1); EmitVertex();
                    gl_Position = vec4(-1, 1,50,1); EmitVertex();
                    gl_Position = vec4( 1,-1,50,1); EmitVertex();
                    gl_Position = vec4( 1, 1,50,1); EmitVertex();
                    EndPrimitive();
                }
            }
        }
    }
}
