Luke H. shows how to write a ray tracer using C# 3 and LINQ in about 400 lines of code.
Ray tracing is a method of rendering 3D images on a two dimensional surface such as a computer screen or a printed page. It usually relies on backtracking a virtual light beam from a pixel on the 2D surface to the first three-dimensional object it strikes. Depending on the texture of the object it strikes, it may continue to backtrack until it reaches a light source.
Luke uses LINQ to simplify code for sorting and filtering collections, as well as a replacement for loops when calculating intersections. Object and collection initializers are demonstrated, though they do not significantly change the code in this example.
The use of lambda expressions instead of subclasses and overrides or explicit delegates is the real winner for increasing clarity and reducing lines of code.
A write-up on the ray tracer and the source code is available on Luke's blog.
Community comments
You should check out the source code...
by Kurt Christensen,
You should check out the source code...
by Kurt Christensen,
Your message is awaiting moderation. Thank you for participating in the discussion.
...because it's pretty damn cool. To say that it's ~400 lines doesn't even do it justice; if you ignore the various utility classes (e.g., Vector, Camera, etc.), the code is just amazingly small and easy to read.