Home

Awesome

CMake Ray Tracer

A simple ray tracer written in pure CMake. Inspired by raytracer.hpp. More information can be found at my blog.

image

Usage

The ray tracer writes its output to stderr, so you can use it with:

cmake -Dimage_width=64 -Dimage_height=64 -Dnum_procs=4 -P CMakeLists.txt 2> image.ppm

Which renders using 4 CPU cores and writes the output to image.ppm. Then use an image viewer capable of opening PPM files (or this) to view.

Alternatively, the ray tracer can directly write PNG files (thanks to @benmcmorran for contributing this). The PNG encoder is also implemented in pure CMake, but either PowerShell or Python is required with this method since CMake is unable to write binary files directly. Set the use_png variable to set the name of the PNG file (without the extension). The example below will write output to render.png:

cmake -Dimage_width=64 -Dimage_height=64 -Dnum_procs=4 -Duse_png=render -P CMakeLists.txt

num_procs controls the number of worker processes spawned. It is recommended to set this to a value no greater than the number of cores in your CPU, for maximum performance. If not provided, it will be automatically detected based on the number of available cores.

To keep the code simple, the image_width, image_height and num_procs must be powers of 2, otherwise the image will not be fully formed. If not specified, these arguments default to the values shown above.

Performance

Using cmake 3.19.2 on Linux 5.4 on a i5-10210U (4 cores, 8 threads), running this command:

for X in 1 2 4 8 16 32 64 128 256 512 ; do echo SIZE $X ; time cmake -Dimage_width=$X -Dimage_height=$X -Dnum_procs=8 -P CMakeLists.txt 2> image_size_${X}.ppm  ; done

PowerShell alternative:

1, 2, 4, 8, 16, 32, 64, 128, 256, 512 | foreach {Write-Host $_; (Measure-Command { cmake "-Dimage_width=$_" "-Dimage_height=$_" "-Dnum_procs=$Env:NUMBER_OF_PROCESSORS" -P CMakeLists.txt 2> image_size_$_.ppm }).TotalSeconds}

Figures reported by time command below (reformatted). As usual, the "real" time is the wall clock time. The others are summed on all processors.

sizerealusersys
10,054s0,130s0,051s
20,035s0,098s0,041s
40,077s0,274s0,018s
80,106s0,460s0,023s
160,367s1,871s0,059s
321,296s7,617s0,132s
645,175s29,455s0,356s
12821,093s2m06,299s1,566s
2561m33,395s9m21,875s5,999s
5127m23,094s45m36,327s32,588s

Contributing

All contributions (issue, PRs) are welcome. This project is licensed under the MIT license.