uniform mat4 Proj, View, ViewInverse;

uniform vec3 EyePos;

uniform vec3 Pos;
uniform float Rad;

varying vec3 PixelWorld;

void main()
{
	vec3 EyeDir = normalize(PixelWorld - EyePos);

	vec3 dis = EyePos - Pos;
	float b = dot(dis, EyeDir);
	if (b < 0.0)
	{
		float c = dot(dis, dis) - Rad * Rad;
		float d = b * b - c;
		if (d > 0.0)
		{
			float distance = -b - sqrt(d);
			vec3 worldHitPos = EyePos + EyeDir * distance;
			vec3 normal = normalize(worldHitPos - Pos);
			
			gl_FragData[0] = vec4(worldHitPos, 0);
			gl_FragData[1] = vec4(normal, 0);
			gl_FragData[2] = vec4(normalize(reflect(EyeDir, normal)), 0);
			gl_FragDepth = 1.0 - 1.0 / (Proj * View * vec4(worldHitPos, 1)).z;
			return;
		}
	}

	discard;
}
