The Monad.Reader/Issue5/HRay: A Haskell ray tracer - Revision history
http://www.haskell.org/haskellwiki/index.php?title=The_Monad.Reader/Issue5/HRay:_A_Haskell_ray_tracer&action=history
Revision history for this page on the wikienMediaWiki 1.19.5-1+deb7u1Sun, 26 Oct 2014 04:29:39 GMTGwern: The Monad.Reader/Issue5/HRay:A Haskell ray tracer moved to The Monad.Reader/Issue5/HRay: A Haskell ray tracer
http://www.haskell.org/haskellwiki/index.php?title=The_Monad.Reader/Issue5/HRay:_A_Haskell_ray_tracer&diff=20921&oldid=prev
http://www.haskell.org/haskellwiki/index.php?title=The_Monad.Reader/Issue5/HRay:_A_Haskell_ray_tracer&diff=20921&oldid=prev<p>The Monad.Reader/Issue5/HRay:A Haskell ray tracer moved to The Monad.Reader/Issue5/HRay: A Haskell ray tracer</p>
<table class='diff diff-contentalign-left'>
<tr valign='top'>
<td colspan='1' style="background-color: white; color:black;">← Older revision</td>
<td colspan='1' style="background-color: white; color:black;">Revision as of 20:03, 12 May 2008</td>
</tr></table>Mon, 12 May 2008 20:03:21 GMTGwernhttp://www.haskell.org/haskellwiki/Talk:The_Monad.Reader/Issue5/HRay:_A_Haskell_ray_tracerGwern: fmt
http://www.haskell.org/haskellwiki/index.php?title=The_Monad.Reader/Issue5/HRay:_A_Haskell_ray_tracer&diff=20889&oldid=prev
http://www.haskell.org/haskellwiki/index.php?title=The_Monad.Reader/Issue5/HRay:_A_Haskell_ray_tracer&diff=20889&oldid=prev<p>fmt</p>
<a href="http://www.haskell.org/haskellwiki/index.php?title=The_Monad.Reader/Issue5/HRay:_A_Haskell_ray_tracer&diff=20889&oldid=20887">Show changes</a>Sat, 10 May 2008 02:51:30 GMTGwernhttp://www.haskell.org/haskellwiki/Talk:The_Monad.Reader/Issue5/HRay:_A_Haskell_ray_tracerGwern: /* Contents */ toc
http://www.haskell.org/haskellwiki/index.php?title=The_Monad.Reader/Issue5/HRay:_A_Haskell_ray_tracer&diff=20887&oldid=prev
http://www.haskell.org/haskellwiki/index.php?title=The_Monad.Reader/Issue5/HRay:_A_Haskell_ray_tracer&diff=20887&oldid=prev<p><span dir="auto"><span class="autocomment">Contents: </span> toc</span></p>
<table class='diff diff-contentalign-left'>
<col class='diff-marker' />
<col class='diff-content' />
<col class='diff-marker' />
<col class='diff-content' />
<tr valign='top'>
<td colspan='2' style="background-color: white; color:black;">← Older revision</td>
<td colspan='2' style="background-color: white; color:black;">Revision as of 02:30, 10 May 2008</td>
</tr><tr>
<td colspan="2" class="diff-lineno">Line 18:</td>
<td colspan="2" class="diff-lineno">Line 18:</td>
</tr>
<tr>
<td class="diff-marker"> </td>
<td style="background: #eee; color:black; font-size: smaller;"><div>= Contents =</div></td>
<td class="diff-marker"> </td>
<td style="background: #eee; color:black; font-size: smaller;"><div>= Contents =</div></td>
</tr>
<tr>
<td class="diff-marker"> </td>
<td style="background: #eee; color:black; font-size: smaller;"></td>
<td class="diff-marker"> </td>
<td style="background: #eee; color:black; font-size: smaller;"></td>
</tr>
<tr>
<td class="diff-marker">−</td>
<td style="background: #ffa; color:black; font-size: smaller;"><div><span class="diffchange diffchange-inline">[[TableOfContents(3)]]</span></div></td>
<td class="diff-marker">+</td>
<td style="background: #cfc; color:black; font-size: smaller;"><div><span class="diffchange diffchange-inline">__TOC__</span></div></td>
</tr>
<tr>
<td class="diff-marker"> </td>
<td style="background: #eee; color:black; font-size: smaller;"></td>
<td class="diff-marker"> </td>
<td style="background: #eee; color:black; font-size: smaller;"></td>
</tr>
<tr>
<td class="diff-marker"> </td>
<td style="background: #eee; color:black; font-size: smaller;"><div>== Overview ==</div></td>
<td class="diff-marker"> </td>
<td style="background: #eee; color:black; font-size: smaller;"><div>== Overview ==</div></td>
</tr>
</table>Sat, 10 May 2008 02:30:49 GMTGwernhttp://www.haskell.org/haskellwiki/Talk:The_Monad.Reader/Issue5/HRay:_A_Haskell_ray_tracerWouterSwierstra at 14:25, 9 May 2008
http://www.haskell.org/haskellwiki/index.php?title=The_Monad.Reader/Issue5/HRay:_A_Haskell_ray_tracer&diff=20841&oldid=prev
http://www.haskell.org/haskellwiki/index.php?title=The_Monad.Reader/Issue5/HRay:_A_Haskell_ray_tracer&diff=20841&oldid=prev<p></p>
<p><b>New page</b></p><div>'''This article needs reformatting! Please help tidy it up.'''--[[User:WouterSwierstra|WouterSwierstra]] 14:25, 9 May 2008 (UTC)<br />
<br />
= HRay: A Haskell ray tracer =<br />
''by KennethHoste for The Monad.Reader IssueFive''<br />
[[BR]]<br />
''2005/06/11''<br />
<br />
http://www.elis.ugent.be/~kehoste/Haskell/hray_logo.png<br />
<br />
'''Abstract.'''<br />
As a thesis subject for Ghent University, I chose to write a ray tracer (HRay) in Haskell. The goal was to show how elegant,<br />
short and maintainable a ray tracing implementation would be in a functional language, as opposed to an imperative or procedural language. To achieve that goal, I first created a formal model for the application, using the functional and <br />
declarative formalism Funmath [[#funmath 1]]. In a next phase, the model was implemented in Haskell to create a working version of the ray tracer. Additional features were added to the model, including a command line and graphical user interface, a parser for input specifications and neat texture support using the Perlin Noise technique.<br />
<br />
This article describes the Haskell implementation of HRay. For more information about the formal model and my thesis, check<br />
the HRay website at [http://www.elis.ugent.be/~kehoste/Haskell/HRay].<br />
<br />
= Contents =<br />
<br />
[[TableOfContents(3)]]<br />
<br />
== Overview ==<br />
<br />
Before discussing the actual implementation, a brief description of the ray tracing algorithm is given. The implementation is<br />
split up into several modules, which are discussed one by one. First of all, the necessary mathematical functions to support<br />
the ray tracing algorithm are discussed. Based on that module, functions are presented which implement the ray tracer. To<br />
support some extra textures, a Perlin noise module is implemented, which will be discussed briefly. The two user interfaces are<br />
presented, one using command line arguments and one using the Haskell GUI library [http://haskell.org/gtk2hs Gtk2Hs]. Finally, some conclusions are drawn.<br />
<br />
== Ray tracing ==<br />
<br />
The powerful ray tracing algorithm is well known for the amazing results it produces [[#raytrac1 2]]. Because the rest of the article is based on the algorithm, we'll give a brief description of it. If you want more details, a good place to start is [[#raytrac2 3]].<br />
<br />
As the name states, the ray tracing algorithm is built upon the notion of rays. A ray is constructed through the point of view and some point of the view window. Given a desired resolution and collection of 3D objects, we calculate the intersection of the ray with the objects, for each pixel of the image. Again using rays, which are constructed as needed, the color for the intersection point (if any) is determined, depending on the color (or texture) of the object and the surrounding objects and light sources. Iterating over all pixels of the image results in a matrix of colors, representing the image. <br />
<br />
In pseudo-code:<br />
<br />
{{{<br />
for each pixel<br />
construct ray from view point to pixel location<br />
(*) determine closest intersection of ray with objects<br />
if no intersection<br />
pixel color = background color<br />
else<br />
for each light source<br />
construct ray from intersection point to light source location<br />
if intersection found between intersection point and light source<br />
shadow, so color = black<br />
else<br />
determine color contribution for light source, remember it<br />
if reflective surface<br />
construct reflected ray, determine contribution (*)<br />
if transparent surface<br />
construct refracted ray, determine contribution (*)<br />
determine color for pixel by summing all contributions<br />
}}}<br />
<br />
This is all quite imperative. The next step we need is to construct functions which can help with implementing the algorithm using a functional style. This is where the formal model came into play, but because we want to concentrate on the implementation of it all in Haskell, I'll just use the model informally: we'll first construct some basic math functions before moving on to the actual ray tracing engine. The needed types and datatypes are presented as needed.<br />
<br />
== Math functions ==<br />
<br />
=== Types and datatypes ===<br />
<br />
First of all, we mention the several (data)types needed to support the needed basic math functions. Because we are making a transition from a 2D to a 3D world, we need to be able to represent points in both worlds. Also, we need vectors for direction purposes, which are defined the same way as points in the 3D world are. This was a little point of critique in the formal model, but because in Haskell giving objects two different types is sufficient to distinguish between them, there is no problem. On the contrary, this way of defining the types supports overloading of functions such as multiplying a point/vector with some factor, and calculating the sum of two points/vectors. <br />
<br />
{{{#!syntax haskell<br />
type Point2D = (Int,Int)<br />
type Point3D = (Double,Double,Double)<br />
type Vector = (Double,Double,Double)<br />
}}}<br />
<br />
Using these new types, we can define a Ray datatype as follows.<br />
<br />
{{{#!syntax haskell<br />
data Ray = Ray Point3D Vector<br />
}}}<br />
<br />
Intuitively, every ray has a point of origin and a direction. Besides rays, the supported objects are also important in this module. For this purpose, the datatype defining the several supported objects is also defined here. To keep the implementation simple, we only support spheres and planes. <br />
<br />
{{{#!syntax haskell<br />
data Object = Sphere Double Point3D<br />
| Plane (Double,Double,Double,Double) <br />
}}}<br />
<br />
For type-convenience and clarity, we also introduce a Resolution and a Dimension type. The use of these types will become clear later on.<br />
<br />
{{{#!syntax haskell<br />
type Resolution = (Int,Int)<br />
type Dimension = (Int,Int)<br />
}}}<br />
<br />
=== Basic math functions ===<br />
<br />
When modelling the ray tracer, the need arose for the extension of some elementary operations on points and vectors. The functions supporting these operations where defined as infix operators, so the several expressions wouldn't become gibberish (don't you just hate when that happens in imperative languages). <br />
The first of these operations (sum of two points/vectors, subtraction of two points/vectors, multiplication of two points/vectors and multiplication of a point/vector with a factor) are given below. For efficiency, the types were not made polymorphic (i.e. using Num). <br />
<br />
{{{#!syntax haskell<br />
(<+>) :: (Double,Double,Double) -> (Double,Double,Double) -> (Double,Double,Double)<br />
(x1,y1,z1) <+> (x2,y2,z2) = (x1+x2, y1+y2, z1+z2)<br />
<br />
(<->) :: (Double,Double,Double) -> (Double,Double,Double)} -> (Double,Double,Double)<br />
(x1,y1,z1) <-> (x2,y2,z2) = (x1-x2,y1-y2,z1-z2)<br />
<br />
(<*>) :: (Double,Double,Double) -> (Double,Double,Double)} -> (Double,Double,Double)<br />
(x1,y1,z1) <*> (x2,y2,z2) = (x1*x2,y1*y2,z1*z2)<br />
<br />
(*>) :: (Double,Double,Double) -> Double -> (Double,Double,Double)<br />
(x,y,z) *> f = (x*f,y*f,z*f)}<br />
}}}<br />
<br />
Also the classic max and min operators are extended, to make the definition of a clip function (which will adjust the RGB values of colors) really simple. <br />
<br />
{{{#!syntax haskell<br />
maxF :: Double -> (Double,Double,Double) -> (Double,Double,Double)<br />
maxF f (x,y,z) = (max x f, max y f, max z f)<br />
<br />
minF :: Double -> (Double,Double,Double) -> (Double,Double,Double)<br />
minF f (x,y,z) = (min x f, min y f, min z f)<br />
}}}<br />
<br />
Besides the generalised functions above, we have defined elementary vector-only functions: scalar product of two vectors, length of a vector, normalizing a vector and creating a normalized vector given two points.<br />
<br />
{{{#!syntax haskell<br />
(*.) :: Vector -> Vector -> Double<br />
(x1,y1,z1) *. (x2,y2,z2) = x1*x2 + y1*y2 + z1*z2<br />
<br />
len :: Vector -> Double<br />
len v = sqrt (v *. v)<br />
<br />
norm :: Vector -> Vector<br />
norm v<br />
| len v < 10**(-9) = (0.0,0.0,0.0)<br />
| otherwise = v *> (1/(len v))<br />
<br />
mkNormVect :: Point3D -> Point3D -> Vector<br />
mkNormVect v w = norm (w <-> v)<br />
}}}<br />
<br />
For shadow purposes, we need a function which determines the distance between two given points, and to avoid 'color spilling', where the RGB values of a color reach values outside the [0,1] interval, we define a clipping function.<br />
<br />
{{{#!syntax haskell<br />
dist :: Point3D -> Point3D -> Double<br />
dist p0 p1 = sqrt ((p1 <-> p0) *. (p1 <-> p0))<br />
<br />
clip :: (Double,Double,Double) -> (Double,Double,Double)<br />
clip = (maxF 0.0) . (minF 1.0)<br />
}}}<br />
<br />
=== Geometric and other math functions ===<br />
Several functions which deal with the geometric issues involved in playing around with rays and geometric objects, are defined to support the ray tracing calculations. An important function is a quadratic solver, which is kept simple: it just returns a list of results... This way, it is compatible with future functions, which might produce more solutions.<br />
<br />
{{{#!syntax haskell<br />
solveq :: (Double,Double,Double) ->[Double]<br />
solveq (a,b,c)<br />
| (d < 0) = []<br />
| (d > 0) = [(- b - sqrt d)/(2*a), (- b + sqrt d)/(2*a)]<br />
| otherwise = [-b/(2*a)]<br />
where<br />
d = b*b - 4*a*c<br />
}}}<br />
<br />
For ray construction, we already have the data constructor Ray which comes with the data declaration of Ray. Because we also will need to create a ray given two points, we define a function which creates a normalized vector out of these points, and uses the Ray data constructor internally.<br />
<br />
{{{#!syntax haskell <br />
mkRay :: Point3D -> Point3D -> Ray<br />
mkRay p1 p2 = Ray p1 (mkNormVect p1 p2)<br />
}}}<br />
<br />
To determine the intersection of a ray with some object, we provide the intRayWith function. It returns a collection of intersection points, which should be sorted from close to far. Since we only support spheres and planes, the code needed if fairly simple.<br />
<br />
{{{#!syntax haskell <br />
intRayWith :: Ray -> Object -> [Double]<br />
intRayWith (Ray start dir) (Sphere rad cen) = solveq (dir *. dir, 2*(dir *. d), (d *. d) - rad^2)<br />
where<br />
d = start <-> cen<br />
intRayWith (Ray start dir) (Plane (a,b,c,d)) = if (abs(part) < 10**(-9)) then [] else [- (d + ((a,b,c) *. start) ) / part]<br />
where<br />
part = (a,b,c) *. dir<br />
}}}<br />
<br />
Ray tracing accurately models light information, i.e. shadows, highlights and fading colors. The calculations which make this possible, use the normals on the surfaces of objects to determine the angle in which the object is seen. For that purpose, we support a normal function (again, fairly simple).<br />
<br />
{{{#!syntax haskell <br />
normal :: Point3D -> Object -> Vector<br />
normal p (Sphere rad cen) = norm ((p <-> cen) *> (1/rad))<br />
normal _ (Plane (a,b,c,d)) = norm (a,b,c)<br />
}}}<br />
<br />
The real power of the ray tracing algorithm is the ease in which it models real-life effects such a reflection and refraction of light rays. Giving some direction, we provide<br />
functions to determine the reflected and refracted directions when the incoming ray intersects with some surface.<br />
<br />
{{{#!syntax haskell <br />
reflectDir :: Vector -> Vector -> Vector<br />
reflectDir i n = i <-> (n *> (2*(n *. i)))<br />
}}}<br />
<br />
{{{#!syntax haskell <br />
refractDir :: Vector -> Vector -> Double -> Vector<br />
refractDir i n r = if (v < 0) then (0.0, 0.0, 0.0) else norm $ (i *> r_c) <+> (n *> (r_c*(abs c) - sqrt v))<br />
where<br />
c = n *. (i *> (-1))<br />
r_c = if (c < 0) then r else 1/r -- when cosVal < 0, inside of sphere (so travelling to vacuum)<br />
v = 1 + (r_c^2) * (c^2 - 1)<br />
}}}<br />
<br />
Because the user can choose the resulting image resolution and the size of the view window, we need to map the pixel indices onto the window dynamically. This is done using the mapToWin function below.<br />
<br />
{{{#!syntax haskell <br />
mapToWin :: Resolution -> Dimension -> Point2D -> Point3D<br />
mapToWin (rx,ry) (w,h) (px,py) = (x/rxD,y/ryD,0.0)<br />
where<br />
(rxD,ryD) = (fromIntegral rx, fromIntegral ry)<br />
(pxD,pyD) = (fromIntegral px, fromIntegral py)<br />
(wD,hD) = (fromIntegral w, fromIntegral h)<br />
(x,y) = ( (pxD-rxD/2)*wD, (pyD-ryD/2)*hD )<br />
}}}<br />
<br />
== Ray tracing engine ==<br />
<br />
Using the mathematical basis of the HRayMath module, we can define the functions which will support the actual raytracing. First, we explain the needed (data)types, in the same way as we did with the math module. Next, we provide some functions which allow extraction of the needed information from an instance of the Intersection datatype. We discuss the functions which do the actual intersecting of rays with objects, determine the color of a pixel and support reflection and refraction effects. At the end of this section, we show the core functions of the raytracing engine, which are pretty short and elegant.<br />
<br />
=== Types and datatypes ===<br />
<br />
When working with (3D) graphics, the notion of color is essential. We represent a color as an RGB value (values between 0 and 1).<br />
<br />
{{{#!syntax haskell<br />
type Color = (Double,Double,Double)<br />
}}}<br />
<br />
As already mentioned, we will support special textures for all objects, besides just plain colors. For this purpose, we created a special dataype called Diff (diffuse color).<br />
<br />
{{{#!syntax haskell<br />
data Diff = Solid Color |<br />
Perlin (Point3D -> Color)<br />
}}}<br />
<br />
Each texture, whether plain or Perlin, has several parameters, to determine the reflection and refraction effects of the specific material. We support specular coefficient along with specularity, and refraction coefficient along with refraction index.<br />
<br />
{{{#!syntax haskell<br />
data Texture = Texture Diff Double Int Double Double<br />
}}}<br />
<br />
Every object in our scene is has a certain type (sphere, plane) and a texture attached to it. Hence we provide a TexturedObject datatype.<br />
<br />
{{{#!syntax haskell<br />
type TexturedObject = (Object,Texture)<br />
}}}<br />
<br />
Every light source has a certain color, which we call Intensity. That way one can use red, blue, bright and dark lights. We also support 2 basic types of light sources: <br />
ambient lights, which is actually a correcting factor, and point lights, which have a certain position in the 3D space.<br />
<br />
{{{#!syntax haskell<br />
type Intensity = (Double,Double,Double)<br />
<br />
data Light = PointLight Point3D Intensity<br />
| AmbientLight Intensity<br />
}}}<br />
<br />
The point of view (or camera) determines which view is rendered of the provided scene. We allow to define the point in space through which the scene is looked at, and the<br />
view window dimensions. The view window is always located in the XY-plane in the origin of the axis.<br />
<br />
{{{#!syntax haskell<br />
data Camera = Camera Point3D Dimension<br />
}}}<br />
<br />
The whole scene is described by describing the camera, background color, list of objects and list of light sources.<br />
<br />
{{{#!syntax haskell<br />
data Scene = Scene Camera Color [TexturedObject] [Light]<br />
}}}<br />
<br />
An intersection of a ray with an object provides the neccesary information for the raytracing calculations. We include the distance to the intersection, the intersecting ray and the object which is intersected.<br />
<br />
{{{#!syntax haskell<br />
data Intersection = Intersection Double Ray TexturedObject<br />
}}}<br />
<br />
The final product of the algorithm, an image representing the 3D scene, is actually a matrix of color. That way, each pixel pair is mapped to a RGB color tuple.<br />
<br />
{{{#!syntax haskell<br />
type Image = Point2D -> Color<br />
}}}<br />
<br />
=== Intersection functions ===<br />
<br />
Because not every ray will intersect with an object, we use the Maybe monad in combination with our own Intersection datatype. In order to make working with the artificial<br />
(Maybe Intersection) type easier, we provide some functions which extract information from a possible intersection. This design choice might be an opportunity for improvement.<br />
We show the distance, texture, color, normal and intersection point functions. Notice how the color of some point in the 3D space is dependent on the location for Perlin textures.<br />
<br />
{{{#!syntax haskell<br />
intDist :: (Maybe Intersection) -> Double<br />
intDist Nothing = 0.0<br />
intDist (Just (Intersection d _ _)) = d<br />
}}}<br />
<br />
{{{#!syntax haskell<br />
intText :: (Maybe Intersection) -> Texture<br />
intText Nothing = Texture (Solid (0.0,0.0,0.0)) 0.0 0 0.0 0.0<br />
intText (Just (Intersection _ _ (_,t))) = t<br />
}}}<br />
<br />
{{{#!syntax haskell<br />
colorAt :: (Maybe Intersection) -> Color<br />
colorAt Nothing = (0.0,0.0,0.0)<br />
colorAt (Just (Intersection _ _ (_,Texture (Solid color) _ _ _ _) )) = color<br />
colorAt i@(Just (Intersection _ _ (_,Texture (Perlin f) _ _ _ _) )) = f (intPt i)<br />
}}}<br />
<br />
{{{#!syntax haskell<br />
normalAt :: (Maybe Intersection) -> Vector<br />
normalAt Nothing = (0.0,0.0,0.0)<br />
normalAt i@(Just (Intersection _ _ (o,_) )) = normal (intPt i) o<br />
}}}<br />
<br />
{{{#!syntax haskell<br />
intPt :: (Maybe Intersection) -> Point3D<br />
intPt Nothing = (0.0,0.0,0.0)<br />
intPt (Just (Intersection d (Ray start dir) _)) = start <+> (dir *> d)<br />
}}}<br />
<br />
=== Intersecting ===<br />
<br />
To determine the intersection (if any) of a ray with the collection of objects, we use the functions below. <br />
<br />
At first, a simple function is used to determine the first positive element in a list of doubles. We chose not to remove the negative values from the list of intersection<br />
distances because we might need them for other uses, when extending the features of the raytracer. <br />
<br />
{{{#!syntax haskell<br />
fstPos :: [Double] -> Double<br />
fstPos [] = 0.0<br />
fstPos (l:ls) = if l > 10**(-6) then l else fstPos ls<br />
}}}<br />
<br />
This function determines whether the intersection formed by the given ray and object (if any) is better than the known intersection. <br />
<br />
{{{#!syntax haskell<br />
closestInt :: Ray -> (Maybe Intersection) -> TexturedObject -> (Maybe Intersection)<br />
closestInt r i (o,m) = if d > 10**(-6) && ((isNothing i) || d < (intDist i)) <br />
then Just (Intersection d r (o,m))<br />
else i<br />
where<br />
d = fstPos (intRayWith r o)<br />
}}}<br />
<br />
To intersect a ray with a collection of objects, we can use the powerfull foldl operator in combination with the closestInt function (which is given a basic empty intersection to start with).<br />
<br />
{{{#!syntax haskell<br />
intersect :: Ray -> [TexturedObject] -> (Maybe Intersection)<br />
intersect r o = foldl (closestInt r) Nothing o<br />
}}}<br />
<br />
=== Determining color ===<br />
<br />
The color of an intersection point is determined by several factors: the diffuse color of the object itself (and the angle of view), the specular influence of the light sources and the other objects, which might be blocking the light from some light sources. The functions diff, spec and shadePt do the neccesary calculations to determine the color at a given intersection point. For more details on how this is done, we point to [[#raytrac2 3]].<br />
<br />
{{{#!syntax haskell<br />
diff :: (Maybe Intersection) -> Light -> Color<br />
diff _ (AmbientLight _) = (0.0,0.0,0.0)<br />
diff i (PointLight pos int) = (int *> ((mkNormVect (intPt i) pos) *. (normalAt i))) <*> (colorAt i)<br />
<br />
spec :: (Maybe Intersection) -> Vector -> Light -> Color<br />
spec _ _ (AmbientLight _) = (0.0,0.0,0.0)<br />
spec i d (PointLight pos int) = int *> (reflCoef * ( ((normalAt i) *. h)**(fromIntegral specCoef) ))<br />
where<br />
h = norm ((d *> (-1)) <+> (mkNormVect (intPt i) pos))<br />
(Texture _ reflCoef specCoef _ _) = intText i <br />
<br />
shadePt :: Intersection -> Vector -> [TexturedObject] -> Light -> Color <br />
shadePt i d o (AmbientLight int) = int<br />
shadePt i d o l@(PointLight pos int)<br />
| s = (0.0,0.0,0.0)<br />
| otherwise = (diff (Just i) l) <+> (spec (Just i) d l)<br />
where <br />
s = not (isNothing i_s) && (intDist i_s) <= dist (intPt (Just i)) pos <br />
i_s = intersect (mkRay (intPt (Just i)) pos) o <br />
}}}<br />
<br />
=== Recursive functions ===<br />
<br />
The reflection and refraction effects are basically contributions of the other objects in the scene to the color of an intersection point. In the raytracing algorithm, this is modelled pretty easily: just look at the other objects in the scene from the intersection, and add the color observed in that point to the color of the intersection (of course taking into account the reflection/refraction component of the texture of the object). In other words: use recursion.<br />
<br />
{{{#!syntax haskell<br />
reflectPt :: Int -> Intersection -> Vector -> [TexturedObject] -> [Light] -> Color <br />
reflectPt depth i d = colorPt depth (Ray (intPt (Just i)) (reflectDir d (normalAt (Just i)))) (0.0,0.0,0.0) <br />
<br />
refractPt :: Int -> Intersection -> Vector -> Color -> [TexturedObject] -> [Light] -> Color <br />
refractPt depth i d b = if refractedDir == (0.0,0.0,0.0) then (\x y -> (0.0,0.0,0.0)) <br />
else colorPt depth (Ray (intPt (Just i)) refractedDir) (b *> refrCoef) <br />
where <br />
refractedDir = refractDir d (normalAt (Just i)) refrIndex <br />
(Texture _ _ _ refrCoef refrIndex) = intText (Just i) <br />
}}}<br />
<br />
=== Core functions ===<br />
<br />
To determine the actual color at some pixel of the image, we shoot a ray through the pixel from some point and add all the different components (object, reflection, refraction) together. To avoid infinite recursion (rays bouncing between two point without changing direction), we use a recursion depth parameter. <br />
<br />
{{{#!syntax haskell<br />
colorPt :: Int -> Ray -> Color -> [TexturedObject] -> [Light] -> Color<br />
colorPt (-1) _ _ _ _ = (0.0, 0.0, 0.0) <br />
colorPt d r@(Ray _ dir) b o l = if (isNothing i) then b else clip $ shadeColor <+> reflectColor <+> refractColor<br />
where <br />
shadeColor = foldl (<+>) (0.0,0.0,0.0) (map (shadePt (fromJust i) dir o) l)<br />
reflectColor = if (reflCoef == 0.0) then (0.0, 0.0, 0.0) <br />
else (reflectPt (d-1) (fromJust i) dir o l) *> reflCoef <br />
refractColor = if (refrCoef == 0.0) then (0.0, 0.0, 0.0) <br />
else (refractPt (d-1) (fromJust i) dir b o l) *> refrCoef <br />
i = intersect r o <br />
(Texture _ reflCoef _ refrCoef _) = intText i <br />
}}}<br />
<br />
The actual algorithm translation to Haskell is really simple: for every pixel, map it to the view window, create a ray and determine the color.<br />
<br />
{{{#!syntax haskell<br />
rayTracePt :: Int -> Scene -> Point3D -> Color <br />
rayTracePt d (Scene (Camera eye _) b o l) p = colorPt d (Ray p (mkNormVect eye p)) b o l <br />
<br />
rayTrace :: Int -> Resolution -> Scene -> Image <br />
rayTrace d r s@(Scene (Camera _ dim) _ _ _) = (rayTracePt d s) . (mapToWin r dim) <br />
}}}<br />
<br />
== Perlin noise textures ==<br />
<br />
Because the article would be too long, we don't elaborate on the implementation of the Perlin Noise textures. The code is freely available on [http://scannedinavian.org/~boegel/HRay], together with a gallery of images produced by the raytracer. If you want more information on the technique, please contact me (again, see the website).<br />
<br />
== A scene description parser ==<br />
<br />
To support creation of scenes, we created a small, simple parser using Happy. When downloading the source code from the website, several example files are included, which should be enough to create your own scenes. Again, because of space limitations, we won't elaborate on the parser implementation.<br />
<br />
== User interfaces ==<br />
<br />
To simplify usage of the raytracer, two simple interfaces were created. First, a very basic command line interface is provided, which gives limited feedback (render time, parse errors). Besides that, a simple GUI was created using the Gtk2Hs graphical library, a Gtk binding for Haskell. This provides a bit more feedback, but requires that Gtk2Hs [http://haskell.org/gtk2hs] installed. For more information on Gtk2Hs, one should read my article published in the first issue of The Monad.Reader [http://www.haskell.org/hawiki/TheMonadReader/IssueOne]. <br />
<br />
== Performance issues ==<br />
<br />
While implementing the raytracer, performance was no issue. The goal was not to implement to fastest possible raytracer imaginable, but to show how elegant and clear a Haskell implementation can be. Because of this, a lot of improvements can be made to the existing code. Everyone who feels like doing so is free to use the code and make the neccesary adjustments. <br />
<br />
== Conlusions ==<br />
<br />
Recently, Jean-Philippe Bernardy added metaball support to HRay (check the gallery at http://scannedinavian.org/~boegel/HRay for images). While implementing, we used the Haskell98 standard. Several improvements are possible, including using type classes, which wasn't possible without using extensions to the Haskell98 standard (more specifically, existential types). Contributions, remarks or/and bugs are welcome. Have fun rendering and hacking !<br />
<br />
== References ==<br />
<br />
[[Anchor(funmath)]]<br />
[1] R.T. Boute "Concrete Generic Functionals: Principles, Design and Applications". Generic Programming 89-119, Kluwer, 2003<br />
<br />
[[Anchor(raytrac1)]]<br />
[2] POV-Ray: Hall of Fame (http://www.povray.org/community/hof/)<br />
<br />
[[Anchor(raytrac2)]]<br />
[3] M. Slater, A. Steed and Y. Chrysanthou "Computer Graphics and Virtual Environments - From Realism to Real-Time". Addison-Wesley, 2001<br />
<br />
----<br />
CategoryArticle</div>Fri, 09 May 2008 14:25:43 GMTWouterSwierstrahttp://www.haskell.org/haskellwiki/Talk:The_Monad.Reader/Issue5/HRay:_A_Haskell_ray_tracer