# Introduction

I first started writing raytracers in 1999 when a friend and me spent a week cobbling together a basic raytracer in C++. The code is still around somewhere, but I looked at it a few years ago and barely recovered. So you’re not seeing it.

The results were however quite satisfying, particularly after a couple of years playing with traditional polygon engines.

Early rayraced image from 1999

Another early render from 1999 raytracer

Anyway; cut a long story short. Done a lot of raytracers, and I’m going to go through the very basics of constructing a raytracer from scratch, partly for my own amusement, and partly because you might find it interesting?

So, first things first… what’s a raytracer? To put it simply, it’s a way of generating an image by simulating rays of light leaving a camera and finding out what they hit.

To be honest, it’s probably easier to understand by example. Imagine you’re sitting in front of a window but you’re only allowed to look at it through a tiny hole in a piece of paper. By looking through the hole you can “sample” the colour of a small section of the picture. Like this…

Example of tracing a single ray into a scene (real world)

If you moved the paper around a few more times you’d be able to build up an idea of what was outside the window by drawing each of the colours into a seperate square…

Example of a number of rays being traced into a scene (real world)

And if you had absolutely nothing to do, you could sample thousands of colours and draw each of these out, and you’d eventually end up with something that looks a lot like the scene outside the window (i.e. the image on the left above).

In a raytracer that’s exactly what we do with every single pixel on the screen. First of all we build a “ray” from the camera position and in a specific direction depending on which pixel we’re tracing. We then calculate whether that ray hits any of the objects in our scene. If the ray does hit an object, we calculate what colour to show. Easy right?

For a very first raytracer I’d suggest implementing a simple ray-sphere intersection. You’ll find everything you need on this in-depth article about the ray-sphere intersection. Then drop it into Visual C# Express and have a go at generating an image.

With a flat diffuse lighting model it won’t be long until you’re generating this…

Simple diffuse lighting model

Next time we’ll go into lighting in a bit more detail. What’s a specular lighting model? Why bother?