#version 150 compatibility

in EllipsoidData {
	vec2  q_tilde;
	float inv_e;
	vec3  nml_e_eye;
	vec3  nml_v_eye;
	vec2  zw_e_clip;
	vec2  zw_v_clip;
	vec3  v_eye;
} Fin;

bool compute_ellipsoid_intersection(out float depth, out vec3 p_eye, out vec3 n_eye, bool show_backside = false)
{
	// check for intersection
	float q_tilde_squared_length = dot(Fin.q_tilde, Fin.q_tilde);
	if (q_tilde_squared_length > 1.0)
		return false;

	// compute ray parameter
	float beta = Fin.inv_e*sqrt(1.0 - q_tilde_squared_length);
	float lambda = show_backside ? 1.0 / (1.0 - beta) : 1.0 / (1.0 + beta);

	// depth correction
	vec2 zw = Fin.zw_e_clip + lambda * Fin.zw_v_clip;
	float z_clip = zw.x / zw.y;
	depth = 0.5*(z_clip + 1.0); // transform from [-1,1] to [0,1]

	// compute sphere position and normal in eye coordinates
	p_eye = lambda*Fin.v_eye;
	n_eye = normalize(Fin.nml_e_eye + lambda * Fin.nml_v_eye);
	if (show_backside) {
		n_eye = -n_eye;
	}
	return true;
}