<?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 Louis Young on Medium]]></title>
        <description><![CDATA[Stories by Louis Young on Medium]]></description>
        <link>https://medium.com/@youngalou?source=rss-1ba122b49c4c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Lr0N207m49sMcoZh.</url>
            <title>Stories by Louis Young on Medium</title>
            <link>https://medium.com/@youngalou?source=rss-1ba122b49c4c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 23:16:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@youngalou/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[Solving a 3D Labyrinth with Pixels! — Our First Dive Into Reinforcement Learning]]></title>
            <link>https://medium.com/42robolab/solving-a-3d-labyrinth-with-pixels-our-first-dive-into-reinforcement-learning-d6ab75295981?source=rss-1ba122b49c4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6ab75295981</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Louis Young]]></dc:creator>
            <pubDate>Mon, 17 Jun 2019 19:33:06 GMT</pubDate>
            <atom:updated>2019-06-17T19:33:06.227Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jEUpofyjhKGrJ0cE2HjDzw.jpeg" /></figure><h3>Solving a 3D Labyrinth with Pixels! — Our First Dive Into Reinforcement Learning</h3><p><em>by </em><a href="https://medium.com/@youngalou"><em>Louis Young</em></a><em> and </em><a href="https://medium.com/@eamon_16082"><em>Eamon Ito-Fisher</em></a></p><p>AI. The dream of creating machines as intelligent and capable as human beings has been a holy grail in research, science fiction, and pop culture for decades. The fact is, we live in an age where AI is already ubiquitous across almost every industry. Everyday we rely on ML based technologies: NLP applications like Siri and Alexa, unsupervised clustering for AdSense, perception systems for self-driving vehicles. As broad of a reach these systems have now, the applications of ML today are fundamentally very rigid. They require a lot of very precise human engineering to operate at their maximum potential, and even when an algorithm learns one particular problem well, it often struggles to learn another. A major area of research in the field now is in algorithms that generalize well to more tasks, and one field in particular has shown promising results. In this article, we’ll introduce you to Reinforcement Learning (RL) and explain some of the methods we used to tackle our first venture in RL, the Obstacle Tower Challenge hosted by Unity and Google.</p><h3>Introduction to Reinforcement Learning</h3><p>We’ll start with a brief overview of Reinforcement Learning as a whole. RL is the third major paradigm in ML research, alongside Supervised Learning and Unsupervised Learning.</p><p>Reinforcement Learning, like many other ML methods, is inspired by the way humans learn from the world around them. As we interact with the world, we learn about the consequences of our actions naturally. Nobody has to teach you not to touch the stove when it’s hot (although it could save you a burn or two). You as a human have the capability to learn this through trial-and-error. By touching the stove and feeling pain, you learn to avoid touching hot things. RL takes this idea of learning individually from experiences, and applies it to machine learning.</p><p>Here, we’ll break down the reinforcement learning process. Buckle up because this is where we get a bit technical.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*W3JO3kXq5cJ9HEi57U50Bg.png" /></figure><p>Any RL algorithm consists of an <em>agent</em> and an <em>environment</em>. The agent is the predictive model we are training, and the environment is the world the agent interacts with and learns from. The learning process for an RL agent is a back-and-forth interaction between the agent and the environment. The agent receives from the environment an observation of the current <em>state.</em> The agent takes this state and provides an <em>action</em> in response. The environment receives this action and modifies its state. The new state is then observed by the agent and the cycle continues.</p><p>This explains how the agent interacts with the environment. But how does it learn what the best actions are to take? The key is <em>reward.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*jPYF-dt2WVJ2jjsKtGg7Lg.png" /></figure><p>When the environment provides the agent with the new state, it also provides a reward signal, letting the agent know how good or bad the outcome of the taken action was. This is analogous to the pleasant warmth you might feel being close to the stove (+ reward), or the pain from getting too close and touching it (- reward). You can give the agent specific goals by defining the rewards it receives from the environment.</p><p>Here’s an example of one iteration in the reinforcement learning loop (in the context of an agent trying to learn Pac-Man):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0D_LiqG2qtcwq6Qh9PV36A.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kzqIlq6zu7_Hv0zLcW7G4Q.gif" /></figure><ol><li>The <strong>agent </strong>observes the current <strong>state </strong>of the <strong>environment</strong>. <em>Example: The current state is Pac-Man in the center of the level.</em></li><li>The agent takes an <strong>action</strong> based on the <strong>state</strong> that was observed. <em>Example: There is a cherry(+10) to the right and a ghost(-100) to the left so the action taken by the agent is move right.</em></li><li>The <strong>environment</strong> receives an <strong>action </strong>from the agent<strong> </strong>and updates its internal state. <em>Example: The action received was move right, so the environment updates Pac-Man’s position one to the right.</em></li><li>The environment provides the agent with the new <strong>state </strong>and <strong>reward </strong>for the action taken. <em>Example: The agent receives the new state and a small positive reward for getting an orb.</em></li></ol><p>This loop repeats until a terminal state while the agent stores information about the state, action, and reward for each iteration. The collection of these state-action-reward pairs is called a <em>trajectory. </em>After the agent has gathered a full trajectory, we can use this data to train.</p><p>The agent decides what action to take at any given time by following a <em>policy</em>. The policy is a function mapping the perceived states of the environment to the actions to be taken in those states. The fundamental purpose of an RL algorithm is to learn the policy that maximizes the reward received over a trajectory, called <em>return.</em></p><p>The Pac-Man environment illustrated above is obviously a very simple one. We have a small number of states and only two possible actions. In an environment like this, the optimal policy would be trivial to learn with even the most naive strategy. Most applications of RL would require much more complex environments.</p><p>The complexity of an environment can generally be summed up in 3 factors:</p><ul><li><strong>state-space</strong> — The total number of possible states in an environment. The larger state-space is, the more complex the environment.</li><li><strong>action-space</strong> — The total number of possible actions for the agent to take in a state. The larger the action-space, the more complex the objective. The state-space tends to scale exponentially with the action-space.</li><li><strong>sparsity of reward</strong> — The frequency of non-zero reward signals received from the environment. (# of rewarded states / # of possible states)</li></ul><p>In most cases, it doesn’t make sense to define non-zero rewards for every state-action. In a sufficiently complex environment, it becomes infeasible to shape the rewards for every possible state-action. And even if we were to do so, we might as well solve the problem programmatically. There would be no point in ‘learning’ the environment when you’ve already engineered the solution. We instead reward our agent for accomplishing larger objectives, without defining exactly how to solve them.</p><p>For example, imagine an environment where our objective is to get an agent to move to a goal across a room. A simple solution would be to shape rewards such that the agent gets increasing reward the closer it gets to the goal. But what if there’s an obstacle in the way? Or what if we don’t know where the goal is? In both scenarios, we’d have to adjust our rewards to solve the problem in a different way.</p><p>With RL, we can solve any of these problems without engineering. Here, we could simply give the agent +1 reward for reaching the goal. But how would the agent learn if it was only rewarded for the final action of reaching the goal? Surely we can’t ignore all of the actions that got it there.</p><ul><li>The agent may have had to perform a long series of actions in order to reach the goal, in which case, all of the actions should be incentivized because they’re equally important to the objective.</li><li>Conversely, the agent may have wasted a lot of actions spinning in circles before getting to the goal, in which case, a lot of the actions would be unproductive towards the objective and therefore should not be incentivized.</li></ul><p>So how do we determine which actions were actually important to accomplishing the objective? This is a common issue in reinforcement learning and it’s called the <em>credit assignment problem</em>. The most common approach to distributing rewards is to propagate them back over time with a discount factor. So the actions preceding the reward signal receive progressively less reward, the further they are from the source.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*_Skw9i1fTVBcYWLCWXRy9w.png" /></figure><p>So to sum everything up: Our agent interacts with the environment by observing states, and taking actions according to its policy. The agent receives rewards for accomplishing certain things in the environment, and eventually collects a trajectory of state-action-reward pairs. We propagate the rewards back with a discount factor to incentivize state-actions that led up to those rewards. And finally, we use this data to improve the agent’s policy.</p><p>With the basics covered, we can dive into the challenge!</p><h3>The Obstacle Tower</h3><p>Given the influx of AI research in recent years, it is crucial that we have a fair way to compare the performance of different methods. Early benchmarks in RL were often based on classic board games like chess, checkers, and more recently go. However, developments like DeepBlue and AlphaGo beating the world’s best chess and go players have made it clear that we require more complex environments to test the limits of modern algorithms.</p><p>To fulfill that demand, video games have become increasingly popular as AI benchmarks. Video games are complicated — requiring real-time decisions in wider state-spaces with often complex interactions, they make for an ideal challenge.</p><p>The most common environment we see used in research papers is the Arcade Learning Environment (ALE), which is based on an emulation of the Atari 2600 video game console. The environment offers a wide range of games, making it easy to compare performance of algorithms across various tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uid3YUH3_D4thvKQKu_Jiw.jpeg" /><figcaption><a href="https://www.reddit.com/r/gaming/comments/24uryx/a_pictorial_az_of_atari_2600_games/">https://www.reddit.com/r/gaming/comments/24uryx/a_pictorial_az_of_atari_2600_games/</a></figcaption></figure><p>While the ALE is very lightweight and versatile, it also comes with several drawbacks. The Atari system from which the ALE is derived operates on 128 bytes of RAM, with no video memory and outputs low-resolution 2D graphics. The console also lacks a means for pseudo-random number generation, meaning all games are deterministic. The low fidelity and deterministic nature of environments like ALE make it easy to overfit to the state-space of a specific game.</p><p>That’s where Unity comes in.</p><blockquote>Obstacle Tower was developed specifically to overcome the limitations of previous game-based AI benchmarks, offering a broad and deep challenge, the solving of which would imply a major advancement in reinforcement learning.</blockquote><blockquote>— <a href="https://arxiv.org/abs/1902.01378">Obstacle Tower: A Generalization Challenge in Vision, Control, and Planning</a></blockquote><p>Obstacle Tower consists of a few key elements that make it an important problem to solve.</p><ul><li><strong>Sparse reward environment with a complex state-space</strong> — Unlike simpler games like Pong or Pac-Man, the agent isn’t provided constant feedback about its performance like a score. The environment only gives the agent its full reward when it completes an entire level. The agent must learn an abstract high-level objective without much direction, encouraging algorithms that take advantage of more sophisticated RL strategies like intrinsic reward and hierarchical reinforcement learning.</li><li><strong>High fidelity 3D procedurally varied graphics </strong>— The complexity of a high fidelity 3D environment is a difficult challenge in perception of its own. In order to succeed, an agent must be capable of identifying key objects like doors under a wide variety of conditions. These objects must be recognized from any angle, at any distance, while under varying lighting conditions, and even varying textures. This type of generalization requires an abstract understanding of the environment and its elements.</li><li><strong>Procedurally generated level design with increasing difficulty</strong> — Every time the agent plays the game, the layout of the labyrinth is different. Hard-coded strategies and quick fixes won’t get you far. A good agent will have to overcome a variety of obstacles and situations, while also learning how to deal with new ones as it gets further along.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EwzsKWqL2z3LeX8y2fW8lA.png" /><figcaption><a href="https://blogs.unity3d.com/2019/01/28/obstacle-tower-challenge-test-the-limits-of-intelligence-systems/">https://blogs.unity3d.com/2019/01/28/obstacle-tower-challenge-test-the-limits-of-intelligence-systems/</a></figcaption></figure><p>Alongside the open-source release of their Obstacle Tower environment, Unity hosted a challenge on AICrowd, getting the word out and encouraging engineers and researchers to christen their new RL benchmark. Coming hot off the press of a machine learning bootcamp with no experience in RL, we decided to try our hand at the challenge.</p><h3>Chronology of Development</h3><p>Here we’ll run through all the algorithms we used chronologically, and give quick(?) intuitive explanations about how they work and what advantages they afford. These are <em>not </em>implementational or technical explanations, but if you want one, let us know! We’d be happy to chat or write more articles.</p><h4><strong>DQN / Rainbow Agent</strong></h4><p>We started with Dopamine, a framework developed by Google for RL. More specifically, we used Dopamine’s <em>Rainbow agent</em> — a cutting edge RL algorithm made by combining several individual improvements to <em>deep Q networks (DQNs) </em>together. DQNs are one of the fundamental methods for deep RL, and are based around the idea of <em>Q values</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ivs72IeaHxZsdpo2zW7NrQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GsfJckCNHNutr2qMhzHc2Q.png" /></figure><p>The <em>optimal</em> Q value of an action is the maximum return for an action, which can be computed as the reward you get for taking the action in a specific state plus the largest of the Q values in the new state, reduced by a certain discount factor. This can be visualized as a chain of Q values, each dependent on the next, that stretches all the way from the current state to the end of the episode. The discount factor is to make sure that rewards received later down this chain aren’t valued as highly as immediate reward. Given equal reward now, or in 10 actions, we should take the immediate action.</p><p>Intuitively, if you have the ability to get the optimal Q values, then given a state and a set of actions you know what the best action to take is. While in simple environments you can brute force calculate these Q values, more complicated environments will require an alternate method to approximate Q values. DQN uses a neural network as a powerful and flexible Q value approximator. First, the existing Q network is leveraged to play the game and collect data. Then, the state-action-reward pairs are used to update our network so that it can better predict Q values. Finally, the updated agent replays the game to collect more data, and the cycle is repeated.</p><h4><strong>Vanilla Policy Gradient (REINFORCE)</strong></h4><p>Rainbow is powerful, but also very complicated. As a group new to RL, we found we felt lost with the tools we were using. In order to gain a more complete understanding, we decided to step back and implement our own algorithm from scratch. This lead us to REINFORCE, one of the simplest and easy to implement algorithms in RL.</p><p>REINFORCE is the base for policy gradient methods — another fundamental group of RL algorithms. While DQN methods learn Q values that inform the policy, policy gradient methods are more direct and optimize the policy itself. Instead of learning the optimal Q values, policy gradient learns a model that takes in a state as input and outputs a probability distribution over the possible actions, with (hopefully) high probability actions being actions that lead it to the maximum return.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xYn1V_DPxqdrGwwD6NLlzA.png" /></figure><p>The goal of policy gradient is then to optimize this policy to maximize expected return. Because truly computing expected return of a policy for every single state isn’t feasible, we instead play the game — producing the action distribution with our model at each state and sampling from it to decide what action to take. We then use this data to approximate our expected return, and use it to improve our policy. This is done by incentivizing actions that lead to positive rewards, and disincentivizing actions that lead to negative rewards, with the magnitude of the reward deciding the magnitude of the incentive.</p><h4>Actor Critic</h4><p>While REINFORCE is easy to implement, it’s also not very powerful. The next step we took was with <em>actor critic</em>. While we did jump straight into <em>Advantage Actor Critic</em> (or just <em>A2C</em>), we’ll start with normal actor critic. Actor critic was formulated to help solve one of the biggest problems with REINFORCE — high variance.</p><p>The problem comes in how we use sampled return to evaluate actions. Imagine all the possible paths from the start to end of a game. Out of that massive pool of trajectories, we sample a tiny amount — hundreds at the very best — and try to use that to approximate how good our actions are. This leads to high variance in reward signals during training as the estimate of how good an action is can vary wildly from sample to sample. The solution offered by actor critic is to instead evaluate each action by the expected or average return of that action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b0bWjBlnprs30sty6-3u7w.png" /></figure><p>Calculating this exact value would involve taking every single possible subsequent trajectory, which isn’t feasible. Instead, in actor critic we use a second model, the critic, to make <em>on-policy</em> Q values that we use to evaluate our actor model. While optimal Q values represent the expected return of an action if you play perfectly afterwards, the on-policy Q values represent the expected return of a action if you follow a policy afterwards. Using the Q value in place of reward significantly reduces variance by reducing our reliance on sampling, at the cost of introducing some bias from using a model which isn’t necessarily perfect.</p><h4>Advantage Actor Critic (A2C)</h4><p>Advantage actor critic adds additional nuance to the evaluation of actions that allows it more stable training. Instead of using our critic to learn expected returns of <em>actions</em>, we instead learn the expected return of our policy in <em>states</em>, otherwise known as <em>value</em>. We can also continue to approximate Q values for actions as the reward for the action plus the value of the resulting state. Using the value of a state, we can calculate <em>advantage</em>, the difference between the expected return of the action we took — the Q value of the action — and the expected return of the state — the value of the state. Intuitively, this can be expressed as how well we <em>did</em> do versus how well we <em>normally</em> do. Advantage encourages stability in training because it rescales reward to a more clear distribution of signals to train the model on.</p><p>Consider these two examples: One where the possible returns are -5, -80 and -100, and another where the possible returns are 100, 101, and 102.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8SdOglaRZCnBOKwvIHzBZQ.png" /><figcaption>Before baseline</figcaption></figure><p>Each scenario poses its own problem. In the first, despite the fact that -5 is clearly the best return, actor critic would disincentivize it for being negative. In the second scenario, despite the fact that 102 is clearly the best return, because the rewards are <em>relatively</em> similar, actor critic would fail to meaningfully incentivize it over the other actions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xq0EMA7KnkZvzv4UmihoCg.png" /><figcaption>After baseline</figcaption></figure><p>A good critic model would subtract appropriate values to rescale both these distributions. -5 becomes 55, and as the only positive reward will easily become the most likely action. Rescaling 101 to 1 and 102 to 2 means that action 3 is now twice as good as action 2, making it clear action 3 is the best action.</p><h4><em>Proximal Policy Optimization (</em>PPO)</h4><p>Training was coming along well with A2C, but could still be improved. To this end, we decided to upgrade to <em>PPO</em>, or <em>Proximal Policy Optimization</em> — a cutting edge algorithm developed and used by OpenAI. To understand one of the reasons why PPO was invented, we must first understand one of the fundamental problems that RL faces; <em>sample efficiency</em>. Sample efficiency denotes how well we use the data that we collect — in essence, how much data we need to collect before we can solve a problem. RL is <em>horrible</em> at this. It can take an agent tens or hundreds of millions of frames of gametime before they can match the level of a human who’s spent minutes with a game. This problem is exasperated in policy gradient methods, where the data collected in training can’t be used again. This is because of the nature of policy gradient — the objective is to maximize the return of the policy. Because an update will change the policy, old data is collected by a different policy and is no longer relevant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E6oZsDY9Klkd_3G3d-Rc9Q.png" /></figure><p>PPO — and its predecessor TRPO — combats this problem by allowing multiple updates on a single sample of data. It accomplishes this enforcing a <em>trust region</em>. We save the probability the model output for the action taken while collecting data and compare it to the probability the model outputs for the action after being updated. This allows us to see how much the policy changed at this point due to the update, and, if the probability of the action has changed too much, allows us to stop updating that action. By constraining the change in the probabilities of actions in this fashion, we can keep the updated policy and old policy similar enough that we can make multiple updates, letting us squeeze more out of our data and increasing sample efficiency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CqfkDy7Zpi5o2nBaVmJF1g.gif" /></figure><h3>In Conclusion</h3><p>At time of writing, PPO is still our algorithm of choice. After passing the first round of the challenge in 19th place, we’re currently at 3rd on the finals leaderboard. Over the course of the rest of the competition, we hope to do more testing with recurrent models and auxiliary outputs. Further, we are looking forward to implementing some hierarchical reinforcement learning strategies to boost performance.</p><p>This project has instilled in us a passion for RL and moving forward, we have several projects and ideas we’d like to explore. Multi-agent and NLP focused reinforcement learning tasks are intriguing, and there are several competitions facilitating research in those areas. The application of new reinforcement learning and meta learning techniques to creative pursuits like music generation is also an exciting area that we are considering pursuing.</p><p>Thanks for reading! If you’d like to reach out and talk about RL or anything exciting, you can find us on LinkedIn:</p><p>Louis Young — <a href="https://www.linkedin.com/in/louis-young/">https://www.linkedin.com/in/louis-young/</a></p><p>Eamon Ito-Fisher — <a href="https://www.linkedin.com/in/eamon-ito-fisher/">https://www.linkedin.com/in/eamon-ito-fisher/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6ab75295981" width="1" height="1" alt=""><hr><p><a href="https://medium.com/42robolab/solving-a-3d-labyrinth-with-pixels-our-first-dive-into-reinforcement-learning-d6ab75295981">Solving a 3D Labyrinth with Pixels! — Our First Dive Into Reinforcement Learning</a> was originally published in <a href="https://medium.com/42robolab">42RoboLab</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ray Visualizer: A Unique Rendering Challenge]]></title>
            <link>https://medium.com/@youngalou/ray-visualizer-a-unique-rendering-challenge-a955d5cbbf1e?source=rss-1ba122b49c4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a955d5cbbf1e</guid>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Louis Young]]></dc:creator>
            <pubDate>Mon, 02 Jul 2018 14:27:42 GMT</pubDate>
            <atom:updated>2018-07-02T14:27:42.942Z</atom:updated>
            <content:encoded><![CDATA[<p>Small preface: CLIVE (computed light in virtual environments) is a bidirectional path traced rendering project that I’m working on with my friend and colleague, Phil. Part of my contribution to the project has been an interactive mode where the user can move through the environment in real-time through a simplified ray-traced view, giving them the ability to view the environment freely and pick a camera position and angle to begin the long render. This article is about a feature I recently added to the interactive mode called ray visualizer.</p><p>During the early development of Clive, I was still new to the concept of ray-tracing. I often found myself picturing the path of a ray through complex geometries for answers on how that ray might be contributing to the image. The problem with this is that my intuition could only take me so far. Soon we were dealing with environments composed of millions of polygons, and imagining the path of a ray in my head just wouldn’t cut it. I know other people struggle to get a visual understanding of ray-tracing, so that’s why I developed the ray visualizer. Particularly with path traced rendering, its valuable to know if an abhorrent contribution was because of a weighting issue, or the ray bouncing in a weird direction.</p><p>The goal with this feature was to have an interactive way to view light paths. What makes this challenge interesting and the reason I decided to write an article about it is that it is the combination of both the rasterizing and ray-tracing rendering methods. We already have an interactive window where the image is ray-traced in real-time, and the drawing of lines in the image will be a process of rasterization.</p><p>Here is a summary of the implementation:</p><p>The renderer will store vertices of paths as it generates the image. The connection of any two sequential vertices is a line.</p><p>The first step is to get two of these points on the screen. We’ll do some basic perspective projection to find the raster coordinates of each point. To ensure that both points are within the camera’s field of view, we clip any points outside to the view frustum edge. Both perspective projection and view frustum culling are techniques that are very well documented, so we won’t cover those here.</p><p>For the sake of simplicity, I will be showing all of this in 2D, looking at the camera from the top-down. We will always be dealing with a set of points that are co-planar so all 3D calculations can be interpreted in 2D.</p><p>First things first, the camera is defined as the image plane and a focus in front it. All of the light that gets recorded in the image will pass through this point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/1*ZunHwph6HLuVZO951YKIOg.png" /></figure><p>The distance between the image plane and the focus is correlated with the field of view of the image and is an important property for calculating coordinates in raster space. The shorter the distance, the wider the FOV and vice versa.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/1*i3FQ0UxFU4SpV9Ve8vkP2g.png" /></figure><p>We now project the points onto the image by connecting a line to the focus, and extrapolating that line onto the image plane.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*7S-85gx-fuWr9Qzx-9YuJQ.png" /></figure><p>Then we fill in all the pixels in between using Bresingham’s line drawing algorithm and boom! We’re done… right? Not quite. What we’ve done now is drawn a 2D line over a 3D environment. We want the line to feel like its a part of that 3D space, so we’re going to have to take it a step further. For the line to appear convincingly 3D it will have to be occluded by the geometry of the environment. To do this we’ll have to compare at each pixel, the distance to the point on the line we’re trying to draw and the distance to the surface rendered in that pixel. The challenge here is that we know only the position of endpoints of the line. We’ll have to do some extra math to fill in the points in between.</p><p>Let’s clarify some terminology. I’m going to be using the words pixel and point a lot. Pixel will always refer to a position on the image plane. Point will always refer to a position on the line between the two endpoints. “The line” is the connection between the two vertices representing a part of a path. The z-buffer is an array that stores that distance the surface rendered in each pixel. We’ll be comparing against this to test the visibility of our line.</p><p>My initial strategy was to use linear interpolation to find the corresponding positions on the line. We’d start by pre-plotting the line to figure out exactly how many pixels needed to be drawn. The division of the total length of the line by the number of pixels would give us a static value representing the distance of each pixel. We start a reference point at the anchor and advance the point along by this value per-pixel. This reference point would be used to compare the distance against the z-buffer at that pixel, to determine whether it should be drawn. This seemed logical because the reference point would always end up at the correct endpoint after iterating over all the pixels. The issue is that each pixel does not represent an equal distance along the line in 3D space. Put simply, this strategy doesn’t account for a FOV above 0 degrees.</p><p>So we’re taking the idea of moving a reference point along the line between the two endpoints, but we’re changing the way we iterate it. We will no longer evenly split the total distance per-pixel.</p><p>We start by defining an ‘anchor’ point. The anchor will be the first point on the line we draw, and will have a corresponding anchor pixel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*oWDPDPcxMqTbQ0Hdl5DEtA.png" /></figure><p>We use the anchor point and anchor pixel to get some important data. First, we get a ratio of similar triangles by dividing p1_z and dist. With this ratio, we can find the correlating side A to the distance between the pixels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*zRW7KCCITQTjKfyGY5yzJg.png" /></figure><p>p1_z is the z component of the anchor point, and dist is the distance to the image plane.</p><p>Ultimately, we’re interested in side C of this triangle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*yJ3BSKqEPlPtd10moC7sHA.png" /></figure><p>C represents the distance along the line, correlated with the distance between the pixels on the image. This will be the value we iterate our reference point by. Note that we won’t be iterating in the += sense. We are evaluating the reference point always with respect to the anchor, so we will be replacing the position of the reference point with:</p><p>reference = anchor + C(dir)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*LUv2kBTOSCm6PtdayvGgvQ.png" /></figure><p>To find the length C, we make simple use of the Law of Sines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/0*Pjuk-Bs4ylMHy8E2" /><figcaption>Law of Sines</figcaption></figure><p>Side C is the desired length. Side A is the length correlated with the pixel delta. From here we require only angles ∠a and ∠c. ∠a is the angle between the direction of the line, and the connection of the focus to the reference point. ∠b is the angle between the direction of the line and the horizontal axis.</p><p>Add the distance of C in the direction of the line to our anchor point, and the reference point will correctly represent the position along the line we want to evaluate.</p><p>The biggest issue I’ve found with this strategy always falls back to rounding error. We use floats for pretty much all of our computations for the sake of speed, but I know they can be rather imprecise. In particular, trigonometric functions like sin() or acos() are unsatisfactory when dealing with really precise angles. Our anchor point will always be in the correct position since it starts at p1, but as our reference point approaches p2 at very sharp angles, the floating point precision becomes apparent in buggy occlusion. I circumvent this by switching the anchor point between p1 and p2, based on which of the two is closer to center of the field of view. This way, points in the center of the screen will always render cleanly, and points that lack precision will either be off-screen or around the edge.</p><p>And that’s all there is to it. Stay tuned for more entries on 3D graphics and the development of Clive. Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a955d5cbbf1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Overview of the Path Tracing Pipeline]]></title>
            <link>https://medium.com/@youngalou/an-overview-of-the-path-tracing-pipeline-eefec92aad35?source=rss-1ba122b49c4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/eefec92aad35</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[computer-graphics]]></category>
            <category><![CDATA[ray-tracing]]></category>
            <category><![CDATA[path-tracing]]></category>
            <dc:creator><![CDATA[Louis Young]]></dc:creator>
            <pubDate>Mon, 23 Apr 2018 15:12:05 GMT</pubDate>
            <atom:updated>2018-04-23T18:42:39.575Z</atom:updated>
            <content:encoded><![CDATA[<p>Although path tracing involves many complicated small operations, the general pipeline to render an image can be broken down into a few understandable steps.</p><h3>Loading the Scene</h3><p>We start with the environment, or the “scene”. This is typically fed to the program as a set of 3 dimensional points (vertices) which each describe a point on the surface of an object. This is followed by a list of faces connecting the aforementioned vertices into 2D shapes that eventually construct the scene that is to be observed. We call these shapes “primitives”, as they are the simplest parts of an often complex structure. Scenes are often found in .obj or .ply formats, but the industry lacks a universal file format, and handling as many as possible to make a robust parser is part of making a good ray-tracer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*Nt1lC92l2J_ZbZ5o4Qsn9Q.png" /><figcaption>A small snippet the sponza.obj file we often render</figcaption></figure><h3>Making it Fast</h3><p>Once we’ve loaded the position and orientation of every primitive in the scene, we then move on to the second step, the bounding volume hierarchy (BVH). The BVH, while not imperative in getting the program to render an image, is a fundamental aspect of accelerating any decent ray-tracer. The primary reason ray-tracing, and path tracing in particular, are slower than other rendering algorithms is collision. For a ray to figure out that it has collided with an primitive, it has to explicitly check against that primitive. This means every ray that is cast has to check against every primitive in the scene to know for sure which one is the closest. When considering complicated scenes constructed of millions of primitives, its easy to see how this can quickly become a bottleneck.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Y-CJr4fgSvN3_NUlTs8iEQ.jpeg" /><figcaption>A visualization of a BVH built around the Stanford bunny</figcaption></figure><p>What a BVH does is essentially eliminate possibilities of collision for the rays so they aren’t doing costly computations for collision on surfaces that are irrelevant. The environment is essentially cut in half so that half the primitives are on one side, and half on the other. When rays are cast they first ask which half of the environment they are in so they only have to check for collision of primitives that are within their half, effectively eliminating 50% of the collisions. This is done not only once, but multiple times until the scene is split into digestible chunks. With each level, the ray can eliminate half of it’s collision load by asking first which half of the volume it occupies. This process will be elaborated upon further in its own article, so don’t worry if it isn’t 100% clear right away.</p><h3>Casting Some Rays!</h3><p>Now that the scene has been thoroughly examined we can get get to the exciting businesses. The rays!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*IqJmi1wne4vSe1v3q0kEWg.jpeg" /><figcaption>Rays cast from the observer through pixels of the screen</figcaption></figure><p>The way light works in reality is simple. A light source emits rays of light that reflect and refract throughout the world, some of the energy and wavelength getting absorbed along the way, until they reach an observer. However, computing light this way would be inefficient as the vast majority of rays won’t reach the observer. A ray-tracer does the opposite. We cast the rays from the observer, “tracing” the paths of the rays back to their light sources. This way, we only consider rays of light that reach the observer.</p><p>This is the point where path tracing begins to diverge from standard ray-tracing. To produce an image through ray tracing, a ray is cast for every pixel of the image. Picture all of the rays starting from the same point on the camera and being shot through the screen into the environment. Each ray will be sent on a trajectory where it will try to “find the light”. When a ray collides with a surface, it will cast a ray from that point to the light sources in the scene to check whether or not the surface is being directly illuminated or is in shadow. We call these “smart rays”, as every ray knows where the light sources are and attempts to render an image by checking specifically against them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*IhHXn77yx51ySD-f0IvoKg.png" /><figcaption>Ray-traced image (left) and a visualization of contributing light rays (right)</figcaption></figure><p>Path tracing, instead of using few of these smart rays to render an image, uses many “dumb rays”. As opposed to sampling each pixel with one ray and returning a color, path tracing samples each pixel multiple times randomly and averages the result of all the rays shot through the pixel. Some of those rays will bounce around and hit a light source and some won’t. The more we sample each pixel, the more accurate the color of the pixel will be to representing how much light it received.</p><p>This process is called Monte Carlo integration. The more rays we cast, the more physically accurate the image will be. A good analogy would be a census on the average height of a male in the United States. If you were to take 10 random males and average their height, your result could be skewed from reality. But if you were to average the height every single man in the U.S., you would get a perfectly accurate result. Averaging every ray of light is of course an impossible task, considering there are infinite rays of light, so we use randomness to represent an infinite population of rays.</p><p>Once this has been done for every pixel, put them all together and you’ve got a gorgeous image! This is obviously a only brief overview of the processes behind a path tracer. Stay tuned for more articles where we dive deep into specific core concepts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eefec92aad35" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>