/**
 *
 * Diplomova prace
 * Stinove techniky na dnesnim hardware a jejich porovnani
 *
 * Michal Toth
 *
 * Fakulta informacnich technologii
 * Vysoke uceni technicke v Brne
 *
 * 2013/2014
 *
 */

/*
 * Geometry shader pro vypocet pruseciku trojuhelniku s paprskem
 */

#version 430

layout(triangles)in;
layout(points, max_vertices =1)out;

uniform vec3 rayOrigin;
uniform vec3 rayDir;
uniform mat4 m;
uniform mat4 mvp;
uniform mat4 mNorm;

struct Res{
    float ax,ay,az;
    float bx,by,bz;
    float cx,cy,cz;
    float ix,iy,iz;
    float l;
};

layout(std430,binding =0)buffer Output{Res res[];};
layout(binding =1,offset =0)uniform atomic_uint counter;


void main(){
    vec3 a=(m*gl_in[0].gl_Position).xyz;
    vec3 b=(m*gl_in[1].gl_Position).xyz;
    vec3 c=(m*gl_in[2].gl_Position).xyz;

    vec3 e1 = b-a;
    vec3 e2 = c-a;

    vec3 P = cross(rayDir,e2);
    float det = dot(e1,P);

    if(det==0) return;

    float invDet = 1.0/det;

    vec3 T = rayOrigin-a;

    float u= dot(T,P)*invDet;
    if(u < 0.0 || u > 1.0) return;

    vec3 Q = cross(T,e1);
    float v = dot(rayDir,Q)*invDet;
    if(v < 0.0 || u + v  > 1.0) return;

    float t = dot(e2,Q)*invDet;
    if(t > 0) {
	uint ptr = atomicCounterIncrement(counter);
	res[ptr].ax=a.x;
	res[ptr].ay=a.y;
	res[ptr].az=a.z;

	res[ptr].bx=b.x;
	res[ptr].by=b.y;
	res[ptr].bz=b.z;

	res[ptr].cx=c.x;
	res[ptr].cy=c.y;
	res[ptr].cz=c.z;

	vec3 i = a+e1*u+e2*v;
	res[ptr].ix=i.x;
	res[ptr].iy=i.y;
	res[ptr].iz=i.z;

	res[ptr].l=length(rayOrigin-i);
    }
}
