Probando el raytracing en AS3

VIEW EXAMPLE

Some time ago I wanted to program a ray tracer on real time. The main problem I faced is that ray tracing is difficult to compute, because the quantity of calculations grows when you place more objects on the scene. In order to get a good frame rate I needed to reduce the calculations per frame to a minimum.

So I started with something very simple: one cube, one sphere and one light. The algorithm trows one ray per pixel of the image from the camera to the scene, checking if it collides with any object on the scene. In the first tries, besides the simplicity of the scene (five squares and one sphere), the performance was very bad. Since I couldn´t reduce more the quantity of objects to show, I had to make some improvements, sacrificing the code legibility, until the point of placing all the functionality in one single function in the style of spaghetti code. I wish I could have a goto instruction in AS3!.

Finally, as a final optimization, every image is drawn in a very small bitmapData, this data is then scaled through the smoothing option found in the Bitmap Class finding the final image with a more useful size. In this case the distortion is very clear, so I “killed” the sphere.

If you are curious, these raytracers are very interesting:
· www.strille.net/works/as3/raytracer/
· www.laserpirate.com/as3raytracer
· www.peternitsch.net/blog/?p=182

Original post in Spanish

Hacía tiempo que tenía en mente programar un ray tracer en tiempo real. El principal problema al que me enfrentaba es que el raytracing es costoso de computar, aumentando la cantidad de cálculos cuantos más objetos hay en la escena. Para conseguir un buen frame rate necesitaba reducir al máximo los cálculos por cada frame.

Así que decidí probar con algo sencillo: un cubo, una esfera y una luz. Básicamente, el algoritmo lanza un rayo por cada píxel de imagen desde la cámara hacia la escena, comprobando si colisiona con algún objeto de la escena. En las primeras pruebas, a pesar de la sencillez de la escena (cinco cuadrados y una esfera), el rendimiento era bastante malo. Ya que no podía reducir más la cantidad de objetos a mostrar, tuve que echar mano de optimizaciones, sacrificando la legibilidad del código, hasta el punto de meter casi toda la funcionalidad en una función principal al estilo spaghetti code. Incluso eché en falta una instruccion goto en AS3.

Finalmente, como última optimización, cada imagen se dibuja en tamaño pequeño ampliandolo mediante la opción smoothing de la clase Bitmap a un tamaño más adecuado. En este caso la distorsión es muy clara, así que eliminé la esfera.

Si tenéis curiosidad, estos raytracers son interesantes:
· www.strille.net/works/as3/raytracer/
· www.laserpirate.com/as3raytracer
· www.peternitsch.net/blog/?p=182


Posted

in

by

Tags: