I am building a simple raytracer for educational purposes and want to add refraction to objects. Using Snells Law, I am able to create a new ray recursively at the intersection points. The raytracer supports currently only spheres and I use a scene where I have multiple spheres nested inside of each other with different refraction indices.
If I start a ray from outside of the spheres, everything seems simple. You start with the refraction index of the scene, and as soon as you hit the first sphere, refract the ray using the refraction index before and the refraction index of the material of the sphere until you hit the next sphere and so on. Using the normals of the intersection I can determine whether I enter or leave the sphere.
However, I don't understand how I should handle sphere leaves and what to do if the ray doesn't start in the outer part of the scene.
- Can I just take a stack of the refraction indices and go one layer up as soon as I leave a sphere?
- How can I determine with what refraction index I have to start if I start inside of the spheres?
Example
You have three spheres, with refraction indices 0.9, 1.1 and 0.8 from outer to inner. Air index is 1.0
Your camera is outside of the sphere and points at the center of the sphere:
- start index is 1.0, you first hit the outer sphere with index 0.9 and refract from 1.0 to 0.9 and save that your ray is now in 0.9 material
- you hit the middle sphere and notice the material constant of 1.1, since you have saved the 0.9, you know that you have to refract from 0.9 to 1.1 and save the 1.1 in addition to the 0.9
- you hit the inner sphere and refract from 1.1 to 0.8 and you have save until now 0.9, 1.1 and 0.8
- you hit the inner sphere again (this time you exit it, so you check your saved values and know that you have to switch back to 1.1)
- ... until you are outside
Problem now, when the camera is inside the sphere. You won't know to what refraction index you have to switch.