<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Joseph Grosso on Medium]]></title>
        <description><![CDATA[Stories by Joseph Grosso on Medium]]></description>
        <link>https://medium.com/@jogrosso?source=rss-5d8a14019851------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8ypM9GGb2XAKql3GdsoZ1g.jpeg</url>
            <title>Stories by Joseph Grosso on Medium</title>
            <link>https://medium.com/@jogrosso?source=rss-5d8a14019851------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 00:16:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jogrosso/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Ray Tracer Challenge — Learning C++ through Computer Graphics]]></title>
            <link>https://medium.com/@jogrosso/the-ray-tracer-challenge-learning-c-through-computer-graphics-e45a68fb7cd5?source=rss-5d8a14019851------2</link>
            <guid isPermaLink="false">https://medium.com/p/e45a68fb7cd5</guid>
            <category><![CDATA[cpp-programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ray-tracing]]></category>
            <category><![CDATA[graphics]]></category>
            <dc:creator><![CDATA[Joseph Grosso]]></dc:creator>
            <pubDate>Wed, 02 Apr 2025 14:42:29 GMT</pubDate>
            <atom:updated>2025-04-29T04:36:32.111Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Ray Tracer Challenge — Learning C++ through Computer Graphics</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*-vkexlwtML76bAHNOk7psg.png" /><figcaption>One of the images created by the ray tracer. Scroll to the bottom of this article to find more renders!</figcaption></figure><p>Over the past year, I’ve been working on creating a ray tracing engine in C++, following the incredible book <a href="http://raytracerchallenge.com/">The Ray Tracer Challenge</a> by Jamis Buck. It’s been a very long and rewarding development journey, and I finally completed the last chapter just a few days ago! This write-up documents exactly what this challenge is, shows what I’ve learned in the process, and presents some of the cool images I’ve created using this tool.</p><p>Interested in the source code? Here’s the link: <a href="https://github.com/joseph-grosso/ray-tracer-challenge">GitHub</a></p><h3>What is ray tracing?</h3><p>Ray tracing is an approach used in computer graphics to render images through computer processing. Computers can generate photorealistic scenes by simulating how rays of light travel to create shadows, reflections, and refractions in different materials.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/0*mOwz5u3eAWIL4xdr" /></figure><p>To render the image, we can use code to define the factors that create the scene: the objects, the lighting, and the camera. Once we define all of the factors, we can use the camera to take samples of the colour at each point of our image. Instead of light coming into our eyes, like in the real world, for each pixel we send a ray out at the scene and check what it hits. When the ray hits an object, we can compute the colour at that point by using the scene lighting and all of the object information to answer many questions, like:</p><ul><li>Is the object’s surface pointed toward or away from our light source?</li><li>What colour is the material, and how do the material’s properties affect how it interacts with the light?</li><li>Is there any object blocking our object from the light source, casting a shadow?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*DT0y29uoM4BFT5Lt" /><figcaption>A simple example of Phong illumination computed using the ray tracing engine.</figcaption></figure><p>All of these factors can affect the colour and realism of the output image.</p><p>We can create very visually interesting pictures using just the techniques above. The magic of ray tracing becomes even more apparent when we add reflection and refraction into the mix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KJE7yYhpt4EpRSOh6Db7_g.png" /></figure><p>We can compute how a ray of light hitting a reflective and transparent surface (e.g., mirrors, glass, or water) affects the resulting image by bouncing out rays from where we hit the object and adding the colours found along the rays to the result. By adding reflection and refraction, we can create scenes that more closely represent how light works in the real world.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oZvmWQmVTPfx3udb" /></figure><h3>What inspired you to work on this?</h3><p>When I first read about the challenge, I thought it was such a unique application of computer programming in an area (computer graphics) I knew very little about. My typical working language was Python; I wanted to branch out with another programming language to expand my skills with a significant personal project. The book is targeted towards experienced developers, so it seemed to fit the exact parameters for a project I was looking for.</p><h3>Why did you choose to use C++ to develop the project?</h3><p>I have long been interested in learning C++ because of its widespread use in animation software (eg. <a href="https://www.blender.org/">Blender</a>) and video game rendering (eg. <a href="https://www.unrealengine.com/en-US">Unreal Engine</a>), where high performance is critical. C++ provides low-level features such as direct memory management and multithreading, which contribute to its speed advantage over interpreted languages like Python. Its massive ecosystem of libraries supports advanced development, and its support for object-oriented programming promotes modular, maintainable design. While I had previously gained experience with C during university, C++ offered a more complex and feature-rich environment that sparked my enthusiasm to explore and master it.</p><h3>How does the book lead you through the project?</h3><p>Each chapter of the book leads you through part of the rendering puzzle and allows your code to complete more complex tasks. Chapters first introduce test cases that you have the chance to solve on your own before giving you the solution in the form of pseudocode or implementation advice.</p><p>The first eight chapters introduce the building blocks of the engine. You begin by implementing points and vectors to represent space, defining matrices that use linear algebra to transform these points, and creating a simple canvas to display colors. Once the foundation is established, you develop a class for your first shape — the sphere — which you render on your canvas using ray casting, the core operation of the ray tracing algorithm. The following chapters build on this foundation by introducing increasingly complex scene elements such as lighting, shadows, diverse material properties, additional shape types, and surface patterns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*nW-7NbhFDXn-FkZhLLUEjQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*kT06SzX__SQ9EKhxHVwzgA.png" /><figcaption>A comparison of the first output made possible by the ray tracer code (left) vs. one of the the last outputs (right).</figcaption></figure><p>I really enjoyed the test-based approach that the book takes to guiding you through the problem. The comprehensive tests that I built early on allowed for me to verify every refactor I made with ease, so even big changes could be verified quickly without breaking the architecture of the program.</p><h3>What tools did you use to build this out?</h3><p>To build the project I used CMake, which had a learning curve to start but allowed for an easier configuration as the complexity of the project went up.</p><p>To test the core libraries I used <a href="https://github.com/google/googletest">GTest</a>, a powerful testing framework for C++ made by Google. I found that the framework allowed for the tests to be very well-organized, repeatable, fast, and verbose when failures occurred.</p><p>For enhancing the performance of the app I enjoyed using <a href="https://perfwiki.github.io/main/">perf</a> and the useful <a href="https://www.brendangregg.com/FlameGraphs/cpuflamegraphs.html">FlameGraph</a> tool to find out where I could drive the most performance improvements (more on that later).</p><h3>What did you learn while implementing this project?</h3><p>The number of programming skills I used for this project is difficult to count, so here’s a quick and incomplete list of some topics that this project made me learn:</p><ul><li>Programming and debugging in C++</li><li>Ray tracing and graphics concepts</li><li>Testing in C++ (GTest)</li><li>Multithreading using OpenMP</li><li>C++ OOP</li><li>Code profiling</li></ul><h3>What was the most difficult feature to implement?</h3><p>The biggest refactor of the code required was the change to incorporate Object Oriented Programming (OOP) into the code. Shapes as a base class are commonly used as an example of OOP, but adding this in my code base required solving several challenges and making large structural changes, like:</p><ul><li>Designing a Shape base class that encapsulates all of the common methods and attributes for all basic shapes we define. This required learning about virtual functions.</li><li>Tying up some loose functions that should be methods on the Shapes class by using forward declarations.</li><li>Refactoring the Sphere class to inherit from the Shapes parent class.</li><li>Passing lists or vectors of shapes by reference rather than by value.</li><li>Changing all of the appropriate tests to directly test attributes of the Shape class rather than the Sphere class.</li><li>Creating a new Plane class which inherits from the Shapes class.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JMq2Z7liH96vc3q6" /><figcaption>A rendering including examples of all of the types of objects implemented in this book. Listed counter clockwise starting in the top right: a sphere, a cube, a cylinder, a cone, a heart constructed using multiple triangles, a Group object using a Pattern, and an object created using Constructive Solid Geometry (CSG).</figcaption></figure><p>After the refactor, the ray tracer was much more powerful with its support of multiple shape types. Adding new geometries was as simple as implementing a new subclass of Shape, which greatly improved the functionality of the ray tracer going forward.</p><h3>How did you debug the project when you ran into issues?</h3><p>For debugging issues with the source code, the test suite made it straightforward to run diagnostic tests quickly. I would typically check the inputs and outputs of the class, reproduce the issue with tests, and add helpful print statements to figure out the root cause/verify correctness. This was usually enough to solve any issues I ran into.</p><p>Visual bugs could be more difficult, like acne being created when adding shadow effects. Many of those bugs took more trial and error to fix, which could be time-consuming when trying to generate an image that was high resolution or had a lot of shapes to render.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*VqsYEUiKL6ndPfcI" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xZgnGdAKL8EcmhY9" /><figcaption>Solving the problem of `shadow acne` required manually tuning parameters, like fine-tuning the epsilon distance used to account for floating point errors.</figcaption></figure><h3>What was the most interesting feature to implement?</h3><p>Patterns were one of the most fun features to write, because once I created the Pattern parent class it was very easy to design new Pattern objects that could be combined to create more visually interesting surfaces in the scenes. It was a reinforcement of the learnings on OOP that I had taken from the design of the Shape class that really helped my understanding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c_iO76qanfh7AB5f" /><figcaption>This would have been just a flat plane before — combining patterns brings a lot more visual appeal.</figcaption></figure><p>Designing my own patterns (outside of what the book recommended) was quick and easy, because it was entirely up to my own imagination how I wanted to implement the class. It also sometimes required outside libraries to do this, testing my understanding of CMake and linking different modules to my code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lfpiZovsD-MMoUpm" /><figcaption>The Perlin noise pattern adds perturbation to a basic checkers pattern on a sphere.</figcaption></figure><h3>What was the most fun feature to use?</h3><p>I loved the chapter on parsing .obj files because it unlocked the ability to create way more complicated images with my code. OBJ is a simple, widely used 3D model format that stores 3D geometry data, including vertices, faces, and texture coordinates, which is widely used in 3D modeling. By parsing that file and turning it into triangle objects that my code can understand, I could render images representing arbitrarily complex scenes. Once implemented, I was able to have some fun rendering some files I found on the internet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-TLufhuVwotikn5O" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rKzDM-CjgFEMgW93" /></figure><h3>How did you optimize the code?</h3><p>The book provides an implementation of ray tracing that works correctly, but optimization of the algorithms is generally left as a learning exercise for the reader. During development, I implemented multiple refactors that greatly improved rendering speeds.</p><h4>Multithreading</h4><p>Parallelism allows for a computer to use more of a computer’s resources at once. It is very straightforward to accomplish this in ray tracing because rendering is <a href="https://en.wikipedia.org/wiki/Embarrassingly_parallel">embarrassingly parallel</a> — each pixel is independent of the pixels surrounding it. Implementing multithreading was a one-line change with the <a href="https://www.openmp.org/">OpenMP library</a>, resulting in ~75% improvement in runtime when parallelized over 8 threads (using the 4 cores of my laptop’s CPU equally).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*iWqDPS-pkS2iJNwS" /></figure><h4>Faster Matrix operations</h4><p>When implementing the book, you are led to implement your own linear algebra/matrix math modules from scratch. That was very satisfying to do on my own, but many linear algebra libraries in C++ are free to use and much faster than any solution I could come up with on my own. I chose to use <a href="https://eigen.tuxfamily.org/index.php?title=Main_Page">Eigen, a C++ template library</a> implementing all of the linear algebra I need. Using Eigen to compute matrix multiplications and vector addition reduced runtimes by another 75% (which probably says more about the performance of my original library than it does about Eigen, but improvement nonetheless).</p><h4>Pre-computing matrix inversions</h4><p>The change I’m most proud of implementing came from analyzing the running time of the program’s functions using Linux’s code profiling tools. Here is a quick overview of the tools involved:</p><ul><li><a href="https://perfwiki.github.io/main/">perf</a> is a powerful command-line tool used for performance analysis, allowing users to monitor, analyze, and optimize the performance of their systems by accessing CPU performance counters and trace points. It allows us to track the performance of a program and how long each component/function is taking to run.</li><li>A flame graph is a visualization tool used to analyze profiling data (like the output of perf), helping to identify performance bottlenecks and understand where an application spends its time by showing a hierarchical view of the call stack. Each rectangle of the graph represents a function call, with all of the functions it calls to stacked on top. Its width is proportional to the time spent in that function. <a href="https://github.com/brendangregg/FlameGraph">FlameGraph</a> is a tool to visualize the text output of perf that I used for this project.</li></ul><p>The image below shows the flame graph for the first sample program I ran this analysis on, which was an image that took ~17.5 seconds to run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*llJjNFtXWxbgp2un" /></figure><p>On top of the functions Shape::intersect and World::is_shadowed, you can see that the vast majority of time in each function is spent on a single function call, Matrix::inverse. Below is the code snippet in question:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/0*lCBu1cURw4nYM_Fw" /></figure><p>Each time my code checked to see if some ray intersected with an object in the scene, the code recalculated the inverse of the shape’s transformation, which turned out to be a very expensive operation while looking like quite an innocent line on its own.</p><p>So how do we stop this inversion from being so expensive? I realized that instead of recomputing the inverse every time we check for intersections, we can compute the inverse of each shape’s transformation matrix once during initialization, then use that saved inverse matrix for our calculations instead of recalculating every time. After changing the Shape class to compute and store the inverse matrix during object construction, the appearance of the algorithm was quite similar:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/0*CYy6roMrwdkaPPXL" /></figure><p>However, the impact on the code was huge — for the cost of storing one more matrix of floats per Shape object, we reduced rendering times by <strong>82% (6x increase in rendering speed!)</strong>. This can be seen in the updated flame graph below, where the inverse functions have been eliminated, reducing runtime from ~17.5s to ~3s.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vxrFpHPQKST1QYOC" /></figure><p>After incorporating all of the optimizations together, I found that runtimes were reduced by ~99%, a 100x speedup! This meant that complex renders could be computed in a matter of minutes instead of hours, completely changing the experience of creating scenes.</p><h3>How does this compare to commercially available ray tracing engines?</h3><p>I wanted to create a comparison between the power of my ray tracer and some commercially available options. The movie Flow, the most recent Oscar winner for Best Animated Picture, was animated in Blender, with each frame of the movie <a href="https://www.blender.org/user-stories/making-flow-an-interview-with-director-gints-zilbalodis/">taking between 0.5 and 10 seconds to render</a>. Using some back-of-the-napkin calculations, I found that it would take my renderer around <em>11 million years</em> to render all of the images in the 80-minute runtime of Flow, which would probably take the indie movie out of budget. So my ray tracer isn’t going to replace the software used in big productions just yet, but my efforts here do help me to understand a lot more of the inner workings of their code than I did before.</p><h3>Are there any other algorithms for creating computer graphics you could implement?</h3><p>Two other commonly used algorithms in computer graphics are rasterization and path tracing.</p><p>Rasterization focuses on projecting 3D objects onto the 2D screen rather than casting light rays onto an image — this allows for use in real-time applications like video games, but usually results in less realistic lighting of images. Hardware improvements in gaming consoles and advancements in ray tracing techniques have allowed for <a href="https://www.youtube.com/watch?v=9b2eZYuORYM">some video games to incorporate ray tracing</a>, but generally rasterization is much more commonly used.</p><p>Another method, path tracing, builds upon the ray tracing algorithm by simulating complex interactions of light in a scene and accounting for indirect lighting, adding even more photorealism to images. This method is even more resource-intensive than regular ray tracing and is used in animated movies and only a handful of video games (for now).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/0*LEJ-y5srVEt_rLlX" /><figcaption><a href="https://blogs.nvidia.com/blog/what-is-path-tracing/">An example</a> of the difference between different rendering techniques</figcaption></figure><p>Both techniques are high on my list for implementing next!</p><h3>So, what will you do next?</h3><p>Not sure! If I’m working with C++ I’ll definitely be expanding the ray tracer to learn more advanced topics in the language and the field of study. For now, I think I’ll be turning back to Python/data personal projects to ensure that my skills are sharp in the language I know best.</p><h3>These images are really cool! Where can I see more of them?</h3><p>I’ve added some of my favourite generated images below. To see all of the photos I’ve generated using the engine I’ve stored them here: <a href="https://github.com/joseph-grosso/ray-tracer-challenge/tree/master/outputs">GitHub link</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3TR1ntegnxvNk32B" /><figcaption>A glass ball with an air pocket — has reflection rays, refraction, and <a href="https://www.dorian-iten.com/fresnel/">the Fresnel effect</a>.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*V2hPohq2yiXoFqSu" /><figcaption>A “hand puppet” demonstrating the effects of shadows.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*pUNlQFZp6VZwHafNESGdRA.png" /><figcaption>Weird things can happen to the ray tracer when objects overlap. Two plane objects were touching here, causing more acne to be generated.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0sAKEQ2rhwsr3bnG" /><figcaption>An example of reflection through a glass ball.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e45a68fb7cd5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>