A Ray Tracer in C#3.0
Ray tracers are a lot of fun. When I was in middle school, I discovered POV-Ray and was so excited about the cool graphics it could create that I would often leave my 286 on overnight rendering ray-traced scenes and movies. When I was in high school, I discovered Computer Graphics: Principles and Practice and spent weeks working through it's ray tracing algorithms trying to implement my own ray tracer in C++. When I was in college, taking an introductory course which used Scheme, I re-wrote the raytracer in Scheme to show some friends that you really could write programs longer than 20 lines in Scheme! And then when I joined the C# team 3 years ago, I of course had to re-write my raytracer in C#.
More recently, I took a pass through the code to update it to use C#3.0. It's not a particularly fancy or efficient ray tracer - but then again, it's only 400 lines of code. Below are a few of the interesting uses of C#3.0 from the ray tracer code.
C#3.0 Without the Databases and XML
Although we often demo C#3.0 using databases and XML to show off LINQ - it turns out that the new language features really are also great for applications which have little to do with querying. Ray tracing, for example, is certainly not one of the prototypical scenario for query and transformation of data. Nonetheless, I found quite a few places in the code where C#3.0 and LINQ to Objects really improved the code - making it easier to express what the program was doing.
LINQ to Objects
Here's one example of the method which computes the intersections of a ray with the objects in a scene.
private IEnumerable<ISect> Intersections(Ray ray, Scene scene)
{
return scene.Things
.Select(obj => obj.Intersect(ray))
.Where(inter => inter != null)
.OrderBy(inter => inter.Dist);
}
The method intersects each object in the scene with the ray, then throws away those that didn't intersect, and finally orders the rest by the distance from the source of the ray. The first object in this result is the closest object hit by the ray. If there are no elements in the result, there were no intersections. The LINQ to Objects query methods provide a nice way to describe this, and lambdas make it easy to write the code which processes the objects and intersections.
Object and Collection Initializers
Here's the code that describes the scene rendered in the image above.
internal readonly Scene DefaultScene =
new Scene() {
Things = new SceneObject[] {
new Plane() {
Norm = Vector.Make(0,1,0),
Offset = 0,
Surface = Surfaces.CheckerBoard
},
new Sphere() {
Center = Vector.Make(0,1,0),
Radius = 1,
Surface = Surfaces.Shiny
},
new Sphere() {
Center = Vector.Make(-1,.5,1.5),
Radius = .5,
Surface = Surfaces.Shiny
}},
Lights = new Light[] {
new Light() {
Pos = Vector.Make(-2,2.5,0),
Color = Color.Make(.49,.07,.07)
},
new Light() {
Pos = Vector.Make(1.5,2.5,1.5),
Color = Color.Make(.07,.07,.49)
},
new Light() {
Pos = Vector.Make(1.5,2.5,-1.5),
Color = Color.Make(.07,.49,.071)
},
new Light() {
Pos = Vector.Make(0,3.5,0),
Color = Color.Make(.21,.21,.35)
}},
Camera = Camera.Create(Vector.Make(3,2,4), Vector.Make(-1,.5,0))
};
The scene consists of a collection of things, a collection of lights, and a camera, all of which are initialized in one statement using object and collection initializers. This makes it quite a bit easier to describe the scene. This format also helps to make the structure of the scene clear.
Lambdas
Here's the code describing the two surface textures used in the image above:
static class Surfaces {
// Only works with X-Z plane.
public static readonly Surface CheckerBoard =
new Surface() {
Diffuse = pos => ((Math.Floor(pos.Z) + Math.Floor(pos.X)) % 2 != 0)
? Color.Make(1,1,1)
: Color.Make(0,0,0),
Specular = pos => Color.Make(1,1,1),
Reflect = pos => ((Math.Floor(pos.Z) + Math.Floor(pos.X)) % 2 != 0)
? .1
: .7,
Roughness = 150
};
public static readonly Surface Shiny =
new Surface() {
Diffuse = pos => Color.Make(1,1,1),
Specular = pos => Color.Make(.5,.5,.5),
Reflect = pos => .6,
Roughness = 50
};
}
These two static fields are initialized with the surface styles for the checkerboard and shiny textures on the objects in the scene above. The surfaces are created with object initializers, and lambda expressions are used to provide the functions to compute diffuse, specular and reflection values based on the position on the surface. The combination makes it possible to do something similar to prototype objects.
Try Out the Code
Want to try it out yourself? Just compile RayTracer.cs with the Orcas C# compiler. Then run.
Comments
Anonymous
April 08, 2007
You've been kicked (a good thing) - Trackback from DotNetKicks.comAnonymous
April 08, 2007
Recently my time has been taken up with a series of internal issues involving Beta1, C# Samples and variousAnonymous
April 09, 2007
C# PM Luke Hoban has posted a simple C# Ray Tracer code that utilizes the new C# 3.0 language capabilities.Anonymous
April 14, 2007
I'm really impressed. Another msdn.com blogger just showed up a really nice example of how to use LINQAnonymous
April 19, 2007
I have been wanting this kind of thing in C++ for ages (well, at least a year). I think it will be useful in terms of writing AI programs and games where you don't keep your game characters in a database. An AI program could first load an entire common-sense database into memory. This is what I will use it for when LINQ comes out. e.g. print "Watch out! There are "+ (select X from gameObjects where X.type==enemyTroll && X.pos.isNearTo(GamePlayer1.pos) ).length
- "trolls near to you!" which is really easy to read. Here is another example that prints prime numbers less than 1000: foreach n in range(2,1000){ if( (select d from range(2,sqrt(n)) where n%d==0).length ==0 ) print n+" is a primen" } How about using LINQ with OpenGL or DirectX where you could use it with vertex lists and things. Or how about using it with pixels in bitmaps: foreach PIXEL in BITMAP if(PIXEL.colour.red<128) PIXEL.color=Color(0,128,0) is this possible? This could be accelerated by DirectX10 shaders. P.S. What are the ideas for c# 4.0? With the idea that the computer should work out the best way to do things it sounds like it is turning into something like Maple, or Mathematica. Or how about using ideas from PROLOG?
Anonymous
April 20, 2007
On connaissait LinQ et ses possibilits pour du requtage type base de donnes, mais voici une application de RayTracing qui met en vidence les possibilits de LinQ dans un contexte compltement inhabituel :Anonymous
April 23, 2007
how about a C# 2.0 version? I'm not allowed to run beta applications at my employer. Thanks!Anonymous
April 25, 2007
Luke, a member of the c# team, created a Ray Tracer in c#. What is ray tracing exactly? Well, WikipediaAnonymous
April 27, 2007
Neat syntax, but... I'd rather see MS finally invest some effort in building decent .NET compilers, making use of the specific processor capabilities so we can do fast vector/matrix math sigh.Anonymous
May 04, 2007
Paulsta - In principle there are places where LINQ could make sense with OpenGL or DirectX. There was one specific topic related to leveraging pixel shaders from C# discussed on the forums recently http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1533657&SiteID=1 - which may be relevent here.Anonymous
June 07, 2007
Hi, I have a little different question: Diffuse = pos => ((Math.Floor(pos.Z) + Math.Floor(pos.X)) % 2 != 0) ? Color.Make(1,1,1) : Color.Make(0,0,0) Is it possible to generate functions / lambdas at runtime other way than emitting IL instructions? I mean a simple way to let user specify a string describing a material(per-pixel basis) and then render that material without parsing the string? Btw, in return scene.Things .Select(obj => obj.Intersect(ray)) .Where(inter => inter != null) .OrderBy(inter => inter.Dist); I don't think the final OrderBy clause is a good approach since you only need the nearest intersection from the camera, so a linear loop over filtered Things would be quicker.Anonymous
June 11, 2007
The comment has been removedAnonymous
October 02, 2007
Not too long ago I blogged about a C# raytracer which took advantage of a lot of C#3.0 language constructs.Anonymous
October 02, 2007
Not too long ago I blogged about a C# raytracer which took advantage of a lot of C#3.0 language constructsAnonymous
October 05, 2007
Multi-cpu systems and multicore processors are becoming ever more common, but writing code that actuallyAnonymous
November 16, 2007
Through Don Syme's blog I read about Luke Hoban moving from the C# team at Microsoft to the F# teamAnonymous
November 30, 2007
Thanks for this, nice to see a non-typical usage for LINQ!Anonymous
December 04, 2007
thank you for this excellent programAnonymous
December 14, 2007
hi, I'm a beginner at C#. When I try to Building your code in VS 2008 RTM, I got those error messages: Error 1 The type or namespace name 'Linq' does not exist in the namespace 'System' (are you missing an assembly reference?) Error 2 The type or namespace name 'Func' could not be found (are you missing a using directive or an assembly reference?) I find the 'System.Data.Linq' and 'System.Xml.Linq', which one I need? And how can I fix the error 2? If you have free time, please tell me how do. My email is bryan.chou@gmail.com. Thanks.Anonymous
December 16, 2007
Bryan - Sounds like you probably don't have "System.Core.dll" referenced in your project. This is where much of the core functionality in .NET 3.5 (including parts of LINQ) is provided.Anonymous
December 25, 2007
i think using Assmebly instruction is very better and has extermly better Performance!Anonymous
January 31, 2008
Nice post on using new language features in C# 3.0 for ray tracing: LukeH's WebLog : A Ray Tracer inAnonymous
February 11, 2008
The comment has been removedAnonymous
February 26, 2008
I've been thinking about ranges again, particularly after catching a book error just in time, andAnonymous
June 04, 2008
The June 2008 Community Technology Preview (CTP) of Parallel Extensions to the .NET Framework was releasedAnonymous
June 09, 2008
I had some free time today and did this: I'd like to note that LukeH made the core raytracing engineAnonymous
June 09, 2008
Hi Luke! This is pretty nice! I decided to use it, and made a Silverlight application out of it: http://blogs.msdn.com/nikola/archive/2008/06/10/raytracing-in-silverlight.aspx You're in the credits - thanks for the great sample!Anonymous
August 11, 2008
Hi, I have made a port of this sample on Mac OS X, by using Mono and the Monobjc bridge. For more details: http://laurent.etiemble.free.fr/dotclear/tb.php?id=123 Laurent Etiemble.Anonymous
January 15, 2009
I've been thinking about ranges again, particularly after catching a book error just in time, andAnonymous
January 23, 2009
The comment has been removedAnonymous
November 16, 2009
düğün davetiyesi ve davetiye sözleriAnonymous
April 25, 2010
hi, the code has some errors, can you mail the whole code to me ? my email is afterburn888@gmail.comAnonymous
August 22, 2011
Inspired from you - silverlight raytracing benchmark: http://silver.urih.com/