Given an incident ray, a normal vector, and both indices of refraction. How can I compute the refracted ray. I know the theoretical aspect of refraction. I just don't know how to implement it.
The function should look like
vec refract(vec incident, vec normal, double index1, double index2);
Note: this is not for a homework so feel free to post any code, ideally in Java
This is what I used for a hobby raytracer:
// refraction for incident ray (i) into surface with normal (n), if total internal reflection occurs, then function
// return false and output vector (r) is not changed
// for example if we entering water from air then ior_ratio = IOR(air)/IOR(water) = 1.0003/1.3333
... bool refract (const V3& i, const V3& n, R ior_ratio, T& r) {
auto cos_i = dot(-i, n);
auto cos_t2 = ((R) 1) - ior_ratio * ior_ratio * (((R) 1)- cos_i * cos_i);
if (cos_t2 <= 0)
return false;
r = ior_ratio * i + ((ior_ratio * cos_i - sqrt(abs(cos_t2))) * n);
return true;
}
Note, it was confusing to me is direction of incident, so check if that is what you expect, otherwise change -i to i. Also, you may need to consider the Fresnel effect http://graphics.stanford.edu/courses/cs148-10-summer/docs/2006--degreve--reflection_refraction.pdf