<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Coding &#8211; Jacco&#039;s Blog</title>
	<atom:link href="https://jacco.ompf2.com/category/coding/feed/" rel="self" type="application/rss+xml" />
	<link>https://jacco.ompf2.com</link>
	<description>Links, Code &#38; Articles</description>
	<lastBuildDate>Tue, 01 Sep 2026 12:31:18 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.0.4</generator>

<image>
	<url>https://jacco.ompf2.com/wp-content/uploads/2019/03/cropped-robotlab-32x32.jpg</url>
	<title>Coding &#8211; Jacco&#039;s Blog</title>
	<link>https://jacco.ompf2.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Rendering for DELTA &#8211; 3D on MSX2</title>
		<link>https://jacco.ompf2.com/2026/03/07/rendering-for-delta-3d-on-msx2/</link>
		
		<dc:creator><![CDATA[jbikker]]></dc:creator>
		<pubDate>Sat, 07 Mar 2026 12:31:28 +0000</pubDate>
				<category><![CDATA[Article]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[MSX]]></category>
		<guid isPermaLink="false">https://jacco.ompf2.com/?page_id=2411</guid>

					<description><![CDATA[Recently we (BUas colleague Peter van Dranen and me) released a 3D racing game for the MSX2...]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Recently we (<a href="https://www.buas.nl/">BUas</a> colleague Peter van Dranen and me) released a 3D racing game for the MSX2 retro platform: A 1986 Z80-based home computer standard, supported by all major manufacturers at the time, including Philips, Sony, JVC, Toshiba and Panasonic.</p>



<p class="wp-block-paragraph">MSX2 is normally not a platform on which one would render 3D graphics. This was the time of the ZX-Spectrum and the Commodore 64, and graphics were tile-based, with additionally (at least on C64 and MSX) hardware sprite support.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img fetchpriority="high" decoding="async" width="520" height="192" src="https://jacco.ompf2.com/wp-content/uploads/2026/03/image-2.png" alt="" class="wp-image-2414" style="width:800px;height:auto" srcset="https://jacco.ompf2.com/wp-content/uploads/2026/03/image-2.png 520w, https://jacco.ompf2.com/wp-content/uploads/2026/03/image-2-300x111.png 300w, https://jacco.ompf2.com/wp-content/uploads/2026/03/image-2-360x133.png 360w" sizes="(max-width: 520px) 100vw, 520px" /><figcaption class="wp-element-caption">Figure 1 &#8211; Left: Jet Set Willy by Software Projects; right: Gradius 2 (Konami).</figcaption></figure>
</div>


<p class="wp-block-paragraph">That being said, some 3D games did exist. For example, David Braben&#8217;s Elite runs well on the platform, if the player is willing to accept a frame rate of about 5 fps, as well as wireframe 3D objects. </p>



<p class="wp-block-paragraph">Also worth mentioning is Konami&#8217;s Penguin Adventure, which used some clever tricks to produce quite convincing 3D.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img decoding="async" width="520" height="192" src="https://jacco.ompf2.com/wp-content/uploads/2026/03/image-3.png" alt="" class="wp-image-2416" style="width:800px" srcset="https://jacco.ompf2.com/wp-content/uploads/2026/03/image-3.png 520w, https://jacco.ompf2.com/wp-content/uploads/2026/03/image-3-300x111.png 300w, https://jacco.ompf2.com/wp-content/uploads/2026/03/image-3-360x133.png 360w" sizes="(max-width: 520px) 100vw, 520px" /><figcaption class="wp-element-caption">Figure 2 &#8211; Left: Elite (ZX-Spectrum); right: Penguin Adventure (Konami).</figcaption></figure>
</div>


<p class="wp-block-paragraph">Still, it seems rather far-fetched to even attempt an action game with full-screen polygon graphics. And in fact it is! However, learning from Konami, and taking advantage of some specific features of the platform, we can produce something that convinces the player that this appears to be precisely what we did.</p>



<p class="wp-block-paragraph">In this article we describe the renderer of DELTA (a.k.a. &#8220;Dodge! Engage! Launch! Target! Assault!&#8221;). We start with a description of the MSX2 platform specifics relevant to the technique. We then show that 3D images of reasonable complexity can be encoded as tiles and sprites. And finally, we show how this data can be compressed to better fit available ROM options, while allowing for fast run-time decompression.</p>



<h2 class="wp-block-heading">Platform Specifics: VDP</h2>



<p class="wp-block-paragraph">The MSX2 platform provides graphics via its VDP <em>(Video Display Processor)</em>, specifically: the V9938. The chip provides several display modes, including a full-colour 256&#215;192 mode and a 16-color 512&#215;192 mode. The modes that offer most freedom are of course also those that require most bandwidth, which makes them often impractical for real-time graphics.</p>



<p class="wp-block-paragraph">Promising are the tile-based modes, which use 8&#215;8 character tiles to fill the screen. Each tile uses a byte per line of 8 pixels to define its &#8216;pattern&#8217;, as well as a byte per line to define the two colors used in that pattern. This way a tile requires only 16 bytes of storage, while allowing the use of 16 colours, as long as no more than two colours per line of 8 pixels are used. Tiles often don&#8217;t change from frame to frame, which further reduces required bandwidth. Instead, the tile based screen modes use a &#8216;name table&#8217; of 768 bytes which index the 256 unique tiles.</p>



<p class="wp-block-paragraph">The screenshot of Gradius 2 shows this approach in action. Colourful tiles are used (and re-used) to build a detailed display. Scrolling happens with 8 pixels at a time, and is done by modifying the name table alone.</p>



<p class="wp-block-paragraph">Gradius 2 also shows another important feature of the MSX2 VDP: <em>Hardware sprites</em>. The player ship, bullets and smaller enemies are rendered using 8&#215;8 or 16&#215;16 images. A maximum number of 32 of these can be displayed at any time, on top of the tile display. There is a limitation however: Each screen line can display a maximum of 8 sprites at a time. These sprites will turn out to be very useful for solving the &#8216;two colours per 8 pixels&#8217; limitation of the tiles.</p>



<h2 class="wp-block-heading">Platform Specifics: Memory</h2>



<p class="wp-block-paragraph">Apart from the VDP there is another important (and rather unique) aspect of the MSX2 hardware standard: <em>Memory</em>. Where other systems at the time were limited to 64 kilobytes or 128 kilobytes, MSX2 went above and beyond.</p>



<p class="wp-block-paragraph">The 64KB limitation is a result of the choice of processor: The Z80 (like other common CPUs at the time) can only use 16 bits for RAM addresses, which limits RAM to 65536 bytes. MSX2 however solves this with various mechanisms (slots, memory mappers, megaroms), effectively doing away with any and all limits on RAM and ROM capacity. Back in 1988 this allowed Konami to use 4 Megabit (512KB) for Metal Gear 2 Solid Snake; however in 2025 the community is producing Flash cartridges of up to 16MB. On top of that, all that memory can be accessed at the same speed: The CPU will never know the difference between the original 64KB and the expanded 16MB. This opens up entirely new ways of doing graphics.</p>



<h2 class="wp-block-heading">Numbers</h2>



<p class="wp-block-paragraph">Before we dive into the specifics of the DELTA renderer, let&#8217;s list some numbers that affect what can and cannot be done.</p>



<p class="wp-block-paragraph"><strong>CPU:</strong> Zilog Z80A, running at 3.58Mhz. It needs four cycles per instruction, at least. At 20 fps, the very best it can do is 179,000 instructions. In practice, it will do far less. The CPU can (at best) copy bytes at a rate of 1 per 5.5 cycles, so ~651KB per second or 32.5KB per frame at 20fps.</p>



<p class="wp-block-paragraph"><strong>VDP:</strong> Data transfer to the VDP is slower. The details are complex, but in general, the VDP cannot accept data faster than 1 byte per 15 cycles, or ~12KB per frame at 20fps.</p>



<p class="wp-block-paragraph"><strong>Bandwidth:</strong> The bandwidth-friendly tile-based mode &#8216;GRAPHIC4&#8217; (see below) displays 32&#215;24=768 tiles. The name table stores a byte for each of these, so changing each tile index requires writing 768 bytes. If we also want to update the tiles themselves, we need to write 16 bytes per tile for patterns and colours, so 4KB in total. And finally, if we want to update the patterns for 32 sprites of 16&#215;16 pixels, we need to write 1KB of data. The colours for those sprites sum up to 512 bytes, and their position and index data is another 128 bytes. It sounds like a lot, but when we sum everything, it turns out that we can update <em>everything that affects screen appearance</em> by writing 6,528 bytes, i.e. well within the bandwidth limit of the VDP.</p>



<p class="wp-block-paragraph"><strong>Data:</strong> For a racing game we need a track of some length. At 20fps, 800 frames yield a 40 second race; two laps make this 1 minute and 20 seconds, which seems about right. At 6,528 bytes per frame, this would be a little more than 5.2MB.</p>



<h2 class="wp-block-heading">The DELTA Renderer</h2>



<p class="wp-block-paragraph">With the above in mind, our goal now becomes to convert a 256&#215;192 16-color bitmap to (no more than) 256 tiles, plus a 32&#215;24 name table indexing those tiles, and a set of sprites. A &#8216;nice to have&#8217; would be some form of compression, so a 16MB cartridge can store at least 4 (but ideally more) tracks.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" width="1024" height="327" src="https://jacco.ompf2.com/wp-content/uploads/2026/03/image-5-1024x327.png" alt="" class="wp-image-2421" style="width:800px" srcset="https://jacco.ompf2.com/wp-content/uploads/2026/03/image-5-1024x327.png 1024w, https://jacco.ompf2.com/wp-content/uploads/2026/03/image-5-300x96.png 300w, https://jacco.ompf2.com/wp-content/uploads/2026/03/image-5-768x245.png 768w, https://jacco.ompf2.com/wp-content/uploads/2026/03/image-5-1536x490.png 1536w, https://jacco.ompf2.com/wp-content/uploads/2026/03/image-5-1222x390.png 1222w, https://jacco.ompf2.com/wp-content/uploads/2026/03/image-5-897x286.png 897w, https://jacco.ompf2.com/wp-content/uploads/2026/03/image-5-360x115.png 360w, https://jacco.ompf2.com/wp-content/uploads/2026/03/image-5.png 1543w" sizes="(max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">Figure 3: Two frames from DELTA, track 1.</figcaption></figure>
</div>


<p class="wp-block-paragraph">The question is of course, will 256 unique tiles be sufficient for <em>all </em>frames of the track, and how many sprites will we need to resolve issues where 8 pixels on a tile need more than 2 colours?</p>



<p class="wp-block-paragraph">Here is a frame from the game (on the left) with the (not yet repaired) tiles on the right:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="347" src="https://jacco.ompf2.com/wp-content/uploads/2026/03/image-6-1024x347.png" alt="" class="wp-image-2422" style="width:800px" srcset="https://jacco.ompf2.com/wp-content/uploads/2026/03/image-6-1024x347.png 1024w, https://jacco.ompf2.com/wp-content/uploads/2026/03/image-6-300x102.png 300w, https://jacco.ompf2.com/wp-content/uploads/2026/03/image-6-768x260.png 768w, https://jacco.ompf2.com/wp-content/uploads/2026/03/image-6-1536x521.png 1536w, https://jacco.ompf2.com/wp-content/uploads/2026/03/image-6-1222x414.png 1222w, https://jacco.ompf2.com/wp-content/uploads/2026/03/image-6-897x304.png 897w, https://jacco.ompf2.com/wp-content/uploads/2026/03/image-6-360x122.png 360w, https://jacco.ompf2.com/wp-content/uploads/2026/03/image-6.png 1652w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">Figure 4: Frame from track 1, and the generated tiles.</figcaption></figure>
</div>


<p class="wp-block-paragraph">The tiles used in this frame are:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" width="515" height="115" src="https://jacco.ompf2.com/wp-content/uploads/2026/03/image-7.png" alt="" class="wp-image-2423" style="width:800px" srcset="https://jacco.ompf2.com/wp-content/uploads/2026/03/image-7.png 515w, https://jacco.ompf2.com/wp-content/uploads/2026/03/image-7-300x67.png 300w, https://jacco.ompf2.com/wp-content/uploads/2026/03/image-7-360x80.png 360w" sizes="auto, (max-width: 515px) 100vw, 515px" /><figcaption class="wp-element-caption">Figure 5: Tileset for the frame shown in Fig. 4.</figcaption></figure>
</div>


<p class="wp-block-paragraph">This is well within budget; in fact 31 tiles remain unused for this frame, some of which are claimed for displaying score and other game data. It turns out that this is the case for all frames of the animation: As long as the detail is dosed carefully, it is quite possible to make a pleasing 3D environment using just 236 or so tiles.</p>



<p class="wp-block-paragraph">The sprite set needed to resolve the remaining issues is modest as well:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" width="522" height="389" src="https://jacco.ompf2.com/wp-content/uploads/2026/03/image-8.png" alt="" class="wp-image-2424" style="width:400px" srcset="https://jacco.ompf2.com/wp-content/uploads/2026/03/image-8.png 522w, https://jacco.ompf2.com/wp-content/uploads/2026/03/image-8-300x224.png 300w, https://jacco.ompf2.com/wp-content/uploads/2026/03/image-8-360x268.png 360w" sizes="auto, (max-width: 522px) 100vw, 522px" /><figcaption class="wp-element-caption">Figure 6: Sprites for the frame shown in Fig. 4.</figcaption></figure>
</div>


<p class="wp-block-paragraph">Note how e.g. the yellow sprites above the car resolve the problem where a single tile must display blue for the water, dark-grey for the track and yellow for the speed lane symbols.</p>



<p class="wp-block-paragraph">Some frames are more complex. For example, this frame from the intro animation:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="375" src="https://jacco.ompf2.com/wp-content/uploads/2026/03/image-9-1024x375.png" alt="" class="wp-image-2426" style="width:800px" srcset="https://jacco.ompf2.com/wp-content/uploads/2026/03/image-9-1024x375.png 1024w, https://jacco.ompf2.com/wp-content/uploads/2026/03/image-9-300x110.png 300w, https://jacco.ompf2.com/wp-content/uploads/2026/03/image-9-768x281.png 768w, https://jacco.ompf2.com/wp-content/uploads/2026/03/image-9-897x328.png 897w, https://jacco.ompf2.com/wp-content/uploads/2026/03/image-9-360x132.png 360w, https://jacco.ompf2.com/wp-content/uploads/2026/03/image-9.png 1066w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">Figure 7: Frame from the intro animation.</figcaption></figure>
</div>


<p class="wp-block-paragraph">Here, the subtle shading on the letters M and S causes substantial issues for the tile conversion. A lot of sprites are needed to remedy this:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" width="519" height="375" src="https://jacco.ompf2.com/wp-content/uploads/2026/03/image-10.png" alt="" class="wp-image-2427" style="width:400px" srcset="https://jacco.ompf2.com/wp-content/uploads/2026/03/image-10.png 519w, https://jacco.ompf2.com/wp-content/uploads/2026/03/image-10-300x217.png 300w, https://jacco.ompf2.com/wp-content/uploads/2026/03/image-10-360x260.png 360w" sizes="auto, (max-width: 519px) 100vw, 519px" /><figcaption class="wp-element-caption">Figure 8: &#8216;Remedial sprites&#8217; for the frame shown in Fig.7.</figcaption></figure>
</div>


<p class="wp-block-paragraph">So many in fact that we run the risk of exceeding the 8 sprites per line limit. This limit is strict on MSX2: Even parts of the sprite that do not contain any pixels contribute to the count, and exceeding the limit makes sprites invisible, exposing the tile issues we where trying to hide. </p>



<p class="wp-block-paragraph">Luckily, most &#8216;remedial sprites&#8217; do not use the full 16&#215;16 square available to them. By shifting the set pixels up or down it is often possible to find a sprite configuration where no line contains more than 8 sprites.</p>



<p class="wp-block-paragraph">During gameplay this challenge is even greater however, and this is where DELTA occasionally fails. The car sprite needs multiple colours, and therefore multiple sprite layers. It is also larger than 16&#215;16 for many angles, and therefore the car is rendered using no less than 8 sprites. These do not occupy the same lines on-screen, but still four sprites do &#8211; and that means the scenery has only four slots to work with, at least on the screen lines occupied by the player car. One consequence of this is that DELTA is strictly a single-player game, without other cars to combat the player.</p>



<h2 class="wp-block-heading">GRAPHIC4</h2>



<p class="wp-block-paragraph">In the next section we will discuss how the prerendered data can be compressed. Before we get to that, we look at the used VDP mode in some more detail.</p>



<h3 class="wp-block-heading">Mirror Mode</h3>



<p class="wp-block-paragraph">GRAPHIC4 on the MSX2 VDP refers to a 16-color tiled video mode, where each of the 16 colours can be chosen from a 9-bit palette. On top of the tiles, up to 32 single-color sprites can be displayed, with a maximum of 8 occupying any screen line.</p>



<p class="wp-block-paragraph">Tile indices are stored in a 768 byte (i.e., 32&#215;24) name table. By default, GRAPHIC4 uses three tile sets: One for the top 1/3rd of the screen, one for tile lines 9 &#8211; 15 and the final one for tile lines 16 &#8211; 23, effectively allowing a unique tile on every location, if desired. <em>Mirror mode</em> allows these three sets to be identical, so that a tile used on position (0,0) can also be used on tile position (0,8). DELTA uses this mode to reduce tile data from 3x 4KB to 1x 4KB.</p>



<h3 class="wp-block-heading">VRAM Layout</h3>



<p class="wp-block-paragraph">The MSX2 VDP lets the programmer select where each of the data tables is located in VRAM. The tables are:</p>



<ul class="wp-block-list">
<li>Name table: Stores tile indices. 768 bytes, by default located at 0x1800.</li>



<li>Tile pattern data: 256 x 8 = 2048 bytes, by default located at 0x0000.</li>



<li>Tile colour data: 256 x 8 = 2048 bytes, by default located at 0x2000.</li>



<li>Sprite pattern data: 32 x 32 = 1024 bytes, by default located at 0x3800.</li>



<li>Sprite colour data: 32 x 16 = 512 bytes, by default located at 0x1C00.</li>



<li>Sprite attribute data: 32 x 4 = 128 bytes, by default located at 0x1E00.</li>
</ul>



<p class="wp-block-paragraph">DELTA renders at 20fps and thus needs 3 NTSC frames to create the next image. This means that double buffering is required. In the case of DELTA, this means: double-buffering <em>all</em> tables. We use the following layout:</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th class="has-text-align-center" data-align="center">Table</th><th class="has-text-align-center" data-align="center">Page 0</th><th class="has-text-align-center" data-align="center">Page 1</th></tr></thead><tbody><tr><td class="has-text-align-center" data-align="center">Name Table</td><td class="has-text-align-center" data-align="center">0x1800</td><td class="has-text-align-center" data-align="center">0x2800</td></tr><tr><td class="has-text-align-center" data-align="center">Tile Patterns</td><td class="has-text-align-center" data-align="center">0x0000</td><td class="has-text-align-center" data-align="center">0x4000</td></tr><tr><td class="has-text-align-center" data-align="center">Tile Colours</td><td class="has-text-align-center" data-align="center">0x2000</td><td class="has-text-align-center" data-align="center">0x6000</td></tr><tr><td class="has-text-align-center" data-align="center">Sprite Patterns</td><td class="has-text-align-center" data-align="center">0x0800</td><td class="has-text-align-center" data-align="center">0x3800</td></tr><tr><td class="has-text-align-center" data-align="center">Sprite Colours</td><td class="has-text-align-center" data-align="center">0x1C00</td><td class="has-text-align-center" data-align="center">0x2C00</td></tr><tr><td class="has-text-align-center" data-align="center">Sprite Attributes</td><td class="has-text-align-center" data-align="center">0x1E00</td><td class="has-text-align-center" data-align="center">0x2E00</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">Switching between the two pages is very fast and can be done during the vertical retrace to avoid tearing.</p>



<p class="wp-block-paragraph">Note that in the above scheme, only 64KB is used, which simplifies setting VRAM addresses somewhat. Moreover, the name table and sprite data for both pages resides within the first 16KB, further reducing the effort of specifying VRAM addresses. Only the tile patterns and colours touch addresses above 0x4000; these are however always written in large batches, amortizing the VRAM address setup cost over many writes.</p>



<h2 class="wp-block-heading">Compression</h2>



<p class="wp-block-paragraph">In the previous sections we discussed the specifics of the MSX2 video processor. Respecting the limitations of the system, but ignoring ROM size for the moment, we conclude the hardware meets our initial requirements:</p>



<ul class="wp-block-list">
<li>We can convert 16-color images containing reasonable polygon detail to less than 256 tiles.</li>



<li>The number of sprites needed to remedy tile colour issues is reasonable.</li>



<li>Bandwidth is within boundaries.</li>
</ul>



<p class="wp-block-paragraph">However, even when we do not use all tiles for all frames, the raw data for 800 animation frames approaches 5MB, which is unwieldy. So, a new question arises: Can this data be compressed, and can the poor Z80 decompress it fast enough to make this worthwhile?</p>



<p class="wp-block-paragraph">We approach this question in three steps:</p>



<ol class="wp-block-list">
<li>Reducing per-frame sprite data traffic</li>



<li>Optimal run-length encoding and decoding of tile colour data</li>



<li>Run-length encoding of tile pattern data</li>



<li>Adaptive run-length encoding of the name table data</li>



<li>Data placement in megarom segments</li>
</ol>



<p class="wp-block-paragraph">Each step is detailed in the following paragraphs.</p>



<h3 class="wp-block-heading">1. Per-frame Sprite Data Traffic</h3>



<p class="wp-block-paragraph">As can be seen in Figure 6 and 8, most remedial sprites are small, often just a few pixels. It thus seems a waste to write full sprite pattern data each frame. Instead, DELTA keeps track of occupied lines in sprites. In subsequent frames, these lines are either overwritten with new data, or cleared.</p>



<p class="wp-block-paragraph">A few examples: A sprite that stores two lines of data that becomes unused in the next frame will have these two lines cleared using two single-byte writes. A sprite that stores three lines while in the next frame that same sprite stores only two lines will have those two lines overwritten (for patterns and colours), and the third line cleared (just the pattern).</p>



<p class="wp-block-paragraph">At the expensive of some non-trivial administration, this approach greatly reduces bandwidth for sprite patterns. A further reduction is possible if we do not overwrite colour data if this did not change, but it turns out that this is too rare to justify the cost of checking this.</p>



<p class="wp-block-paragraph">Table 1 shows the sprite traffic of several frames of track 1.</p>



<figure class="wp-block-table"><table><thead><tr><th class="has-text-align-center" data-align="center">Frame#</th><th class="has-text-align-center" data-align="center">#Sprites</th><th class="has-text-align-center" data-align="center">Avg lines</th></tr></thead><tbody><tr><td class="has-text-align-center" data-align="center">10</td><td class="has-text-align-center" data-align="center">13</td><td class="has-text-align-center" data-align="center">1.54</td></tr><tr><td class="has-text-align-center" data-align="center">20</td><td class="has-text-align-center" data-align="center">11</td><td class="has-text-align-center" data-align="center">2.00</td></tr><tr><td class="has-text-align-center" data-align="center">30</td><td class="has-text-align-center" data-align="center">7</td><td class="has-text-align-center" data-align="center">5.43</td></tr><tr><td class="has-text-align-center" data-align="center">40</td><td class="has-text-align-center" data-align="center">12</td><td class="has-text-align-center" data-align="center">3.75</td></tr><tr><td class="has-text-align-center" data-align="center">50</td><td class="has-text-align-center" data-align="center">11</td><td class="has-text-align-center" data-align="center">3.45</td></tr></tbody></table><figcaption class="wp-element-caption">Table 1: Remedial sprite count and size for five representative frames of track 1.</figcaption></figure>



<h3 class="wp-block-heading">2. Compressing Tile Colours</h3>



<p class="wp-block-paragraph">As can be seen in Figure 5, tiles for a particular frame often use only two colours. We thus split all tiles in two groups: One group for 2-colour tiles, and one group for tiles that require more colours. The 2-colour tiles are then sorted in such a way that large continues spans of the same colour values emerge. Figure 5 clearly shows this. Run-length encoding of this data becomes very effective, reducing tile colour data to a fraction of its original size.</p>



<p class="wp-block-paragraph">The run-length scheme used in DELTA is simple and translates to efficient Z80 assembler for decoding directly to VRAM. The compressor distinguishes two types of span:</p>



<ol class="wp-block-list">
<li>&#8216;Uniform spans&#8217;, storing three or more identical values, with a maximum length of 128 pixels</li>



<li>&#8216;Raw spans&#8217;, storing arbitrary values, also with a maximum length of 128 pixels.</li>
</ol>



<p class="wp-block-paragraph">A span starts with a single byte that stores the span type in 1 bit and the length in the remaining 7 bits. To speed up decompression, a raw span is assumed to be followed by a uniform span.</p>



<p class="wp-block-paragraph">The core of the Z80 decompression code is shown below. Timings include the M1 wait on MSX, as specified on <a href="https://map.grauw.nl/resources/z80instr.php">Grauw&#8217;s website</a>.</p>



<pre class="wp-block-preformatted">      ...  setup VRAM access<br>      ld a, (hl)          // 7  - get first command<br>loop:						<br>      rra                 // 5T  - lowest bit contains span type (1)<br>      ld b, a             // 5T  - b = length of raw span<br>      jp c, dospan        // 11T - span is uniform?<br>      inc hl              // 7T  - advance input stream pointer<br>      otir                // 23T - emit 'b' bytes reading from [hl]<br>      ld b, (hl)          // 7T  - b = length of uniform span minus two<br>dospan:<br>      inc hl              // 7T  - advance input stream pointer<br>      ld a, (hl)          // 7T  - a = value for uniform span<br>      out (0x98), a       // 12T - write first pixel of span (2)<br>      inc hl              // 7T  - advance input stream pointer<br>      out (0x98), a       // 12T - write second pixel of span (2)<br>      nop                 // 5T  - VDP timing (3)<br>uniform_loop:<br>      out (0x98), a       // 12T - write remaining span pixels<br>      djnz uniform_loop   // 14T - while (--b) goto uniform_loop<br>      xor (hl)            // 8T  - obtain next command (4)<br>      jp nz loop          // 11T - if not zero: next pair of spans (5)</pre>



<p class="wp-block-paragraph">The run-length decompression code is pivotal for the performance of the renderer. It has thus been very carefully crafted. Some details:</p>



<ol class="wp-block-list">
<li>The span type is stored in the lowest bit of each span header. This way, it can be shifted into the carry flag using the rra instruction.</li>



<li>A uniform span is at least three pixels. The first two are drawn unconditionally, outside the loop.</li>



<li>The nop is needed to avoid timing issues for the VDP, as the out instruction before it takes less than 15 cycles.</li>



<li>After the first two spans, span headers are xor&#8217;ed with the value used in the previous uniform span. This way, a single xor (hl) sets the zero flag on end-of-stream while obtaining the next command in all other cases.</li>



<li>The final span must be a uniform span (of at least three bytes), even if the input data does not need this. For this reason, the target buffer must have room for this dummy span. In DELTA, line 23 in the name table starts with three spaces for this reason.</li>
</ol>



<p class="wp-block-paragraph">And finally: Instead of the final jp nz it is more efficient to unroll the code (several times), as not taking a jump is faster on the Z80. DELTA unrolls the code three times for this purpose.</p>



<figure class="wp-block-table"><table><thead><tr><th class="has-text-align-center" data-align="center">Frame#</th><th class="has-text-align-center" data-align="center">Colour data size</th><th class="has-text-align-center" data-align="center">Compressed size</th><th class="has-text-align-center" data-align="center">Ratio</th></tr></thead><tbody><tr><td class="has-text-align-center" data-align="center">10</td><td class="has-text-align-center" data-align="center">1568</td><td class="has-text-align-center" data-align="center">196</td><td class="has-text-align-center" data-align="center">12.5%</td></tr><tr><td class="has-text-align-center" data-align="center">20</td><td class="has-text-align-center" data-align="center">1592</td><td class="has-text-align-center" data-align="center">136</td><td class="has-text-align-center" data-align="center">8.5%</td></tr><tr><td class="has-text-align-center" data-align="center">30</td><td class="has-text-align-center" data-align="center">1732</td><td class="has-text-align-center" data-align="center">166</td><td class="has-text-align-center" data-align="center">9.6%</td></tr><tr><td class="has-text-align-center" data-align="center">40</td><td class="has-text-align-center" data-align="center">1576</td><td class="has-text-align-center" data-align="center">140</td><td class="has-text-align-center" data-align="center">8.9%</td></tr><tr><td class="has-text-align-center" data-align="center">50</td><td class="has-text-align-center" data-align="center">1664</td><td class="has-text-align-center" data-align="center">204</td><td class="has-text-align-center" data-align="center">12.3%</td></tr></tbody></table><figcaption class="wp-element-caption">Table 2: Tile colour data size, original and compressed, in bytes.</figcaption></figure>



<p class="wp-block-paragraph">Table 2 shows details on the compression of tile colour data. Simple run-length encoding is able to decimate the data rate here.</p>



<h3 class="wp-block-heading">3. Compressing Tile Patterns</h3>



<p class="wp-block-paragraph">At first sight, tile pattern data appears to be mostly random and thus unsuitable for basic run-length encoding. It turns out however that this is worthwhile. </p>



<p class="wp-block-paragraph">DELTA further improves run-length encoding of tile pattern data using <em>random reordering</em>. This is based on the observation that the order of tiles within a slice of equally coloured tiles is irrelevant; swapping two tiles (along with their indices in the name table) yields the same image. We obtain a near-optimal ordering using a random process, in which we repeatedly swap tiles and assess the rate of compression, keeping advantageous mutations. </p>



<p class="wp-block-paragraph">Table 3 shows the result of tile pattern compression. Although compression is not nearly as efficient as in the case of colour data, size is still almost halved in many cases.</p>



<figure class="wp-block-table"><table><thead><tr><th class="has-text-align-center" data-align="center">Frame#</th><th class="has-text-align-center" data-align="center">Pattern data size</th><th class="has-text-align-center" data-align="center">Compressed</th><th class="has-text-align-center" data-align="center">Compressed (mutated)</th><th class="has-text-align-center" data-align="center">Ratio</th></tr></thead><tbody><tr><td class="has-text-align-center" data-align="center">10</td><td class="has-text-align-center" data-align="center">1568</td><td class="has-text-align-center" data-align="center">1050</td><td class="has-text-align-center" data-align="center">958</td><td class="has-text-align-center" data-align="center">61.1%</td></tr><tr><td class="has-text-align-center" data-align="center">20</td><td class="has-text-align-center" data-align="center">1592</td><td class="has-text-align-center" data-align="center">1128</td><td class="has-text-align-center" data-align="center">996</td><td class="has-text-align-center" data-align="center">62.6%</td></tr><tr><td class="has-text-align-center" data-align="center">30</td><td class="has-text-align-center" data-align="center">1704</td><td class="has-text-align-center" data-align="center">1079</td><td class="has-text-align-center" data-align="center">927</td><td class="has-text-align-center" data-align="center">54.4%</td></tr><tr><td class="has-text-align-center" data-align="center">40</td><td class="has-text-align-center" data-align="center">1576</td><td class="has-text-align-center" data-align="center">1009</td><td class="has-text-align-center" data-align="center">853</td><td class="has-text-align-center" data-align="center">54.1%</td></tr><tr><td class="has-text-align-center" data-align="center">50</td><td class="has-text-align-center" data-align="center">1664</td><td class="has-text-align-center" data-align="center">955</td><td class="has-text-align-center" data-align="center">805</td><td class="has-text-align-center" data-align="center">48.4%</td></tr></tbody></table><figcaption class="wp-element-caption">Table 3: Tile pattern data size, original and compressed, in bytes.</figcaption></figure>



<h3 class="wp-block-heading">4. Compressing the Name Table</h3>



<p class="wp-block-paragraph">Each frame uses 32&#215;23 tile indices in the name table (the last line of tiles displays score and such). Like the tile colours, this data is run-length compressible, although the gains are often modest. </p>



<p class="wp-block-paragraph">We found that for some complex frames maintaining 20fps was difficult. Therefore, name table compression is made optional: It is skipped when the tile count exceeds a certain threshold, which is a good indicator for frame complexity. Copying raw data is always faster than decompression; by making it adaptive we sacrifice compression efficiency for rendering performance. If needed, this could be extended to other data, e.g. the tile pattern data.</p>



<p class="wp-block-paragraph">Table 4 shows the efficiency of name table compression. Compared to colour and pattern data, name table compression shows somewhat poor compression.</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th class="has-text-align-center" data-align="center">Frame#</th><th class="has-text-align-center" data-align="center">Compressed size</th><th class="has-text-align-center" data-align="center">Ratio</th></tr></thead><tbody><tr><td class="has-text-align-center" data-align="center">10</td><td class="has-text-align-center" data-align="center">429</td><td class="has-text-align-center" data-align="center">58.3%</td></tr><tr><td class="has-text-align-center" data-align="center">20</td><td class="has-text-align-center" data-align="center">454</td><td class="has-text-align-center" data-align="center">61.7%</td></tr><tr><td class="has-text-align-center" data-align="center">30</td><td class="has-text-align-center" data-align="center">470</td><td class="has-text-align-center" data-align="center">63.9%</td></tr><tr><td class="has-text-align-center" data-align="center">40</td><td class="has-text-align-center" data-align="center">465</td><td class="has-text-align-center" data-align="center">63.2%</td></tr><tr><td class="has-text-align-center" data-align="center">50</td><td class="has-text-align-center" data-align="center">469</td><td class="has-text-align-center" data-align="center">63.7%</td></tr></tbody></table><figcaption class="wp-element-caption">Table 4: Name table compression efficiency. Original data is 736 bytes for 23 lines.</figcaption></figure>



<h3 class="wp-block-heading">5. Storing Frames in Segments</h3>



<p class="wp-block-paragraph">After compressing all data for a frame, the end result is somewhere between 800 bytes and 2 kilobytes, with an average size of 1695 bytes for track 1 frames. This data has to be stored in one of the 16KB segments of the final megarom, and for efficiency reasons, it should not span a segment boundary. At 1695 bytes per frame, this would leave (on  average) a gap of 848 bytes at the end of each segment, which is a 5% waste of space.</p>



<p class="wp-block-paragraph">Here we again use the stochastic optimization approach. After generating all track frames, we reorder them in such a way that each megarom segment is as full as possible. For the 802 frames of track 1, this reduces wasted space in the segments to just a few bytes.</p>



<h2 class="wp-block-heading">Future Work</h2>



<p class="wp-block-paragraph">As stated in the previous paragraph, compression of track data yields an average size of 1695 bytes per frame, which is a solid improvement over storing raw data, while still allowing run-time decompression. There is however room for improvement.</p>



<p class="wp-block-paragraph">To improve rendering speed and compression efficiency, we should reuse data more often. The tile colour table is 2KB for 256 characters; yet from frame to frame tile colours will be similar. We may be able to avoid writing a substantial part of that 2KB if we carefully order our tiles. This would however require a strict sequential decompression of frames, potentially using occasional keyframes.</p>



<p class="wp-block-paragraph">Similarly, we could simply leave all (or most) tile colours untouched, by predefining groups of tiles with specific colour pairs.</p>



<p class="wp-block-paragraph">If memory capacity increases even further, it may be advantageous eventually to discard compression altogether. Clever reuse of frame-to-frame coherence then becomes the only useful scheme.</p>



<p class="wp-block-paragraph">And finally, we did not explore the use of a dynamic palette. Currently a track can use 16 colours, of which 3 are shared with the player car and another one (white) with the score display. The remaining 12 colours are rarely in view at the same time, which should allow for more freedom in this regard.</p>



<h2 class="wp-block-heading">Concluding Remarks</h2>



<p class="wp-block-paragraph">The main technical contribution in DELTA is, we believe, the use of GRAPHIC4 mode combined with sprites to display pre-rendered polygon graphics. The available bandwidth and sprite count allows for a level of detail that is sufficient for a 256&#215;192 display, as evidenced by the game.</p>



<p class="wp-block-paragraph">Additionally we demonstrated that basic run-length encoding is effective for all data streams: Although tile colour data benefits most, tile pattern data and name table data still benefit substantially, while decompression remains simple enough to be used at 20fps on the Z80 CPU.</p>



<p class="wp-block-paragraph">Finally, we indicated several avenues for further improving the technique. This could either allow for higher frame rates (25 fps seems feasible), more complex scenery, a larger display (using &#8216;overscan&#8217; for 26.5 lines of tiles), or more complex game play and/or music.</p>



<p class="wp-block-paragraph">The technique does impose strong limitations on gameplay. When properly mitigated, we believe the proposed technique provides a visual style that is rather unique for the platform.</p>



<h2 class="wp-block-heading">Playing DELTA</h2>



<p class="wp-block-paragraph">DELTA has been submitted to the <a href="https://www.msxdev.org/2026/02/21/msxdev25-30-delta/">MSXDev25 competition</a> and can be played for free via <a href="https://www.file-hunter.com/MSXdev/?id=delta">File-Hunter.com</a>.</p>



<p class="wp-block-paragraph">Contact us in case of questions / remarks: <a href="mailto:bikker.j@gmail.com">bikker.j@gmail.com</a>.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="696" src="https://jacco.ompf2.com/wp-content/uploads/2026/02/shot2-1024x696.jpg" alt="" class="wp-image-2392" style="width:400px" srcset="https://jacco.ompf2.com/wp-content/uploads/2026/02/shot2-1024x696.jpg 1024w, https://jacco.ompf2.com/wp-content/uploads/2026/02/shot2-300x204.jpg 300w, https://jacco.ompf2.com/wp-content/uploads/2026/02/shot2-768x522.jpg 768w, https://jacco.ompf2.com/wp-content/uploads/2026/02/shot2-1536x1045.jpg 1536w, https://jacco.ompf2.com/wp-content/uploads/2026/02/shot2-1222x831.jpg 1222w, https://jacco.ompf2.com/wp-content/uploads/2026/02/shot2-897x610.jpg 897w, https://jacco.ompf2.com/wp-content/uploads/2026/02/shot2-360x245.jpg 360w, https://jacco.ompf2.com/wp-content/uploads/2026/02/shot2.jpg 1544w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Ray Tracing with Voxels in C++ Series &#8211; Part 6</title>
		<link>https://jacco.ompf2.com/2024/05/29/ray-tracing-with-voxels-in-c-series-part-6/</link>
					<comments>https://jacco.ompf2.com/2024/05/29/ray-tracing-with-voxels-in-c-series-part-6/#comments</comments>
		
		<dc:creator><![CDATA[jbikker]]></dc:creator>
		<pubDate>Wed, 29 May 2024 09:08:23 +0000</pubDate>
				<category><![CDATA[Article]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Tutorial]]></category>
		<guid isPermaLink="false">https://jacco.ompf2.com/?p=2046</guid>

					<description><![CDATA[In this series we build a physically based renderer for a dynamic voxel world. From &#8216;Whitted-style&#8217; ray...]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">In this series we build a physically based renderer for a dynamic voxel world. From &#8216;Whitted-style&#8217; ray tracing with shadows, glass and mirrors, we go all the way to &#8216;unbiased path tracing&#8217; &#8211; and beyond, exploring advanced topics such as reprojection, denoising and blue noise. The accompanying source code is <a href="https://github.com/jbikker/voxpopuli">available on Github</a> and is written in easy-to-read &#8216;sane C++&#8217;.</p>



<p class="wp-block-paragraph">This series consists of nine articles. Contents:  <em>(tentative until finalized)</em></p>



<ol class="wp-block-list">
<li><a href="https://jacco.ompf2.com/?p=1715">Starting point: Voxel ray tracing template code. Lights and shadows</a>.</li>



<li><a href="https://jacco.ompf2.com/?p=1755&amp;preview=true">Whitted-style: Reflections, recursion, glass</a>.</li>



<li><a href="https://jacco.ompf2.com/?p=1803">Stochastic techniques: Anti-aliasing and soft shadows</a>.</li>



<li><a href="https://jacco.ompf2.com/?p=1839">Noise reduction: Stratification and blue noise</a>.</li>



<li><a href="https://jacco.ompf2.com/?p=1887">Converging under movement: Reprojection</a>.</li>



<li><strong>Path tracing: Basics first; then: Importance Sampling (this article).</strong></li>



<li>Denoising fundamentals.</li>



<li>Acceleration structures: Extending the grid to a multi-level grid.</li>



<li>Acceleration structures: Adding a TLAS.   </li>
</ol>



<h2 class="wp-block-heading">In This Article&#8230;</h2>



<p class="wp-block-paragraph">After all the noise and noise suppression techniques it is time to move forward and improve the visual fidelity of the renderer. We will do so using probably the most beautiful algorithm in computer graphics: <em>Path Tracing</em>. The core &#8216;ground truth&#8217; algorithm turns out to be surprisingly simple &#8211; and stunningly close to the &#8220;God Algorithm&#8221;: Light transport (via photons) in the Real World. </p>



<p class="wp-block-paragraph">At the end of this episode an extension to the basic path tracing implementation is introduced that improves its efficiency, while still producing an image identical to &#8216;ground truth&#8217;.</p>



<h2 class="wp-block-heading">Starting Point</h2>



<p class="wp-block-paragraph">We start with a new scene: The &#8220;Floating Island of the Potion Brewer&#8221;, converted from a Sketchfab model by author <a href="https://sketchfab.com/vilmariina">Vilmariina</a>. The scene is 256x256x256 voxels, so, in <code>scene.h</code>, set <code>WORLDSIZE</code> to 256. Then, load the scene using the following code:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">Scene::Scene()
{
    grid = (uint*)MALLOC64( GRIDSIZE3 * sizeof( uint ) );
    gzFile f = gzopen( "assets/floating256.bin", "rb" );
    gzread( f, grid, sizeof( int3 ) );
    gzread( f, grid, GRIDSIZE3 * sizeof( uint ) );
    gzclose( f );
}</pre></div>



<p class="wp-block-paragraph">Next, replace <code>Renderer::Trace</code> (in <code>renderer.cpp</code>) by something simple:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 Renderer::Trace( Ray&amp; ray, int, int, int depth )
{
    scene.FindNearest( ray );
    if (ray.voxel == 0) return float3( 1.2f, 1.2f, 1.0f );
    return ray.albedo;
}</pre></div>



<p class="wp-block-paragraph">That&#8217;s it, we&#8217;re all set. </p>



<h2 class="wp-block-heading">Cheese</h2>



<p class="wp-block-paragraph">This time, we&#8217;re going to dive right in and start with the &#8216;finished product&#8217;. Run the code and find a camera view similar to the shot shown below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="661" src="https://jacco.ompf2.com/wp-content/uploads/2024/05/viewfind-1-1024x661.jpg" alt="" class="wp-image-2112" style="width:512px" srcset="https://jacco.ompf2.com/wp-content/uploads/2024/05/viewfind-1-1024x661.jpg 1024w, https://jacco.ompf2.com/wp-content/uploads/2024/05/viewfind-1-300x194.jpg 300w, https://jacco.ompf2.com/wp-content/uploads/2024/05/viewfind-1-768x496.jpg 768w, https://jacco.ompf2.com/wp-content/uploads/2024/05/viewfind-1-897x579.jpg 897w, https://jacco.ompf2.com/wp-content/uploads/2024/05/viewfind-1-360x232.jpg 360w, https://jacco.ompf2.com/wp-content/uploads/2024/05/viewfind-1.jpg 1214w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">Figure 1: A good viewpoint to enjoy the scene.</figcaption></figure>
</div>


<p class="wp-block-paragraph">Next, add the accumulator from Episode 3. Either <a href="https://jacco.ompf2.com/2024/05/08/ray-tracing-with-voxels-in-c-series-part-3/">go there</a> for detailed instructions, or copy/paste the shortified code below, replacing <code>Renderer::Init</code> and <code>Renderer::Tick</code>:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void Renderer::Init()
{
    accumulator = new float3[SCRWIDTH * SCRHEIGHT];
    memset( accumulator, 0, SCRWIDTH * SCRHEIGHT * sizeof( float3 ) );
}</pre></div>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void Renderer::Tick( float deltaTime )
{
    static int spp = 1;
    const float scale = 1.0f / spp++;
#pragma omp parallel for schedule(dynamic)
    for (int y = 0; y &lt; SCRHEIGHT; y++) for (int x = 0; x &lt; SCRWIDTH; x++)
    {
        Ray r = camera.GetPrimaryRay( x + RandomFloat(), y + RandomFloat() );
        accumulator[x + y * SCRWIDTH] += Trace( r );
        float3 average = accumulator[x + y * SCRWIDTH] * scale;
        screen-&gt;pixels[x + y * SCRWIDTH] = RGBF32_to_RGB8( average );
    }
    if (!camera.HandleInput( deltaTime )) return; else spp = 1;
    memset( accumulator, 0, SCRWIDTH * SCRHEIGHT * sizeof( float3 ) );
}</pre></div>



<p class="wp-block-paragraph">And finally, replace <code>Renderer::Trace</code> by the following magical code snippet.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 Renderer::Trace( Ray&amp; ray, int, int, int depth )
{
    scene.FindNearest( ray );
    if (ray.voxel == 0) return float3( 1.2f, 1.2f, 1.0f );
    if (depth == 4) return float3( 0 );
    float3 N = ray.GetNormal(), I = ray.IntersectionPoint();
    float3 R = diffuseReflection( N );
    float3 brdf = ray.GetAlbedo() / PI;
    float pdf = 1.0f / TWOPI;
    float3 indirect = Trace( Ray( I, R ), 0, 0, depth + 1 ); 
    return brdf * indirect * (dot( N, R ) / pdf);
}</pre></div>



<p class="wp-block-paragraph">Now run <em>this.</em> The output is breath-taking:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="662" src="https://jacco.ompf2.com/wp-content/uploads/2024/05/magic-2-1024x662.jpg" alt="" class="wp-image-2121" style="width:600px" srcset="https://jacco.ompf2.com/wp-content/uploads/2024/05/magic-2-1024x662.jpg 1024w, https://jacco.ompf2.com/wp-content/uploads/2024/05/magic-2-300x194.jpg 300w, https://jacco.ompf2.com/wp-content/uploads/2024/05/magic-2-768x496.jpg 768w, https://jacco.ompf2.com/wp-content/uploads/2024/05/magic-2-897x580.jpg 897w, https://jacco.ompf2.com/wp-content/uploads/2024/05/magic-2-360x233.jpg 360w, https://jacco.ompf2.com/wp-content/uploads/2024/05/magic-2.jpg 1216w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">Figure 2: Path-traced render of the scene.</figcaption></figure>
</div>


<p class="wp-block-paragraph">In fact, your output may be darker than that but this is easily resolved by modifying variable <code>average</code> before plotting it:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">average.x = sqrtf( average.x );
average.y = sqrtf( average.y );
average.z = sqrtf( average.z );</pre></div>



<p class="wp-block-paragraph">The purpose of these three lines is <em><a href="https://www.cambridgeincolour.com/tutorials/gamma-correction.htm">gamma correction</a></em>. The renderer is producing correct values in &#8216;linear color space&#8217;, i.e.: Doubling a value makes it exactly twice as bright. The average monitor or laptop screen however uses a different curve, which isn&#8217;t linear at all: a relative large change is needed to make a dark pixel somewhat brighter. The square root counters this, so that the color gradients on the screen look natural. </p>



<p class="has-drop-cap has-white-color has-pale-cyan-blue-background-color has-text-color has-background has-link-color wp-elements-047d08677c8aa73e1a58f4f92ca12236 wp-block-paragraph" style="font-style:italic;font-weight:400">Gamma is useful by the way, because our eyes have a similar curve in sensitivity: We can detect smaller differences between dark colors than between bright colors. Having more values in the low regions thus accommodates the human visual system. Just like the red/green/blue color blending: The <a href="https://askabiologist.asu.edu/rods-and-cones">rods and cones</a> in our eyes that detect light happen to be sensitive to exactly those colors.  </p>



<p class="wp-block-paragraph">Looking at the path traced image in Figure 2, we see subtle soft shadows, subtle darkening near voxels, light inside the buildings, and an overall <em>natural</em> appearance of the illumination. But, there are no lights&#8230; So, how does this work?</p>



<h2 class="wp-block-heading">God&#8217;s Algorithm</h2>



<p class="wp-block-paragraph">Light energy in nature travels from light sources to sensors (eyes, cameras) in the form of photons. Photon behavior is really simple: A photon travels in a straight line (unless close to a black hole, but lets ignore that here), and when it hits something, it gets absorbed, or it changes direction.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" width="446" height="342" src="https://jacco.ompf2.com/wp-content/uploads/2024/05/room.jpg" alt="" class="wp-image-2131" style="width:512px" srcset="https://jacco.ompf2.com/wp-content/uploads/2024/05/room.jpg 446w, https://jacco.ompf2.com/wp-content/uploads/2024/05/room-300x230.jpg 300w, https://jacco.ompf2.com/wp-content/uploads/2024/05/room-360x276.jpg 360w" sizes="auto, (max-width: 446px) 100vw, 446px" /><figcaption class="wp-element-caption">Figure 3: God&#8217;s algorithm in a student room. The lightbulb emits <span class="wp-katex-eq" data-display="false">10^{20}</span> photons per second, but the behavior of each photon is simple.</figcaption></figure>
</div>


<p class="wp-block-paragraph">We can simulate that behavior for physically-based, photo-realistic images. And that is precisely the basis of the path tracing algorithm. Look at this line:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 indirect = Trace( Ray( I, R ), 0, 0, depth + 1 );</pre></div>



<p class="wp-block-paragraph">That&#8217;s a recursive call to the <code>Renderer::Trace</code> function. So, at the end of the Trace function, a new ray is generated, and whatever indirect light it brings back is what the primary ray returns to the <code>Tick</code> function. The bouncing rays together form a path, which ends at a specific length (four, in this case) or when a light is found.</p>



<p class="wp-block-paragraph">So this does replicate photon behavior, and quite successfully, judging from the outcome. One thing is strange though: The path is formed in the <em>reversed</em> direction; i.e. from the camera to the lights. It turns out that this is fine: A physics rule named the <a href="https://en.wikipedia.org/wiki/Helmholtz_reciprocity">Helmholtz reciprocity principle</a> states that source and observation point can be swapped without affecting the outcome. The great benefit of the reversed path is that we now effectively ignore all the photon paths that do not connect to the camera.</p>



<h2 class="wp-block-heading">Pi, pdf etc.</h2>



<p class="wp-block-paragraph">Let&#8217;s reformulate the base algorithm a bit to understand it better:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 Renderer::Trace( Ray&amp; ray, int, int, int )
{
    float3 throughput( 1, 1, 1 );
    for( int bounce = 0; bounce &lt; 4; bounce++ )
    {
        // find nearest surface
        scene.FindNearest( ray );
        if (ray.voxel == 0) 
        {
            // path found the sky
            return throughput * float3( 1.2f, 1.2f, 1.0f );
        }
        // get surface interaction data
        float3 N = ray.GetNormal(), I = ray.IntersectionPoint();
        float3 brdf = ray.GetAlbedo() / PI;
        // generate new path segment
        float3 R = diffuseReflection( N );
        float pdf = 1.0f / TWOPI;
        throughput *= brdf * (dot( N, R ) / pdf);
        ray = Ray( I, R );
    }
    return { 0 }; // path too long
}</pre></div>



<p class="wp-block-paragraph">Functionally nothing changed here. That being said: The function now no longer uses recursion; instead, a simple loop keeps track of the bounces. The amount of light the path transports from the sky to the camera is kept track of using variable <code>throughput</code>.</p>



<p class="wp-block-paragraph">At each surface that the path visits, the throughput is changed using three values, which we will discuss in more detail.</p>



<ol class="wp-block-list">
<li>The material color, or more precisely: the BRDF;</li>



<li>A &#8216;probability density function&#8217; PDF;</li>



<li>A dot product between the surface normal <span class="wp-katex-eq" data-display="false">N</span> and the new ray direction <span class="wp-katex-eq" data-display="false">R</span>.</li>
</ol>



<p class="wp-block-paragraph">All of these are vital for the correctness of the simulation.</p>



<h2 class="wp-block-heading">BRDF</h2>



<p class="wp-block-paragraph">All materials (even the super-dark <a href="https://www.surreynanosystems.com/about/vantablack">Vantablack</a>) reflect light. The amount of reflected light and the direction of the reflection depends on the specific material. If you look into a bathroom mirror for example, the reflected light is (almost) the same as the incoming light, and the direction of the reflection is very specific. A sheet of red paper on the other hand does reflect, but mostly the red part of the visible spectrum; other colors are absorbed. And, the direction of the outgoing light is pretty much random for such a material.</p>



<p class="wp-block-paragraph">The reflection properties of a material can be described using a BRDF, the <em>Bidirectional Reflection Distribution Function</em>. For a given incoming and outgoing direction, the BRDF describes how much light is reflected. For a mirror, the BRDF describes that all light for a specific incoming direction leaves into a single outgoing direction. But for a diffuse material, like paper, it states that any incoming direction can be coupled to any outgoing direction.</p>



<p class="wp-block-paragraph">The BRDF in the above code snippet is formulated as <code>ray.GetAlbedo() / PI</code>. With that formula, there is no dependency on incoming and outgoing directions; the only thing that matters is absorption. The division by <span class="wp-katex-eq" data-display="false">\pi</span> is needed <a href="https://sakibsaikia.github.io/graphics/2019/09/10/Deriving-Lambertian-BRDF-From-First-Principles.html">for reasons</a> beyond the scope of this article.</p>



<p class="wp-block-paragraph">The random scattering itself is implemented in function <code>diffuseReflection</code>, which you can find in <code>tmpl8math.h</code>. It reads:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">inline float3 diffuseReflection( const float3&amp; N )
{
    float3 R;
    do
    {
        R = make_float3( RandomFloat(), RandomFloat(), RandomFloat() ) * 2 - 1;
    } while (dot( R, R ) &gt; 1);
    return normalize( dot( R, N ) &lt; 0 ? -R : R );
}</pre></div>



<p class="wp-block-paragraph">The purpose of this function is to generate a random new direction that does not travel into the surface with normal <span class="wp-katex-eq" data-display="false">N</span>. </p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="790" src="https://jacco.ompf2.com/wp-content/uploads/2024/05/diffrefl-1024x790.jpg" alt="" class="wp-image-2140" style="width:400px" srcset="https://jacco.ompf2.com/wp-content/uploads/2024/05/diffrefl-1024x790.jpg 1024w, https://jacco.ompf2.com/wp-content/uploads/2024/05/diffrefl-300x231.jpg 300w, https://jacco.ompf2.com/wp-content/uploads/2024/05/diffrefl-768x592.jpg 768w, https://jacco.ompf2.com/wp-content/uploads/2024/05/diffrefl-897x692.jpg 897w, https://jacco.ompf2.com/wp-content/uploads/2024/05/diffrefl-360x278.jpg 360w, https://jacco.ompf2.com/wp-content/uploads/2024/05/diffrefl.jpg 1058w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">Figure 4: Generating a random bounce in the surface defined by normal <span class="wp-katex-eq" data-display="false">N</span>.</figcaption></figure>
</div>


<p class="wp-block-paragraph">In 2D, to generate a &#8216;random bounce&#8217; we first generate a random vector with <span class="wp-katex-eq" data-display="false">x</span>, <span class="wp-katex-eq" data-display="false">y</span> and <span class="wp-katex-eq" data-display="false">z</span> in the range of <span class="wp-katex-eq" data-display="false">-1 .. 1</span>. We recalculate this vector if it is outside the circle of radius 1: This is to prevent a higher density of rays towards the corners of the rectangle. Next, if the chosen point is behind the surface (detected using <code>dot(R, N) &lt; 0</code> ), we negate it. This will always take it to the correct side. And finally, we normalize the calculated point to place it exactly on the half-circle of radius 1.</p>



<p class="wp-block-paragraph">In 3D the process is the same. The half-sphere of radius 1 is now called the <em>hemisphere</em> over the surface point that we hit.  </p>



<h2 class="wp-block-heading">(Ir)radiance</h2>



<p class="wp-block-paragraph">The random direction <span class="wp-katex-eq" data-display="false">R</span> away from the surface is thus used to collect light, maybe directly from the sky, or maybe via another surface, maybe via several. In any case, the light arrives in the form of <em>radiance</em>, while the BRDF must be applied to <em>irradiance.</em> To understand the difference, look at the following diagram:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="688" src="https://jacco.ompf2.com/wp-content/uploads/2024/05/project-1-1024x688.jpg" alt="" class="wp-image-2147" style="width:512px" srcset="https://jacco.ompf2.com/wp-content/uploads/2024/05/project-1-1024x688.jpg 1024w, https://jacco.ompf2.com/wp-content/uploads/2024/05/project-1-300x201.jpg 300w, https://jacco.ompf2.com/wp-content/uploads/2024/05/project-1-768x516.jpg 768w, https://jacco.ompf2.com/wp-content/uploads/2024/05/project-1-1222x821.jpg 1222w, https://jacco.ompf2.com/wp-content/uploads/2024/05/project-1-897x602.jpg 897w, https://jacco.ompf2.com/wp-content/uploads/2024/05/project-1-360x242.jpg 360w, https://jacco.ompf2.com/wp-content/uploads/2024/05/project-1.jpg 1251w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">Figure 5: Projected radiance becomes irradiance.</figcaption></figure>
</div>


<p class="wp-block-paragraph">Here, two identical beams of light strike a surface. The left beam affects a small area, but the right one affects a much bigger area. This has a consequence: The <em>energy</em> in the right beam is distributed over a larger area, and therefore, for a single point on the surface, the projected energy is a lot lower.</p>



<p class="wp-block-paragraph">We call light energy that travels freely through space <em>radiance</em>, while energy that got projected onto a surface is called <em>irradiance.</em> We calculate irradiance from radiance by multiplying the radiance by the cosine of the angle between the normal and a vector towards the light. Or, much more conveniently, we can replace that by <code>dot( N, R )</code>, which is precisely what the path tracing code does.</p>



<h2 class="wp-block-heading">PDF</h2>



<p class="wp-block-paragraph">That leaves one final term: The &#8216;pdf&#8217;, which is stated to be <span class="wp-katex-eq" data-display="false">1/{2\pi}</span>. The concept is a bit complex, but what it boils down to is this: The single random ray we send to the hemisphere accounts for light arriving over a hemisphere with an area of <span class="wp-katex-eq" data-display="false">2\pi</span>. If each point on that hemisphere has the same chance of being picked, the probability density is a constant <span class="wp-katex-eq" data-display="false">1/{2\pi}</span>. More details in a separate article: <a href="https://jacco.ompf2.com/2019/12/11/probability-theory-for-physically-based-rendering/">Probability Theory for Physically Based Rendering</a>.   </p>



<h2 class="wp-block-heading">Interlude</h2>



<p class="wp-block-paragraph">Summarizing, a path tracer is a reverse photon simulator, where a path starts at the camera and bounces around the scene randomly until it encounters a light source. At each surface it encounters it loses some energy: Because of the color (a.k.a. albedo) of the material, and because of projection onto the surface, a.k.a. radiance to irradiance conversion.</p>



<p class="wp-block-paragraph">Some thoughts before we advance:</p>



<ul class="wp-block-list">
<li>It&#8217;s good that we are rendering an outdoor scene here: The sky counts as a light in this scene and even short paths are able to find it. On the other hand, that means that the current path tracer will struggle with an indoor scene illuminated by a small light.</li>



<li>All materials so far are diffuse, but paths will happily bounce off of a mirror as well. In that case, the bounce is deterministic instead of random, and the new path direction is calculated using the reflection formula we saw in <a href="https://jacco.ompf2.com/2024/05/01/ray-tracing-with-voxels-in-c-series-part-2/">Episode 2</a>.</li>



<li>A path will bring back less energy the longer it gets. At the same time, these paths are costly; each ray takes time to trace after all. To use compute resources effectively, we need a way to focus on short paths which are expected to bring back more energy. </li>
</ul>



<p class="wp-block-paragraph">That last thought is an important one. Focusing on the <em>important paths</em> is the main way to make a path tracer more efficient.</p>



<h2 class="wp-block-heading">Importance</h2>



<p class="wp-block-paragraph">Let&#8217;s make some changes to the path tracer. Change the lines that calculate the reflected direction and the pdf to the following new code:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 R = cosweightedDiffuseReflection( N );
float pdf = dot( N, R ) / PI;</pre></div>



<p class="wp-block-paragraph">Running the path tracer with this change yields a substantially better image. In the following image, the left half was rendered with the old approach; the right half uses the new technique.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/is.jpg" alt="" style="width:512px"/><figcaption class="wp-element-caption">Figure 6: The impact of importance sampling.</figcaption></figure>
</div>


<p class="wp-block-paragraph">That looks a lot nicer, especially when the camera is moving. But, is it still the same image? We can easily check. Add the following code at the end of the <code>Tick</code> function:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float sum = 0;
for( int i = 0; i &lt; SCRWIDTH * SCRHEIGHT; i++ )
{
    float3 pixel = accumulator[i] * scale;
    sum += pixel.x + pixel.y + pixel.z;
}
printf( "%.2f\n", sum );</pre></div>



<p class="wp-block-paragraph">This code loops over all the pixels in the accumulator and sums their (averaged) red, green and blue color values. The result is a large number which represents the total energy in the rendered image.</p>



<p class="wp-block-paragraph">Now we can compare numbers between the old method and the new one. On my system, I get about 3834000 for the old method, and for the new method, nothing changes: Also about 3834000. Because of the randomness no two frames are identical, but quite obviously, the two methods <em>on average</em> produce the same answer. The difference is in the noise: Statistically speaking, the new method has less variance.</p>



<h2 class="wp-block-heading">Cosine-Weighted</h2>



<p class="wp-block-paragraph">Importance sampling for diffuse materials uses a new function to calculate a random direction to the hemisphere, named <code>cosweightedDiffuseReflection</code>. It&#8217;s implementation is similar to <code>diffuseReflection</code>:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 R;
do
{
    R = make_float3( RandomFloat(), RandomFloat(), RandomFloat() ) * 2 - 1;
} while (dot( R, R ) &gt; 1);
return normalize( N + normalize( R ) );</pre></div>



<p class="wp-block-paragraph">Just like <code>diffuseReflection</code>, this function can produce any direction on the hemisphere. However, there is a difference: Directions straight up (along the normal) occur with a greater probability. This is because these directions are <em>more important</em>. Recall the original path tracer code:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">return brdf * indirect * (dot( N, R ) / pdf);</pre></div>



<p class="wp-block-paragraph">Because of the radiance-to-irradiance conversion, every sample is scaled by <code>dot( N, R )</code>. The outcome of this dot product is close to 1 if <span class="wp-katex-eq" data-display="false">R</span> is close to <span class="wp-katex-eq" data-display="false">N</span>; however, it is close to 0 if <span class="wp-katex-eq" data-display="false">R</span> is almost parallel to the surface. So, if we pick a direction that grazes the surface, the <em>whole path</em> will have a low throughput and our effort will be mostly wasted. We cannot exclude these paths, because we never know what we will find there; perhaps the only light source is in that direction. But, generally speaking, we should make it <em>unlikely</em> that such a direction is picked.</p>



<p class="wp-block-paragraph">The <em>optimal</em> distribution is in this case very specific. Contributions are scaled by <code>dot( N, R )</code>, i.e. a cosine curve. And that&#8217;s precisely what <code>cosweightedDiffuseReflection</code> does.</p>



<p class="wp-block-paragraph">If we would just change the distribution of random rays we would obviously change the rendered image. So, we need to compensate somewhere for this. And that is where the pdf comes into play. If we scale unlikely samples by a high value, and likely samples by a lower value, the end result comes statistically sound again. This is why the pdf is now no longer a constant <span class="wp-katex-eq" data-display="false">1/{2\pi}</span>: Instead, it becomes <code>dot( N, R ) / pi</code>. For more details please read <a href="https://jacco.ompf2.com/2019/12/13/probability-theory-for-physically-based-rendering-part-2/">Probability Theory for Physically Based Rendering Part 2</a>. </p>



<h2 class="wp-block-heading">Beyond</h2>



<p class="wp-block-paragraph">With the basic path tracing algorithm in place it is time to stop. Beyond this point is treasure, but also dragons. There is Russian roulette, which weeds out the long paths. There is <em>direct light sampling</em> a.k.a. <em>next event estimation</em> which makes scenes with small light sources efficient. If there are multiple lights, these can be importance sampled as well. Read some recent research on <a href="https://benedikt-bitterli.me/restir/">ReSTIR</a> to see how to take this to extremes for scenes with millions of lights. There is photon mapping for difficult paths through water and glass. And much more.</p>



<p class="wp-block-paragraph">For this series we&#8217;ll instead move on to denoising. </p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"><em>The next article may arrive a bit later due to real-world obligations&#8230; Sorry about that.</em></p>



<p class="wp-block-paragraph"></p>



<h2 class="wp-block-heading">Challenges</h2>



<p class="wp-block-paragraph"><strong>Challenge 1.</strong> If you have not done so already, replace the solid background color by an HDR skydome and illuminate the scene with that. Implementation details can be found in <a href="https://jacco.ompf2.com/2022/05/27/how-to-build-a-bvh-part-8-whitted-style/">this article</a>. You may want to differentiate between a &#8216;direct hit&#8217; on the skydome and subsequent encounters to make it perfect for <em>Image Based Lighting.</em> </p>



<p class="wp-block-paragraph"><strong>Challenge 2.</strong> Besides light from the sky, you could add lighting from voxels. Find a way to assign bright colors to certain voxels; the rest should work &#8216;out-of-the-box&#8217;.</p>



<p class="wp-block-paragraph"><strong>Challenge 3.</strong> Path tracers greatly benefit from reprojection. Combine the concepts of the <a href="https://jacco.ompf2.com/2024/05/22/ray-tracing-with-voxels-in-c-series-part-5/">previous episode</a> with the path tracer code.</p>



<h2 class="wp-block-heading">Etc.</h2>



<p class="wp-block-paragraph">If you want to share some of your work, consider posting on X about it. You can also follow me there <em>(<a href="https://twitter.com/j_bikker">@j_bikker</a>)</em>, or contact me at <a href="mailto:bikker.j@gmail.com">bikker.j@gmail.com</a>.</p>



<p class="wp-block-paragraph"><strong>Want to read more about computer graphics?</strong> Also on this blog:</p>



<ul class="wp-block-list">
<li><a href="https://jacco.ompf2.com/2022/04/13/how-to-build-a-bvh-part-1-basics/">How to build a BVH series</a></li>



<li><a href="https://jacco.ompf2.com/2020/04/07/speeding-up-lighthouse-2/">Speeding up the Lighthouse 2 renderer</a></li>



<li><a href="https://jacco.ompf2.com/2020/03/18/opt1profiling/">Software Optimization</a></li>
</ul>



<p class="wp-block-paragraph">Other articles in the &#8220;Ray Tracing with Voxels in C++&#8221; series:</p>



<ol class="wp-block-list">
<li><a href="https://jacco.ompf2.com/?p=1715">Starting point: Voxel ray tracing template code. Lights and shadows</a>.</li>



<li><a href="https://jacco.ompf2.com/?p=1755&amp;preview=true">Whitted-style: Reflections, recursion, glass</a>.</li>



<li><a href="https://jacco.ompf2.com/?p=1803">Stochastic techniques: Anti-aliasing and soft shadows</a>.</li>



<li><a href="https://jacco.ompf2.com/?p=1839">Noise reduction: Stratification and blue noise</a>.</li>



<li><a href="https://jacco.ompf2.com/?p=1887">Converging under movement: Reprojection</a>.</li>



<li><strong>Path tracing: Basics first; then: Importance Sampling (this article).</strong></li>



<li>Denoising fundamentals.</li>



<li>Acceleration structures: Extending the grid to a multi-level grid.</li>



<li>Acceleration structures: Adding a TLAS.</li>
</ol>
]]></content:encoded>
					
					<wfw:commentRss>https://jacco.ompf2.com/2024/05/29/ray-tracing-with-voxels-in-c-series-part-6/feed/</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>Ray Tracing with Voxels in C++ Series &#8211; Part 5</title>
		<link>https://jacco.ompf2.com/2024/05/22/ray-tracing-with-voxels-in-c-series-part-5/</link>
					<comments>https://jacco.ompf2.com/2024/05/22/ray-tracing-with-voxels-in-c-series-part-5/#comments</comments>
		
		<dc:creator><![CDATA[jbikker]]></dc:creator>
		<pubDate>Wed, 22 May 2024 08:34:03 +0000</pubDate>
				<category><![CDATA[Article]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Tutorial]]></category>
		<guid isPermaLink="false">https://jacco.ompf2.com/?p=1887</guid>

					<description><![CDATA[In this series we build a physically based renderer for a dynamic voxel world. From &#8216;Whitted-style&#8217; ray...]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">In this series we build a physically based renderer for a dynamic voxel world. From &#8216;Whitted-style&#8217; ray tracing with shadows, glass and mirrors, we go all the way to &#8216;unbiased path tracing&#8217; &#8211; and beyond, exploring advanced topics such as reprojection, denoising and blue noise. The accompanying source code is <a href="https://github.com/jbikker/voxpopuli">available on Github</a> and is written in easy-to-read &#8216;sane C++&#8217;.</p>



<p class="wp-block-paragraph">This series consists of nine articles. Contents:  <em>(tentative until finalized)</em></p>



<ol class="wp-block-list">
<li><a href="https://jacco.ompf2.com/?p=1715">Starting point: Voxel ray tracing template code. Lights and shadows</a>.</li>



<li><a href="https://jacco.ompf2.com/?p=1755&amp;preview=true">Whitted-style: Reflections, recursion, glass</a>.</li>



<li><a href="https://jacco.ompf2.com/?p=1803">Stochastic techniques: Anti-aliasing and soft shadows</a>.</li>



<li><a href="https://jacco.ompf2.com/?p=1839">Noise reduction: Stratification and blue noise</a>.</li>



<li><strong>Converging under movement: Reprojection (this article).</strong></li>



<li><a href="https://jacco.ompf2.com/2024/05/29/ray-tracing-with-voxels-in-c-series-part-6/">Path tracing: Basics first; then: Importance Sampling</a>.</li>



<li>Denoising fundamentals.</li>



<li>Acceleration structures: Extending the grid to a multi-level grid.</li>



<li>Acceleration structures: Adding a TLAS.   </li>
</ol>



<h2 class="wp-block-heading">In This Article&#8230;</h2>



<p class="wp-block-paragraph">Rendering complex effects in a ray tracer requires random sampling &#8211; which produces noise. A <a href="https://jacco.ompf2.com/?p=1803">previous episode</a> introduced the concept of the <em>accumulator</em>, which combines fast moving &#8211; but noisy &#8211; images with converged images for a stationary camera, by averaging samples over time. In this article we will explore how we can accumulate samples over time, even when the camera is moving.</p>



<p class="wp-block-paragraph">Reprojection is an important, but complex topic. That means that there will be open problems at the end of the article. See the list of challenges at the end of the text for some of these.</p>



<h2 class="wp-block-heading">Starting Point</h2>



<p class="wp-block-paragraph">As usual we will first prepare the unmodified template code for the purpose of this episode. For <code>Renderer::Trace()</code> we will use a short version with basic soft shadows from a hard-coded area light. See <a href="https://jacco.ompf2.com/?p=1803">Episode 3</a> for an explanation of this technique.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 Renderer::Trace( Ray&amp; ray, int depth, int x, int y )
{
    scene.FindNearest( ray );
    if (ray.voxel == 0) return float3( 0.4f, 0.5f, 1.0f );
    float3 I = ray.IntersectionPoint();
    float3 P( (RandomFloat() + 1) / 2, (RandomFloat() + 6) / 5, 3 );
    float3 L = normalize( P - I );
    if (scene.IsOccluded( Ray( I, L, 10 ) )) return 0.2f;
    return ray.GetAlbedo() * 2 * max( 0.2f, dot( ray.GetNormal(), L ) );
}</pre></div>



<p class="wp-block-paragraph">In <code>scene.cpp</code>, swap out the default scene for the scene introduced at the end of Episode 3:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">Scene::Scene()
{
    grid = (uint*)MALLOC64( GRIDSIZE3 * 4 );
    gzFile f = gzopen( "assets/viking.bin", "rb" );
    gzread( f, grid, 16 ); // skip size data
    gzread( f, grid, 1 &lt;&lt; 23 );
}</pre></div>



<p class="wp-block-paragraph">And finally, since we will be working on reprojection, let&#8217;s automate scene movement. In <code>camera.cpp</code>, replace <code>HandleInput</code> by the following turntable code:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">bool Camera::HandleInput( const float t )
{
    static float r = 0, a;
    r += t * 0.001f, a = 0.7f * sinf( r ) + 1.6f;
    camPos = 0.7f * float3( cosf( a ) + 0.7, 0.7f, sinf( a ) + 0.7f );
    mat4 M = mat4::LookAt( camPos, float3( 5, 3, 5 ) / 10 );
    float3 x( M[0], M[4], M[8] ), y( M[1], M[5], M[9] ), z( M[2], M[6], M[10] );
    topLeft = camPos + 2 * z - aspect * x + y;
    topRight = camPos + 2 * z + aspect * x + y;
    bottomLeft = camPos + 2 * z - aspect * x - y;
    return true;
}</pre></div>



<p class="wp-block-paragraph">I admit that all the above code was optimized for brevity, not clarity. Feel free to rectify that before proceeding. Or, accept this random challenge and shorten it further. Here&#8217;s a <a href="https://pastebin.com/c7n66AVm">tiny ray tracer</a> in C in case you need some inspiration.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/spin.jpg" alt="" style="width:540px"/><figcaption class="wp-element-caption">Figure 1: The starting point for this episode: A rotating voxel scene. </figcaption></figure>
</div>


<p class="wp-block-paragraph">To do something about the noise in those soft shadows we have several options:</p>



<ol class="wp-block-list">
<li>We could take more samples. This would of course affect framerate.</li>



<li>We could take better samples, using blue noise.</li>



<li>We can accumulate samples over time. But this requires a stationary camera.</li>
</ol>



<p class="wp-block-paragraph">If we ignore the fact that the camera is not stationary, and use the accumulator anyway, we get a horrible blur&#8230;</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/blur.jpg" alt="" style="width:540px"/><figcaption class="wp-element-caption">Figure 2: Accumulating while ignoring the moving camera.</figcaption></figure>
</div>


<p class="wp-block-paragraph">The problem is: After 100 frames, all frames contribute equally to the average. The longer this runs, the less impact new samples have. The opposite should be the case: Newer samples should have a greater weight than older ones, with ancient samples slowly diminishing. This is what we get if we replace the accumulator by a <em>running average.</em></p>



<h2 class="wp-block-heading">Running Average</h2>



<p class="wp-block-paragraph">The running average is defined mathematically as:</p>



<p class="wp-block-paragraph"><span class="wp-katex-eq" data-display="false">A_{new}=w A_{old}+(1-w)S</span></p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Here, <span class="wp-katex-eq" data-display="false">A_{old}</span> is the value in the accumulator, which will be replaced for the next frame by <span class="wp-katex-eq" data-display="false">A_{new}</span>. Value <span class="wp-katex-eq" data-display="false">S</span> is a new sample which we obtain by calling <code>Renderer::Trace</code>. And finally, <span class="wp-katex-eq" data-display="false">w</span> is a blending factor. A typical value for <span class="wp-katex-eq" data-display="false">w</span> is <span class="wp-katex-eq" data-display="false">0.9</span>, which would replace the accumulator by 90% of whatever was in it, plus 10% of a new sample. This sounds like the new sample is still pretty unimportant, but in reality, <em>all</em> previous samples have to share the 90% weight, and older samples become obsolete as we move on, while the new sample always gets the 10% share.</p>



<p class="wp-block-paragraph">To implement the running average, we need room for the accumulator:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void Renderer::Init()
{
    accumulator = new float3[SCRWIDTH * SCRHEIGHT];
}</pre></div>



<p class="wp-block-paragraph">We can now use the accumulator to keep track of the running average.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">for (int x = 0; x &lt; SCRWIDTH; x++)
{
    Ray r = camera.GetPrimaryRay( (float)x, (float)y );
    float3&amp; pixel = accumulator[x + y * SCRWIDTH];
    pixel = 0.8f * pixel + 0.2f * Trace( r );
    screen-&gt;pixels[x + y * SCRWIDTH] = RGBF32_to_RGB8( pixel );
}</pre></div>



<p class="wp-block-paragraph">Note that in this code pixel is a bit different than in previous snippets. It is a float3 <em>reference</em>, so it maps directly to a value in the accumulator array.</p>



<p class="wp-block-paragraph">Compared to the original accumulator, calculating the running average is a bit simpler. For starters, we don&#8217;t need to keep track of the number of frames that contribute to the average. We also don&#8217;t need to scale the accumulated value: Since <span class="wp-katex-eq" data-display="false">w+(1-w)=1</span>, the pixels in the accumulator do not get brighter over time, and we can use them as-is.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/runavg.jpg" alt="" style="width:540px"/><figcaption class="wp-element-caption">Figure 3: Accumulating using a running average fades out older samples.</figcaption></figure>
</div>


<p class="wp-block-paragraph">We can now play with the weight factor <span class="wp-katex-eq" data-display="false">w</span>. Using <span class="wp-katex-eq" data-display="false">0.8</span> we get considerable ghosting. A larger weight (e.g. <span class="wp-katex-eq" data-display="false">0.99</span>) will make this worse. A lower value reduces ghosting, but now the average discards more of the old value, which makes the shadows noisier. </p>



<p class="wp-block-paragraph">The real power of the running average is in different weights per pixel however. Think of <span class="wp-katex-eq" data-display="false">w</span> as a <em>trust value:</em> If we believe that the value in the accumulator should contribute to a pixel, we make <span class="wp-katex-eq" data-display="false">w</span> a value close to 1. If on the other hand we suspect the history contains useless data, e.g. because we moved the camera really fast, then we reduce <span class="wp-katex-eq" data-display="false">w</span>, maybe all the way to zero &#8211; which fully discards the old data and overwrites it with the new sample.</p>



<h2 class="wp-block-heading">Hindsight</h2>



<p class="wp-block-paragraph">So far, when we read &#8216;historic&#8217; data from the accumulator, we read a pixel at the same location as the pixel we&#8217;re working on. That doesn&#8217;t always make sense. Imagine we have a camera that slowly moves to the right. In that case, the perfect pixel to blend with is always a bit to the <em>left</em>. In fact, if we could calculate <em> by how much</em>, we should in theory get perfect blending, without any ghosting.</p>



<p class="wp-block-paragraph">So, the million dollar question is: For a pixel location <span class="wp-katex-eq" data-display="false">(x,y)</span> in the current frame, <em>where was this pixel in the previous frame?</em></p>



<p class="wp-block-paragraph">At first sight, this looks like a very hard thing to calculate. But, when we take a moment to think over the math, it turns out to be&#8230; not impossible.</p>



<p class="wp-block-paragraph">Consider the following situation:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/primhit.png" alt="" style="width:440px"/><figcaption class="wp-element-caption">Figure 4: Primary hit for a pixel, in world space.</figcaption></figure>
</div>


<p class="wp-block-paragraph">Here, a ray is sent through a pixel. It then hits the red ball. </p>



<p class="wp-block-paragraph">There is something about the coordinates used for <em>everything</em> in this setup: <em>It&#8217;s all happening in world space.</em> The camera, the primary hit, even the pixel position; it&#8217;s all defined in one coordinate system. And, if we move on to the next frame, this is <em>still </em>true:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/moving.png" alt="" style="width:440px"/><figcaption class="wp-element-caption">Figure 5: Camera moving downwards in world space.</figcaption></figure>
</div>


<p class="wp-block-paragraph">That point <span class="wp-katex-eq" data-display="false">P</span> in the new frame <span class="wp-katex-eq" data-display="false">t</span> <em>was </em>in fact in view in the previous frame <span class="wp-katex-eq" data-display="false">t-1</span>. So, if we can construct a ray from the <em>previous </em>camera to <span class="wp-katex-eq" data-display="false">P</span>, and we figure out through which pixel this ray travels, then we know exactly where our pixel was in the previous frame.</p>



<p class="wp-block-paragraph">The original question, <em>&#8220;where was this pixel in the previous frame?&#8221;</em> has now been refined to: <em>&#8220;through which pixel of the previous frame is <span class="wp-katex-eq" data-display="false">P</span> visible?&#8221;</em></p>



<p class="wp-block-paragraph">An intuitive way to answer this question is illustrated in the next image.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/frustum.png" alt="" style="width:450px"/><figcaption class="wp-element-caption">Figure 6: Pixel position relative to frustum planes.</figcaption></figure>
</div>


<p class="wp-block-paragraph">Point <span class="wp-katex-eq" data-display="false">P</span> is visible through the red pixel. It turns out that the position of the pixel corresponds to the distance of <span class="wp-katex-eq" data-display="false">P</span> to the top and bottom plane. More formally: On a scale of 0..1, the position of the red point is <span class="wp-katex-eq" data-display="false">d_1/(d_1+d_2)</span>. This works in a 2D situation, but also in 3D: In that case, we need <em>four</em> planes, which together make up a pyramid shape, known as the view frustum.</p>



<h2 class="wp-block-heading">Mathematics</h2>



<p class="wp-block-paragraph">Let&#8217;s summarize. We have a point <span class="wp-katex-eq" data-display="false">P</span>, which is a point in the world on a surface visible through a pixel in the current frame. We <em>need</em> the four distances of this point to the four planes for the view frustum of the previous frame. Using these distances, we can calculate through which pixel point <span class="wp-katex-eq" data-display="false">P</span> was visible.</p>



<p class="wp-block-paragraph">The first mathematical construct is thus the set of four planes. A plane can be defined in several ways, but for our purposes the <em>implicit</em> <em>definition</em> is useful. It&#8217;s form is <span class="wp-katex-eq" data-display="false">Ax+By+Cz-d=0</span>. Here, <span class="wp-katex-eq" data-display="false">ABC</span> form the normal of the plane; scalar <span class="wp-katex-eq" data-display="false">d</span> is the distance of the plane to the origin. The normal vector is calculated as the cross-product between two vectors in the plane. For each of the four planes, we thus must find two vectors. We can produce these from the four screen corners and the camera position.</p>



<p class="wp-block-paragraph">The camera is defined in file <code>camera.h</code>:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">class Camera
{
public:
    Camera();
    ~Camera();
    Ray GetPrimaryRay( const float x, const float y );
    bool HandleInput( const float t );
    float aspect = (float)SCRWIDTH / (float)SCRHEIGHT;
    float3 camPos, camTarget;
    float3 topLeft, topRight, bottomLeft;
};</pre></div>



<p class="wp-block-paragraph">It contains all the data we need. To calculate the normal of the top plane for example, we use the vector from <code>topLeft</code> to <code>topRight</code> and the vector from <code>camPos</code> to <code>topLeft</code>. And, for the left plane we use the vector from <code>camPos</code> to <code>topLeft</code> and the vector from <code>topLeft</code> to <code>bottomLeft</code>. Note that a <code>bottomRight</code> point is missing, but a vector from <code>topRight</code> to <code>bottomRight</code> is identical to the vector from <code>topLeft</code> to <code>bottomLeft</code>, so we don&#8217;t need it.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" width="933" height="628" src="https://jacco.ompf2.com/wp-content/uploads/2024/05/fr3d-1.jpg" alt="" class="wp-image-2093" style="width:500px" srcset="https://jacco.ompf2.com/wp-content/uploads/2024/05/fr3d-1.jpg 933w, https://jacco.ompf2.com/wp-content/uploads/2024/05/fr3d-1-300x202.jpg 300w, https://jacco.ompf2.com/wp-content/uploads/2024/05/fr3d-1-768x517.jpg 768w, https://jacco.ompf2.com/wp-content/uploads/2024/05/fr3d-1-897x604.jpg 897w, https://jacco.ompf2.com/wp-content/uploads/2024/05/fr3d-1-360x242.jpg 360w" sizes="auto, (max-width: 933px) 100vw, 933px" /><figcaption class="wp-element-caption">Figure 7: The view frustum. The bounding planes can be constructed using vectors in the planes.</figcaption></figure>
</div>


<p class="wp-block-paragraph">The template does not have a &#8216;Plane&#8217; class, but we can easily make one. Add the following lines to <code>camera.h</code>, above the <code>Camera</code> class definition:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">typedef float4 Plane;
struct Frustum { Plane plane[4]; };
inline float distance( Plane&amp; plane, float3&amp; pos )
{
    return dot( float3( plane ), pos ) - plane.w;
}</pre></div>



<p class="wp-block-paragraph">The first line defines the <code>Plane</code> type as a <code>float4</code>. That looks rather minimalistic, but it is just what we need: <code>xyz</code> in the <code>float4</code> will hold the plane normal, while the <code>w</code> component will store the distance of the plane to the origin. The second line defines a frustum as a collection of four planes. And finally, the one-line function will simplify working with the new <code>Plane</code> type: It calculates the distance between a point and a plane.</p>



<p class="wp-block-paragraph">We now have everything we need to calculate four planes for a camera. The functionality is implemented as a new method of the <code>Camera</code> class.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">Frustum BuildFrustum()
{
    Frustum f;
    f.plane[0] = cross( topLeft - bottomLeft, topLeft - camPos );
    f.plane[1] = cross( topRight - camPos, topLeft - bottomLeft );
    f.plane[2] = cross( topRight - topLeft, topLeft - camPos );
    f.plane[3] = cross( bottomLeft - camPos, topRight - topLeft );
    for (int i = 0; i &lt; 4; i++) f.plane[i].w = distance( f.plane[i], camPos );
    return f;
}</pre></div>



<p class="wp-block-paragraph">Plane 0 and 1 are the planes on the left and the right side of the view frustum. Plane 2 and 3 are the planes at the top and the bottom. The vectors used in the cross product are carefully chosen so the normals points inwards. This way, we get positive distances for points inside the view frustum. We can optionally normalize the result of the cross product, but in this specific case, this is not needed, so we can spare the effort.</p>



<p class="wp-block-paragraph">Method <code>Camera::BuildFrustum</code> ends with the calculation of the distance of each plane to the origin. For this, we take one point on the plane (conveniently, <code>camPos</code> will do in all cases), and calculate the dot product of this point and the normal. </p>



<h2 class="wp-block-heading">Applying Mathematics</h2>



<p class="wp-block-paragraph">Remember that the view frustum of the camera of the previous frame is needed for reprojection. So, we return to <code>renderer.cpp</code>, and add a global variable at the top of the file:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">Frustum previous;</pre></div>



<p class="wp-block-paragraph">Then, <em>after</em> rendering a frame but just <em>before</em> we change the camera for the next frame (using a call to <code>camera.HandleInput(..))</code> we fill variable <code>previous</code>:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">// handle user input
previous = camera.BuildFrustum();
camera.HandleInput( deltaTime );</pre></div>



<p class="wp-block-paragraph">The final step is to actually use the set of four planes for reprojection. We need an intersection point for this: The point <span class="wp-katex-eq" data-display="false">P</span> used in the math. This point P is obtained from the ray:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">Ray r = camera.GetPrimaryRay( (float)x, (float)y );
float3 sample = Trace( r );
if (r.voxel &gt; 0)
{
    float3 P = r.O + r.t * r.D;
    ...</pre></div>



<p class="wp-block-paragraph">Note the condition: <code>r.voxel &gt; 0</code>. We cannot reproject if the ray hit nothing: In that case, we just plot the sky color, without using reprojection. If we <em>did</em> hit a voxel, the hit location <span class="wp-katex-eq" data-display="false">P</span> is along the ray: Starting at the ray origin <code>r.O</code>, we travel <code>r.t</code> units in the ray direction <code>r.D</code>. The distance <code>r.t</code> is what <code>scene.FindNearest</code> (called from <code>Trace</code>) calculated. </p>



<p class="wp-block-paragraph">We now calculate the distance of <span class="wp-katex-eq" data-display="false">P</span> to the left and right planes, and to the top and bottom planes:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float dLeft = distance( previous.plane[0], P );
float dRight = distance( previous.plane[1], P );
float dUp = distance( previous.plane[2], P );
float dDown = distance( previous.plane[3], P );</pre></div>



<p class="wp-block-paragraph">Using these distances we then calculate the pixel location for <span class="wp-katex-eq" data-display="false">P</span> in the previous frame.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float prev_x = (SCRWIDTH * dLeft) / (dLeft + dRight);
float prev_y = (SCRHEIGHT * dUp) / (dUp + dDown);</pre></div>



<p class="wp-block-paragraph">Remember that <span class="wp-katex-eq" data-display="false">d_{left}/(d_{left}+d_{right})</span> yields a number between 0 and 1; we thus scale by the resolution of the screen to get the actual pixel position. The reprojection was successful if the calculated screen coordinates are actually on the screen:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">if (prev_x &gt;= 0 &amp;&amp; prev_x &lt; SCRWIDTH - 1 &amp;&amp; prev_y &gt;= 0 &amp;&amp; prev_y &lt; SCRHEIGHT - 1)
{
    ...
}</pre></div>



<h2 class="wp-block-heading">History</h2>



<p class="wp-block-paragraph">For reprojection we need to read pixels from the previous frame, while writing pixels for the current frame. Since we do not read from the same pixels we&#8217;re writing to, we need a copy of the &#8216;history&#8217;. Add the following line to <code>Renderer::Init()</code> to add a second pixel buffer:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">history = new float3[SCRWIDTH * SCRHEIGHT];</pre></div>



<p class="wp-block-paragraph">Then, at the end of each frame, we copy the <code>accumulator</code> to <code>history</code>. Or, we simply swap the two buffers, which is a bit more efficient. All it takes is the following line at the end of <code>Renderer::Tick</code>:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">swap( history, accumulator );</pre></div>



<p class="wp-block-paragraph">We can now complete the <code>if</code> statement:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">if (prev_x &gt;= 0 &amp;&amp; prev_x &lt; SCRWIDTH - 1 &amp;&amp; prev_y &gt;= 0 &amp;&amp; prev_y &lt; SCRHEIGHT - 1)
{
    historySample = history[(int)prev_x + (int)prev_y * SCRWIDTH];
}</pre></div>



<p class="wp-block-paragraph">And there it is: This <code>historySample</code> is what we will assign a large weight in the running average from the start of this article. The full pixel loop, in all its glory: </p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">// trace a primary ray for each pixel on the line
for (int x = 0; x &lt; SCRWIDTH; x++)
{
    Ray r = camera.GetPrimaryRay( (float)x, (float)y );
    float3 historySample, sample = Trace( r );
    float historyWeight = 0;
    if (r.voxel &gt; 0)
    {
        // reproject
        float3 P = r.O + r.t * r.D;
        float dLeft = distance( previous.plane[0], P );
        float dRight = distance( previous.plane[1], P );
        float dUp = distance( previous.plane[2], P );
        float dDown = distance( previous.plane[3], P );
        float prev_x = (SCRWIDTH * dLeft) / (dLeft + dRight);
        float prev_y = (SCRHEIGHT * dUp) / (dUp + dDown);
        if (prev_x &gt;= 0 &amp;&amp; prev_x &lt; SCRWIDTH - 1 &amp;&amp; prev_y &gt;= 0 &amp;&amp; prev_y &lt; SCRHEIGHT - 1)
        {
            historyWeight = 0.95f;
            historySample = history[(int)prev_x + (int)prev_y * SCRWIDTH];
        }
    }
    float3 pixel = historyWeight * historySample + (1 - historyWeight) * sample;
    accumulator[x + y * SCRWIDTH] = pixel;
    screen-&gt;pixels[x + y * SCRWIDTH] = RGBF32_to_RGB8( pixel );
}</pre></div>



<p class="wp-block-paragraph">Note how the weight that we apply to the history value simply becomes zero when we can&#8217;t reproject. In that case, we will use the new sample alone.</p>



<p class="wp-block-paragraph">The result of all this effort is&#8230; Underwhelming.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/underwhelm.jpg" alt="" style="width:540px"/><figcaption class="wp-element-caption">Figure 8: The initial result of reprojection.</figcaption></figure>
</div>


<p class="wp-block-paragraph">At this point, it is easy to be discouraged or to assume that the approach is buggy or not working at all. But, let&#8217;s not give up just yet! There&#8217;s two important problems that need to be solved, which should get us a lot closer to a correct looking result:</p>



<ol class="wp-block-list">
<li>The reprojected coordinate is not an integer coordinate. Yet, we unceremoniously casted it to integer to read a single pixel from the history.</li>



<li>Not all history values are valid. What if the point we see through the reprojected pixel location is not <span class="wp-katex-eq" data-display="false">P</span> at all, but something closer, or farther away?</li>
</ol>



<p class="wp-block-paragraph">We will tackle these one by one.</p>



<h2 class="wp-block-heading">Bilerp</h2>



<p class="wp-block-paragraph">To read a pixel from a floating point pixel coordinate we use a technique called <em>bilinear interpolation</em>. This is illustrated in the following image:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/bilerp.jpg" alt=""/><figcaption class="wp-element-caption">Figure 9: Bilinear interpolation: Replacing a point sample by an area sample.</figcaption></figure>
</div>


<p class="wp-block-paragraph">To read at the position indicated by the yellow dot, we currently simply use pixel <span class="wp-katex-eq" data-display="false">P_0</span>. But, if we do not take a <em>point sample</em> but instead read a 1&#215;1 sized square, we need <em>four</em> pixels, blended in a very specific way: Pixel <span class="wp-katex-eq" data-display="false">P_0</span> should have a weight proportional to the area of the overlap between <span class="wp-katex-eq" data-display="false">P_0</span> and the white rectangle; similarly, <span class="wp-katex-eq" data-display="false">P_1</span>, <span class="wp-katex-eq" data-display="false">P_2</span> and <span class="wp-katex-eq" data-display="false">P_3</span> contribute to the blend depending on their overlap with the white rectangle. Obviously, the sum of the four weights is 1, that is the area of the white rectangle.</p>



<p class="wp-block-paragraph">We calculate the weights by looking at the fractional part of the pixel coordinate. Let&#8217;s say that the yellow dot is at position <span class="wp-katex-eq" data-display="false">x=14.2</span>, <span class="wp-katex-eq" data-display="false">y=8.2</span>. In that case, the fractional position of the dot is <span class="wp-katex-eq" data-display="false">x=0.2, y=0.2</span>, and the area of overlap is <span class="wp-katex-eq" data-display="false">(1-0.2)*(1-0.2)=0.64</span>. The full set of weights, in C code:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float fx = fracf( prev_x ), fy = fracf( prev_y );
float w0 = (1 - fx) * (1 - fy);
float w1 = fx * (1 - fy);
float w2 = (1 - fx) * fy;
float w3 = fx * fy;</pre></div>



<p class="wp-block-paragraph">We can now read 2&#215;2 pixels, and scale them by these weights.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">int a = (int)prev_x + (int)prev_y * SCRWIDTH;
float3 p0 = history[a]; // (x,y)
float3 p1 = history[a + 1]; // (x+1,y)
float3 p2 = history[a + SCRWIDTH]; // (x,y+1)
float3 p3 = history[a + SCRWIDTH + 1]; // (x+1,y+1)
historySample = p0 * w0 + p1 * w1 + p2 * w2 + p3 * w3;</pre></div>



<p class="wp-block-paragraph">One important change is needed when we read 2&#215;2 pixels. We cannot read outside the history buffer, but at position <code>x=SCRWIDTH-1</code> we will do just that. The easiest fix is to limit <code>prev_x</code> and <code>prev_y</code> to a smaller range:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">if (prev_x &gt;= 0 &amp;&amp; prev_x &lt; SCRWIDTH - 2 &amp;&amp; prev_y &gt;= 0 &amp;&amp; prev_y &lt; SCRHEIGHT - 2)
{
    ...
}</pre></div>



<p class="wp-block-paragraph">Time to put the bilinear interpolation code to the test. The result is <em>much</em> better:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/birepro.jpg" alt="" style="width:540px"/><figcaption class="wp-element-caption">Figure 10: Reprojection with bilinear interpolation of reads from the history buffer.</figcaption></figure>
</div>


<h2 class="wp-block-heading">(Dis)occlusions</h2>



<p class="wp-block-paragraph">The second problem that remains to be solved is the issue of geometry that gets occluded or disoccluded during camera movement. When that happens, point <span class="wp-katex-eq" data-display="false">P</span> wasn&#8217;t visible in the previous frame; we can look in its direction but if we do that, we will find a different point. Luckily, it&#8217;s easy to check this. For this, we need the previous camera position. Add a global variable to it, just below the <code>Frustum previous</code> definition:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 prevCamPos;</pre></div>



<p class="wp-block-paragraph">We update this variable just before the call to <code>camera.HandleInput()</code>:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">prevCamPos = camera.camPos;</pre></div>



<p class="wp-block-paragraph">And finally, we use the previous camera to fire a ray at <span class="wp-katex-eq" data-display="false">P</span> in the previous frame. If this ray hits something that is close to P, we&#8217;re good; otherwise, we will assume that the reprojection failed after all.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">if (prev_x &gt;= 0 &amp;&amp; prev_x &lt; SCRWIDTH - 1 &amp;&amp; prev_y &gt;= 0 &amp;&amp; prev_y &lt; SCRHEIGHT - 1)
{
    // verify reprojection
    Ray r( prevCamPos, P - prevCamPos );
    scene.FindNearest( r );
    float3 Q = prevCamPos + r.t * r.D;
    if (sqrLength( P - Q ) &lt; 0.001f)
    {
        ...</pre></div>



<p class="wp-block-paragraph">And this time, reprojection is as good as it gets.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/reprofinal.jpg" alt="" style="width:600px"/><figcaption class="wp-element-caption">Figure 11: Reprojection with sample rejection.</figcaption></figure>
</div>


<p class="wp-block-paragraph">Now, this image still has issues. There are some rather noisy areas, and the picture as a whole looks a bit blurry. Some ghosting also remains. We can tweak the ghosting by finetuning the maximum distance between <span class="wp-katex-eq" data-display="false">P</span> and <span class="wp-katex-eq" data-display="false">Q</span>, but there is no perfect setting. The blurring can be countered somewhat using a sharpening filter.</p>



<p class="wp-block-paragraph">But, this is already a very lengthy episode&#8230; So I will leave these challenges as an &#8216;exercise for the reader&#8217;. Literally.</p>



<p class="wp-block-paragraph">Next time: Path Tracing. There is mathematical beauty ahead, and although it will introduce more noise, it also is capable of producing some breath-taking pictures. See you next week!</p>



<h2 class="wp-block-heading">Challenges</h2>



<p class="wp-block-paragraph"><strong>Challenge 1.</strong> As suggested in the text, post-process the final image with a 3&#215;3 sharpening filter to reduce the blurriness of the reprojected image. The process is explained quite well on <a href="https://en.wikipedia.org/wiki/Unsharp_masking">Wikipedia</a>. Applying the sharpening filter will cause quite some memory traffic on your CPU. Consider using multi-threading to speed it up.</p>



<p class="wp-block-paragraph"><strong>Challenge 2.</strong> The article uses a ray to detect (dis)occlusions. A more performant method is to reject history samples if their color differs too much from the colors in the new frame. The method is described in the paper &#8220;<a href="http://behindthepixels.io/assets/files/TemporalAA.pdf">A Survey of Temporal Antialiasing Techniques</a>&#8221; by Yang et al., in Section 4.2. Implement this method. You can also find an implementation in <a href="https://www.shadertoy.com/view/4dSBDt">this Shadertoy</a>.</p>



<p class="wp-block-paragraph"><strong>Challenge 3.</strong> Pixels for which reprojection failed are relatively noisy, as shown in Figure 11. It is possible to send these pixels extra rays, to improve the estimate, at the expense of more new samples. This is known as <em>adaptive sampling</em>. Implement this technique.</p>



<h2 class="wp-block-heading">Etc.</h2>



<p class="wp-block-paragraph">If you want to share some of your work, consider posting on X about it. You can also follow me there <em>(<a href="https://twitter.com/j_bikker">@j_bikker</a>)</em>, or contact me at <a href="mailto:bikker.j@gmail.com">bikker.j@gmail.com</a>.</p>



<p class="wp-block-paragraph"><strong>Want to read more about computer graphics?</strong> Also on this blog:</p>



<ul class="wp-block-list">
<li><a href="https://jacco.ompf2.com/2022/04/13/how-to-build-a-bvh-part-1-basics/">How to build a BVH series</a></li>



<li><a href="https://jacco.ompf2.com/2020/04/07/speeding-up-lighthouse-2/">Speeding up the Lighthouse 2 renderer</a></li>



<li><a href="https://jacco.ompf2.com/2020/03/18/opt1profiling/">Software Optimization</a></li>
</ul>



<p class="wp-block-paragraph">Other articles in the &#8220;Ray Tracing with Voxels in C++&#8221; series:</p>



<ol class="wp-block-list">
<li><a href="https://jacco.ompf2.com/?p=1715">Starting point: Voxel ray tracing template code. Lights and shadows</a>.</li>



<li><a href="https://jacco.ompf2.com/?p=1755&amp;preview=true">Whitted-style: Reflections, recursion, glass</a>.</li>



<li><a href="https://jacco.ompf2.com/?p=1803">Stochastic techniques: Anti-aliasing and soft shadows</a>.</li>



<li><a href="https://jacco.ompf2.com/?p=1839">Noise reduction: Stratification and blue noise</a>.</li>



<li><strong>Converging under movement: Reprojection (this article).</strong></li>



<li><a href="https://jacco.ompf2.com/2024/05/29/ray-tracing-with-voxels-in-c-series-part-6/">Path tracing: Basics first; then: Importance Sampling</a>.</li>



<li>Denoising fundamentals.</li>



<li>Acceleration structures: Extending the grid to a multi-level grid.</li>



<li>Acceleration structures: Adding a TLAS.   </li>
</ol>
]]></content:encoded>
					
					<wfw:commentRss>https://jacco.ompf2.com/2024/05/22/ray-tracing-with-voxels-in-c-series-part-5/feed/</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
			</item>
		<item>
		<title>Ray Tracing with Voxels in C++ Series &#8211; Part 4</title>
		<link>https://jacco.ompf2.com/2024/05/15/ray-tracing-with-voxels-in-c-series-part-4/</link>
					<comments>https://jacco.ompf2.com/2024/05/15/ray-tracing-with-voxels-in-c-series-part-4/#comments</comments>
		
		<dc:creator><![CDATA[jbikker]]></dc:creator>
		<pubDate>Wed, 15 May 2024 07:47:10 +0000</pubDate>
				<category><![CDATA[Article]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Tutorial]]></category>
		<guid isPermaLink="false">https://jacco.ompf2.com/?p=1839</guid>

					<description><![CDATA[In this series we build a physically based renderer for a dynamic voxel world. From &#8216;Whitted-style&#8217; ray...]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">In this series we build a physically based renderer for a dynamic voxel world. From &#8216;Whitted-style&#8217; ray tracing with shadows, glass and mirrors, we go all the way to &#8216;unbiased path tracing&#8217; &#8211; and beyond, exploring advanced topics such as reprojection, denoising and blue noise. The accompanying source code is <a href="https://github.com/jbikker/voxpopuli">available on Github</a> and is written in easy-to-read &#8216;sane C++&#8217;.</p>



<p class="wp-block-paragraph">This series consists of nine articles. Contents:  <em>(tentative until finalized)</em></p>



<ol class="wp-block-list">
<li><a href="https://jacco.ompf2.com/?p=1715">Starting point: Voxel ray </a><a href="https://jacco.ompf2.com/2024/04/24/ray-tracing-with-voxels-in-c-series-part-1/">tracing</a><a href="https://jacco.ompf2.com/?p=1715"> template code. Lights and shadows</a>.</li>



<li><a href="https://jacco.ompf2.com/?p=1755&amp;preview=true">Whitted-style: Reflections, recursion, </a><a href="https://jacco.ompf2.com/2024/05/01/ray-tracing-with-voxels-in-c-series-part-2/">glass</a>.</li>



<li><a href="https://jacco.ompf2.com/?p=1803">Stochastic techniques: Anti-aliasing and soft </a><a href="https://jacco.ompf2.com/2024/05/08/ray-tracing-with-voxels-in-c-series-part-3/">shadows</a>.</li>



<li><strong>Noise reduction: Stratification and blue noise (this article).</strong></li>



<li><a href="https://jacco.ompf2.com/2024/05/22/ray-tracing-with-voxels-in-c-series-part-5/">Converging under movement: Reprojection</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/29/ray-tracing-with-voxels-in-c-series-part-6/">Path tracing: Basics first; then: Importance Sampling</a>.</li>



<li>Denoising fundamentals.</li>



<li>Acceleration structures: Extending the grid to a multi-level grid.</li>



<li>Acceleration structures: Adding a TLAS.   </li>
</ol>



<h2 class="wp-block-heading">In This Article&#8230;</h2>



<p class="wp-block-paragraph">In the last article we enabled some complex rendering features for the ray tracer using random sampling and accumulation over time. This yields pretty images, except when the camera is moving. It&#8217;s not going to be easy to get rid of this noise entirely, but there are a lot of things we can do to improve the situation. We start at the basis: The random numbers we use to generate samples.</p>



<p class="wp-block-paragraph">Warning: This is a somewhat theoretical episode.</p>



<h2 class="wp-block-heading">Starting Point</h2>



<p class="wp-block-paragraph">For this episode we will need a simple scene and some noise. A suitable scene can be constructed by replacing <code>Scene::Scene()</code> in <code>scene.cpp</code> by:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">Scene::Scene()
{
    grid = (uint*)MALLOC64( GRIDSIZE3 * sizeof( uint ) );
    for (int i = 0; i &lt; 128 * 128 * 128; i++)
    {
        const int x = i &amp; 127, y = (i &gt;&gt; 7) &amp; 127, z = i &gt;&gt; 14;
        bool v = y &lt; 10, p = z &gt; 90 &amp;&amp; z &lt; 94;
        p &amp;= (x &amp; 31) &gt; 10 &amp;&amp; (x &amp; 31) &lt; 18 &amp;&amp; y &lt; 80;
        Set( x, y, z, p || v ? 0xffffff : 0 );
    }
}</pre></div>



<p class="wp-block-paragraph">This produces a floor and four pillars. Next, we render the scene with an area light and some basic shading, using the following minimalistic <code>Renderer::Trace</code> function:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 Renderer::Trace( Ray&amp; ray, int depth, int x, int y )
{
    scene.FindNearest( ray );
    if (ray.voxel == 0) return float3( 0.4f, 0.5f, 1.0f );
    float3 P( (RandomFloat() + 1) / 2, (RandomFloat() + 6) / 5, 3 );
    float3 I = ray.IntersectionPoint(), L = normalize( P - I );
    if (scene.IsOccluded( Ray( I, L, 10 ) )) return 0.2f;
    return 2 * max( 0.2f, dot( ray.GetNormal(), L ) );
}</pre></div>



<p class="wp-block-paragraph">This should produce the following output. It should run in real-time; if it instead looks like a slide show, you may be running a Debug build. Select &#8216;Release&#8217; to resolve this.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="659" src="https://jacco.ompf2.com/wp-content/uploads/2024/04/pillars-1024x659.jpg" alt="" class="wp-image-1851" style="width:542px;height:auto" srcset="https://jacco.ompf2.com/wp-content/uploads/2024/04/pillars-1024x659.jpg 1024w, https://jacco.ompf2.com/wp-content/uploads/2024/04/pillars-300x193.jpg 300w, https://jacco.ompf2.com/wp-content/uploads/2024/04/pillars-768x494.jpg 768w, https://jacco.ompf2.com/wp-content/uploads/2024/04/pillars-897x577.jpg 897w, https://jacco.ompf2.com/wp-content/uploads/2024/04/pillars-360x232.jpg 360w, https://jacco.ompf2.com/wp-content/uploads/2024/04/pillars.jpg 1212w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">Figure 1: Soft shadows using white noise.</figcaption></figure>
</div>


<p class="wp-block-paragraph">And that&#8217;s where this article begins.</p>



<p class="has-text-align-center wp-block-paragraph">&#8211; o &#8211; </p>



<h2 class="wp-block-heading">Stratification</h2>



<p class="wp-block-paragraph">The noise in the <em><a href="https://en.wikipedia.org/wiki/Umbra,_penumbra_and_antumbra#Penumbra">penumbra</a></em> of the soft shadows of the pillars has a name: It&#8217;s <em><a href="https://en.wikipedia.org/wiki/White_noise">white noise</a></em>. We obtain it by using a proper pseudo-random number generator: &#8216;Pseudo&#8217;, because that&#8217;s the best a computer can do. The RNG used in the template is a fast but good one: Marsaglia&#8217;s <a href="https://www.jstatsoft.org/article/view/v008i14">Xor32</a> algorithm. You can find its implementation in <code>tmpl8math.cpp</code>. Each time we call <code>RandomFloat</code> we get a number between 0 and 1. The random number is <em>uniform</em>, which means that every value between 0 and 1 should have the same probability of being generated. If we use this RNG to produce 100 x-coordinates and 50 y-coordinates, we get this image:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" width="828" height="808" src="https://jacco.ompf2.com/wp-content/uploads/2024/04/xor32.png" alt="" class="wp-image-1853" style="width:320px" srcset="https://jacco.ompf2.com/wp-content/uploads/2024/04/xor32.png 828w, https://jacco.ompf2.com/wp-content/uploads/2024/04/xor32-300x293.png 300w, https://jacco.ompf2.com/wp-content/uploads/2024/04/xor32-768x749.png 768w, https://jacco.ompf2.com/wp-content/uploads/2024/04/xor32-360x351.png 360w" sizes="auto, (max-width: 828px) 100vw, 828px" /><figcaption class="wp-element-caption">Figure 2: White noise distribution.</figcaption></figure>
</div>


<p class="wp-block-paragraph">The RNG has a problem. Quite often, two or more white dots are right next to each other. In fact, some of them are in the same position. To make matters worse, some parts of the picture have rather few dots. The same pattern, clusters and all, appears in the noisy penumbra of the soft shadow.</p>



<p class="wp-block-paragraph">An easy way to improve matters is a technique called <em>stratification.</em> It works like this: We calculate 100 random dots, but instead of giving each dot the full rectangle to pick a spot on, we limit each to a <em>stratum</em>:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" width="804" height="800" src="https://jacco.ompf2.com/wp-content/uploads/2024/04/strata.png" alt="" class="wp-image-1854" style="width:320px" srcset="https://jacco.ompf2.com/wp-content/uploads/2024/04/strata.png 804w, https://jacco.ompf2.com/wp-content/uploads/2024/04/strata-300x300.png 300w, https://jacco.ompf2.com/wp-content/uploads/2024/04/strata-150x150.png 150w, https://jacco.ompf2.com/wp-content/uploads/2024/04/strata-768x764.png 768w, https://jacco.ompf2.com/wp-content/uploads/2024/04/strata-360x358.png 360w" sizes="auto, (max-width: 804px) 100vw, 804px" /><figcaption class="wp-element-caption">Figure 3: Stratification with 10&#215;10 strata.</figcaption></figure>
</div>


<p class="wp-block-paragraph">Here, the rectangle is divided in 100 equal <em>strata</em>, and each <em>stratum</em> receives one random dot. The effect is interesting: Each location in the full rectangle still has a chance of being covered by a dot, but the dots are now much better distributed.</p>



<p class="wp-block-paragraph">We can use this technique to improve the shadow. Change the call to Trace inside <code>Renderer::Tick()</code> to:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 pixel = Trace( r, 0, x, y );</pre></div>



<p class="wp-block-paragraph">This tells <code>Trace</code> what the pixel coordinate is for the ray we&#8217;re tracing; we need that info inside <code>Renderer::Trace</code> to determine the stratum. Inside <code>Renderer::Trace()</code>, change the single line that picks a random point <code>P</code> on the light. It reads:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 P( (RandomFloat() + 1) / 2, (RandomFloat() + 1) / 5, 3 );</pre></div>



<p class="wp-block-paragraph">Modify it to:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float r0 = RandomFloat(), r1 = RandomFloat();
if (x &gt; SCRWIDTH / 2)
{
    if (x &amp; 1) r0 *= 0.5f; else r0 = (r0 + 1) * 0.5f;
    if (y &amp; 1) r1 *= 0.5f; else r1 = (r1 + 1) * 0.5f;
}
float3 P( (r0 + 1) / 2, (r1 + 6) / 5, 3 );</pre></div>



<p class="wp-block-paragraph">For the left side of the screen this changes nothing, so we have something to compare to. For the right half of the screen however, groups of 2&#215;2 pixels become strata: The top-left pixel of the group will use random numbers for x and y in the range 0 .. 0.5, while the bottom-right pixel uses random numbers in the range 0.5 .. 1. This works&#8230; Sort of:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="472" src="https://jacco.ompf2.com/wp-content/uploads/2024/04/badstrata-1024x472.png" alt="" class="wp-image-1855" style="width:542px" srcset="https://jacco.ompf2.com/wp-content/uploads/2024/04/badstrata-1024x472.png 1024w, https://jacco.ompf2.com/wp-content/uploads/2024/04/badstrata-300x138.png 300w, https://jacco.ompf2.com/wp-content/uploads/2024/04/badstrata-768x354.png 768w, https://jacco.ompf2.com/wp-content/uploads/2024/04/badstrata-1536x708.png 1536w, https://jacco.ompf2.com/wp-content/uploads/2024/04/badstrata-2048x943.png 2048w, https://jacco.ompf2.com/wp-content/uploads/2024/04/badstrata-1222x563.png 1222w, https://jacco.ompf2.com/wp-content/uploads/2024/04/badstrata-897x413.png 897w, https://jacco.ompf2.com/wp-content/uploads/2024/04/badstrata-360x166.png 360w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">Figure 4: One sample per pixel. Left: White noise. Right: Stratification over 2&#215;2 pixels, resulting in patterns due to correlation.</figcaption></figure>
</div>


<p class="wp-block-paragraph">When you think about it, it makes sense. For each pixel in a 2&#215;2 pixel group, each pixel will <em>always</em> sample the <em>same</em> quadrant of the area light. The pixel next to it will <em>always</em> sample a different quadrant. If one quadrant is fully visible, while the other isn&#8217;t, we get patterns: There is now a <em>correlation</em> between the position of a pixel, and the random numbers generated for it.</p>



<p class="wp-block-paragraph">The solution is simple. If we sample each stratum for each pixel, we no longer skip quadrants, but we do keep the benefits of stratification. In this case we have four strata, so we take four samples in <code>Renderer::Tick()</code>:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 pixel = 0.25f *
    (Trace( r, 0, x + 1, y + 1 ) + Trace( r, 0, x, y ) +
    Trace( r, 0, x + 1, y ) + Trace( r, 0, x, y + 1 ));</pre></div>



<p class="wp-block-paragraph">The result:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="334" src="https://jacco.ompf2.com/wp-content/uploads/2024/04/strata4-1024x334.png" alt="" class="wp-image-1859" style="width:640px" srcset="https://jacco.ompf2.com/wp-content/uploads/2024/04/strata4-1024x334.png 1024w, https://jacco.ompf2.com/wp-content/uploads/2024/04/strata4-300x98.png 300w, https://jacco.ompf2.com/wp-content/uploads/2024/04/strata4-768x250.png 768w, https://jacco.ompf2.com/wp-content/uploads/2024/04/strata4-897x293.png 897w, https://jacco.ompf2.com/wp-content/uploads/2024/04/strata4-360x117.png 360w, https://jacco.ompf2.com/wp-content/uploads/2024/04/strata4.png 1110w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">Figure 5: Four samples per pixel. Left: White noise. Right: Stratification with four strata.</figcaption></figure>
</div>


<p class="wp-block-paragraph">It is quite clear that even with four strata the result is much better than just white noise. More strata will be even better &#8211; with diminishing returns, though. Sadly, there is a drawback to stratification: For <span class="wp-katex-eq" data-display="false">N</span> strata, we need to take <span class="wp-katex-eq" data-display="false">N</span> samples for each pixels to avoid correlation, and that will quickly reduce the ray tracer to a slideshow&#8230;</p>



<p class="wp-block-paragraph">Luckily, there is a way to get the benefits of stratification even with a single sample per pixel.</p>



<p class="has-text-align-center wp-block-paragraph">&#8211; o &#8211; </p>



<h2 class="wp-block-heading">Blue Noise</h2>



<p class="wp-block-paragraph">Stratification for an area light works because it ensures that four samples actually sample all four quadrants of the area light. But, we can do even better. How about this distribution of samples over the surface of the light source:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img decoding="async" src="https://upload.wikimedia.org/wikipedia/commons/b/bb/Poisson_disk_sampling.svg" alt=""/></figure>
</div>


<p class="wp-block-paragraph">This is <em>blue noise</em>, where each sample has a minimum distance to other samples. This beats even the 10&#215;10 strata we saw earlier. Problem is: How do we generate the positions of these samples? The answer is: We don&#8217;t; we use pre-calculated values. Have a look at this texture, which is generously provided by Christoph Peters on his <a href="https://momentsingraphics.de/BlueNoise.html">Moments in Graphics</a> blog:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="256" height="256" src="https://jacco.ompf2.com/wp-content/uploads/2024/04/LDR_RG01_0-1.png" alt="" class="wp-image-1864" srcset="https://jacco.ompf2.com/wp-content/uploads/2024/04/LDR_RG01_0-1.png 256w, https://jacco.ompf2.com/wp-content/uploads/2024/04/LDR_RG01_0-1-150x150.png 150w" sizes="auto, (max-width: 256px) 100vw, 256px" /><figcaption class="wp-element-caption">Figure 7: Precalculated blue noise. Source: Christoph Peters / Moments in Graphics.</figcaption></figure>
</div>


<p class="wp-block-paragraph">In this texture the red and green channels are used to store the precalculated blue noise. Image data is generally integer data, but if we extract red and green and divide by 256, we get numbers in the range 0..1, which we can then use as random numbers.</p>



<p class="wp-block-paragraph">Let&#8217;s put that to the test. For this, we tile the texture over the screen, and use the values in red and green as our &#8216;random numbers&#8217;. </p>



<p class="wp-block-paragraph">First, undo the last change to <code>Tick</code>, so pixels once again use a single sample:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 pixel = Trace( r, 0, x, y );</pre></div>



<p class="wp-block-paragraph">After that, the modifications in <code>Renderer::Trace()</code> are modest.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">static Surface blue( "assets/LDR_RG01_0.png" );
float r0 = RandomFloat(), r1 = RandomFloat();
if (x &gt; SCRWIDTH / 2)
{
    int pixel = blue.pixels[(x &amp; 63) + (y &amp; 63) * 64];
    int red = pixel &gt;&gt; 16, green = (pixel &gt;&gt; 8) &amp; 255;
    r0 = red / 256.0f;  
    r1 = green / 256.0f;
}</pre></div>



<p class="wp-block-paragraph">The result is staggering.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="426" src="https://jacco.ompf2.com/wp-content/uploads/2024/04/blueshadow-1024x426.png" alt="" class="wp-image-1867" style="width:640px" srcset="https://jacco.ompf2.com/wp-content/uploads/2024/04/blueshadow-1024x426.png 1024w, https://jacco.ompf2.com/wp-content/uploads/2024/04/blueshadow-300x125.png 300w, https://jacco.ompf2.com/wp-content/uploads/2024/04/blueshadow-768x320.png 768w, https://jacco.ompf2.com/wp-content/uploads/2024/04/blueshadow-1222x509.png 1222w, https://jacco.ompf2.com/wp-content/uploads/2024/04/blueshadow-897x373.png 897w, https://jacco.ompf2.com/wp-content/uploads/2024/04/blueshadow-360x150.png 360w, https://jacco.ompf2.com/wp-content/uploads/2024/04/blueshadow.png 1230w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">Figure 8: Sampling an area light using precalculated blue noise.</figcaption></figure>
</div>


<p class="wp-block-paragraph">Blue noise is indeed far better than white noise, and even better than stratification. We will still need to deal with the stationary nature of the blue noise though before we can use it together with the accumulator from the <a href="https://jacco.ompf2.com/?p=1803">previous article</a>.</p>



<p class="has-text-align-center wp-block-paragraph">&#8211; o &#8211; </p>



<h2 class="wp-block-heading">Converge</h2>



<p class="wp-block-paragraph">There are several ways to make the blue noise animate over time. We could for instance use multiple blue noise tiles, or shift the tile data. In practice, it turns out that these options are not all that great. More details on that can be found in <a href="https://link.springer.com/content/pdf/10.1007/978-1-4842-7185-8_24.pdf">Chapter 24</a> of Ray Tracing Gems II, by NVIDIAs Alan Wolfe, but I am sharing here his conclusion:</p>



<p class="wp-block-paragraph">To animate blue noise, we just repeatedly add the <em>golden ratio</em> to the values. This will yield values outside the range 0..1, so we keep just the fractional part. Like so:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">r0 = fracf( r0 + frame * 0.61803399f );
r1 = fracf( r1 + frame * 0.61803399f );</pre></div>



<p class="wp-block-paragraph">We made quite some changes, so here is the full <code>Renderer::Trace()</code> function:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 Renderer::Trace( Ray&amp; ray, int frame, int x, int y )
{
    scene.FindNearest( ray );
    if (ray.voxel == 0) return float3( 0.4f, 0.5f, 1.0f );
    static Surface blue( "assets/LDR_RG01_0.png" );
    float r0 = RandomFloat(), r1 = RandomFloat();
    if (x &gt; SCRWIDTH / 2)
    {
        int pixel = blue.pixels[(x &amp; 63) + (y &amp; 63) * 64];
        int red = pixel &gt;&gt; 16, green = (pixel &gt;&gt; 8) &amp; 255;
        r0 = fracf( red / 256.0f + frame * 0.61803399f );
        r1 = fracf( green / 256.0f + frame * 0.61803399f );
    }
    float3 P( (r0 + 1) / 2, (r1 + 6) / 5, 3 );
    float3 I = ray.IntersectionPoint(), L = normalize( P - I );
    if (scene.IsOccluded( Ray( I, L, 10 ) )) return 0.2f;
    return 2 * max( 0.2f, dot( ray.GetNormal(), L ) );
}</pre></div>



<p class="wp-block-paragraph">This function now requires a &#8216;frame&#8217; argument, which we provide from <code>Renderer::Tick()</code>:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 pixel = Trace( r, frame, x, y );</pre></div>



<p class="wp-block-paragraph">Here, &#8216;frame&#8217; is a static variable that we increment each frame. It can be placed just before the <code>#pragma omp parallel for</code> line:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">static int frame = 0;
frame++;</pre></div>



<p class="wp-block-paragraph">Combined with accumulation (see challenges!), the image now greatly benefits from the blue noise.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="386" src="https://jacco.ompf2.com/wp-content/uploads/2024/04/animblue-1024x386.png" alt="" class="wp-image-1906" style="width:640px" srcset="https://jacco.ompf2.com/wp-content/uploads/2024/04/animblue-1024x386.png 1024w, https://jacco.ompf2.com/wp-content/uploads/2024/04/animblue-300x113.png 300w, https://jacco.ompf2.com/wp-content/uploads/2024/04/animblue-768x289.png 768w, https://jacco.ompf2.com/wp-content/uploads/2024/04/animblue-897x338.png 897w, https://jacco.ompf2.com/wp-content/uploads/2024/04/animblue-360x136.png 360w, https://jacco.ompf2.com/wp-content/uploads/2024/04/animblue.png 1190w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">Figure 9: Accumulating over time with blue noise samples.</figcaption></figure>
</div>


<p class="wp-block-paragraph">And with that, we reached the end of the fourth episode. Episode 5 will be about accumulating over time when the camera moves. See you next week!</p>



<p class="has-text-align-center wp-block-paragraph">&#8211; o &#8211; </p>



<h2 class="wp-block-heading">Challenges</h2>



<p class="wp-block-paragraph"><strong>Challenge 1.</strong> Combine the concepts of this article with those of previous articles in the series to produce a real-time accumulating voxel renderer with colored voxels, glass, mirrors, anti-aliasing, and blue-noise soft shadows, all accumulating to a converged image for a stationary camera.</p>



<p class="wp-block-paragraph"><strong>Challenge 2.</strong> The sampling problem in this episode is a 2D one: each sample needs two random numbers. Applying blue noise to Fresnel (see episode 2) is a 1D problem, but applying it to a light transport path that involves an area light <em>and</em> a single Fresnel event makes the dimensionality of the path 3. Research how to apply blue noise to paths with an even higher dimensionality.</p>



<h2 class="wp-block-heading">Etc.</h2>



<p class="wp-block-paragraph">If you want to share some of your work, consider posting on X about it. You can also follow me there <em>(<a href="https://twitter.com/j_bikker">@j_bikker</a>)</em>, or contact me at <a href="mailto:bikker.j@gmail.com">bikker.j@gmail.com</a>.</p>



<p class="wp-block-paragraph"><strong>Want to read more about computer graphics?</strong> Also on this blog:</p>



<ul class="wp-block-list">
<li><a href="https://jacco.ompf2.com/2022/04/13/how-to-build-a-bvh-part-1-basics/">How to build a BVH series</a></li>



<li><a href="https://jacco.ompf2.com/2020/04/07/speeding-up-lighthouse-2/">Speeding up the Lighthouse 2 renderer</a></li>



<li><a href="https://jacco.ompf2.com/2020/03/18/opt1profiling/">Software Optimization</a></li>
</ul>



<p class="wp-block-paragraph">Other articles in the &#8220;Ray Tracing with Voxels in C++&#8221; series:</p>



<ol class="wp-block-list">
<li><a href="https://jacco.ompf2.com/?p=1715">Starting point: Voxel ray </a><a href="https://jacco.ompf2.com/2024/04/24/ray-tracing-with-voxels-in-c-series-part-1/">tracing</a><a href="https://jacco.ompf2.com/?p=1715"> template code. Lights and shadows</a>.</li>



<li><a href="https://jacco.ompf2.com/?p=1755&amp;preview=true">Whitted-style: Reflections, recursion, </a><a href="https://jacco.ompf2.com/2024/05/01/ray-tracing-with-voxels-in-c-series-part-2/">glass</a>.</li>



<li><a href="https://jacco.ompf2.com/?p=1803">Stochastic techniques: Anti-aliasing and soft </a><a href="https://jacco.ompf2.com/2024/05/08/ray-tracing-with-voxels-in-c-series-part-3/">shadows</a>.</li>



<li><strong>Noise reduction: Stratification and blue noise (this article).</strong></li>



<li><a href="https://jacco.ompf2.com/2024/05/22/ray-tracing-with-voxels-in-c-series-part-5/">Converging under movement: Reprojection</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/29/ray-tracing-with-voxels-in-c-series-part-6/">Path tracing: Basics first; then: Importance Sampling</a>.</li>



<li>Denoising fundamentals.</li>



<li>Acceleration structures: Extending the grid to a multi-level grid.</li>



<li>Acceleration structures: Adding a TLAS.</li>
</ol>
]]></content:encoded>
					
					<wfw:commentRss>https://jacco.ompf2.com/2024/05/15/ray-tracing-with-voxels-in-c-series-part-4/feed/</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
		<item>
		<title>Ray Tracing with Voxels in C++ Series &#8211; Part 3</title>
		<link>https://jacco.ompf2.com/2024/05/08/ray-tracing-with-voxels-in-c-series-part-3/</link>
					<comments>https://jacco.ompf2.com/2024/05/08/ray-tracing-with-voxels-in-c-series-part-3/#comments</comments>
		
		<dc:creator><![CDATA[jbikker]]></dc:creator>
		<pubDate>Wed, 08 May 2024 07:23:37 +0000</pubDate>
				<category><![CDATA[Article]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Tutorial]]></category>
		<guid isPermaLink="false">https://jacco.ompf2.com/?p=1803</guid>

					<description><![CDATA[In this series we build a physically based renderer for a dynamic voxel world. From &#8216;Whitted-style&#8217; ray...]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">In this series we build a physically based renderer for a dynamic voxel world. From &#8216;Whitted-style&#8217; ray tracing with shadows, glass and mirrors, we go all the way to &#8216;unbiased path tracing&#8217; &#8211; and beyond, exploring advanced topics such as reprojection, denoising and blue noise. The accompanying source code is <a href="https://github.com/jbikker/voxpopuli">available on Github</a> and is written in easy-to-read &#8216;sane C++&#8217;.</p>



<p class="wp-block-paragraph">This series consists of nine articles. Contents:  <em>(tentative until finalized)</em></p>



<ol class="wp-block-list">
<li><a href="https://jacco.ompf2.com/2024/04/24/ray-tracing-with-voxels-in-c-series-part-1/">Starting point: Voxel ray tracing template code. Lights and shadows</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/01/ray-tracing-with-voxels-in-c-series-part-2/">Whitted-style: Reflections, recursion, glass</a>.</li>



<li><strong>Stochastic techniques: Anti-aliasing and soft shadows</strong> <strong>(this article).</strong></li>



<li><a href="https://jacco.ompf2.com/2024/05/15/ray-tracing-with-voxels-in-c-series-part-4/">Noise reduction: Stratification, blue noise</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/22/ray-tracing-with-voxels-in-c-series-part-5/">Converging under movement: Reprojection</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/29/ray-tracing-with-voxels-in-c-series-part-6/">Path tracing: Basics first; then: Importance Sampling</a>.</li>



<li>Denoising fundamentals.</li>



<li>Acceleration structures: Extending the grid to a multi-level grid.</li>



<li>Acceleration structures: Adding a TLAS.   </li>
</ol>



<h2 class="wp-block-heading">In This Article&#8230;</h2>



<p class="wp-block-paragraph">In this article we move beyond <em>Whitted-style</em> ray tracing with some stochastic rendering techniques. This will unlock new and interesting features, such as soft shadows from area lights, motion blur and depth of field. It all starts with anti-aliasing, as this simple technique already uses the ingredients we will need for the more impactful techniques. And finally, we will see how stochastic rendering solves the main problem of Whitted-style ray tracing: Performance.</p>



<h2 class="wp-block-heading">Starting Point</h2>



<p class="wp-block-paragraph">As with the previous articles, we start with the standard template for this series, which you can find in its <a href="https://github.com/jbikker/voxpopuli">repository on Github</a>. Let&#8217;s change <code>Renderer::Trace</code> to a smaller version of the code used in <a href="https://jacco.ompf2.com/?p=1755">article 2</a>: </p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 Renderer::Trace( Ray&amp; ray, int depth, int, int )
{
    scene.FindNearest( ray );
    if (ray.voxel == 0) return float3( 0.5f, 0.6f, 1.0f );
    static const float3 L = normalize( float3( 3, 2, 1 ) );
    return max( 0.3f, dot( ray.GetNormal(), L ) );
}</pre></div>



<p class="wp-block-paragraph">When you zoom in on an edge, maybe after taking a screenshot, an issue emerges:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/jaggies.png" alt="" style="width:540px;height:auto"/><figcaption class="wp-element-caption">Figure 1: &#8216;Jaggies&#8217;: rasterization / point sampling artifacts.</figcaption></figure>
</div>


<p class="wp-block-paragraph">The &#8216;jaggies&#8217; on the edges are <em>aliasing artifacts</em>. They result from displaying an image on a computer screen, which is a raster of more or less square pixels. If we zoom in on a small set of pixels, the root cause of the problem emerges.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/onespp.png" alt="" style="width:396px;height:auto"/><figcaption class="wp-element-caption">Figure 2: Point samples detect geometry only at a single point on the area of a pixel.</figcaption></figure>
</div>


<p class="wp-block-paragraph">The pixel colors are supposed to be a representation of the geometry that we can see though a small rectangle. But, the ray tracer <em>samples</em> the geometry using a single ray, here depicted by a yellow dot. So, when a pixel should display a blend of the sky color and a shaded voxel, it <em>actually</em> displays one or the other.</p>



<p class="wp-block-paragraph">Take the bottom right pixel. Based on the sample, that pixel is blue. A better color would be ~90% blue and ~10% grey: This ratio depends on the <em>area</em> of the blue and the grey patches. IN this particular case, this ratio could theoretically be calculated, but this becomes hard when the scene is more complex. We can however <em>estimate</em> it, by using multiple rays per pixel.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/fourspp.png" alt="" style="width:290px;height:auto"/><figcaption class="wp-element-caption">Figure 3: Multi-sampling gives us a coarse estimate of the true color of a pixel.</figcaption></figure>
</div>


<p class="wp-block-paragraph">This time, the bottom right corner more or less accurately estimates the color to be half blue, half grey, since two rays hit the sky, and two rays hit the geometry. The top-right pixel however is still just blue, despite the extra work we spent on it. We can fix this by sending more rays, and as the number of rays approaches infinity, the answer will become correct, no matter how complex the things we &#8216;see&#8217; through the pixel. This technique is called <em>numerical integration</em>. We <em>estimate</em> the energy arriving through a pixel by taking a number of <em>point samples</em>. More samples improve the estimate.</p>



<p class="has-text-align-center wp-block-paragraph">&#8211; o &#8211; </p>



<h2 class="wp-block-heading">Code</h2>



<p class="wp-block-paragraph">Let&#8217;s implement anti-aliasing with multiple rays per pixel. On line 37 of <code>Renderer::Tick</code> we currently create a single primary ray for each pixel:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">Ray r = camera.GetPrimaryRay( (float)x, (float)y );</pre></div>



<p class="wp-block-paragraph">Let&#8217;s make that four rays.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">Ray r1 = camera.GetPrimaryRay( (float)x, (float)y );
Ray r2 = camera.GetPrimaryRay( x + 0.5f, (float)y );
Ray r3 = camera.GetPrimaryRay( (float)x, y + 0.5f );
Ray r4 = camera.GetPrimaryRay( x + 0.5f, y + 0.5f );
float3 sample1 = Trace( r1 );
float3 sample2 = Trace( r2 );
float3 sample3 = Trace( r3 );
float3 sample4 = Trace( r4 );
float3 pixel = 0.25f * (sample1 + sample2 + sample3 + sample4);</pre></div>



<p class="wp-block-paragraph">First observation after running this program: This works. The jaggies have substantially been reduced. Second observation: It now runs four times slower. Yeah, ray tracers tend to do that. Luckily, the template lets you remedy that relatively easily. Open up <code>camera.h</code>, and you&#8217;ll see the screen resolution used by the template:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">// default screen resolution
#define SCRWIDTH	1280
#define SCRHEIGHT	800
// #define FULLSCREEN
// #define DOUBLESIZE</pre></div>



<p class="wp-block-paragraph">Change the resolution to 640 by 400, and uncomment DOUBLESIZE. This will render every pixel as a 2&#215;2 block, effectively cutting the work the program has to do to 25%.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/aa2x2.png" alt="" style="width:540px"/><figcaption class="wp-element-caption">Figure 4: 2&#215;2 samples per pixel greatly reduce the jaggies.</figcaption></figure>
</div>


<p class="wp-block-paragraph">There is however a different solution to the performance problem, and that solution is a bit more fundamental.</p>



<p class="has-text-align-center wp-block-paragraph">&#8211; o &#8211; </p>



<h2 class="wp-block-heading">One Sample</h2>



<p class="wp-block-paragraph">Instead of sending 4, 9, 16, 25 or even infinite rays through each pixel, we can do something clever: We send <em>one ray</em> through every pixel, but, instead of aiming it at a <em>fixed</em> position on the pixel, we aim at a <em>random</em> position. This has two consequences:</p>



<ol class="wp-block-list">
<li>We immediately get our original performance back, because each pixel is calculated using one ray;</li>



<li>Geometry edges are now noisy.</li>
</ol>



<p class="wp-block-paragraph">The code we need looks like this:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">Ray r = camera.GetPrimaryRay( x + RandomFloat(), y + RandomFloat() );
float3 pixel = Trace( r );</pre></div>



<p class="wp-block-paragraph">And the output is noisy, as promised:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/jaggies1spp.png" alt="" style="width:500px"/><figcaption class="wp-element-caption">Figure 5: Random point samples on pixels yield a noisy result.</figcaption></figure>
</div>


<p class="wp-block-paragraph">It turns out that things improve when we send <em>multiple</em> random rays through each pixel. Try the following snippet, starting at line 32:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">// trace a primary ray for each pixel on the line
for (int x = 0; x &lt; SCRWIDTH; x++)
{
    float3 pixel( 0 );
    for ( int sample = 0; sample &lt; 8; sample++ )
    {
        Ray r = camera.GetPrimaryRay( x + RandomFloat(), y + RandomFloat() );
        pixel += Trace( r );
    }
    screen-&gt;pixels[x + y * SCRWIDTH] = RGBF32_to_RGB8( pixel * 0.125f );
}</pre></div>



<p class="wp-block-paragraph">This produces the following image:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/jaggies4spp.png" alt="" style="width:500px"/><figcaption class="wp-element-caption">Figure 6: Multiple random samples show a result that is still noisy, but closer to the correct solution.</figcaption></figure>
</div>


<p class="wp-block-paragraph">It&#8217;s still noisy, but it is approaching the result that we are looking for, similar to the 2&#215;2 raster of samples that we used earlier.</p>



<p class="wp-block-paragraph">This experiment reveals that there is something special about the noisy pixels. More of them get us closer to the correct result, because the <em>probability</em> that a random sample finds a particular color through a pixel is proportional to the area of that particular color. Let that sink in, because it is important. We just replaced the <em>calculation</em> of the area of a sub-pixel feature by the <em>chance</em> that we hit it with a random ray. Or, in math terms, we replaced an <em>integral</em> by the <em>expected value</em> of a random process.</p>



<p class="has-text-align-center wp-block-paragraph">&#8211; o &#8211; </p>



<h2 class="wp-block-heading">Converge</h2>



<p class="wp-block-paragraph">Now that we know that more random samples improve the quality of the anti-aliasing, it&#8217;s time to add something cool to the ray tracer. We start with a modification to <code>Renderer::Init</code> in <code>renderer.cpp</code>. This function is called once before all frames are drawn and is useful to do things we need only once. Modify it as follows: </p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void Renderer::Init()
{
    accumulator = new float3[SCRWIDTH * SCRHEIGHT];
    memset( accumulator, 0, SCRWIDTH * SCRHEIGHT * sizeof( float3 ) );
}</pre></div>



<p class="wp-block-paragraph">The pixel plotting loop is restored to the single random sample variant:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">// trace a primary ray for each pixel on the line
for (int x = 0; x &lt; SCRWIDTH; x++)
{
    Ray r = camera.GetPrimaryRay( x + RandomFloat(), y + RandomFloat() );
    float3 pixel = Trace( r );
    screen-&gt;pixels[x + y * SCRWIDTH] = RGBF32_to_RGB8( pixel );
}</pre></div>



<p class="wp-block-paragraph">The <code>accumulator</code> array is pure magic. We use it to calculate multiple samples per pixel <em>over time</em>. It starts empty, with every pixel set to 0. Observe the low-level magic used here: The 32-bit <em>integer</em> number 0, when interpreted as 32-bit floating point data, is also 0.0f, which allows us to quickly zero the large <code>accumulator</code> array. We then add a value for each pixel to it:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">for (int x = 0; x &lt; SCRWIDTH; x++)
{
    Ray r = camera.GetPrimaryRay( x + RandomFloat(), y + RandomFloat() );
    accumulator[x + y * SCRWIDTH] += Trace( r );
}</pre></div>



<p class="wp-block-paragraph">The value in the accumulator will thus get brighter with each frame. But, if we divide the accumulated values by the number of frames, we will get the correct average. So, just above function <code>Renderer::Tick</code>, we add a line:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">static int spp = 1;</pre></div>



<p class="wp-block-paragraph">Then, we add a line just before the <code>#pragma omp</code> parallel line, so that the value is available to all rendering threads:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">const float scale = 1.0f / spp++;</pre></div>



<p class="wp-block-paragraph">Almost there. We now modify the pixel loop so that the average of each accumulated pixel is plotted to the screen:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">// trace a primary ray for each pixel on the line
for (int x = 0; x &lt; SCRWIDTH; x++)
{
    Ray r = camera.GetPrimaryRay( x + RandomFloat(), y + RandomFloat() );
    accumulator[x + y * SCRWIDTH] += Trace( r );
    float3 average = accumulator[x + y * SCRWIDTH] * scale;
    screen-&gt;pixels[x + y * SCRWIDTH] = RGBF32_to_RGB8( average );
}</pre></div>



<p class="wp-block-paragraph">Now run <em>this.</em> The result is <em>absolutely perfect</em> anti-aliasing, thanks to some basic probability theory.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/perfectaa.png" alt="" style="width:600px"/><figcaption class="wp-element-caption">Figure 7: Perfectly converged anti-aliasing for a stationary camera, accumulated over time.</figcaption></figure>
</div>


<p class="wp-block-paragraph">One problem remains: When you move the camera, nothing happens, or at best a massive smear is the result. There&#8217;s an easy fix for that: Whenever the camera moves, we should clear the accumulator, and restart accumulation. Replace the last line of <code>Renderer::Tick</code> with:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">if (camera.HandleInput( deltaTime ))
{
    spp = 1;
    memset( accumulator, 0, SCRWIDTH * SCRHEIGHT * sizeof( float3 ) );
}</pre></div>



<p class="wp-block-paragraph">That&#8217;s all! Function <code>Camera::HandleInput</code> will let you know when user input changed the view; when this happens, we reset the static <code>spp</code> (&#8216;samples per pixel&#8217;) variable to 1, and clear the values in the accumulator. This time the image is noisy only when the camera moves, and quickly converges when it becomes stationary.</p>



<p class="has-text-align-center wp-block-paragraph">&#8211; o &#8211; </p>



<h2 class="wp-block-heading">Soft Shadows</h2>



<p class="wp-block-paragraph">With perfect anti-aliasing in place, it turns out to be pretty easy to add soft shadows to the renderer. </p>



<p class="wp-block-paragraph">Soft shadows represent a pretty high end rendering feature. They occur naturally when light is cast by an <em>area light</em>, i.e. any light that is not a point. </p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/photoshadows.png" alt="" style="width:534px;height:auto"/><figcaption class="wp-element-caption">Figure 8: Soft-shadows in a photograph.</figcaption></figure>
</div>


<p class="wp-block-paragraph">Even the sun is an area light: In fact, point lights were pretty rare until we got LEDs, which sometimes approach point lights.</p>



<p class="wp-block-paragraph">Some terminology: The soft edge of a soft shadow is called the <em>penumbra</em>, this is the area from which the area light source is partially visible. The part of the shadow for which the light is fully blocked is called the <em>umbra</em>. To calculate a soft shadow in a ray tracer, we are thus interested in the <em>visibility</em> of a light source. For a point light, this is all or nothing: A shadow ray can get there, or it is blocked. For an area light, we may be able to get to some part of the light, or all of it, or some percentage. You probably can see where this is going: If we would fire a shadow ray to a <em>random</em> point on a light source, and we would determine the <em>probability</em> that this ray arrives unobstructed, then this probability can perfectly <em>replace visibility</em>.</p>



<p class="wp-block-paragraph">Let&#8217;s setup a basic area light to play with. The simplest shape is a horizontal rectangle. A random point on such a rectangle is easily obtained:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 RandomPointOnLight()
{
    return float3( RandomFloat() - 1, 3, RandomFloat() - 1 );
}</pre></div>



<p class="wp-block-paragraph">Recall that the world is 1x1x1, located at the origin, so this would be a large plane floating some distance diagonally above it. We use the new <code>RandomPointOnLight</code> function in modified version of the <code>Renderer::Trace()</code> code from the <a href="https://jacco.ompf2.com/2024/04/24/ray-tracing-with-voxels-in-c-series-part-1/">first article</a>:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 Renderer::Trace( Ray&amp; ray, int depth, int, int )
{
    scene.FindNearest( ray );
    if (ray.voxel == 0) return float3( 0.4f, 0.5f, 1.0f );
    float3 I = ray.IntersectionPoint();
    float3 L = RandomPointOnLight() - I;
    float distance = length( L );
    L = normalize( L );
    float cosa = max( 0.0f, dot( ray.GetNormal(), L ) );
    Ray shadowRay( I, L, distance );
    if (scene.IsOccluded( shadowRay )) return 0;
    return 20 * ray.GetAlbedo() * cosa / pow2f( distance );
}</pre></div>



<p class="wp-block-paragraph">Using the <code>RandomPointOnLight</code> function we now apply the same magic that allowed us to do anti-aliasing with just <em>one </em>ray. Without the accumulator, things are interesting already: </p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/noisy.jpg" alt="" style="width:600px"/><figcaption class="wp-element-caption">Figure 9: Taking random samples on an area light source yields soft shadows, where the density of the black spots is proportional to the visibility of the light source.</figcaption></figure>
</div>


<p class="wp-block-paragraph">Even with one sample per pixel, the soft shadow already emerges. Every individual sample is still &#8216;hit&#8217; or &#8216;miss&#8217;, but <em>on average</em>, these samples capture the smoothly varying visibility of the area light. That becomes even more clear when we use the accumulator:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/gorgeous.png" alt="" style="width:600px"/><figcaption class="wp-element-caption">Figure 10: Combining the accumulator with point samples on the pixel and the light yields a perfect result.</figcaption></figure>
</div>


<p class="wp-block-paragraph">That looks just gorgeous. And here comes the kicker: <em>One </em>sample through every pixel not only gets us this beautiful soft shadow; we <em>still </em>have the anti-aliasing as well! And all of that with an absolutely tiny piece of code.</p>



<p class="has-text-align-center wp-block-paragraph">&#8211; o &#8211; </p>



<h2 class="wp-block-heading">And Finally</h2>



<p class="wp-block-paragraph">There&#8217;s one last thing to introduce here. So far we have been working with rather boring test data. To improve on that situation I have converted a 3D mesh from author <a href="https://sketchfab.com/PabloDebusschere">PabloDebusschere</a> on Sketchfab to voxels and compressed it using zlib. You can find the resulting file, <code>viking.bin</code>, in the assets folder. To load it, replace <code>Scene</code> constructor by the following code:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">Scene::Scene()
{
    // allocate room for the world
    grid = (uint*)MALLOC64( GRIDSIZE3 * sizeof( uint ) );
    gzFile f = gzopen( "assets/viking.bin", "rb" );
    int3 size;
    gzread( f, &amp;size, sizeof( int3 ) );
    gzread( f, grid, size.x * size.y * size.z * 4 );
    gzclose( f );
}</pre></div>



<p class="wp-block-paragraph">After carefully picking a good looking camera view, the result is as shown below. </p>



<p class="wp-block-paragraph">And with that we end this week&#8217;s episode. In the next episode we will look at methods to reduce the noise that is clearly visible when the camera is moving. See you then! </p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="563" src="https://jacco.ompf2.com/wp-content/uploads/2024/05/viking-1-1024x563.jpg" alt="" class="wp-image-1965" style="width:600px" srcset="https://jacco.ompf2.com/wp-content/uploads/2024/05/viking-1-1024x563.jpg 1024w, https://jacco.ompf2.com/wp-content/uploads/2024/05/viking-1-300x165.jpg 300w, https://jacco.ompf2.com/wp-content/uploads/2024/05/viking-1-768x422.jpg 768w, https://jacco.ompf2.com/wp-content/uploads/2024/05/viking-1-1222x672.jpg 1222w, https://jacco.ompf2.com/wp-content/uploads/2024/05/viking-1-897x493.jpg 897w, https://jacco.ompf2.com/wp-content/uploads/2024/05/viking-1-360x198.jpg 360w, https://jacco.ompf2.com/wp-content/uploads/2024/05/viking-1.jpg 1244w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">Figure 11: Viking military outpost scene by <a href="https://sketchfab.com/PabloDebusschere">PabloDebusschere</a> on Sketchfab.</figcaption></figure>
</div>


<p class="has-text-align-center wp-block-paragraph">&#8211; o &#8211; </p>



<h2 class="wp-block-heading">Challenges</h2>



<p class="wp-block-paragraph"><strong>Challenge 1.</strong> Combine the concepts of this article with those described in article 1 and 2. Concrete, add support for multiple lights, as well as reflective and refractive materials to produce high quality images. Make sure to share some online. And if you made a game at the end of article 1, by now it should look extremely nice!</p>



<p class="wp-block-paragraph"><strong>Challenge 2.</strong> Now that everything is random, we can solve the &#8216;splitting ray&#8217; issue of Whitted-style ray tracing. For your glass material, chose randomly between the reflected and refracted directions. The probability of each should of course be determined by Fresnel.</p>



<p class="wp-block-paragraph"><strong>Challenge 3.</strong> You can find several <code>.bin</code> files in the <code>assets</code> folder. Create some code that adds them to a world, even when their size is not exactly 128x128x128 voxels, as with the Viking scene. You can even modify <code>Scene::Scene</code> to load several <code>.bin</code> files, perhaps at a custom location in the world.</p>



<p class="wp-block-paragraph"><strong>Challenge 4.</strong> In <a href="https://jacco.ompf2.com/2022/05/27/how-to-build-a-bvh-part-8-whitted-style/">another series of articles</a> on <a href="https://jacco.ompf2.com/">this blog</a> you can find instructions for adding a skydome to your scene. Follow the instructions. <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> </p>



<h2 class="wp-block-heading">Etc.</h2>



<p class="wp-block-paragraph">If you want to share some of your work, consider posting on X about it. You can also follow me there <em>(<a href="https://twitter.com/j_bikker">@j_bikker</a>)</em>, or contact me at <a href="mailto:bikker.j@gmail.com">bikker.j@gmail.com</a>.</p>



<p class="wp-block-paragraph"><strong>Want to read more about computer graphics?</strong> Also on this blog:</p>



<ul class="wp-block-list">
<li><a href="https://jacco.ompf2.com/2022/04/13/how-to-build-a-bvh-part-1-basics/">How to build a BVH series</a></li>



<li><a href="https://jacco.ompf2.com/2020/04/07/speeding-up-lighthouse-2/">Speeding up the Lighthouse 2 renderer</a></li>



<li><a href="https://jacco.ompf2.com/2020/03/18/opt1profiling/">Software Optimization</a></li>
</ul>



<p class="wp-block-paragraph">Other articles in the &#8220;Ray Tracing with Voxels in C++&#8221; series:</p>



<ol class="wp-block-list">
<li><a href="https://jacco.ompf2.com/2024/04/24/ray-tracing-with-voxels-in-c-series-part-1/">Starting point: Voxel ray tracing template code. Lights and shadows</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/01/ray-tracing-with-voxels-in-c-series-part-2/">Whitted-style: Reflections, recursion, glass</a>.</li>



<li><strong>Stochastic techniques: Anti-aliasing and soft shadows</strong> <strong>(this article).</strong></li>



<li><a href="https://jacco.ompf2.com/2024/05/15/ray-tracing-with-voxels-in-c-series-part-4/">Noise reduction: Stratification, blue noise</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/22/ray-tracing-with-voxels-in-c-series-part-5/">Converging under movement: Reprojection</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/29/ray-tracing-with-voxels-in-c-series-part-6/">Path tracing: Basics first; then: Importance Sampling</a>.</li>



<li>Denoising fundamentals.</li>



<li>Acceleration structures: Extending the grid to a multi-level grid.</li>



<li>Acceleration structures: Adding a TLAS.   </li>
</ol>
]]></content:encoded>
					
					<wfw:commentRss>https://jacco.ompf2.com/2024/05/08/ray-tracing-with-voxels-in-c-series-part-3/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Ray Tracing with Voxels in C++ Series &#8211; Part 2</title>
		<link>https://jacco.ompf2.com/2024/05/01/ray-tracing-with-voxels-in-c-series-part-2/</link>
					<comments>https://jacco.ompf2.com/2024/05/01/ray-tracing-with-voxels-in-c-series-part-2/#comments</comments>
		
		<dc:creator><![CDATA[jbikker]]></dc:creator>
		<pubDate>Wed, 01 May 2024 09:53:58 +0000</pubDate>
				<category><![CDATA[Article]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Tutorial]]></category>
		<guid isPermaLink="false">https://jacco.ompf2.com/?p=1755</guid>

					<description><![CDATA[In this series we build a physically based renderer for a dynamic voxel world. From &#8216;Whitted-style&#8217; ray...]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">In this series we build a physically based renderer for a dynamic voxel world. From &#8216;Whitted-style&#8217; ray tracing with shadows, glass and mirrors, we go all the way to &#8216;unbiased path tracing&#8217; &#8211; and beyond, exploring advanced topics such as reprojection, denoising and blue noise. The accompanying source code is <a href="https://github.com/jbikker/voxpopuli">available on Github</a> and is written in easy-to-read &#8216;sane C++&#8217;.</p>



<p class="wp-block-paragraph">This series consists of nine articles. Contents:  <em>(tentative until finalized)</em></p>



<ol class="wp-block-list">
<li><a href="https://jacco.ompf2.com/2024/04/24/ray-tracing-with-voxels-in-c-series-part-1/">Starting point: Voxel ray tracing template code. Lights and shadows.</a></li>



<li><strong>Whitted-style: Reflections, recursion, glass (this article).</strong></li>



<li><a href="https://jacco.ompf2.com/2024/05/08/ray-tracing-with-voxels-in-c-series-part-3/">Stochastic techniques: Anti-aliasing and soft shadows</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/15/ray-tracing-with-voxels-in-c-series-part-4/">Noise reduction: Stratification, blue noise</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/22/ray-tracing-with-voxels-in-c-series-part-5/">Converging under movement: Reprojection</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/29/ray-tracing-with-voxels-in-c-series-part-6/">Path tracing: Basics first; then: Importance Sampling</a>.</li>



<li>Denoising fundamentals.</li>



<li>Acceleration structures: Extending the grid to a multi-level grid.</li>



<li>Acceleration structures: Adding a TLAS.   </li>
</ol>



<h2 class="wp-block-heading">In This Article&#8230;</h2>



<p class="wp-block-paragraph">To the basic ray tracer of the first article we will now add reflections (including recursive reflections) and glass, to turn it into a full <em>Whitted-style</em> ray tracer. This requires the concept of <em>materials</em>, so we can differentiate between regular, mirror and glass voxels. We will test the new features in a fresh test scene, the code for which you will find in the next paragraph.</p>



<h2 class="wp-block-heading">Starting Point</h2>



<p class="wp-block-paragraph">For this article we will use the unmodified <a href="https://github.com/jbikker/voxpopuli">template code</a> as a starting point. You are encouraged to combine concepts from this second article with the lights and shadows introduced in the first article, but this is not required.</p>



<p class="wp-block-paragraph">Let&#8217;s first make some modifications, for the purpose of this article. Replace the world creation code in <code>Scene::Scene</code> in file <code>scene.cpp</code>, line 30:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">for (int z = 0; z &lt; 128; z++)
    for (int y = 0; y &lt; 128; y++) for (int x = 0; x &lt; 128; x++ )
        if (x &lt; 2 || x &gt; 125 || z &gt; 125 || y &lt; 2 || y &gt; 125)
            Set( x, y, z, 0xeeeeee );
        else if (y &gt; 30 &amp;&amp; y &lt; 50 &amp;&amp; z &gt; 50 &amp;&amp; z &lt; 70 &amp;&amp; x &gt; 20)
            if (x &lt; 40) Set( x, y, z, 0xff7777 );
            else if (x &gt; 55 &amp;&amp; x &lt; 75) Set( x, y, z, 0xaaffaa );
            else if (x &gt; 90 &amp;&amp; x &lt; 110) Set( x, y, z, 0x7777ff );</pre></div>



<p class="wp-block-paragraph">Next, replace the <code>Renderer::Trace</code> function in <code>renderer.cpp</code> with:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 Renderer::Trace( Ray&amp; ray, int depth, int, int )
{
    scene.FindNearest( ray );
    if (ray.voxel == 0) return float3( 0.5f, 0.6f, 1.0f ); // or a fancy sky color
    float3 N = ray.GetNormal();
    float3 I = ray.IntersectionPoint();
    float3 albedo = ray.GetAlbedo();
    static const float3 L = normalize( float3( 3, 2, 1 ) );
    return albedo * max( 0.3f, dot( N, L ) );
}</pre></div>



<p class="wp-block-paragraph">The result is a basic room scene with three floating cubes, each with a different color.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="612" src="https://jacco.ompf2.com/wp-content/uploads/2024/03/image-14-1024x612.png" alt="" class="wp-image-1792" style="width:512px" srcset="https://jacco.ompf2.com/wp-content/uploads/2024/03/image-14-1024x612.png 1024w, https://jacco.ompf2.com/wp-content/uploads/2024/03/image-14-300x179.png 300w, https://jacco.ompf2.com/wp-content/uploads/2024/03/image-14-768x459.png 768w, https://jacco.ompf2.com/wp-content/uploads/2024/03/image-14-897x536.png 897w, https://jacco.ompf2.com/wp-content/uploads/2024/03/image-14-360x215.png 360w, https://jacco.ompf2.com/wp-content/uploads/2024/03/image-14.png 1200w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p class="has-text-align-center wp-block-paragraph">&#8211; o &#8211; </p>



<h2 class="wp-block-heading">Reflections</h2>



<p class="wp-block-paragraph">In the first article we saw that ray tracing is all about light transport between light sources and the camera. A ray through a pixel finds an object; from there, a shadow ray attempts to reach the light source. If there is no obstacle, the object seen through the pixel is illuminated by the light source. But what if the object is a <em>mirror?</em> </p>



<figure class="wp-block-image size-large"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/reflsitu.png" alt=""/></figure>



<p class="wp-block-paragraph">Like other surfaces, a mirror reflects light. However: Only in very specific directions. In fact, for a perfect mirror, a single incoming direction is linked to a single outgoing direction. In the right image, one of the two rays that hit the mirror ball bounces to the green sphere. The corresponding pixel will thus show a green sphere, mirrored in a dark, shiny sphere. </p>



<p class="wp-block-paragraph">Note that the green sphere reflects green light because it is visible from the light source. There is thus light transport: From the light to the green sphere, then via the mirror to the pixel, and finally to the camera.</p>



<p class="wp-block-paragraph">To add reflections to the voxel ray tracer, we need two things:</p>



<ol class="wp-block-list">
<li>A way to calculate the reflected direction, so we can spawn a new ray;</li>



<li>A way to detect that an object is reflective.</li>
</ol>



<p class="wp-block-paragraph">Regarding that second point on the list: We will introduce the concept of <em>materials</em>. A mirror is fundamentally different from our basic (&#8216;diffuse&#8217;) material. And, later we will add a third type of material, which is used for glass and water.</p>



<p class="wp-block-paragraph">Let&#8217;s take another look at the world creation code. We used four &#8216;HTML&#8217; colors, which are in fact simply 24-bit hexadecimal numbers: <code>0xEEEEEE</code> for (almost) white, <code>0xFF7777</code> for (pastel) red, <code>0xAAFFAA</code> for green and <code>0x7777FF</code> for blue. A voxel actually can store 32-bit data, so there&#8217;s some headroom. Let&#8217;s agree that <code>0x00xxxxxxxx</code> means that we have a diffuse material with color xxxxxx, and that <code>0x01xxxxxx</code> indicates that the material is in fact reflective. So, we can make the floor reflective by changing its color to 0x019999BB:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">...
if (x &lt; 2 || x &gt; 125 || z &gt; 125 || y &lt; 2 || y &gt; 125)
    Set( x, y, z, y == 1 ? 0x19999bb : 0xffffff );
...</pre></div>



<p class="wp-block-paragraph">Now, in <code>Renderer::Trace</code> we can easily detect the mirror material. Replace the last line, which returns the shaded albedo, with the following construct:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">if ((ray.voxel &gt;&gt; 24) == 1)
{
    // mirror material
    // TODO
}
else
{
    // diffuse material
    return albedo * max( 0.3f, dot( N, L ) );
}</pre></div>



<p class="wp-block-paragraph">The bitshift operator <code>&gt;&gt;</code> shifts the contents of the 32-bit <code>ray.voxel</code> variable to the right by the specified number of bits. This effectively makes the top 8 bits, in which we stored the material type, the only remaining bits. </p>



<p class="wp-block-paragraph">To calculate the reflected color we need a reflection ray. The <em>origin</em> of this ray is simply the end of the primary ray. The <em>direction</em> is a bit more involved. The reflection direction depends on the orientation of the surface we hit, and thus we use the local normal vector, like we did with the calculation of the shading. The formula for vector reflection is:</p>



<p class="wp-block-paragraph"><span class="wp-katex-eq" data-display="false">R=D-2N(D \cdot N)</span>  </p>



<p class="wp-block-paragraph">Here, <span class="wp-katex-eq" data-display="false">D</span> is the direction of the incoming ray and <span class="wp-katex-eq" data-display="false">R</span> is the reflected direction. The reflected ray can now be constructed:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 R = ray.D - 2 * N * dot( ray.D, N );
Ray r( I, R );</pre></div>



<p class="wp-block-paragraph">Things get interesting when we actually use this new ray. Behold the final reflection code:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">if ((ray.voxel &gt;&gt; 24) == 1)
{
    // mirror material
    float3 R = ray.D - 2 * N * dot( ray.D, N );
    return albedo * Trace( Ray( I, R ) );
}</pre></div>



<p class="wp-block-paragraph">We use a <em>recursive </em>call to Renderer::Trace to handle the reflection. This is powerful: Whatever we find at the end of the reflected ray will be handled by <em>code we already have</em>. This will work if we find a diffuse surface: in that case, the existing code in Trace will cast a shadow ray. It will <em>also </em>work if we find <em>another mirror</em>. In that case, we just bounce again.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/reflfloor.png" alt="" style="width:512px"/></figure>
</div>


<p class="wp-block-paragraph">With great power comes great responsibility. It is not hard to setup a scene where rays may bounce infinitely (there&#8217;s a reason I suggested to make just the floor reflective). We&#8217;ll need to somehow limit how often we bounce. For that, we can use the optional &#8216;depth&#8217; argument of <code>Renderer::Trace</code>. By default it is called with 0. We can increase it for each recursion step:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">return albedo * Trace( Ray( I, R ), depth + 1 );</pre></div>



<p class="wp-block-paragraph">Now it is straight-forward to cap recursion. Just add a line at the start of the <code>Trace</code> function:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">if (depth == 5) return{ 0 };</pre></div>



<p class="wp-block-paragraph">Instead of <code>5</code> you can use larger (or smaller) numbers. Just be careful: Many bounces will bring down the performance of the ray tracer.</p>



<p class="has-text-align-center wp-block-paragraph"> &#8211; o &#8211; </p>



<h2 class="wp-block-heading">Refraction</h2>



<p class="wp-block-paragraph">The final feature for this article is <em>glass</em>. In the real world, glass has surprisingly complex behavior. It transmits light, but it is also reflective. To make matters worse, reflection doesn&#8217;t just happen on the outside of a glass object, but also on the inside, when we try to leave the object.</p>



<figure class="wp-block-image size-large"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/fresnelsitu.png" alt=""/><figcaption class="wp-element-caption">Left: The water surface is reflective when seen from below. Right: Also when seen from above.</figcaption></figure>



<p class="wp-block-paragraph">So, in order to add <em>refraction</em> to the ray tracer, we need three things:</p>



<ol class="wp-block-list">
<li>A <em>reflected</em> ray</li>



<li>A <em>refracted </em>(or: <em>transmitted)</em> ray, into the glass or water</li>



<li>A way to <em>blend</em> the two.</li>
</ol>



<p class="wp-block-paragraph">The reflection is easy: This is identical to the mirror functionality we already added.</p>



<p class="wp-block-paragraph">For the direction of a refracted ray we need to look at the work of an old Dutch scientist, named Willebrord Snel van Royen, better known as &#8216;Snellius&#8217;, or just &#8216;Snell&#8217;. Snell has a physics law named after him that looks like this:</p>



<p class="wp-block-paragraph"><span class="wp-katex-eq" data-display="false">\frac{sin \theta_i}{sin \theta_o} = \frac{v_1}{v_2}</span></p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Here, <span class="wp-katex-eq" data-display="false">\theta_i</span> (&#8220;theta i&#8221;) is the angle at which a ray arrives at a surface (relative to the normal); <span class="wp-katex-eq" data-display="false">\theta_o</span> is the angle at which the ray leaves the surface at the other side, and <span class="wp-katex-eq" data-display="false">v_1</span> and <span class="wp-katex-eq" data-display="false">v_2</span> are the speeds at which light travels on either side of the surface. Instead of <span class="wp-katex-eq" data-display="false">v_1</span> and <span class="wp-katex-eq" data-display="false">v_2</span> we can also use <span class="wp-katex-eq" data-display="false">n_1</span> and <span class="wp-katex-eq" data-display="false">n_2</span>, i.e. the <em>refraction indices</em> of the media on either sides of the surface.</p>



<p class="wp-block-paragraph">That&#8217;s great, but we are looking for a vector, not an angle. To obtain the refracted vector, we can borrow some formulas from the <a href="https://registry.khronos.org/OpenGL-Refpages/gl4/html/refract.xhtml">glsl reference manual</a>, which states that it is calculated as follows:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">k = 1 - eta * eta * (1 - dot(N, D) * dot(N, D));
if (k &lt; 0)
    R = 0;
else
    R = eta * D - (eta * dot(N, D) + sqrtf(k)) * N;</pre></div>



<p class="wp-block-paragraph">And that is actually useful for our purposes. Variable &#8216;eta&#8217;, by the way, is calculated as <span class="wp-katex-eq" data-display="false">n_1 / n_2</span>. For air, <span class="wp-katex-eq" data-display="false">n_1</span> is simply 1.0. For glass, <span class="wp-katex-eq" data-display="false">n_2</span> is approximately 1.46. So, when going from air to glass, eta is 1/1.46. But, in the opposite direction eta is 1.46/1. This is relevant when we leave a block of glass on the other side. </p>



<p class="wp-block-paragraph">Refractive indices of more materials can be found <a href="https://en.wikipedia.org/wiki/List_of_refractive_indices">here</a>.</p>



<p class="wp-block-paragraph">The final ingredient is the blending of energy returned by the reflected and refracted rays. Another scientist studied this topic: His name is Fresnel. His &#8216;Fresnel Equations&#8217; are intimidating, but luckily, someone (mr. Schlick) made a simpler approximation, which is gets pretty close:</p>



<p class="wp-block-paragraph"><span class="wp-katex-eq" data-display="false">f=R_0+(1-R_0)(1-(D \cdot N))^5</span>, where <span class="wp-katex-eq" data-display="false">R_0=(\frac{n_1-n_2}{n_1+n_2})^2</span></p>



<p class="wp-block-paragraph">We can now put everything together in the ray tracer. Let&#8217;s label the new &#8216;glass&#8217; material &#8216;<code>02</code>&#8216; in the scene, to differentiate it from the regular material &#8216;<code>00</code>&#8216; and the mirror material &#8216;<code>01</code>&#8216;. To make the green cube a glass cube we change its color to <code>0x02AAFFAA</code>. We then detect the new material in <code>Renderer::Trace</code>:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">if ((ray.voxel &gt;&gt; 24) == 2)
{
    // glass material
    // TODO
}</pre></div>



<p class="wp-block-paragraph">We start the new material code with specifying <span class="wp-katex-eq" data-display="false">n_1</span> and <span class="wp-katex-eq" data-display="false">n_2</span>. And note: If we hit the plane that separates air and glass from <em>within</em> the glass, we need to swap <span class="wp-katex-eq" data-display="false">n_1</span> and <span class="wp-katex-eq" data-display="false">n_2</span>. In the template, we can just &#8216;ask&#8217; the ray if this is the case.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float n1 = 1.0f, n2 = 1.46f; // ior for glass
if (ray.inside) swap( n1, n2 );</pre></div>



<p class="wp-block-paragraph">Next, we prepare for calculating the refracted ray direction. Efficiently calculating <code>k</code> requires some care. The dot product between <span class="wp-katex-eq" data-display="false">N</span> and <code>-ray.D</code> is used a few times and should thus be precalculated. Also note that, instead of the generic &#8216;std::powf&#8217; function (which is <em>very</em> costly), we use a simple function from the template to calculate the square of the dot product.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float d = dot( N, -ray.D );
float eta = n1 / n2;
float k = 1 - eta * eta * (1 - pow2f( d ));</pre></div>



<p class="wp-block-paragraph">Now we can trace the refracted ray, if <code>k</code> is greater than <code>0</code>.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 reflected( 0 ), refracted( 0 );
if (k &gt; 0)
{
    float3 R = eta * ray.D + (eta * d - sqrtf( k )) * N;
    refracted = Trace( Ray( I, R ), depth + 1 );
}</pre></div>



<p class="wp-block-paragraph">As discussed, glass also is reflective. This uses the same logic we have seen before.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 R = ray.D - 2 * N * d;
reflected = Trace( Ray( I, R ), depth + 1 );</pre></div>



<p class="wp-block-paragraph">And finally, we blend reflection and refraction using Fresnel. Something special happens when refraction is not possible: We get <em>total internal reflection</em>. In that case, the reflected ray gets a <span class="wp-katex-eq" data-display="false">1.0</span> weight. We can detect this situation by looking at variable <code>k</code>, which should be greater than <code>0</code>.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float R0 = pow2f( (n1 - n2) / (n1 + n2) );
float fresnel = k &gt; 0 ? R0 + (1 - R0) * pow5f( 1 - d ) : 1;
return albedo * (fresnel * reflected + (1 - fresnel) * refracted);</pre></div>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/glassworx.png" alt="" style="width:512px"/></figure>
</div>


<p class="wp-block-paragraph">And there it is&#8230; A pretty complex block, with light going in, changing direction, getting reflected on the inside, and so on. At each surface interaction the path splits off a reflected and refracted ray, so be gentle with that recursion depth!</p>



<p class="has-text-align-center wp-block-paragraph"> &#8211; o &#8211; </p>



<h2 class="wp-block-heading">Whitted</h2>



<p class="wp-block-paragraph">We now have a full implementation of the famous paper by Turner Whitted, which he wrote in 1980: &#8220;An Improved Illumination Model for Shaded Display&#8221;. You can find a copy of the paper <a href="https://www.cs.drexel.edu/~deb39/Classes/Papers/p343-whitted.pdf">here</a>. The groundbreaking idea of the paper is that we can &#8216;do graphics&#8217; by applying principles from the field of optics, including shadows, reflection and refraction. The technique is ever since known as <em>Whitted-style ray tracing</em>. Now you know!</p>



<p class="has-text-align-center wp-block-paragraph"> &#8211; o &#8211; </p>



<h2 class="wp-block-heading">Challenges</h2>



<p class="wp-block-paragraph"><strong>Challenge 1</strong>: Combine the concepts of this article with those from the first article. In short, add point lights and shadows, and make them work together with the recursive reflections and refractions.</p>



<p class="wp-block-paragraph"><strong>Challenge 2</strong>: The way we blended between refraction and reflection can also be applied to materials that are partially diffuse and partially reflective. Create a material for which a shadow ray <em>and </em>a reflection ray is cast, and blend the two layers using a weight of 50% for each.</p>



<p class="wp-block-paragraph"><strong>Challenge 3</strong>: The template comes with <a href="https://github.com/ocornut/imgui">ImGui</a> integration. Use this to make the refraction index of the glass configurable at run-time. Find a way to change properties of other materials via the interface as well.</p>



<h2 class="wp-block-heading">Etc.</h2>



<p class="wp-block-paragraph">If you want to share some of your work, consider posting on X about it. You can also follow me there <em>(<a href="https://twitter.com/j_bikker">@j_bikker</a>)</em>, or contact me at <a href="mailto:bikker.j@gmail.com">bikker.j@gmail.com</a>.</p>



<p class="wp-block-paragraph"><strong>Want to read more about computer graphics?</strong> Also on this blog:</p>



<ul class="wp-block-list">
<li><a href="https://jacco.ompf2.com/2022/04/13/how-to-build-a-bvh-part-1-basics/">How to build a BVH series</a></li>



<li><a href="https://jacco.ompf2.com/2020/04/07/speeding-up-lighthouse-2/">Speeding up the Lighthouse 2 renderer</a></li>



<li><a href="https://jacco.ompf2.com/2020/03/18/opt1profiling/">Software Optimization</a></li>
</ul>



<p class="wp-block-paragraph">Other articles in the &#8220;Ray Tracing with Voxels in C++&#8221; series:</p>



<ol class="wp-block-list">
<li><a href="https://jacco.ompf2.com/2024/04/24/ray-tracing-with-voxels-in-c-series-part-1/">Starting point: Voxel ray tracing template code. Lights and shadows.</a></li>



<li><strong>Whitted-style: Reflections, recursion, glass (this article).</strong></li>



<li><a href="https://jacco.ompf2.com/2024/05/08/ray-tracing-with-voxels-in-c-series-part-3/">Stochastic techniques: Anti-aliasing and soft shadows</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/15/ray-tracing-with-voxels-in-c-series-part-4/">Noise reduction: Stratification, blue noise</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/22/ray-tracing-with-voxels-in-c-series-part-5/">Converging under movement: Reprojection</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/29/ray-tracing-with-voxels-in-c-series-part-6/">Path tracing: Basics first; then: Importance Sampling</a>.</li>



<li>Denoising fundamentals.</li>



<li>Acceleration structures: Extending the grid to a multi-level grid.</li>



<li>Acceleration structures: Adding a TLAS.</li>
</ol>
]]></content:encoded>
					
					<wfw:commentRss>https://jacco.ompf2.com/2024/05/01/ray-tracing-with-voxels-in-c-series-part-2/feed/</wfw:commentRss>
			<slash:comments>7</slash:comments>
		
		
			</item>
		<item>
		<title>Ray Tracing with Voxels in C++ Series &#8211; Part 1</title>
		<link>https://jacco.ompf2.com/2024/04/24/ray-tracing-with-voxels-in-c-series-part-1/</link>
					<comments>https://jacco.ompf2.com/2024/04/24/ray-tracing-with-voxels-in-c-series-part-1/#comments</comments>
		
		<dc:creator><![CDATA[jbikker]]></dc:creator>
		<pubDate>Wed, 24 Apr 2024 12:43:02 +0000</pubDate>
				<category><![CDATA[Article]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Tutorial]]></category>
		<guid isPermaLink="false">https://jacco.ompf2.com/?p=1715</guid>

					<description><![CDATA[In this series we build a physically based renderer for a dynamic voxel world. From &#8216;Whitted-style&#8217; ray...]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">In this series we build a physically based renderer for a dynamic voxel world. From &#8216;Whitted-style&#8217; ray tracing with shadows, glass and mirrors, we go all the way to &#8216;unbiased path tracing&#8217; &#8211; and beyond, exploring advanced topics such as reprojection, denoising and blue noise. The accompanying source code is <a href="https://github.com/jbikker/voxpopuli">available on Github</a> and is written in easy-to-read &#8216;sane C++&#8217;.</p>



<p class="wp-block-paragraph">This series consists of nine articles. Contents:  <em>(tentative until finalized)</em></p>



<ol class="wp-block-list">
<li><strong>Starting point: Voxel ray tracing template code. Lights and shadows</strong> <strong>(this article).</strong></li>



<li><a href="https://jacco.ompf2.com/2024/05/01/ray-tracing-with-voxels-in-c-series-part-2/">Whitted-style: Reflections, recursion, glass</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/08/ray-tracing-with-voxels-in-c-series-part-3/">Stochastic techniques: Anti-aliasing and soft shadows</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/15/ray-tracing-with-voxels-in-c-series-part-4/">Noise reduction: Stratification, blue noise</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/22/ray-tracing-with-voxels-in-c-series-part-5/">Converging under movement: Reprojection</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/29/ray-tracing-with-voxels-in-c-series-part-6/">Path tracing: Basics first; then: Importance Sampling</a>.</li>



<li>Denoising fundamentals.</li>



<li>Acceleration structures: Extending the grid to a multi-level grid.</li>



<li>Acceleration structures: Adding a TLAS.   </li>
</ol>



<h2 class="wp-block-heading">In This Article&#8230;</h2>



<p class="wp-block-paragraph">In this first article we will use the bare-bones template and add some color to it, as well as lights, and shadows. Shadows will be calculated using rays to the light sources. If these concepts are already clear to you, feel free to skip to the <a href="#challenges"><strong>challenges</strong></a> at the end of the article, or to the next article <em>(once it is released)</em>: Each article starts with the same template code, so you can jump in at any point.</p>



<h2 class="wp-block-heading">Starting Point</h2>



<p class="wp-block-paragraph">For this series we will use a somewhat unusual starting point: a ready-made template that renders a basic image using ray tracing. The scene is a small voxel world, procedurally generated. You can find this template in <a href="https://github.com/jbikker/voxpopuli">its github repo</a>. It runs out-of-the-box on a Windows system: just open the .sln file in Microsoft Visual Studio <a href="https://visualstudio.microsoft.com/vs/community/">Community Edition</a> and press F5 to build and run it.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/barebones.png" alt="" style="width:414px;height:auto"/><figcaption class="wp-element-caption">Figure 1: Output of the unmodified template: 128³ voxels with color-coded normals, and 50 million rays per second.</figcaption></figure>
</div>


<p class="wp-block-paragraph"><em><strong>Note: </strong>Compared to starting &#8216;from scratch&#8217;, the template has the benefit that we quickly get to the interesting ray tracing topics: shadows, reflections, fancy cameras and so on. At the same time, the template is simple enough to make low-level optimizations worthwhile. Article 8 exploits this as we add a multi-level grid to improve the performance of the base code.</em></p>



<p class="has-text-align-center wp-block-paragraph">&#8211; o &#8211;</p>



<h2 class="wp-block-heading">A Brief Tour</h2>



<p class="wp-block-paragraph">In its pure form, <em>ray tracing</em> is a process that produces an image from a 3D scene by following the path that light takes, from a light source, to a camera, or rather: in the opposite direction.</p>



<figure class="wp-block-image size-large"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/shdsituation.png" alt=""/><figcaption class="wp-element-caption">Figure 2, left: primary rays finding the nearest object. Right: using shadow rays to establish light transport.</figcaption></figure>



<p class="wp-block-paragraph">This is shown in the left image. The camera (or eye) looks at pixels on a screen. This is simulated with a &#8216;ray&#8217;, i.e. a line of (potentially) infinite length, originating at the camera. The ray continues until it encounters an object. The first object along the ray is the object we &#8216;see&#8217; through the pixel. Some rays hit nothing; they disappear into the void and do not bring back any light. In that case we can plot a black pixel, or perhaps a blue one, to simulate the sky.</p>



<p class="wp-block-paragraph">You can find this functionality implemented in source file <code>renderer.cpp</code>, in the <code>Renderer::Tick</code> function. The code in this function loops over the pixels on the screen, creates a primary ray for each, and uses the <code>Renderer::Trace</code> function to determine what the color of the pixel should be. The <code>Renderer::Trace</code> function finds the nearest intersection of the ray and the scene. If nothing is found, it simply returns <code>float3(0)</code>, i.e. black. Otherwise, it calculates a color for the hitpoint, but this functionality is not complete yet.</p>



<p class="wp-block-paragraph"><em><strong>Note:</strong> We&#8217;re intentionally skipping details here. Line 31, for example: This line assigns each row of pixels to a thread, using OpenMP. This way, the renderer runs significantly faster on a multi-core CPU. And, on line 39, a floating point color is converted to an integer color. Monitors expect integer values, but ray tracing requires floating point colors for range and precision. More on that later.</em></p>



<p class="wp-block-paragraph">For the rays that did hit an object we now need to determine if light flows via that object. This is illustrated in the right image. New rays are created from the hitpoint to the light source. If these rays get to the light without encountering any obstructions, we know that the surface may reflect light, via the pixel, to the camera.</p>



<p class="wp-block-paragraph">Determining the flow of light via the object is what ray tracing is all about. Initially, the light is a simple <em>point light</em>, and the object has a simple material. But soon, we will be illuminating using many complex lights, and reflect via subtle materials. Light will travel via mirrors and through glass. The camera will have an aperture, which causes depth of field.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/mcrt.png" alt="" style="width:411px;height:auto"/><figcaption class="wp-element-caption">Figure 3: Minecraft with ray tracing effects.</figcaption></figure>
</div>


<p class="wp-block-paragraph">Rendering images like the above one is not all that hard. On top of that, we can do it in real-time, on a CPU. Have a look at the code in <code>scene.cpp</code>: The code in there is all that is needed to replicate the behavior of modern ray tracing enabled GPUs. It may not be the simplest code, but at 150-ish lines of code it is hardly a vast code base either.</p>



<p class="wp-block-paragraph">This concludes our brief tour. And now, it&#8217;s time to establish <em>light transport</em>.</p>



<p class="has-text-align-center wp-block-paragraph">&#8211; o &#8211; </p>



<h2 class="wp-block-heading">Into the Light</h2>



<p class="wp-block-paragraph">Let&#8217;s start by adding a light source to the world. The simplest light is a<em> point light:</em> all it needs is a <em>position </em>and a <em>color</em>. So, just above <code>Renderer::Trace</code> we add:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 pos( 1, 1, 1 );
float3 color( 1, 1, 1 );</pre></div>



<p class="wp-block-paragraph">A word about the light position <code>pos</code>: In the template, the voxel object occupies space between x=0..1, y=0..1 and z=0..1. The whole shape is thus a 1x1x1 cube. The size of the world can be changed in <code>scene.h</code>, where <code>WORLDSIZE</code> is set to <code>128</code>. Changing this value does however not change the size of the voxel object; it merely changes its resolution. Funny thing is: <em>that&#8217;s the same thing.</em> We can simply bring the camera closer to make the object <em>look</em> larger, or move it back to make it look smaller.</p>



<p class="wp-block-paragraph">So, a light at x=1, y=1 and z=1 is located on one of the corners of the voxel object. </p>



<p class="wp-block-paragraph">Note that the <em>color</em> of the light is also its <em>intensity:</em> Because we use floating point colors, a bright yellow light might have a color like <code>float3(100,100,20)</code>. Obviously, for a nearby light that would be blinding, but if the light is very far away, such a color is not extreme at all.</p>



<p class="wp-block-paragraph">The effect of light on a point on the surface of a voxel depends on four factors:</p>



<ol class="wp-block-list">
<li>The <em>distance</em> between the light and the surface point;</li>



<li>The <em>brightness</em> and <em>color</em> of the light source;</li>



<li>The <em>orientation</em> of the surface to the light;</li>



<li>The mutual <em>visibility</em> of the light and the surface point.</li>
</ol>



<p class="wp-block-paragraph">And, since we are interested in how much light the surface point reflects towards the camera, we must also take into account the <em>color</em> of the material (in ray tracing jargon: the <em>albedo</em>).</p>



<p class="wp-block-paragraph">Let&#8217;s see what information we have inside <code>Renderer::Trace</code> to work with.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 Renderer::Trace( Ray&amp; ray, int depth, int, int )
{
    scene.FindNearest( ray );
    if (ray.voxel == 0) return float3(0); // or a fancy sky color
    float3 N = ray.GetNormal();
    float3 I = ray.IntersectionPoint();
    float3 albedo = ray.GetAlbedo();
    return (N + 1) * 0.5f;
}</pre></div>



<p class="wp-block-paragraph">To calculate the <strong>distance </strong>between the light and the intersection point, we create a vector between the two positions, and take its length:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 L = pos - I;
float distance = length( L );</pre></div>



<p class="wp-block-paragraph">With this information we evaluate the first factor on our list: <em>Distance attenuation.</em> The strength of a light decreases by the squared distance, so we scale by <span class="wp-katex-eq" data-display="false">1/distance^2</span>.</p>



<p class="wp-block-paragraph">The vector to the light, <span class="wp-katex-eq" data-display="false">L</span>, is also used to take into account the <em>orientation </em>of the surface towards the light. For this we take the dot product between the surface normal <span class="wp-katex-eq" data-display="false">N</span> and the normalized vector <span class="wp-katex-eq" data-display="false">L</span>. This value becomes negative when the light is behind the surface, so we clamp it to zero.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float cosa = max( 0.0f, dot( N, normalize( L ) ) );</pre></div>



<p class="wp-block-paragraph">Putting everything together, we can now calculate the light reflected by the surface:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">return color * albedo * (1 / (distance * distance)) * cosa;</pre></div>



<p class="wp-block-paragraph"><code>Renderer::Trace</code> now produces the following image:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/newlight.png" alt="" style="width:527px;height:auto"/><figcaption class="wp-element-caption">Figure 4: Basic lighting on the voxels.</figcaption></figure>
</div>


<p class="wp-block-paragraph">The only thing missing is <em>shadows</em>. We need to find out if the light is visible from the intersection point.</p>



<p class="has-text-align-center wp-block-paragraph">&#8211; o &#8211; </p>



<h2 class="wp-block-heading">Into the Shadows</h2>



<p class="wp-block-paragraph">For that we use a new ray: the <em>shadow ray</em>. It&#8217;s a bit different from the primary ray that we cast from the camera through a pixel: instead of detecting the nearest object along an infinite line, a shadow ray merely detects an obstacle between two points. All it needs to give us is a yes/no answer: can we get there? And: The ray is just as long as the distance between the intersection point and the light; we are not interested in geometry beyond the light source.</p>



<p class="wp-block-paragraph">The template provides shadow ray functionality, in the form of the <code>Scene::IsOccluded</code> function. It takes a <code>Ray</code>, and it returns a boolean.</p>



<p class="wp-block-paragraph">We can set up the shadow ray and cast it into the scene:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">Ray shadowRay( I, L, distance );
if (scene.IsOccluded( shadowRay )) return float3( 0 );</pre></div>



<p class="wp-block-paragraph">Placing this before the line that returned the reflected light gets us shadows.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/blackvox.png" alt="" style="width:552px;height:auto"/><figcaption class="wp-element-caption">Figure 5: Lighting and shadows.</figcaption></figure>
</div>


<p class="wp-block-paragraph">As you can see, there is a lot of pitch-black pixels: the &#8216;sky&#8217; is black, and so are the shadows. Fixing the sky is easy: we can for example return <code>float3( 0.7f, 0.8f, 1 )</code> instead of <code>float3( 0 )</code>. To fix the black shadows, we should add <em>more</em> lights. With just the single source of light, blackness is a logical consequence. See for example this photo of Saturn, which is also illuminated (almost exclusively) by a single point light.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/nasa.png" alt="" style="width:513px;height:auto"/><figcaption class="wp-element-caption">Figure 6: Saturn illuminated by the sun, with (almost) hard shadows on the rings. Image: JPL/NASA</figcaption></figure>
</div>


<p class="wp-block-paragraph">Scenes on Earth rarely have pitch black shadows. There is always a source of light: the sky, distant light sources or subtle reflections between objects. How to render this properly is a topic for another day.</p>



<p class="has-text-align-center wp-block-paragraph">&#8211; o &#8211; </p>



<h2 class="wp-block-heading">Beyond Black and White</h2>



<p class="wp-block-paragraph">The pictures we have rendered so far are all black and white. This is inevitable: The light we added is white, and the voxels are all white, since that is really the only color ever returned by <code>Ray::GetAlbedo()</code>. To do something about this, we have to look into the Creation of the World.</p>



<p class="wp-block-paragraph">This monumental event is handled by the code in the <code>Scene</code> constructor, which starts on line 23 of file <code>scene.cpp</code>. The world in the template consists of 128x128x128 voxels. Each voxel stores a 32-bit value. If this value is <code>0</code>, the voxel is considered to be empty space. All other voxels are set to <code>0xFFFFFF</code>, which in a HTML editor would be the color white. We can swap this uniform whiteness for an orange gradient based on the y-coordinate in the world:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">Set( x, y, z, n &gt; 0.09f ? 0x020101 * y : 0 );</pre></div>



<p class="wp-block-paragraph">Together with a slightly yellow light source and a blue sky, the world now looks a lot nicer.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/orangevox.png" alt="" style="width:572px;height:auto"/><figcaption class="wp-element-caption">Figure 7: Shading, shadows and better colors.</figcaption></figure>
</div>


<p class="wp-block-paragraph">It&#8217;s time to finish this article. In the next section you will find some (totally optional) challenges to practice with the theory presented here. In the next article we will add reflections, glass and a more realistic sky to the world.</p>



<p class="has-text-align-center wp-block-paragraph">&#8211; o &#8211; </p>



<h2 class="wp-block-heading" id="challenges">Challenges</h2>



<p class="wp-block-paragraph"><strong>Challenge 1:</strong> Increase the resolution of the world to 256x256x256. Add three freely floating cubes of 16x16x16 voxels each to the world: one green, one red, one blue cube. <strong>Note:</strong> Generating the world will now take pretty long: it will help to cache the world to disk and load it from a file on subsequent runs.</p>



<p class="wp-block-paragraph"><strong>Challenge 2:</strong> Add support for multiple light sources to <code>Renderer::Trace</code>. Use this to add a red, a green and a blue light. Demonstrate that overlapping the three light colors creates white light. Make the lights dynamic and give them interesting paths.</p>



<p class="wp-block-paragraph"><strong>Challenge 3</strong>: Replace the world generation code by something creative. This could be a mathematical shape, or a 3D room, or something you load from a <a href="https://ephtracy.github.io/">MagicaVoxel</a> file.</p>



<p class="wp-block-paragraph"><strong>Challenge 4:</strong> Produce a minimalist game in the voxel world. For example: Recreate <a href="https://www.ponggame.org/">Pong</a>. Later on, the dynamic game world will be a great test scenario for newly added functionality.</p>



<p class="has-text-align-center wp-block-paragraph">&#8211; o &#8211; </p>



<h2 class="wp-block-heading">Etc.</h2>



<p class="wp-block-paragraph">If you want to share some of your work, consider posting on X about it. You can also follow me there <em>(<a href="https://twitter.com/j_bikker">@j_bikker</a>)</em>, or contact me at <a href="mailto:bikker.j@gmail.com">bikker.j@gmail.com</a>.</p>



<p class="wp-block-paragraph"><strong>Want to read more about computer graphics?</strong> Also on this blog:</p>



<ul class="wp-block-list">
<li><a href="https://jacco.ompf2.com/2022/04/13/how-to-build-a-bvh-part-1-basics/">How to build a BVH series</a></li>



<li><a href="https://jacco.ompf2.com/2020/04/07/speeding-up-lighthouse-2/">Speeding up the Lighthouse 2 renderer</a></li>



<li><a href="https://jacco.ompf2.com/2020/03/18/opt1profiling/">Software Optimization</a></li>
</ul>



<p class="wp-block-paragraph">Other articles in the &#8220;Ray Tracing with Voxels in C++&#8221; series:</p>



<ol class="wp-block-list">
<li><strong>Starting point: Voxel ray tracing template code. Lights and shadows</strong> <strong>(this article).</strong></li>



<li><a href="https://jacco.ompf2.com/2024/05/01/ray-tracing-with-voxels-in-c-series-part-2/">Whitted-style: Reflections, recursion, glass</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/08/ray-tracing-with-voxels-in-c-series-part-3/">Stochastic techniques: Anti-aliasing and soft shadows</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/15/ray-tracing-with-voxels-in-c-series-part-4/">Noise reduction: Stratification, blue noise</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/22/ray-tracing-with-voxels-in-c-series-part-5/">Converging under movement: Reprojection</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/29/ray-tracing-with-voxels-in-c-series-part-6/">Path tracing: Basics first; then: Importance Sampling</a>.</li>



<li>Denoising fundamentals.</li>



<li>Acceleration structures: Extending the grid to a multi-level grid.</li>



<li>Acceleration structures: Adding a TLAS.    </li>
</ol>
]]></content:encoded>
					
					<wfw:commentRss>https://jacco.ompf2.com/2024/04/24/ray-tracing-with-voxels-in-c-series-part-1/feed/</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>Writing an MSX2 game&#8230; in 2023 &#8211; PART 1</title>
		<link>https://jacco.ompf2.com/2023/09/14/writing-an-msx2-game-in-2023-part-1/</link>
					<comments>https://jacco.ompf2.com/2023/09/14/writing-an-msx2-game-in-2023-part-1/#comments</comments>
		
		<dc:creator><![CDATA[jbikker]]></dc:creator>
		<pubDate>Thu, 14 Sep 2023 06:58:26 +0000</pubDate>
				<category><![CDATA[Article]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[MSX]]></category>
		<category><![CDATA[Tutorial]]></category>
		<guid isPermaLink="false">https://jacco.ompf2.com/?p=1610</guid>

					<description><![CDATA[One day before writing this I submitted a game to the MSXDev&#8217;23 contest. &#8220;Eggy&#8217;s Maze&#8221; will be...]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">One day before writing this I submitted a game to the <a href="https://www.msxdev.org/msxdev23/">MSXDev&#8217;23 contest</a>. &#8220;Eggy&#8217;s Maze&#8221; will be the 15th entry to the competition, with almost two months to go. Last year&#8217;s winner, &#8220;<a href="https://www.msxdev.org/2022/10/05/msxdev22-31-lillys-saga-the-stones-of-evergreen/">Lilly&#8217;s Saga</a>&#8220;, is on sale as a <a href="https://cotegamers.com/shop/en/accueil/142-lilly-s-saga-the-stones-of-evergreen.html">physical cartridge</a>, just like many other <a href="https://cotegamers.com/shop/en/35-msxmsx2">new games</a> for the 1984 platform that MSX is. My favorite retro machine is not an exception either; people are writing software for the <a href="https://youtu.be/WHy7DR-9QwI?list=PLxOanVBhqd3tifbfdE3mgtIgpBmpij6qp">ZX-Spectrum</a> and <a href="https://www.lemonamiga.com/games/list.php?list_year=2023&amp;list_hardware=AGA">Amiga</a> as well as the <a href="https://www.lemon64.com/games/list.php?list_year=2023">C64</a> and many other platforms, and there&#8217;s even new hardware being developed (<a href="https://msxmakers.design.blog/proyectos/">MSX</a>, <a href="https://www.specnext.com/">ZX-Spectrum</a>, <a href="https://wereallgeeks.wordpress.com/2023/04/06/diy_c64/">C64</a>).</p>



<p class="wp-block-paragraph"><em>Why?</em></p>



<p class="wp-block-paragraph">Nostalgia is a big factor, obviously. Or, <a href="https://www.theguardian.com/games/2021/sep/15/kids-raised-in-the-digital-era-are-yearning-for-this-the-people-making-new-games-for-old-consoles">experiencing computer history</a>, rather than just collecting it. But also: the challenge of making something work on hardware that was not remotely designed for it. Did you know that you can play <a href="https://doom.fandom.com/wiki/Game_Boy_Advance">Doom on a GBA</a>, and <a href="https://www.calculatorti.com/ti-games/ti-83-plus-ti-84-plus/mirageos/wolfenstein-3d/">Wolfenstein 3D on a TI-83</a> calculator (well, sort of)?</p>



<p class="wp-block-paragraph">Or perhaps it&#8217;s just about building something of a reasonable scale, all by yourself, without deadlines. A hobby. This is not about improving the world or paying the bills. It does bring a sense of power though: internet is far better than the smudgy magazines and manuals of the past, and PCs (with their emulators, cross-compilers and multiple monitors) are mighty development machines. It&#8217;s not hard to do <em>much </em>better than what was possible in the 80s.</p>



<p class="wp-block-paragraph">My point is: I may not be completely out of my mind for trying this. So, with this apologetic introduction, let&#8217;s dive in the main topic: Writing an MSX2 game&#8230; In 2023.</p>



<h2 class="wp-block-heading">Hardware</h2>



<p class="wp-block-paragraph">The MSX standard was introduced in 1983. It was a bit different than other offerings of the time: Like the early PCs, it was extendable and backed by multiple vendors.</p>



<figure class="wp-block-image size-large"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/msx1.jpg" alt=""/></figure>



<p class="wp-block-paragraph">An MSX computer (as well as MSX2 and MSX2+ successors) is powered by a Zilog Z80A processor, running at 3.58MHz, the same CPU used in the ZX-Spectrum, TRS-80, Amstrad CPC and others. To get a sense of how it compares to a modern CPU: It can do <em>at most </em>1 million instructions per second, operate on at most 16 bits at a time, it doesn&#8217;t support floating point numbers at all, and it has no cache. It can also only address 64KB of memory. Luckily, the MSX standard lets you swap chunks of 16KB ROM/RAM in and out of that 64KB range, to get access to more memory, if needed.</p>



<p class="wp-block-paragraph">For graphics, another common processor of the era is used: The Texas Instruments TMS9918, which was already battle-tested in the <a href="https://www.retrogames.cz/konzole_SegaSG1000.php">SEGA SG-1000</a>. This is a reasonably advanced chip, which supports tile mapped graphics modes and hardware sprites. The MSX2 uses a revamped version of this chip, the Yamaha <a href="https://www.msx.org/wiki/Yamaha_V9938">V9938</a>. It adds more sprites, but also color palettes and more versatile graphics modes. Understanding and programming this chip is probably the main challenge when writing games.</p>



<p class="wp-block-paragraph">Sound on the MSX is handled by a 3-voice &#8216;PSG&#8217; (programmable sound generator), the <a href="https://en.wikipedia.org/wiki/General_Instrument_AY-3-8910">AY-3-8910</a>. This is a rather basic chip, so it was rather common to add a sound chip via the cartridge slot. Many Konami games did this.</p>



<p class="wp-block-paragraph">So, in short: one painfully slow CPU, a tiny memory pool, and simple coprocessors for graphics and sound. How does one program such a beast if any decent level of performance is required?</p>



<h2 class="wp-block-heading">Software</h2>



<p class="wp-block-paragraph">&#8220;Back in de days&#8221; it was common to write software straight in assembler. The alternative was BASIC, the programming language that was built into many homecomputers of the era. BASIC was executed using an interpreter, making it impractically slow for many applications. Assembler on the other hand is hard to use, especially without today&#8217;s emulators.</p>



<p class="wp-block-paragraph">But, things have changed. Assembler for Z80A processors can now be generated by the &#8216;small device C compiler&#8217;, <a href="https://sdcc.sourceforge.net/">SDCC</a>, which reached version 4.3.0 recently and is quite mature. It runs on modern PCs; the actual retro hardware will thus only be needed to test the final code. SDCC lets you use inline assembly code for performance-critical parts, but it is rather great that at least the application skeleton can now be written in efficient C code.</p>



<p class="wp-block-paragraph">Besides SDCC, there is are several accurate emulators for the MSX platform (and all common extensions). The most well-known emulators (for PC) are <a href="https://openmsx.org/">OpenMSX</a>, <a href="https://www.bluemsx.com/">BlueMSX</a> and <a href="https://webmsx.org/">WebMSX</a>.</p>



<p class="wp-block-paragraph">There are also debuggers. The well-known <a href="https://emulicious.net/">Emulicious</a> has support for MSX and MSX2 (besides other Z80A platforms) and will talk directly to Visual Studio while it executes the Z80A code.</p>



<p class="wp-block-paragraph">The final important piece of software is <a href="https://github.com/aoineko-fr/MSXgl">MSXgl</a>, a library of functions that make it easy to control the hardware. It can also serve as a library of knowledge about the video processor and memory system. The code truly is a treasure trove for MSX game developers.</p>



<p class="wp-block-paragraph">Although the PC-based C compiler, emulators, debugger and libraries make it relatively easy to develop for the ancient platform, it still remains a significant challenge. Writing code without std::vector, uint_64 and float is difficult; debugging the subtleties of the video hardware can be a nightmare with finicky timing issues, hardcoded special-purpose values, and of course those tiny memories.</p>



<h2 class="wp-block-heading">Let&#8217;s do this</h2>



<p class="wp-block-paragraph">Enough introduction, let&#8217;s compile something for MSX. Follow the steps below to produce your first ROM.</p>



<ol class="wp-block-list">
<li>Download the MSXgl <a href="https://github.com/aoineko-fr/MSXgl/archive/refs/heads/main.zip">source package</a> from github.</li>



<li>Extract the contents of the resulting MSXgl-main.zip to a folder, e.g. <code>c:\projects</code>.</li>



<li>Open a command prompt in folder <code>c:\projects\template_msx2</code>.</li>



<li>Execute <code>build.bat</code>.</li>
</ol>



<p class="wp-block-paragraph">The build.bat script will invoke the SDCC build system on MSXgl library files and the source files in the <code>template_msx2</code> folder (<code>template.c, template.h</code>). It produces a <code>.rom</code> file in the &#8217;emul/rom&#8217; folder. This ROM can now be executed using WebMSX: </p>



<ol class="wp-block-list">
<li>Navigate to <a href="https://webmsx.org/">webmsx.org</a></li>



<li>In Windows explorer, drag <code>template.rom</code> to the WebMSX tab in your browser.</li>
</ol>



<p class="wp-block-paragraph">If this all worked (it should), you can try to make life easier by automatically deploying compiled ROM files to a emulator installed on your machine. Edit <code>project_config.js</code> to suit your needs, but be prepared to spend some time setting up everything correctly.</p>



<details class="wp-block-details is-layout-flow wp-block-details-is-layout-flow"><summary>Click here to learn how to use OpenMSX to deploy your ROM.</summary>
<p class="wp-block-paragraph">While WebMSX works well for most ROMs, dragging a ROM file from a folder to a browser tab is cumbersome. To alleviate this, you can install OpenMSX to the tools folder in <code>c:\projects\MSXgl-main</code>. First, <a href="https://github.com/openMSX/openMSX/releases/download/RELEASE_19_1/openmsx-19.1-windows-vc-x64-bin.zip">download OpenMSX</a>. Add a folder <code>OpenMSX</code> to the <code>tools</code> folder and add the contents of the downloaded zip file to it. Then, edit <code>default_config.js</code> in <code>c:\projects\MSXgl-main\projects</code>: disable line 41, and enable line 42 to use OpenMSX. And finally, in the <code>template_msx2</code> folder, edit <code>project_config.js</code> to change line 18 to <code>DoRun = true;</code> . Now <code>built.bat</code> will run your ROM in OpenMSX, if there are no errors.</p>
</details>



<h2 class="wp-block-heading">Moving in</h2>



<p class="wp-block-paragraph">Now that all the tools are operational, we can start replacing the template code by our own. Here&#8217;s a minimal application that will draw a red square on the screen:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">#include "msxgl.h"
void main()
{
	VDP_SetMode(VDP_MODE_GRAPHIC4);
	for( u8 y = 50; y &lt; 100; y++ )
		for( u8 x = 25; x &lt; 50; x++ )
			VDP_Poke_128K(0x99, x + y * 128, 0 );
	while(true) {}
}</pre></div>



<p class="wp-block-paragraph">Paste this code in <code>template.c</code> (overwriting existing content), and build the ROM. On my machine this produces the following output:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="746" src="https://jacco.ompf2.com/wp-content/uploads/2023/09/image-1024x746.png" alt="" class="wp-image-1623" style="width:523px;height:381px" srcset="https://jacco.ompf2.com/wp-content/uploads/2023/09/image-1024x746.png 1024w, https://jacco.ompf2.com/wp-content/uploads/2023/09/image-300x218.png 300w, https://jacco.ompf2.com/wp-content/uploads/2023/09/image-768x559.png 768w, https://jacco.ompf2.com/wp-content/uploads/2023/09/image-897x653.png 897w, https://jacco.ompf2.com/wp-content/uploads/2023/09/image-360x262.png 360w, https://jacco.ompf2.com/wp-content/uploads/2023/09/image.png 1148w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p class="wp-block-paragraph">There is a red square, but there&#8217;s also some garbage. The easiest way to get rid of that is by adding one line, just before the <code>for</code> loops, that reads: <code>VDP_ClearVRAM();</code> .</p>



<p class="wp-block-paragraph">The code is illustrating many aspects of MSX graphics programming. There is some typical C code: a main function, and the inclusion of the MSXgl library. At the end of main, the code simply &#8216;hangs&#8217; using an infinite while loop; we produce a ROM after all so there&#8217;s nothing to return to at the end of the program.</p>



<p class="wp-block-paragraph">A more interesting line is the VDP_SetMode command, which calls a function in MSXgl. The code for this function can be found in <code>c:\projects\MSXgl-main\engine\src\vdp.c</code>. At the time of writing, it starts on line 1501. The constant <code>VDP_MODE_GRAPHIC4</code> refers to one of the graphics modes of the V9938 chip. Detailed info about this mode can be found in the MSX2 Technical Handbook, in <a href="https://konamiman.github.io/MSX2-Technical-Handbook/md/Chapter4a.html#36-graphic-4-mode">Chapter 4</a>. Here we read that GRAPHIC4 is an MSX2-only mode, where we have 256&#215;212 pixels, each of which can be set to one of 16 colors. The 16 colors are stored in a <em>palette</em>. Each palette entry can be picked from 512 unique colors. The manual also specifies that the &#8216;pattern table&#8217; (in this case: the pixel buffer) for this mode starts at address 0 in VRAM. This table holds 2 pixels per byte; a full screen is thus 128&#215;212 bytes, so 26.5KB. By the way: We can change the address of the pattern table, which will be useful if we want to use double buffering later on.</p>



<p class="wp-block-paragraph">Two pixels per byte means: each pixel takes 4 <em>bits</em>. However, we can only write whole <em>bytes</em> to VRAM. So, to plot 1 pixel, we need to determine if its x-coordinate is odd or even. If it is even, the color goes to the left half of the byte, otherwise it is stored in the right half. When plotting one pixel, the other half must remain unchanged, so we first must obtain its contents from VRAM. Putting it all together, plotting one pixel becomes pretty complex:</p>



<p class="wp-block-paragraph">Note that bit fiddling is not optional on this platform; it is ubiquitous. And not just that: variable types are carefully chosen to be as simple as possible. An address must be 16 bit, but has no sign, so we use <code>u16</code>. A color needs only 4 bits, and no sign, so we pick the smallest type: <code>u8</code>. Odd or even is established by looking at the lowest bit (here: <code>x &amp; 1</code>): all odd numbers have this set to 1. Moving data to the left side of a byte: <code>c &lt;&lt; 4</code>. And so on. It grows on you, but initially, this leads to some pretty alien code.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void Plot( const u8 x, const u8 y, const u8 c /* 0..15 */)
{
	const u16 a = x / 2 + y * 128;
	const u8 v = VDP_Peek_128K( a, 0 );
	if (x &amp; 1) VDP_Poke_128K( (v &amp; 0xF0) + c, a, 0 );
	else VDP_Poke_128K( (v &amp; 15) + (c &lt;&lt; 4), a, 0 );
}</pre></div>



<details class="wp-block-details is-layout-flow wp-block-details-is-layout-flow"><summary>Click here to learn how to change the palette.</summary>
<p class="wp-block-paragraph">MSX computers have a default palette, which we used in the above example. In this palette, color 9 is bright red. You can find the full palette <a href="https://paulwratt.github.io/programmers-palettes/HW-MSX/HW-MSX-palettes.html">here</a>. To change the palette, use the MSXgl function <code>VDP_SetPalette</code>. This takes a <code>u16</code> array of 15 elements (palette 0 is not used), in which each 16-bit value encodes one of the 512 possible colors. To construct a color, pick a value between 0..7 for red, green and blue, and combine them as follows: <code>entry=(green&lt;&lt;8)+(red&lt;&lt;4)+blue</code>. For example: In hexadecimal numbers, white is 0x777, red is 0x070, blue is 0x007 and yellow is 0x770.</p>
</details>



<h2 class="wp-block-heading">Speed</h2>



<p class="wp-block-paragraph">Drawing the red rectangle using the custom Plot function is <em>slow</em>. In the emulator, the square visibly builds up. Obviously, this is not the way to draw interactive game content. The original code was a lot faster by the way:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">for( u8 y = 50; y &lt; 100; y++ )
		for( u8 x = 25; x &lt; 50; x++ )
			VDP_Poke_128K(0x99, x + y * 128, 0 );</pre></div>



<p class="wp-block-paragraph">That is because it always plots two pixels at a time. But even that code is not fast enough to render the square in real-time. We can do better, but before we attempt that, let&#8217;s establish what we <em>can</em> do in a single frame. For that, we need to have some way to measure performance.</p>



<p class="wp-block-paragraph">The code that we overwrite contained an important line:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">VDP_EnableVBlank(TRUE);</pre></div>



<p class="wp-block-paragraph">This enables an <em>interrupt handler</em>. Interrupts are hardware events that the Z80A CPU can respond to. Such events include key presses, but also the <em>vertical retrace</em> (a.k.a. <em>vsync</em>), which is the event that the electron beam on a <em>cathode ray tube</em> (CRT) moves back to the top of the screen to start a new frame. That&#8217;s not relevant for modern monitors, but the event is still there, and it happens 50 (or 60) times per second. Synchronizing to that event lets us write code that runs at a consistent speed.</p>



<p class="wp-block-paragraph">The nice thing about the VBlank interrupt is: We can wait for it. For this, we use the command Halt(). The new code, with some changes to make the rectangle move:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">#include "msxgl.h"
void main()
{
	VDP_SetMode(VDP_MODE_GRAPHIC4);
	u8 pos = 0;
	while (true)
	{
		for( u8 y = 50; y &lt; 100; y++ )
		{
			// clear pixel on left side of square
			VDP_Poke_128K(0, pos + y * 128, 0 );
			// draw a horizontal line of pixels
			for( u8 x = 1; x &lt; 25; x++ )
			VDP_Poke_128K(0x99, x + pos + y * 128, 0 );
		}
		Halt();
		pos++;
	}
}</pre></div>



<p class="wp-block-paragraph">Clearing the screen each frame is obviously not an option, so the above code only removes pixels on the left side of the rectangle. That is of course something that would also work on the right side: many pixels do not need to be changed from frame to frame. It&#8217;s a simple change:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">// draw a horizontal line of pixels
		if (pos == 0) for( u8 x = 1; x &lt; 25; x++ )
			VDP_Poke_128K(0x99, x + pos + y * 128, 0 );
		else
			VDP_Poke_128K(0x99, 24 + pos + y * 128, 0 );</pre></div>



<p class="wp-block-paragraph">This time, the rectangle <em>almost</em> moves smoothly. Sadly, the <em>tearing</em> tells us that even this small amount of work is not completed within one frame. If we optimize the code a bit, we get close:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">while (true)
	{
		u16 a = pos + 50 * 128;
		for( u8 y = 50; y &lt; 100; y++ )
		{
			// clear pixel on left side of square
			VDP_Poke_128K(0, a, 0 );
			// draw a horizontal line of pixels
			if (pos == 0) for( u8 x = 1; x &lt; 25; x++ )
				VDP_Poke_128K(0x99, a + pos, 0 );
			else
				VDP_Poke_128K(0x99, a + 24, 0 );
			a += 128;
		}
		Halt();
		pos++;
	}</pre></div>



<p class="wp-block-paragraph">In this code, variable <code>a</code> holds the start address of a line of pixels for the rectangle. The top-left corner is on pixel <code>pos + 50 * 128</code>; after that we simply add 128 to a to get to the next line. As a result, the formulas in the VDP_Poke calls are much simpler, and that clearly helps.</p>



<p class="wp-block-paragraph">We reach our goal with one more improvement:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">#include "msxgl.h"
void main()
{
	VDP_SetMode(VDP_MODE_GRAPHIC4);
	// clear the screen to black (palette entry 1)
	for( u8 y = 0; y &lt; 212; y++ ) VDP_FillVRAM_128K( 0x11, y * 128, 0, 128 );
	// draw initial rectangle
	for( u8 y = 50; y &lt; 100; y++ ) VDP_FillVRAM_128K( 0x99, y * 128, 0, 25 );
	// move the rectangle
	u8 pos = 0;
	while (true)
	{
		u16 a = pos + 50 * 128;
		for( u8 y = 50; y &lt; 100; y++, a += 128 )
		{
			// clear pixel on left side of square
			VDP_Poke_128K(0x11, a, 0 );
			// draw a pixel on the right side
			VDP_Poke_128K(0x99, a + 24, 0 );
		}
		Halt();
		pos++;
	}
}</pre></div>



<p class="wp-block-paragraph">This time, after clearing the screen, a full rectangle is drawn once; after that, we can unconditionally remove two pixels on the left, and add two on the right. Skipping the conditions that we had before matters: This time the work is done without tearing.</p>



<p class="wp-block-paragraph">So, it seems that the work fits in a single frame. But, we can be more precise than that.</p>



<p class="wp-block-paragraph">The MSXgl command <code>VDP_SetColor</code> lets us set the screen border color. It defaults to color 0 (which is apparently blue), but we can also make it red, like the rectangle:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">VDP_SetColor(9);</pre></div>



<p class="wp-block-paragraph">We can then change it to green once we are done working on the rectangle, just before the <code>Halt()</code>:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">VDP_SetColor(3);</pre></div>



<p class="wp-block-paragraph">If we set the border to red at the start of the body of the while loop, and change it to green just before the <code>Halt()</code>, we get an interesting effect:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="748" src="https://jacco.ompf2.com/wp-content/uploads/2023/09/image-1-1024x748.png" alt="" class="wp-image-1632" style="width:523px;height:382px" srcset="https://jacco.ompf2.com/wp-content/uploads/2023/09/image-1-1024x748.png 1024w, https://jacco.ompf2.com/wp-content/uploads/2023/09/image-1-300x219.png 300w, https://jacco.ompf2.com/wp-content/uploads/2023/09/image-1-768x561.png 768w, https://jacco.ompf2.com/wp-content/uploads/2023/09/image-1-897x655.png 897w, https://jacco.ompf2.com/wp-content/uploads/2023/09/image-1-360x263.png 360w, https://jacco.ompf2.com/wp-content/uploads/2023/09/image-1.png 1180w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p class="wp-block-paragraph">The border color now is an indication of the frame time used for updating the rectangle. And, apparently only about half a frame is used, so we have time for other things. Note the red border at the bottom: the vertical retrace interrupt happens once the last pixels have been send to the screen. For the MSX system, the bottom of the screen is the bottom of the black rectangle. The monitor is still emitting the border color beyond that point, but that color gets changed.</p>



<h2 class="wp-block-heading">Finally</h2>



<p class="wp-block-paragraph">We covered quite some ground: Something runs on MSX <em>(well, on an emulator)</em>, and we can specify what it is in plain C. We plotted pixels in GRAPHIC4 mode and made them fast using some optimization tricks. It is clearly very important to write compact code that is easy to digest for the Z80A CPU.</p>



<p class="wp-block-paragraph">To move a bit more per frame we will need additional tricks. The next article will explain how to add sprites to the screen. We will also investigate a more efficient screen mode.</p>



<p class="wp-block-paragraph">Until that time: leave a comment below if something was unclear.</p>



<p class="wp-block-paragraph">Happy retro coding!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://jacco.ompf2.com/2023/09/14/writing-an-msx2-game-in-2023-part-1/feed/</wfw:commentRss>
			<slash:comments>9</slash:comments>
		
		
			</item>
		<item>
		<title>How to build a BVH &#8211; part 9b: Massive</title>
		<link>https://jacco.ompf2.com/2022/06/15/how-to-build-a-bvh-part-9b-massive/</link>
					<comments>https://jacco.ompf2.com/2022/06/15/how-to-build-a-bvh-part-9b-massive/#comments</comments>
		
		<dc:creator><![CDATA[jbikker]]></dc:creator>
		<pubDate>Wed, 15 Jun 2022 09:30:36 +0000</pubDate>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Demo]]></category>
		<category><![CDATA[Source Code]]></category>
		<category><![CDATA[Tutorial]]></category>
		<guid isPermaLink="false">https://jacco.ompf2.com/?p=1445</guid>

					<description><![CDATA[In this series we explore the wonderful world of the bounding volume hierarchy: the mysterious data structure...]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">In this series we explore the wonderful world of the <em>bounding volume hierarchy:</em> the mysterious data structure that enables real-time ray tracing on recent GPUs, in complex, animated scenes. Despite the broad adoption of ray tracing in games, in-depth understanding of the underlying technology seems to be reserved to a select few. In this article we show how a proper BVH is implemented without support from DXR / RTX / OptiX / Vulkan, in easy-to-read &#8216;sane C++&#8217;. Whether this is actually useful for you, or just interesting as background information, depends on your needs, obviously.</p>



<p class="wp-block-paragraph">This series consist of ten articles. For each article, full source code is <a href="https://github.com/jbikker/bvh_article">available on Github</a>, in easy-to-read &#8216;Sane C++&#8217;. Contents:</p>



<ol class="wp-block-list">
<li><a href="https://jacco.ompf2.com/2022/04/13/how-to-build-a-bvh-part-1-basics/">Basics: data structure, simple construction and ray traversal</a>.</li>



<li><a href="https://jacco.ompf2.com/2022/04/18/how-to-build-a-bvh-part-2-faster-rays/">Faster rays: the Surface Area Heuristic and ordered traversal</a>.</li>



<li><a href="https://jacco.ompf2.com/2022/04/21/how-to-build-a-bvh-part-3-quick-builds/">Faster construction: binned BVH building</a>.</li>



<li><a href="https://jacco.ompf2.com/2022/04/26/how-to-build-a-bvh-part-4-animation/">BVHs for animated models: refitting and rebuilding</a>.</li>



<li><a href="https://jacco.ompf2.com/2022/05/07/how-to-build-a-bvh-part-5-tlas-blas/">BVHs for animated scenes: the top-level BVH</a>.</li>



<li><a href="https://jacco.ompf2.com/2022/05/13/how-to-build-a-bvh-part-6-all-together-now/">TLAS &amp; BLAS part 2 – all together now</a>.</li>



<li><a href="https://jacco.ompf2.com/2022/05/20/how-to-build-a-bvh-part-7-consolidate/">Consolidating, part 1: ray tracing textured and shaded meshes</a>.</li>



<li><a href="https://jacco.ompf2.com/2022/05/27/how-to-build-a-bvh-part-8-whitted-style/">Consolidating, part 2: Whitted-style ray tracing</a>.</li>



<li><a href="https://jacco.ompf2.com/2022/06/03/how-to-build-a-bvh-part-9a-to-the-gpu/">OpenCL: GPU ray tracing, part 1</a>.</li>



<li><strong>OpenCL: GPU ray tracing, part 2 (SERIES FINAL, this article).</strong></li>



<li>P.S.: Concurrency <em>(under construction)</em></li>
</ol>



<p class="wp-block-paragraph" id="block-0335045c-892a-4222-aee1-ff87a91ce61a">This is the end. Last time we ported the ray tracing code to the GPU, or at least: BLAS traversal and basic visualization. All that is left to do is some cleaning up, and TLAS traversal. With that in place, we will have the same power on CPU and GPU, in terms of animation: we will be able to specify a transform (rotate, translate, scale) for each instance, on top of the capability to rebuild or refit meshes on-the-fly.</p>



<p class="wp-block-paragraph">In this final article we implement TLAS traversal and the recursive Whitted-style ray tracer on the GPU. For that a few details need to be sorted out. The final product deserves a fitting final demo, for which I will take some inspiration from the <a href="https://www.youtube.com/watch?v=J513nnZyh5o">work of two of my students</a> at Utrecht University.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/logsof-1024x374.jpg" alt="" style="width:512px"/><figcaption class="wp-element-caption">Dragons. Lots of dragons.</figcaption></figure>
</div>


<h2 class="wp-block-heading">Preparations</h2>



<p class="wp-block-paragraph">To keep the <a href="https://jacco.ompf2.com/2022/06/03/how-to-build-a-bvh-part-9a-to-the-gpu/">article 9a</a> code intact we start with a new file, titled <code>raytracer.cl</code>, which is initially a copy of <code>kernels.cl</code>. The new file will be loaded from <code>::Init()</code> on the CPU side:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">tracer = new Kernel( "cl/raytracer.cl", "render" );</pre></div>



<p class="wp-block-paragraph">The OpenCL source file currently includes <code>template/common.h</code>. We add <code>cl/tools.h</code>, which currently just contains some functions for generating random numbers.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">#include "cl/tools.h"</pre></div>



<p class="wp-block-paragraph">We can now move most of the code from raytracer.cl to tools.h. I propose to move the various structs (<code>Intersection</code>, <code>Ray</code>, <code>Tri</code>, <code>TriEx</code>, <code>BVHNode</code>, <code>TLASNode</code> and <code>BVHInstance</code>), as well as the color format conversion function <code>RGB32FtoRGB8</code> and the intersection functions <code>IntersectTri</code> and <code>IntersectAABB</code>. And finally, also <code>BVHIntersect</code>, for BLAS traversal. All that remains in <code>raytracer.cl</code> is then:</p>



<ul class="wp-block-list">
<li><code>float3 Trace(...)</code>, which will replicate the functionality of the Trace function we used on the CPU, and</li>



<li><code>__kernel void render(...)</code>, the OpenCL kernel, which we call from the C++ code.</li>
</ul>



<p class="wp-block-paragraph">The reorganized code lets us deal with high-level things in <code>raytracer.cl</code>, while the low-level details are hidden away in <code>tools.h</code>.</p>



<p class="wp-block-paragraph">To match the theme of the article, a new mesh has been added to the assets folder: <code>dragon.obj</code>. </p>


<div class="wp-block-image is-resized">
<figure class="aligncenter size-large"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/dragonmesh.jpg" alt="" style="width:512px"/></figure>
</div>


<p class="wp-block-paragraph">This version of the <a href="https://graphics.stanford.edu/data/3Dscanrep/">Stanford Dragon</a> consists of 19332 triangles, and it replaces the 1024 triangle <a href="https://www.computerhistory.org/revolution/computer-graphics-music-and-art/15/206">Utah teapot</a>. Some changes to the <code>Mesh</code> class are needed to accommodate the larger number of polygons:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">class Mesh
{
public:
    Mesh() = default;
    Mesh( const char* objFile, const char* texFile );
    Tri tri[19500];		// triangle data for intersection
    TriEx triEx[19500];		// triangle data for shading
    ...
};</pre></div>



<p class="wp-block-paragraph">Similar changes are needed in the implementation of the <code>Mesh</code> constructor.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">Mesh::Mesh( const char* objFile, const char* texFile )
{
    // bare-bones obj file loader; only supports very basic meshes
    texture = new Surface( texFile );
    float2* UV = new float2[11050]; // enough for dragon.obj
    float3* N = new float3[11050], *P = new float3[19500];</pre></div>



<p class="wp-block-paragraph">Here, 11050 is approximately the number of vertices in the dragon mesh.</p>



<p class="wp-block-paragraph">With these changes, the code still works, but there is a small issue:</p>


<div class="wp-block-image is-resized">
<figure class="aligncenter size-large"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/small-1-1024x572.jpg" alt="" style="width:512px"/><figcaption class="wp-element-caption">&#8220;Small&#8221; may be a poorly chosen word.</figcaption></figure>
</div>


<p class="wp-block-paragraph">The white shape that obscures the sky is a massive dragon. In the CPU code we would resolve this by assigning a scaling matrix to the instance of the dragon mesh. Or rather: we would apply the inverse of this matrix to the rays that intersects the dragon.</p>



<p class="wp-block-paragraph">Time to add TLAS traversal.</p>



<h2 class="wp-block-heading">GPU TLAS</h2>



<p class="wp-block-paragraph">The concept of the TLAS (a.k.a. <em>top level BVH</em>) was introduced in <a href="https://jacco.ompf2.com/2022/05/07/how-to-build-a-bvh-part-5-tlas-blas/">article 5</a> and <a href="https://jacco.ompf2.com/2022/05/13/how-to-build-a-bvh-part-6-all-together-now/">article 6</a>. The idea is to build and traverse a BVH over BVHs, where each of those BVHs can have a 4&#215;4 matrix transform, for translation, rotation, and scaling. Using the same BVH multiple times but with a different matrix enables instancing.</p>



<p class="wp-block-paragraph">We already have the necessary data on the GPU. There is the <code>TLASNode</code> struct:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">struct TLASNode
{
    float minx, miny, minz;
    uint leftRight; // 2x16 bits
    float maxx, maxy, maxz;
    uint BLAS;
};</pre></div>



<p class="wp-block-paragraph">And an array of <code>BVHInstance</code> objects, indexed by the <code>BLAS</code> field of the <code>TLASNode</code>:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">struct BVHInstance
{
    uint dummy1, dummy2;
    uint idx;
    float16 transform;
    float16 invTransform; // inverse transform
    uint dummy[6];
};</pre></div>



<p class="wp-block-paragraph">The strange <code>dummy</code> array at the end is there to ensure that the size and layout of the OpenCL struct matches the CPU struct, at least to the extend that fields <code>transform</code> and <code>invTransform</code> are in the correct location. More on that in a second, because I made some serious mistakes here that need fixing&#8230;</p>



<p class="wp-block-paragraph">We can now port the <code>TLAS::Intersect(...)</code> method. The process is similar to porting the <code>BVH::Intersect</code> method, so I paste the result here without going over every step in detail.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void TLASIntersect( struct Ray* ray, struct Tri* tri, 
    struct BVHInstance* bvhInstance, struct TLASNode* tlasNode, 
    struct BVHNode* bvhNode, uint* triIdx )
{
    // initialize reciprocals for TLAS traversal
    ray-&gt;rD = (float3)(1.0f / ray-&gt;D.x, 1.0f / ray-&gt;D.y, 1.0f / ray-&gt;D.z);
    // use a local stack instead of a recursive function
    struct TLASNode* node = &amp;tlasNode[0], *stack[32];
    uint stackPtr = 0;
    // traversl loop; terminates when the stack is empty
    while (1)
    {
        if (node-&gt;leftRight == 0) // isLeaf()
        {
            // current node is a leaf: intersect instance
            InstanceIntersect( ray, &amp;bvhInstance[node-&gt;BLAS], node-&gt;BLAS, tri, bvhNode, triIdx );
            // pop a node from the stack; terminate if none left
            if (stackPtr == 0) break; else node = stack[--stackPtr];
            continue;
        }
        // current node is an interior node: visit child nodes, ordered
        struct TLASNode* child1 = &amp;tlasNode[node-&gt;leftRight &amp; 0xffff];
        struct TLASNode* child2 = &amp;tlasNode[node-&gt;leftRight &gt;&gt; 16];
        float dist1 = IntersectAABB( ray, child1 );
        float dist2 = IntersectAABB( ray, child2 );
        if (dist1 &gt; dist2) 
        { 
            float d = dist1; dist1 = dist2; dist2 = d;
            struct TLASNode* c = child1; child1 = child2; child2 = c;
        }
        if (dist1 == 1e30f)
        {
            // missed both child nodes; pop a node from the stack
            if (stackPtr == 0) break; else node = stack[--stackPtr];
        }
        else
        {
            // visit near node; push the far node if the ray intersects it
            node = child1;
            if (dist2 != 1e30f) stack[stackPtr++] = child2;
        }
    }
}</pre></div>



<p class="wp-block-paragraph">We call two functions from <code>TLASIntersect</code> that we have not defined yet.</p>



<p class="wp-block-paragraph">The first one is particularly interesting: We call <code>IntersectAABB</code>, with a <code>TLASNode*</code> rather than a <code>BVHNode*</code>. To my surprise, this <em>just works</em>. The <code>TLASNode</code> struct has, for the purpose of AABB intersection, the same layout as a <code>BVHNode</code>. And OpenCL doesn&#8217;t complain about the pointer type mismatch&#8230; Great, for now, but definitely something to keep in mind: Next time this &#8216;flexibility&#8217; may not be what we expect.</p>



<p class="wp-block-paragraph">The second function requires more work. Here is the code for <code>InstanceIntersect</code>, based on <code>BVHInstance::Intersect</code> from the CPU code:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void InstanceIntersect( struct Ray* ray, struct BVHInstance* bvhInstance,
    int blasIdx, struct Tri* tri, struct BVHNode* bvhNode, uint* triIdx )
{
    // backup and transform ray using instance transform
    struct Ray backup = *ray;
    TransformRay( ray, &amp;bvhInstance-&gt;invTransform );
    // traverse the BLAS
    BVHIntersect( ray, blasIdx, tri, bvhNode, triIdx );
    // restore ray without overwriting intersection record
    backup.hit = ray-&gt;hit;
    *ray = backup;
}</pre></div>



<p class="wp-block-paragraph">This function in turn calls <code>TransformRay</code>, which is defined as follows:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void TransformRay( struct Ray* ray, float16* invTransform )
{
    // do the transform
    ray-&gt;D = (float3)(
        dot( invTransform-&gt;s012, ray-&gt;D ),
        dot( invTransform-&gt;s456, ray-&gt;D ),
        dot( invTransform-&gt;s89A, ray-&gt;D )
    ); // see TransformVector in template.cpp
    ray-&gt;O = (float3)(
        dot( invTransform-&gt;s012, ray-&gt;O ) + invTransform-&gt;s3,
        dot( invTransform-&gt;s456, ray-&gt;O ) + invTransform-&gt;s7,
        dot( invTransform-&gt;s89A, ray-&gt;O ) + invTransform-&gt;sB
    ); // see TransformPosition in template.cpp
    // update ray direction reciprocals
    ray-&gt;rD = (float3)(1.0f / ray-&gt;D.x, 1.0f / ray-&gt;D.y, 1.0f / ray-&gt;D.z);
}</pre></div>



<p class="wp-block-paragraph">This implements the <code>TransformVector</code> and <code>TransformPosition</code> matrix functions we used in the CPU code: In OpenCL, we have to implement these ourselves. </p>



<p class="wp-block-paragraph">Note how the <code>float16</code> data is addressed here: To make a <code>float3</code> out of cells 0, 1 and 2, we write <code>invTransform-&gt;s012</code>. A same technique is available for all OpenCL vector types. For instance, to access <code>x</code> of <code>ray-&gt;D</code> we can simply write <code>ray-&gt;D.x</code>, but we can also get a <code>float2</code> based on the fields: e.g., <code>ray-&gt;D.xy</code>, but also: <code>ray-&gt;D.xx</code>, which would duplicate the first field, or <code>ray-&gt;D.zyx</code>, which would flip the three available fields and yields a <code>float3</code>. Any combination of x, y and z works. The technique is called <em>swizzling</em>. For a float16, x, y and z are obviously insufficient. In this case the fields are labeled 0..9 and A..F (or a..f, if you prefer that): this is the hexadecimal index of the 16 matrix cells.</p>



<h2 class="wp-block-heading">Debugging</h2>



<p class="wp-block-paragraph">There is a problem with all this new code: <em>it doesn&#8217;t work.</em> When that happens, we debug, of course. But in OpenCL that is easier said than done: Breakpoints do not exist, and would be somewhat pointless anyway, considering that the code runs on (potentially) thousands of GPU threads. We do have some tools however. We can for example use <code>printf</code> from a kernel:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void TLASIntersect( struct Ray* ray, struct Tri* tri, 
    struct BVHInstance* bvhInstance, struct TLASNode* tlasNode, 
    struct BVHNode* bvhNode, uint* triIdx )
{
    printf( "hello\n" );
    ...</pre></div>



<p class="wp-block-paragraph">Besides that, we can visualize assumptions. For example:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 Trace( struct Ray* ray, float* skyPixels, struct Tri* triData, struct BVHNode* bvhNodeData, uint* idxData )
{
    // check incoming data
    if (skyPixels == 0 || triData == 0) return (float3)(1, 0, 0);
    ...</pre></div>



<p class="wp-block-paragraph">In the latter case, <code>Trace</code> will return a red pixel if we passed it an non-existent <code>skyPixels</code> or <code>triData</code> buffer. Other colors can be used to return information on different problems. Since the visualization is per-pixel, this can yield more detailed information than the <code>printf</code>.</p>



<p class="wp-block-paragraph">With these limited tools I found several issues. The first is in struct <code>TLASNode</code>, which is very similar to <code>BVHNode</code>, and should thus be &#8216;just fine&#8217;:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">struct TLASNode
{
    float minx, miny, minz;
    uint leftRight; // 2x16 bits
    float maxx, maxy, maxz;
    uint BLAS;
};</pre></div>



<p class="wp-block-paragraph">If this has you scratching your head: look no further, because the problem is not here, it is in the CPU version of this struct.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">// top-level BVH node
struct TLASNode
{
    float3 aabbMin;
    uint leftRight;
    float3 aabbMax;
    uint BLAS;
    bool isLeaf() { return leftRight == 0; }
};</pre></div>



<p class="wp-block-paragraph">Now, one would assume that the two structs have the same size. Sadly, they don&#8217;t. The <code>float3</code> type takes 16 bytes in OpenCL, and therefore, the CPU-side version mimics this, to ensure data compatibility. We thus have a CPU TLASNode that is substantially larger than 32 bytes.</p>



<p class="wp-block-paragraph">The problem is quickly resolved by changing the CPU-side struct:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">// top-level BVH node
struct TLASNode
{
    union { struct { float dummy1[3]; uint leftRight; }; float3 aabbMin; };
    union { struct { float dummy2[3]; uint BLAS; }; float3 aabbMax; };
    bool isLeaf() { return leftRight == 0; }
};</pre></div>



<p class="wp-block-paragraph">That is very ugly, but: Now the two 16-byte structs overlap the <code>float3</code> fields in memory, which causes fields <code>leftRight</code> and <code>BLAS</code> to be exactly in the right location.</p>



<p class="wp-block-paragraph">After this fix, we still get no useful results out of <code>TLASIntersect</code>. It turns out that there is <em>another </em>problematic struct; this time it is <code>BVHInstance</code>. The struct contains two float16 <code>fields</code>, which have the same size as a <code>mat4</code> in the CPU code. The problem is: OpenCL dictates that any field must be positioned in a struct such that its offset is a multiple of its size. In this case, the size of a <code>float16</code> is 64 bytes; we have only 12 bytes before the first <code>float16</code> and therefore OpenCL will inject 52 unused bytes between field <code>idx</code> and the first transform&#8230;</p>



<p class="wp-block-paragraph">Fixing this is again easier on the CPU side. We modify the <code>BVHInstance</code> struct to:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">class BVHInstance
{
    ...
    mat4 transform;
    mat4 invTransform; // inverse transform
    aabb bounds; // in world space
    BVH* bvh = 0;
    uint idx;
    int dummy[7];
};</pre></div>



<p class="wp-block-paragraph">In the new layout, <code>transform</code> and <code>invTransform</code> are properly aligned: <code>transform</code> now has an offset of 0, and <code>invTransform</code> is at offset 64. The array of dummy integers at the end ensures that the size of the whole struct is now a multiple of 64 bytes: This way, in an array of <code>BVHInstances</code> object other than the first also have proper offsets for the <code>float16</code> fields.</p>



<p class="wp-block-paragraph">With these fixes, we finally have the full TLAS &amp; BLAS functionality on the GPU, albeit without any fancy shading:</p>


<div class="wp-block-image is-resized">
<figure class="aligncenter size-large"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/gputlas-1024x516.jpg" alt="" style="width:512px"/></figure>
</div>


<h2 class="wp-block-heading">Restoring Light</h2>



<p class="wp-block-paragraph">The hard part is now done. Adding some shading is a matter of porting the body of the <code>Trace</code> function. This should not have too many surprises:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 Trace( struct Ray* ray, float* skyPixels, 
    struct BVHInstance* instData, struct TLASNode* tlasData,
    uint* texData, struct Tri* triData, struct TriEx* triExData,
    struct BVHNode* bvhNodeData, uint* idxData )
{
    TLASIntersect( ray, triData, instData, tlasData, bvhNodeData, idxData );
    struct Intersection i = ray-&gt;hit;
    if (i.t == 1e30f)
    {
        // sample sky
        ...
    }
    // calculate texture uv based on barycentrics
    uint triIdx = i.instPrim &amp; 0xfffff;
    uint instIdx = i.instPrim &gt;&gt; 20;
    struct TriEx* tri = triExData + triIdx;
    float2 uv = i.u * tri-&gt;uv1 + i.v * tri-&gt;uv2 + (1 - (i.u + i.v)) * tri-&gt;uv0;
    int iu = (int)(uv.x * 1024) &amp; 1023;
    int iv = (int)(uv.y * 1024) &amp; 1023;
    uint texel = texData[iu + (iv &lt;&lt; 10)];
    float3 albedo = RGB8toRGB32F( texel );
    // calculate the normal for the intersection
    float3 N0 = (float3)( tri-&gt;N0x, tri-&gt;N0y, tri-&gt;N0z );
    float3 N1 = (float3)( tri-&gt;N1x, tri-&gt;N1y, tri-&gt;N1z );
    float3 N2 = (float3)( tri-&gt;N2x, tri-&gt;N2y, tri-&gt;N2z );
    float3 N = i.u * N1 + i.v * N2 + (1 - (i.u + i.v)) * N0;
    N = normalize( TransformVector( &amp;N, &amp;instData[instIdx].transform ) );
    float3 I = ray-&gt;O + i.t * ray-&gt;D;
    // calculate the diffuse reflection in the intersection point
    float3 L = lightPos - I;
    float dist = length( L );
    L *= 1.0f / dist;
    return albedo * (ambient + max( 0.0f, dot( N, L ) ) * lightColor * (1.0f / (dist * dist)));
}</pre></div>



<p class="wp-block-paragraph">Note that the size of the brick texture is now hardcoded. We&#8217;ll want to change that at a later stage, to make the renderer more versatile. The light source is also still very much hardcoded, as it was in the CPU version. The three constants for the light source can be defined at global scope, somewhere above the <code>Trace</code> function:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">__constant float3 lightPos = (float3)(3, 10, 2);
__constant float3 lightColor = (float3)(150, 150, 120);
__constant float3 ambient = (float3)(0.2f, 0.2f, 0.4f);</pre></div>



<p class="wp-block-paragraph">To convert pixels read from the texture to float3 we also need a port of the <code>RGB8toRGB32F</code> function. It&#8217;s straightforward, and should go to <code>tools.cl</code>:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 RGB8toRGB32F( uint c )
{
    float s = 1 / 256.0f;
    int r = (c &gt;&gt; 16) &amp; 255;
    int g = (c &gt;&gt; 8) &amp; 255;
    int b = c &amp; 255;
    return (float3)(r * s, g * s, b * s);
}</pre></div>



<p class="wp-block-paragraph">And finally, transforming the normal vector using the matrix for the intersected instance now uses a new function <code>TransformVector</code>, which in hindsight would come in handy in the <code>TransformRay</code> function as well. It is defined as:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 TransformVector( float3* V, float16* T )
{
    return (float3)( dot( T-&gt;s012, *V ), dot( T-&gt;s456, *V ), dot( T-&gt;s89A, *V ) );
}</pre></div>



<p class="wp-block-paragraph">And with that we have properly textured and illuminated dragons.</p>


<div class="wp-block-image is-resized">
<figure class="aligncenter size-large"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/dragonslit-1024x540.jpg" alt="" style="width:512px"/></figure>
</div>


<h2 class="wp-block-heading">Mirror Mirror</h2>



<p class="wp-block-paragraph">The next challenge for the OpenCL port of the recursive ray tracer is: Recursion, which we need for mirrors, as well as glass and water (<em>dielectrics</em>). There is however a problem with recursion in OpenCL: <em>It is forbidden</em>. Yet, in the original <code>::Trace</code> function on the CPU, it was rather instrumental to our needs:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 WhittedApp::Trace( Ray&amp; ray, int rayDepth )
{
    ...
    if (mirror)
    {	
        // calculate the specular reflection in the intersection point
        Ray secondary;
        secondary.D = ray.D - 2 * N * dot( N, ray.D );
        secondary.O = I + secondary.D * 0.001f;
        secondary.hit.t = 1e30f;
        if (rayDepth &gt;= 10) return float3( 0 );
        return Trace( secondary, rayDepth + 1 );
    }
    else
    {
        // calculate the diffuse reflection in the intersection point
        ...
    }
}</pre></div>



<p class="wp-block-paragraph">The highlighted line (line 12) calls the <code>Trace</code> function itself with a just constructed <em>secondary ray</em>, which starts at the intersection point, and extends into the direction calculated using the specular reflection formula on line 8.</p>



<p class="wp-block-paragraph">Luckily, we have ways to bypass recursion. We already did this to traverse the BVH: Instead of calling <code>BVHIntersect</code> for the left and right child nodes, we switch processing to the nearest child node, while we push the far node on a stack. And, whenever we would normally return, we now pop work from the stack, until the stack is empty.</p>



<p class="wp-block-paragraph">We can deploy the same scheme here. Except, it will be simpler: Until we add glass or water, the path of a ray does not split up. It ends whenever we hit the skydome, but also when we hit a diffuse object. Only when we hit a reflective dragon we bounce, but in that case we can just restart the Trace function after replacing the original ray by a reflected ray. Like this:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 Trace( ... )
{
    int rayDepth = 0;
    // bounce until we hit the sky or a diffuse surface
    while (rayDepth &lt; 10)
    {
        TLASIntersect( ray, ... );
        struct Intersection i = ray-&gt;hit;
        if (i.t == 1e30f)
        {
            // sample sky
            ...
            return ... ;
        }
        ...           
        if (mirror)
        {
            // calculate the specular reflection in the intersection point
            ray-&gt;D = ray-&gt;D - 2 * N * dot( N, ray-&gt;D );
            ray-&gt;O = I + ray-&gt;D * 0.001f;
            ray-&gt;hit.t = 1e30f;
            rayDepth++;
        }
        else
        {
            // calculate the diffuse reflection in the intersection point
            return ... ;
        }
    }
    return (float3)( 1, 1, 1 );
}</pre></div>



<p class="wp-block-paragraph">Basically, this loop makes a ray bounce around, until it does <em>not </em>hit a mirror. Of course we need to be careful with infinite &#8216;recursion&#8217; (in this case: an infinite loop). So, we keep track of the &#8216;bounce depth&#8217; and once it exceeds a certain value, we terminate the loop. In that case the last surface we hit must have been a mirror; we thus return white, i.e. <code>(float3)(1, 1, 1)</code>, which is probably better than any other color.</p>



<p class="wp-block-paragraph">The scheme is quite effective, and brings back the shiny dragons:</p>


<div class="wp-block-image is-resized">
<figure class="aligncenter size-large"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/shiny-1024x486.jpg" alt="" style="width:512px"/></figure>
</div>


<h2 class="wp-block-heading">MASSIVE</h2>



<p class="wp-block-paragraph">One advantage of ray tracing is how it handles massive scenes. For simple scenes, traditional rasterization is typically a lot faster, but at some point, the tables turn. This has everything to do with the BVH: once build (that&#8217;s a rather important condition!), a BVH over <span class="wp-katex-eq" data-display="false">N</span> triangles requires on average <span class="wp-katex-eq" data-display="false">log_2 N</span> steps to get from the root of the tree to a leaf node. For 1,000 triangles we get to a single leaf in 10 steps; for 1,000,000 we get there in 20 steps: Twice the cost, for a thousand times the complexity. Even a <em>billion</em> triangles is doable; this only take three times more work than one thousand.</p>



<p class="wp-block-paragraph">To put that to the test we will create a scene, in which every vertex of the dragon model is replaced by a dragon. The dragon has 11,042 vertices, and 19,332 polygons; the scene thus will have a bit more than 213 million triangles. You&#8217;ll have to believe me when I say that adding another zero to that number will hardly matter.</p>



<p class="wp-block-paragraph">The scene is constructed in the <code>::Init()</code> function:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void MassiveApp::Init()
{
    mesh = new Mesh( "assets/dragon.obj", "assets/bricks.png" );
    // load HDR sky
    ...
    // dragons in the shape of a dragon
    bvhInstance = new BVHInstance[11042];
    for( int i = 0; i &lt; 11042; i++ )
    {
        bvhInstance[i] = BVHInstance( mesh-&gt;bvh, i );
        bvhInstance[i].SetTransform( 
            mat4::Translate( mesh-&gt;P[i] * 0.2f ) * 
            mat4::Scale( 0.0025f  ) *
            mat4::Rotate( mesh-&gt;N[i], 0 ) *
            mat4::RotateX( PI / 2 )
        );
    }
    tlas = TLAS( bvhInstance, 11042 );
    tlas.Build();
    ...</pre></div>



<p class="wp-block-paragraph">To make that work, the <code>BVHInstance</code> array in the application class definition in <code>massive.h</code> is changed to a pointer:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">BVHInstance* bvhInstance;</pre></div>



<p class="wp-block-paragraph">The <code>::Init()</code> function needs access to vertex positions and normals. These were stored in local arrays (<code>P</code> and <code>N</code>) in the <code>Mesh</code> constructor. We add pointers to this data to the <code>Mesh</code> class, and make a small change to the <code>Mesh</code> constructor:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">Mesh::Mesh( const char* objFile, const char* texFile )
{
    // bare-bones obj file loader; only supports very basic meshes
    ...
    N = new float3[11043], P = new float3[11043];
    ...</pre></div>



<p class="wp-block-paragraph">Tiny but important detail: Indices in obj files start at 1; we thus either make the arrays 1 element larger, or subtract 1 from every index that we use &#8211; hence the 11043 figure.</p>



<p class="wp-block-paragraph">We are almost ready to show the scene: The scene is constructed, the (single) BLAS for the 11,042 dragon instances is built, and we have a TLAS &#8211; which constructs in about half a second on my machine. Half a second: That means the TLAS will have to be static, for now. We thus build it and copy it once to the GPU, in the <code>::Init()</code> function. The <code>tlasData-&gt;CopyToDevice()</code> and <code>instData-&gt;CopyToDevice()</code> commands can now also be moved to ::Init(); we will render a static scene.</p>



<p class="wp-block-paragraph">If you typed along, you now have a &#8216;dragon of dragons&#8217;, and it runs at a respectable speed.</p>



<h2 class="wp-block-heading">Camera</h2>



<p class="wp-block-paragraph">Such a scene deserves a proper view.</p>



<p class="wp-block-paragraph">For that, we will move the camera along a smooth path. The <a href="https://qroph.github.io/2018/07/30/smooth-paths-using-catmull-rom-splines.html">Catmull-Rom spline</a> is ideal for this: it is smooth, and moves through a series of points.</p>


<div class="wp-block-image is-resized">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="642" height="378" src="https://jacco.ompf2.com/wp-content/uploads/2022/06/Catmull-Rom_Spline.png" alt="" class="wp-image-1479" style="width:512px" srcset="https://jacco.ompf2.com/wp-content/uploads/2022/06/Catmull-Rom_Spline.png 642w, https://jacco.ompf2.com/wp-content/uploads/2022/06/Catmull-Rom_Spline-300x177.png 300w, https://jacco.ompf2.com/wp-content/uploads/2022/06/Catmull-Rom_Spline-360x212.png 360w" sizes="auto, (max-width: 642px) 100vw, 642px" /><figcaption class="wp-element-caption">One segment of the Catmull-Rom spline, from <span class="wp-katex-eq" data-display="false">P_1</span> to <span class="wp-katex-eq" data-display="false">P_2</span>: we need <span class="wp-katex-eq" data-display="false">P_0</span> and <span class="wp-katex-eq" data-display="false">P_3</span> to define the direction at <span class="wp-katex-eq" data-display="false">P_1</span> and <span class="wp-katex-eq" data-display="false">P_2</span>.</figcaption></figure>
</div>


<p class="wp-block-paragraph">Given <span class="wp-katex-eq" data-display="false">P_0 .. P_3</span>, we can find a point on the segment <span class="wp-katex-eq" data-display="false">P_1 .. P_2</span> with the following code:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 CatmullRom( float t, float3&amp; p0, float3&amp; p1, float3&amp; p2, float3&amp; p3 )
{
    float3 c = 2 * p0 - 5 * p1 + 4 * p2 - p3, d = 3 * (p1 - p2) + p3 - p0;
    return 0.5f * (2 * p1 + ((p2 - p0) * t) + (c * t * t) + (d * t * t * t));
}</pre></div>



<p class="wp-block-paragraph">By varying <span class="wp-katex-eq" data-display="false">t</span> from 0..1, this function allows us to smoothly travel the curve. Once we reach <span class="wp-katex-eq" data-display="false">t=1</span> (or <span class="wp-katex-eq" data-display="false">t=0</span>, if we move backwards), we simply select the next set of four points on the curve; this way, the smooth path can consist of any number of points.</p>



<p class="wp-block-paragraph">Let&#8217;s take this one step further: If we move not just the camera over a smooth curve, but also a <em>point at which the camera is aimed</em>, we get a pretty versatile camera system. Consider the following set of points:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 spline[] = {
    float3( 1.32, 11.35, 0.31 ), float3( 0.35, 11.56, 0.18 ),
    float3( -0.92, 11.35, 2.92 ), float3( -1.58, 11.55, 2.19 ),
    float3( -5.51, 13.43, 4.96 ), float3( -5.82, 13.63, 4.03 ),
    float3( -10.90, 13.48, 4.53 ), float3( -10.39, 13.68, 3.69 ),
    float3( -13.15, 15.33, 2.21 ), float3( -12.20, 15.52, 1.96 ),
    float3( -12.44, 15.33, -1.92 ), float3( -11.92, 15.51, -1.08 ),
    float3( -8.17, 15.48, -4.71 ), float3( -7.32, 15.38, -4.19 ),
    float3( -0.19, 13.22, -6.09 ), float3( 0.31, 12.72, -5.38 ),
    float3( 8.44, 8.37, -5.22 ), float3( 8.01, 7.81, -4.52 ),
    float3( 14.31, 4.71, -1.89 ), float3( 13.40, 4.46, -1.56 ),
    float3( 11.81, 4.97, 6.36 ), float3( 11.19, 4.65, 5.64 ),
    float3( 10.57, 4.58, 5.19 ), float3( 9.85, 4.39, 4.52 ),
    float3( 7.33, 4.66, 2.14 ), float3( 6.61, 4.59, 1.45 ),
    float3( 6.01, 4.77, 0.68 ), float3( 5.28, 4.70, 0 ),
    float3( 3.00, 4.48, -2.16 ), float3( 2.27, 4.42, -2.85 ),
    float3( -1.53, 4.27, -5.49 ), float3( -1.89, 4.21, -4.56 ),
    float3( -3.63, 4.12, -3.77 ), float3( -3.80, 4.06, -2.78 ),
    float3( -4.97, 3.97, 2.62 ), float3( -5.38, 3.98, 3.53 ),
    float3( -9.38, 3.97, 7.47 ), float3( -8.92, 3.98, 6.59 ),
    float3( -16.17, 5.36, 7.89 ), float3( -15.37, 5.37, 7.29 ),
    float3( -27.30, 10.08, -1.143 ), float3( -26.33, 10.00, -0.89 ),
    float3( -30.81, 10.88, -13.78 ), float3( -29.94, 10.80, -13.30 )
};</pre></div>



<p class="wp-block-paragraph">Each pair in this array contains one camera position (on the left) and a camera target (on the right). I obtained these points by manually navigating the scene, and recording 20 points to a file. The code for that is left in the program; feel free to replace the spline with a new path.</p>



<p class="wp-block-paragraph">The camera can now be updated in the <code>::Tick()</code> function, with a little help from the new <code>SplineCam</code> function:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void SplineCam( int seg, float t )
{
    float3 c0 = spline[seg * 2 - 2],
           c1 = spline[seg * 2],
           c2 = spline[seg * 2 + 2], 
           c3 = spline[seg * 2 + 4];
    float3 t0 = spline[seg * 2 - 1], 
           t1 = spline[seg * 2 + 1], 
           t2 = spline[seg * 2 + 3], 
           t3 = spline[seg * 2 + 5];
    camPos = CatmullRom( t, c0, c1, c2, c3 );
    camTarget = CatmullRom( t, t0, t1, t2, t3 );
}

void MassiveApp::Tick( float deltaTime )
{
    // playback spline path
    static int seg = 1;
    static float t = 0;
    t += deltaTime * 0.0005f;
    if (t &gt; 1) { t -= 1.0f; if (++seg == 20) seg = 1; }
    SplineCam( seg, t );
    mat4 M = mat4::LookAt( camPos, camTarget );
    ...</pre></div>



<p class="wp-block-paragraph">And with that, we have reached our final destination.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/collage-1024x1019.jpg" alt="" style="width:512px"/></figure>
</div>


<h2 class="wp-block-heading">Bandwidth</h2>



<p class="wp-block-paragraph">There&#8217;s one thing that is rather silly about the current demo, and it has to do with the template used. It is however a generic thing, so let me explain.</p>



<p class="wp-block-paragraph">To render an image, the CPU code creates a buffer in VRAM. The OpenCL kernel fills this buffer with pixels. Next, we copy the buffer back to the CPU. And then what? Well, under hood the template maintains a single texture, the size of which matches the window size. The rendered pixels are copied to this texture once per frame, after <code>::Tick()</code> completes. OpenGL is then used to draw a screen filling quad using this texture. This is how a frame ends up on the monitor. We thus have:</p>



<ul class="wp-block-list">
<li>Pixels rendered on the GPU using OpenCL</li>



<li>Pixels transferred to CPU RAM</li>



<li>Pixels copied from CPU RAM to a texture <em>in VRAM</em></li>
</ul>



<p class="wp-block-paragraph">That feels like a rather long route with unnecessary detours, and it is. Luckily, there is a shortcut, and the name of the shortcut is <em>GL/CL interop</em>. This is a technique where OpenGL makes a resource (in this case: a texture) available to OpenCL, so OpenCL can render directly to it. And this saves time, obviously.</p>



<p class="wp-block-paragraph">To enable the shortcut, we replace one line in <code>::Init()</code>. The line that currently reads</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">target = new Buffer( SCRWIDTH * SCRHEIGHT * 4 );</pre></div>



<p class="wp-block-paragraph">is to be replaced by</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">target = new Buffer( GetRenderTarget()-&gt;ID, 0, Buffer::TARGET );
    screen = 0;</pre></div>



<p class="wp-block-paragraph">This is inevitably highly template-specific. The first line creates the buffer using an OpenGL texture identifier, obtained from the render target of the template. The second line is used to tell the template to stop sending frames to the OpenGL texture &#8211; we are using OpenCL for that now.</p>



<p class="wp-block-paragraph">A few more changes are needed. In ::Tick(), we delete the two lines that &#8216;obtain the rendered result&#8217;. And, in the kernel code, the first argument is now different:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">__kernel void render( 
    write_only image2d_t target,
    ...
)
{
    ...
}</pre></div>



<p class="wp-block-paragraph">And finally, plotting to the target changes. We used a unsigned int array before, but now we have a floating point OpenGL texture to work with. We use the following line to write to it:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">write_imagef( target, (int2)(x, y), (float4)( color, 1 ) );</pre></div>



<p class="wp-block-paragraph">After this change the demo works again, this time without wasting time sending pixel data back and forth.</p>



<h2 class="wp-block-heading">Future Work</h2>



<p class="wp-block-paragraph">Where do we go from here? Well, as a wise man once said, you can be &#8220;Ray Tracing &#8211; the Rest of Your Life&#8221;&#8230;</p>



<p class="wp-block-paragraph"><em><strong>Faster BVH building</strong></em> &#8211; The BVH for the dragon is constructed in just a few milliseconds, on a single core. For multiple meshes multiple cores can be used &#8211; until they run out. Take it further by optimizing the BVH builder: Some SIMD magic should bring down the time significantly, and beyond that, well, there&#8217;s ways to make it <em>very </em>fast. An important trick is to build your BVH <em>while the GPU is tracing rays</em>: the only thing that needs to happen between frames is sending the updated data. And even that isn&#8217;t strictly necessary.</p>



<p class="wp-block-paragraph"><em><strong>Faster traversal</strong></em> &#8211; We trace hundreds of millions of rays per second now on the GPU &#8211; without RTX. But, the code is far from optimal&#8230; There are BVH layouts that are better suited for the GPU, and there&#8217;s 4-wide and 8-wide BVHs, which further improve performance. On the CPU packet traversal makes a huge difference, especially for primary rays. By the way, we never implemented proper shadow rays, so that should be on the top of your list.</p>



<p class="wp-block-paragraph"><em><strong>Better rendering</strong></em> &#8211; A few reflecting dragons is nice, but what about more interesting materials, normal maps, depth of field, motion blur, soft shadows, indirect light? This is a field in which you can explore endlessly. Start with basic path tracing, and quickly your code will be too slow again, forcing you to look into filtering techniques and ReSTIR for efficiently sampling many lights. A life is not going to be enough, I&#8217;m afraid.</p>



<p class="wp-block-paragraph"><em><strong>Engine flexibility</strong></em> &#8211; The code of this tutorial is short and hopefully clear, but definitely not robust. Handling multiple meshes and textures and being able to delete them and add them at runtime will require a lot of administration &#8211; especially if you still want to render on the GPU. And while you&#8217;re at it: A fixed-size skydome is not how things should be, obviously. Do mind compile times, once you start cleaning things up: you may have noticed that the tutorial code compiles in a flash, and that&#8217;s not just a lucky accident.</p>



<p class="wp-block-paragraph"><em><strong>OptiX-CL</strong></em> &#8211; NVIDIA provides RTX support from CUDA in the form of a library called OptiX. It would be nice if the functionality of this library became available <em>outside of CUDA</em>, and thus for all devices of all vendors. If you see a challenge here: Let me know! Perhaps we can join forces. Especially the now obsolete OptiX Prime API would be very interesting (and relatively simple) to replicate.</p>



<p class="wp-block-paragraph"><em><strong>Lightouse 2</strong></em> &#8211; Speaking of OptiX: My Lighthouse 2 project uses OptiX to quickly render complex scenes on the GPU, but it is NVIDIA only, essentially. A proper render core using OpenCL or even using the CPU would be great to have. One day, perhaps.</p>


<div class="wp-block-image is-resized">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="651" src="https://jacco.ompf2.com/wp-content/uploads/2020/02/shot4-1024x651.png" alt="" class="wp-image-480" style="width:600px" srcset="https://jacco.ompf2.com/wp-content/uploads/2020/02/shot4-1024x651.png 1024w, https://jacco.ompf2.com/wp-content/uploads/2020/02/shot4-300x191.png 300w, https://jacco.ompf2.com/wp-content/uploads/2020/02/shot4-768x489.png 768w, https://jacco.ompf2.com/wp-content/uploads/2020/02/shot4-400x254.png 400w, https://jacco.ompf2.com/wp-content/uploads/2020/02/shot4.png 1344w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">Frame from the Lighthouse 2 real-time path tracing benchmark.</figcaption></figure>
</div>


<p class="wp-block-paragraph">That&#8217;s just my ideas though. Let me know what your plans are, but whatever you do, keep tracing.</p>



<p class="wp-block-paragraph">And with that, allow me to sign off for once as if it&#8217;s 1999 on Flipcode:</p>



<p class="wp-block-paragraph">Love you all,</p>



<p class="wp-block-paragraph">Jacco Bikker, <em>a.k.a. &#8220;The Phantom&#8221;.</em></p>



<h2 class="wp-block-heading">Closing Remarks</h2>



<p class="wp-block-paragraph">The complete code for this project, in ten convenient incremental stages, <a href="https://github.com/jbikker/bvh_article">can be found on GitHub</a> (for Windows / Visual Studio).</p>



<p class="wp-block-paragraph">Enjoyed the article? Spotted an error?</p>



<p class="wp-block-paragraph">Ping me on Twitter (<a href="https://twitter.com/j_bikker">@j_bikker</a>), comment on this article, or send an email to <a href="mailto:bikker.j@gmail.com">bikker.j@gmail.com</a>.<br>You can also find me on Github:  <a href="https://github.com/jbikker/lighthouse2">https://github.com/jbikker</a>.</p>



<p class="wp-block-paragraph">Or read some more articles: <a href="https://jacco.ompf2.com">https://jacco.ompf2.com</a>. Some favorites:</p>



<ul class="wp-block-list">
<li><a href="https://jacco.ompf2.com/2019/07/18/wavefront-path-tracing/">Wavefront path tracing</a></li>



<li>Probability Theory for Physically Based Rendering &#8211; <a href="https://jacco.ompf2.com/2019/12/11/probability-theory-for-physically-based-rendering/">part 1</a></li>



<li>Probability Theory for Physically Based Rendering &#8211; <a href="https://jacco.ompf2.com/2019/12/13/probability-theory-for-physically-based-rendering-part-2/">part 2</a></li>



<li><a href="https://jacco.ompf2.com/2020/05/12/opt3simd-part-1-of-2/">OPT#3: SIMD</a> (part 1 of 2) &#8211; <em>also check the other optimization blog posts!</em></li>
</ul>
]]></content:encoded>
					
					<wfw:commentRss>https://jacco.ompf2.com/2022/06/15/how-to-build-a-bvh-part-9b-massive/feed/</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
		<item>
		<title>How to build a BVH &#8211; part 9a: To the GPU</title>
		<link>https://jacco.ompf2.com/2022/06/03/how-to-build-a-bvh-part-9a-to-the-gpu/</link>
					<comments>https://jacco.ompf2.com/2022/06/03/how-to-build-a-bvh-part-9a-to-the-gpu/#respond</comments>
		
		<dc:creator><![CDATA[jbikker]]></dc:creator>
		<pubDate>Fri, 03 Jun 2022 08:24:45 +0000</pubDate>
				<category><![CDATA[Article]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Source Code]]></category>
		<category><![CDATA[Tutorial]]></category>
		<guid isPermaLink="false">https://jacco.ompf2.com/?p=1377</guid>

					<description><![CDATA[In this series we explore the wonderful world of the bounding volume hierarchy: the mysterious data structure...]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">In this series we explore the wonderful world of the <em>bounding volume hierarchy:</em> the mysterious data structure that enables real-time ray tracing on recent GPUs, in complex, animated scenes. Despite the broad adoption of ray tracing in games, in-depth understanding of the underlying technology seems to be reserved to a select few. In this article we show how a proper BVH is implemented without support from DXR / RTX / OptiX / Vulkan, in easy-to-read &#8216;sane C++&#8217;. Whether this is actually useful for you, or just interesting as background information, depends on your needs, obviously.</p>



<p class="wp-block-paragraph">This series consist of ten articles. For each article, full source code is <a href="https://github.com/jbikker/bvh_article">available on Github</a>, in easy-to-read &#8216;Sane C++&#8217;. Contents:</p>



<ol class="wp-block-list">
<li><a href="https://jacco.ompf2.com/2022/04/13/how-to-build-a-bvh-part-1-basics/">Basics: data structure, simple construction and ray traversal</a>.</li>



<li><a href="https://jacco.ompf2.com/2022/04/18/how-to-build-a-bvh-part-2-faster-rays/">Faster rays: the Surface Area Heuristic and ordered traversal</a>.</li>



<li><a href="https://jacco.ompf2.com/2022/04/21/how-to-build-a-bvh-part-3-quick-builds/">Faster construction: binned BVH building</a>.</li>



<li><a href="https://jacco.ompf2.com/2022/04/26/how-to-build-a-bvh-part-4-animation/">BVHs for animated models: refitting and rebuilding</a>.</li>



<li><a href="https://jacco.ompf2.com/2022/05/07/how-to-build-a-bvh-part-5-tlas-blas/">BVHs for animated scenes: the top-level BVH</a>.</li>



<li><a href="https://jacco.ompf2.com/2022/05/13/how-to-build-a-bvh-part-6-all-together-now/">TLAS &amp; BLAS part 2 – all together now</a>.</li>



<li><a href="https://jacco.ompf2.com/2022/05/20/how-to-build-a-bvh-part-7-consolidate/">Consolidating, part 1: ray tracing textured and shaded meshes</a>.</li>



<li><a href="https://jacco.ompf2.com/2022/05/27/how-to-build-a-bvh-part-8-whitted-style/">Consolidating, part 2: Whitted-style ray tracing</a>.</li>



<li><strong>OpenCL: GPU ray tracing, part 1 (this article).</strong></li>



<li><a href="https://jacco.ompf2.com/2022/06/15/how-to-build-a-bvh-part-9b-massive/">OpenCL: GPU ray tracing, part 2 (series final)</a>.</li>
</ol>



<p class="wp-block-paragraph" id="block-0335045c-892a-4222-aee1-ff87a91ce61a">We approach the end of this series. After building the BVH on the CPU, and rendering an animated scene with textured and reflective teapots on the CPU, we take the rendering process to the GPU, chasing visions of better performance. The GPU bits in this article will be implemented in OpenCL. The GPU code will not rely on any hardware ray tracing; in fact, we&#8217;ll not use any of that. Of course we will do some performance measurements, and compare against RTX &#8211; in article 10.</p>



<h2 class="wp-block-heading" id="block-0335045c-892a-4222-aee1-ff87a91ce61a">GPU</h2>



<p class="wp-block-paragraph" id="block-0335045c-892a-4222-aee1-ff87a91ce61a">Compared to a CPU, a GPU is a strange beast. It sits pretty isolated in a computer: separated, by a slow connection, from CPU, RAM, user input, disk I/O and other commodities. The only thing it has quick access to is the display. In terms of processing it&#8217;s an oddity as well: a large group of cores chews on an even larger number of threads, which ideally all do the same thing, just on different data. Still, the prospect of vast bandwidth and great compute power is tempting, and justifies some pain and effort to get this beast under control.</p>



<p class="wp-block-paragraph" id="block-0335045c-892a-4222-aee1-ff87a91ce61a">In this article we will use OpenCL to access the GPU. This is a somewhat arbitrary choice; e.g. CUDA (NVIDIA only) or compute shaders would also do the job. Regardless of the chosen GPU programming framework, we&#8217;ll have to deal with an API, which can be a bit cumbersome, especially compared to the quite pure C++ we have been using so far. To make our lives a bit easier, templates exist, and the template we&#8217;ve been using so far comes with some decent OpenCL functionality. If you are not using the template, please copy the OpenCL specifics from the template to your own code; it&#8217;s a pretty thin wrapper.</p>



<p class="wp-block-paragraph">The OpenCL program we&#8217;re going to run is pretty simple:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">__kernel void render( __global uint* target, int offset )
{
    // plot a pixel into the target array in GPU memory
    int threadIdx = get_global_id( 0 );
    int x = threadIdx % 640;
    int y = threadIdx / 640;
    int red = x / 3 + offset, green = y / 3;
    target[x + y * 640] = (red &lt;&lt; 16) + (green &lt;&lt; 8);
}</pre></div>



<p class="wp-block-paragraph">The code would produce a a nice gradient, but we&#8217;re not quite there yet. Someone needs to start this code, ideally from some C++. To do that, we store the OpenCL code in a file, <code>kernels.cl</code>, and load it from the C++ code that we have been developing. To <code>::Init()</code> we add:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">// prepare OpenCL
    tracer = new Kernel( "cl/kernels.cl", "render" );
    target = new Buffer( 640 * 640 * 4 );</pre></div>



<p class="wp-block-paragraph">The first line loads the OpenCL source file from subdirectory <code>cl</code>, compiles it, and looks for a kernel function called <code>render</code>. The second line creates a <code>Buffer</code> of 640 * 640 * 4 bytes. This &#8216;Buffer&#8217; is something special: the bytes it stores can reside in regular RAM, or on the GPU, or both. The two locations are not automatically in sync, but we can copy from VRAM to RAM (using <code>Buffer::CopyFromDevice()</code> ) or from RAM to VRAM (using <code>Buffer::CopyToDevice()</code> ). So now we have a way to provide the <code>render</code> kernel with data, and we have a way to obtain results, back to the CPU, where we can operate on them more easily.</p>



<p class="wp-block-paragraph">We can now execute the kernel, e.g. in the <code>::Tick()</code> function:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">tracer-&gt;SetArguments( target, 0 );
    tracer-&gt;Run( 640 * 640 );</pre></div>



<p class="wp-block-paragraph">The kernel is expecting two arguments: the first is a <code>__global uint*</code>, the second a simple <code>int</code>. The call to <code>SetArguments(...)</code> passes the buffer we created, and 0 for the integer, to OpenCL; the second line starts the kernel on the GPU, using 640&#215;640 threads.</p>



<p class="wp-block-paragraph">Once the kernel is done (which will be in an instant), we can get the results by copying the buffer from the GPU to RAM:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">target-&gt;CopyFromDevice();</pre></div>



<p class="wp-block-paragraph">The buffer now contains 640&#215;640 unsigned integers, which we can now simply copy to the screen surface. We could use a nested for loop over x and y for that, but a <code>memcpy</code> does the job more quickly:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">memcpy( screen-&gt;pixels, target-&gt;GetHostPtr(), target-&gt;size );</pre></div>



<p class="wp-block-paragraph">And <em>now </em>we can start the program, and admire its glorious GPU-calculated gradient.</p>


<div class="wp-block-image is-resized">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="635" height="636" src="https://jacco.ompf2.com/wp-content/uploads/2022/05/gradient.jpg" alt="" class="wp-image-1378" style="width:400px" srcset="https://jacco.ompf2.com/wp-content/uploads/2022/05/gradient.jpg 635w, https://jacco.ompf2.com/wp-content/uploads/2022/05/gradient-300x300.jpg 300w, https://jacco.ompf2.com/wp-content/uploads/2022/05/gradient-150x150.jpg 150w, https://jacco.ompf2.com/wp-content/uploads/2022/05/gradient-360x361.jpg 360w" sizes="auto, (max-width: 635px) 100vw, 635px" /></figure>
</div>


<p class="wp-block-paragraph">With that out of the way, we can now focus on getting some ray tracing done on the GPU. We just created GPU code that produces colors that we can display; all that we need to do now is calculate these colors using a <code>Trace</code> function &#8211; running on the GPU. The <code>Trace</code> function will need data: a skybox, triangles, and of course: a BVH.</p>



<div class="wp-block-group has-background" style="background:linear-gradient(135deg,rgb(201,232,255) 2%,rgb(255,255,255) 69%)"><div class="wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow">
<h2 class="wp-block-heading">GPGPU Best Practices</h2>



<p class="wp-block-paragraph">From here, we will port the existing CPU ray tracer to the GPU, one bit at a time. A few &#8216;best practices&#8217; will help to make this process (and probably other GPGPU projects) go smooth:</p>



<p class="wp-block-paragraph">First of all, we <strong>start with working CPU code</strong>. Debugging on the GPU is hard; it really helps if we don&#8217;t complicate things further by building new things directly in GPU code.</p>



<p class="wp-block-paragraph">Secondly, start with something simple and build from there. We just did that: getting anything to the screen (&#8216;<strong>first image</strong>&#8216;) is an important first step, from a practical and psychological point of view. From there, small, verifiable steps will ultimately lead to a finished project.</p>



<p class="wp-block-paragraph">Third, <strong>functionality comes before speed</strong>. &#8220;The most important optimization is the one that turns a not working program into a working one,&#8221; and: &#8220;Premature optimization is the root of all evil.&#8221; Applied to GPGPU: make it work first, in the most intuitive manner; tweaking is for later.</p>



<p class="wp-block-paragraph">And finally, <strong>let the GPU do what it does best</strong>. In our case: Building a BVH is not easy to do on a massive parallel architecture. So: don&#8217;t! Tracing rays on the other hand is a perfect fit: We basically execute the same task, for thousands of pixels.</p>
</div></div>



<h2 class="wp-block-heading">Trace</h2>



<p class="wp-block-paragraph">Before we proceed, let&#8217;s make some small changes to the render kernel, so that it can work with a different window size than the hardcoded 640&#215;640 we used so far.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">__kernel void render( __global uint* target, int offset )
{
    // plot a pixel into the target array in GPU memory
    int threadIdx = get_global_id( 0 );
    int x = threadIdx % SCRWIDTH;
    int y = threadIdx / SCRWIDTH;
    int red = x / 3 + offset, green = y / 3;
    target[x + y * 640] = (red &lt;&lt; 16) + (green &lt;&lt; 8);
}</pre></div>



<p class="wp-block-paragraph">This requires two additional changes. The constants <code>SCRWIDTH</code> and <code>SCRHEIGHT</code> (used later) are defined in a file named <code>common.h</code>, which can be found in the <code>template</code> folder. We thus include this file at the top of <code>kernels.cl</code>:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">#include "template/common.h"</pre></div>



<p class="wp-block-paragraph">Note that <code>common.h</code> will now be included by the CPU code as well as the GPU code. This is a great way to share some functionality, and to ensure that both use the same settings (such as screen size, in this case).</p>



<p class="wp-block-paragraph">The second change is a replacement of <code>640 * 640</code> by <code>SCRWIDTH * SCRHEIGHT</code> in the CPU code. This occurs in two places: once for the allocation of the target buffer, and once for the invocation of the trace kernel, in <code>::Tick</code>.</p>



<p class="wp-block-paragraph">Time to do some Tracin&#8217;. In the render kernel we can use pixel coordinates <code>x</code> and <code>y</code> to generate a primary ray:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">__kernel void render( __global uint* target, ... )
{
    // plot a pixel into the target array in GPU memory
    int threadIdx = get_global_id( 0 );
    int x = threadIdx % SCRWIDTH;
    int y = threadIdx / SCRWIDTH;
    // create a primary ray for the pixel
    struct Ray ray;
    ray.O = camPos;
    float3 pixelPos = ray.O + p0 +
        (p1 - p0) * ((float)x / SCRWIDTH) +
        (p2 - p0) * ((float)y / SCRHEIGHT);
    ray.D = normalize( pixelPos - ray.O );
    ray.hit.t = 1e30f; // 1e30f denotes 'no hit'
    // trace the primary ray
    ...
}</pre></div>



<p class="wp-block-paragraph">Setting up the ray requires a camera position <code>camPos</code> and three screen corners <code>p0</code>, <code>p1</code> and <code>p2</code>. On the CPU we would calculate those outside the tile/pixel loop, because they are the same for all pixels. For GPU code, the only way to do something &#8216;outside the loop&#8217; is to do it <em>on the CPU</em>. We thus pass the four positions as arguments of the kernel:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">__kernel void render( __global uint* target, float3 camPos, float3 p0, float3 p1, float3 p2 )
{
    ...
}</pre></div>



<p class="wp-block-paragraph">On the CPU-side, the change is straight-forward:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">tracer-&gt;SetArguments( target, camPos, p0, p1, p2 );</pre></div>



<p class="wp-block-paragraph">Setting up a ray requires a <code>Ray</code> class. We could move the CPU-side <code>Ray</code> definition to <code>common.h</code> to use the same struct on CPU and GPU, but that has issues: The CPU <code>Ray</code> definition uses <code>__m128</code> variables for SIMD processing, which is not supported on GPUs. It is simpler to just re-define <code>Ray</code> in <code>kernels.cl</code>, and, with it, <code>Intersection</code>:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">struct Intersection
{
    float t;                    // intersection distance along ray
    float u, v;	                // barycentric coordinates of the intersection
    uint instPrim;              // instance index (12 bit) and primitive index (20 bit)
};

struct Ray
{
    float3 O, D, rD;            // in OpenCL, each of these will be padded to 16 bytes
    struct Intersection hit;    // total ray size: 64 bytes
};</pre></div>



<p class="wp-block-paragraph">Note the strong similarity between C code and OpenCL code. Some differences exist as well though; where C++ lets us get away with just using <code>Intersection</code> as a type for member <code>hit</code> in struct <code>Ray</code>, OpenCL insists on calling it <code>struct Intersection hit</code>. Likewise, <code>Ray ray</code> in the kernel <em>must</em> be labeled <code>struct Ray ray</code>. Another notable difference that we encounter early on: you can&#8217;t pass anything <em>&#8216;by reference&#8217;</em>, so when we call the <code>Trace</code> function, we either pass the ray <em>&#8216;by value&#8217;</em> or using a pointer.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 Trace( struct Ray* ray )
{
    return (float3)( 1, 1, 1 );
}</pre></div>



<p class="wp-block-paragraph">The initial version of function Trace (which just returns a white pixel) reveals one more nuisance. A <code>float3</code> is not constructed using <code>float3( 1, 1, 1 )</code>, but instead using <code>(float3)( 1, 1, 1 )</code>, as shown in the code snippet.</p>



<p class="wp-block-paragraph">Function <code>Trace</code> returns a <code>float3</code>, like we did in the CPU code. Since the buffer that the kernel operates on is in fact an unsigned int buffer, we need to convert the final pixel value from <code>float3</code> to <code>uint</code>:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">inline uint RGB32FtoRGB8( float3 c )
{
    int r = (int)(min( c.x, 1.f ) * 255);
    int g = (int)(min( c.y, 1.f ) * 255);
    int b = (int)(min( c.z, 1.f ) * 255);
    return (r &lt;&lt; 16) + (g &lt;&lt; 8) + b;
}

__kernel void render( __global uint* target, float3 camPos, float3 p0, float3 p1, float3 p2 )
{
    ...
    // trace the primary ray
    float3 color = Trace( &amp;ray );
    // plot the result
    target[x + y * SCRWIDTH] = RGB32FtoRGB8( color );
}</pre></div>



<p class="wp-block-paragraph">We now have a kernel that renders a white window. But let&#8217;s look on the bright side: The white pixels are produced using correct primary rays, using a <code>Trace</code> function that should be easy to extend to what we had on the CPU.</p>



<h2 class="wp-block-heading">Sky</h2>



<p class="wp-block-paragraph">The easiest way to prove that the primary rays are in fact correct is by converting the skydome functionality.</p>



<p class="wp-block-paragraph">In the CPU code, in <code>::Tick</code>, we create a new buffer:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">skyData = new Buffer( skyWidth * skyHeight * 3 * sizeof( float ), skyPixels );
    skyData-&gt;CopyToDevice();</pre></div>



<p class="wp-block-paragraph">The buffer takes the existing HDR skydome, stored in <code>skyPixels</code>. The second line copies the data to the GPU. We need to do this only once: Skydomes generally don&#8217;t change over time, so there will be no per-frame data transport for this data. To use the data in the kernel we do however need to pass a pointer to it. We add an argument to the kernel:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">__kernel void render( __global uint* target, float* skyData, float3 camPos, float3 p0, float3 p1, float3 p2 )
{
    ...
}</pre></div>



<p class="wp-block-paragraph">In the CPU code, in <code>::Tick</code>, we pass the pointer to the data on the GPU device.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">tracer-&gt;SetArguments( target, skyData, camPos, p0, p1, p2 );</pre></div>



<p class="wp-block-paragraph">To make the data accessible in the Trace function, we simply pass it along:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 Trace( struct Ray* ray, float* skyPixels )
{
    ...
}

__kernel void render( __global uint* target, float* skyPixels, float3 camPos, float3 p0, float3 p1, float3 p2 )
{
    ...
    // trace the primary ray
    float3 color = Trace( &amp;ray, skyPixels );
    // plot the result
    target[x + y * SCRWIDTH] = RGB32FtoRGB8( color );
}</pre></div>



<p class="wp-block-paragraph">Inside <code>Trace</code>, we now have a ray, and <code>skyPixels</code>. We can test both by pretending that we never hit any geometry; this should yield a rotating skydome without teapots. Code:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 Trace( struct Ray* ray, float* skyPixels )
{
    // sample sky
    float phi = atan2( ray-&gt;D.z, ray-&gt;D.x );
    uint u = (uint)(3200 * (phi &gt; 0 ? phi : (phi + 2 * PI)) * INV2PI - 0.5f);
    uint v = (uint)(1600 * acos( ray-&gt;D.y ) * INVPI - 0.5f);
    uint skyIdx = (u + v * 3200) % (3200 * 1600);
    return 0.65f * (float3)(skyPixels[skyIdx * 3], skyPixels[skyIdx * 3 + 1], skyPixels[skyIdx * 3 + 2]);
}</pre></div>



<p class="wp-block-paragraph">That requires some explanation. First of all, the size of the skydome texture is now hardcoded. To make that more generic, we really should really pass <code>skyWidth</code> and <code>skyHeight</code> along with the <code>skyPixels</code> pointer. Secondly, <code>INVPI</code> and <code>INV2PI</code> are conveniently used from <code>common.h</code>: Including it pays off again. And finally: some math functions have different names in OpenCL. Here: <code>atan2f</code> and <code>acosf</code> become <code>atan2</code> and <code>acos</code>. Some functions also have slightly different behavior. Here: <code>atan2</code> can yield a negative number that we need to handle.</p>



<p class="wp-block-paragraph">The kernel now produces a considerably more interesting image:</p>


<div class="wp-block-image is-resized">
<figure class="aligncenter size-large"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/gpusky-1-1024x599.jpg" alt="" style="width:512px"/></figure>
</div>


<h2 class="wp-block-heading">BVH Data</h2>



<p class="wp-block-paragraph">Let&#8217;s take a step back, and see what other data we need on the GPU to complete the <code>Trace</code> function.</p>



<ul class="wp-block-list">
<li>A single mesh, with Tri and TriEx arrays.</li>



<li>A BVH for the mesh, consisting of a triangle index array and a set of nodes.</li>



<li>A texture: again, just one.</li>



<li>An array of BVHInstances, which includes transforms.</li>



<li>A TLAS, with instance indices in the leaves.</li>
</ul>



<p class="wp-block-paragraph">To get all this data to the GPU, we start with creating seven buffers, using the data we have created on the CPU side, at the end of the <code>::Init()</code> function:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">triData = new Buffer( 1024 * sizeof( Tri ), mesh-&gt;tri );
    triExData = new Buffer( 1024 * sizeof( TriEx ), mesh-&gt;triEx );
    Surface* tex = mesh-&gt;texture;
    texData = new Buffer( tex-&gt;width * tex-&gt;height * sizeof( uint ), tex-&gt;pixels );
    instData = new Buffer( 256 * sizeof( BVHInstance ), bvhInstance );
    tlasData = new Buffer( tlas.nodesUsed * sizeof( TLASNode ), tlas.tlasNode );
    bvhData = new Buffer( mesh-&gt;bvh-&gt;nodesUsed * sizeof( BVHNode ), mesh-&gt;bvh-&gt;bvhNode );
    idxData = new Buffer( 1024 * sizeof( uint ), mesh-&gt;bvh-&gt;triIdx );</pre></div>



<p class="wp-block-paragraph">Buffers <code>triData</code> and <code>triExData</code> still assume the hardcoded triangle limit of 1024 triangles in the <code>Mesh</code> class, which is enough for the teapot object. If you already relaxed this constraint, you can just replace 1024 by the actual number of triangles in the mesh.</p>



<p class="wp-block-paragraph">Once all the buffers are created, we copy them to the GPU: </p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">triData-&gt;CopyToDevice();
    triExData-&gt;CopyToDevice();
    texData-&gt;CopyToDevice();
    instData-&gt;CopyToDevice();
    bvhData-&gt;CopyToDevice();
    idxData-&gt;CopyToDevice();</pre></div>



<p class="wp-block-paragraph">One buffer is missing from this list: the <code>tlasData</code> buffer. This buffer changes every frame when we animate objects and update the TLAS; the call to <code>CopyToDevice()</code> will thus go to the <code>::Tick()</code> function rather than the <code>::Init()</code> function.</p>



<p class="wp-block-paragraph">To get pointers to all this data in the kernel code, we pass all the pointers to the kernel, like we did with the skydome texture data:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">tracer-&gt;SetArguments( 
        target, skyData, 
        triData, triExData, texData, tlasData, instData, bvhData, idxData, 
        camPos, p0, p1, p2 
    );</pre></div>



<p class="wp-block-paragraph">In <code>kernels.cl</code> we update the definition of the <code>render</code> kernel:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">__kernel void render( __global uint* target, __global float* skyPixels,
    __global struct Tri* triData, __global struct TriEx* triExData,
    __global uint* texData, __global struct TLASNode* tlasData,
    __global struct BVHInstance* instData,
    __global struct BVHNode* bvhNodeData, __global uint* idxData,
    float3 camPos, float3 p0, float3 p1, float3 p2 
)
{
    ...
}</pre></div>



<p class="wp-block-paragraph">OpenCL allows us to pass pointers to undefined structs like <code>Tri</code> and <code>TriEx</code>, but to use these, we&#8217;ll need to properly define them. This however reveals an important complication.</p>



<h2 class="wp-block-heading">Alignment</h2>



<p class="wp-block-paragraph">The problem is the <code>float3</code> type. On the CPU side, we expect it to be 12 bytes in size; in fact, we rely on this, e.g. in the (rather important) <code>TLASNode</code> class, which fits snuggly in 32 bytes:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">struct TLASNode
{
    float3 aabbMin;
    uint leftRight; // 2x16 bits
    float3 aabbMax;
    uint BLAS;
    ...
};</pre></div>



<p class="wp-block-paragraph">In OpenCL, things are different. A GPU can read 16 bytes from memory more quickly than 12 bytes, and therefore, a <code>float3</code> is padded with a dummy field, to make it 16 bytes. To enforce the correct layout of the <code>TLASNode</code>s that we receive from the CPU, we can define the struct as follows:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">struct TLASNode
{
    float minx, miny, minz;
    uint leftRight; // 2x16 bits
    float maxx, maxy, maxz;
    uint BLAS;
};</pre></div>



<p class="wp-block-paragraph">This struct is 32 bytes in size, and has the same layout as the CPU version. Copying data into this should thus yield the correct result. </p>



<p class="wp-block-paragraph">The other structs that use <code>float3</code> variables can be modified in a similar fashion:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">struct Tri 
{ 
    float v0x, v0y, v0z;
    float v1x, v1y, v1z;
    float v2x, v2y, v2z;
    float cx, cy, cz;
};

struct TriEx 
{ 
    float2 uv0, uv1, uv2; 
    float N0x, N0y, N0z;
    float N1x, N1y, N1z;
    float N2x, N2y, N2z;
    float dummy;
};

struct BVHNode
{
    float minx, miny, minz;
    int leftFirst;
    float maxx, maxy, maxz;
    int triCount;
};</pre></div>



<p class="wp-block-paragraph">The last structure that we need is the <code>BVHInstance</code> class. The CPU version of this class has some data and methods that we don&#8217;t need for rendering on the GPU: on the GPU end we just need the two matrices it holds. Still, synchronization is easier if we keep the same layout, so we devise a struct that does the job:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">struct BVHInstance
{
    uint dummy1, dummy2;
    uint idx;
    float16 transform;
    float16 invTransform; // inverse transform
    uint dummy[6];
};</pre></div>



<p class="wp-block-paragraph">The variables <code>dummy1</code> and <code>dummy2</code> together take up 8 bytes, just like the <code>BVH*</code> in the original class. The last member variable, <code>aabb bounds</code>, is 6 times 4 bytes in size, just like the <code>uint dummy</code> array at the end of the proposed struct. Note the odd <code>float16</code> data type: this will represent the <code>mat4</code> we used on the CPU.</p>



<p class="wp-block-paragraph">All data is in position, time to start rendering.</p>



<h2 class="wp-block-heading">Tea Time</h2>



<p class="wp-block-paragraph">To render a teapot using ray tracing on the GPU, we need an OpenCL version of the <code>BVH::Intersect</code> function, which implements BLAS traversal. Once this works, we can convert TLAS traversal and shading, but all that will not produce anything verifiable without proper BLAS traversal. Let&#8217;s start with the CPU code, and tweak it until it works:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void BVH::Intersect( Ray&amp; ray, uint instanceIdx )
{
    BVHNode* node = &amp;bvhNode[0], *stack[64];
    uint stackPtr = 0;
    while (1)
    {
        if (node-&gt;isLeaf())
        {
            for (uint i = 0; i &lt; node-&gt;triCount; i++)
            {
                uint instPrim = (instanceIdx &lt;&lt; 20) + triIdx[node-&gt;leftFirst + i];
                IntersectTri( ray, mesh-&gt;tri[instPrim &amp; 0xfffff /* 20 bits */], instPrim );
            }
            if (stackPtr == 0) break; else node = stack[--stackPtr];
            continue;
        }
        BVHNode* child1 = &amp;bvhNode[node-&gt;leftFirst];
        BVHNode* child2 = &amp;bvhNode[node-&gt;leftFirst + 1];
        float dist1 = IntersectAABB( ray, child1-&gt;aabbMin, child1-&gt;aabbMax );
        float dist2 = IntersectAABB( ray, child2-&gt;aabbMin, child2-&gt;aabbMax );
        if (dist1 &gt; dist2) { swap( dist1, dist2 ); swap( child1, child2 ); }
        if (dist1 == 1e30f)
        {
            if (stackPtr == 0) break; else node = stack[--stackPtr];
        }
        else
        {
            node = child1;
            if (dist2 != 1e30f) stack[stackPtr++] = child2;
        }
    }
}</pre></div>



<p class="wp-block-paragraph">The first change we make is the function header. OpenCL is not an object-oriented language, so <code>BVH::Intersect</code> will have to be a function at the global scope. We also need to make changes to the data we pass into it: The <code>Ray&amp;</code> must either become a <code>struct Ray*</code>, or simply a <code>struct Ray</code> (i.e., by value). In this case the pointer is the better option, primarily because we will change the ray that is handed to us. And finally, we&#8217;ll need some additional data that we accessed via the <code>BVH</code> class so far: The triangle data, and of course the BVH data, consisting of nodes and triangle indices.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void BVHIntersect( struct Ray* ray, uint instanceIdx, 
    struct Tri* tri, struct BVHNode* bvhNode, uint* triIdx )
{
    ...
}</pre></div>



<p class="wp-block-paragraph">After adding the struct keyword on lines 3, 17 and 18 (before each <code>BVHNode*</code> declaration), line 7 shows up in the error log. Because strict methods are not allowed in OpenCL, we replace the condition by:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">if (node-&gt;triCount &gt; 0) // isLeaf()</pre></div>



<p class="wp-block-paragraph">Next up is the call to <code>IntersectTri(...)</code>. This function doesn&#8217;t exist yet, so let&#8217;s add it and convert it to OpenCL:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void IntersectTri( struct Ray* ray, struct Tri* tri, const uint instPrim )
{
    float3 v0 = (float3)(tri-&gt;v0x, tri-&gt;v0y, tri-&gt;v0z);
    float3 v1 = (float3)(tri-&gt;v1x, tri-&gt;v1y, tri-&gt;v1z);
    float3 v2 = (float3)(tri-&gt;v2x, tri-&gt;v2y, tri-&gt;v2z);
    float3 edge1 = v1 - v0, edge2 = v2 - v0;
    float3 h = cross( ray-&gt;D, edge2 );
    float a = dot( edge1, h );
    if (a &gt; -0.00001f &amp;&amp; a &lt; 0.00001f) return; // ray parallel to triangle
    float f = 1 / a;
    float3 s = ray-&gt;O - v0;
    float u = f * dot( s, h );
    if (u &lt; 0 || u &gt; 1) return;
    float3 q = cross( s, edge1 );
    float v = f * dot( ray-&gt;D, q );
    if (v &lt; 0 || u + v &gt; 1) return;
    float t = f * dot( edge2, q );
    if (t &gt; 0.0001f &amp;&amp; t &lt; ray-&gt;hit.t)
        ray-&gt;hit.t = t, ray-&gt;hit.u = u,
        ray-&gt;hit.v = v, ray-&gt;hit.instPrim = instPrim;
}</pre></div>



<p class="wp-block-paragraph">Note that after obtaining the three <code>float3</code>&#8216;s for the vertices (lines 3-5, highlighted), the code is quite straight-forward and close to the C++ original: Even the cross-product on line 7 is supported out-of-the-box by OpenCL. We call the <code>IntersectTri</code> from <code>BVHIntersect</code>, using a pointer to a single triangle:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">IntersectTri( ray, &amp;tri[instPrim &amp; 0xfffff /* 20 bits */], instPrim );</pre></div>



<p class="wp-block-paragraph">One more remaining issue is now the AABB intersection, called from lines 19 and 20. Luckily we kept the non-SIMD version, which is easily converted to OpenCL. Original:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">inline float IntersectAABB( const Ray&amp; ray, const float3 bmin, const float3 bmax )
{
    float tx1 = (bmin.x - ray.O.x) * ray.rD.x, tx2 = (bmax.x - ray.O.x) * ray.rD.x;
    float tmin = min( tx1, tx2 ), tmax = max( tx1, tx2 );
    float ty1 = (bmin.y - ray.O.y) * ray.rD.y, ty2 = (bmax.y - ray.O.y) * ray.rD.y;
    tmin = max( tmin, min( ty1, ty2 ) ), tmax = min( tmax, max( ty1, ty2 ) );
    float tz1 = (bmin.z - ray.O.z) * ray.rD.z, tz2 = (bmax.z - ray.O.z) * ray.rD.z;
    tmin = max( tmin, min( tz1, tz2 ) ), tmax = min( tmax, max( tz1, tz2 ) );
    if (tmax &gt;= tmin &amp;&amp; tmin &lt; ray.hit.t &amp;&amp; tmax &gt; 0) return tmin; else return 1e30f;
}</pre></div>



<p class="wp-block-paragraph">And the OpenCL version, which uses the &#8216;three-float notation&#8217; for the extends of the bounding box stored in a <code>BVHNode</code>:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float IntersectAABB( struct Ray* ray, struct BVHNode* node )
{
    float tx1 = (node-&gt;minx - ray-&gt;O.x) * ray-&gt;rD.x, tx2 = (node-&gt;maxx - ray-&gt;O.x) * ray-&gt;rD.x;
    float tmin = min( tx1, tx2 ), tmax = max( tx1, tx2 );
    float ty1 = (node-&gt;miny - ray-&gt;O.y) * ray-&gt;rD.y, ty2 = (node-&gt;maxy - ray-&gt;O.y) * ray-&gt;rD.y;
    tmin = max( tmin, min( ty1, ty2 ) ), tmax = min( tmax, max( ty1, ty2 ) );
    float tz1 = (node-&gt;minz - ray-&gt;O.z) * ray-&gt;rD.z, tz2 = (node-&gt;maxz - ray-&gt;O.z) * ray-&gt;rD.z;
    tmin = max( tmin, min( tz1, tz2 ) ), tmax = min( tmax, max( tz1, tz2 ) );
    if (tmax &gt;= tmin &amp;&amp; tmin &lt; ray-&gt;hit.t &amp;&amp; tmax &gt; 0) return tmin; else return 1e30f;
}</pre></div>



<p class="wp-block-paragraph">The final problem in BVHIntersect is a bit silly: OpenCL doesn&#8217;t have a &#8216;swap&#8217; function. So, when we find that the second child is closer than the first, we swap their pointers and distances manually:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">if (dist1 &gt; dist2) 
    { 
        float d = dist1; dist1 = dist2; dist2 = d;
        struct BVHNode* c = child1; child1 = child2; child2 = c; 
    }</pre></div>



<p class="wp-block-paragraph">The full BVHIntersect function, ported to OpenCL:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void BVHIntersect( struct Ray* ray, uint instanceIdx, 
    struct Tri* tri, struct BVHNode* bvhNode, uint* triIdx )
{
    struct BVHNode* node = &amp;bvhNode[0], *stack[32];
    uint stackPtr = 0;
    while (1)
    {
        if (node-&gt;triCount &gt; 0) // isLeaf()
        {
            for (uint i = 0; i &lt; node-&gt;triCount; i++)
            {
                uint instPrim = (instanceIdx &lt;&lt; 20) + triIdx[node-&gt;leftFirst + i];
                IntersectTri( ray, &amp;tri[instPrim &amp; 0xfffff /* 20 bits */], instPrim );
            }
            if (stackPtr == 0) break; else node = stack[--stackPtr];
            continue;
        }
        struct BVHNode* child1 = &amp;bvhNode[node-&gt;leftFirst];
        struct BVHNode* child2 = &amp;bvhNode[node-&gt;leftFirst + 1];
        float dist1 = IntersectAABB( ray, child1 );
        float dist2 = IntersectAABB( ray, child2 );
        if (dist1 &gt; dist2) 
        { 
            float d = dist1; dist1 = dist2; dist2 = d;
            struct BVHNode* c = child1; child1 = child2; child2 = c; 
        }
        if (dist1 == 1e30f)
        {
            if (stackPtr == 0) break; else node = stack[--stackPtr];
        }
        else
        {
            node = child1;
            if (dist2 != 1e30f) stack[stackPtr++] = child2;
        }
    }
}</pre></div>



<p class="wp-block-paragraph">All done. We can call this function from <code>Trace</code>, to see if the rather massive amount of new code and data actually works. At the start of the <code>Trace</code> function we call the new <code>BVHIntersect</code> function:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">// see if we hit a teapot
    BVHIntersect( ray, 0, triData, bvhNodeData, idxData );
    if (ray-&gt;hit.t &lt; 1e30f) return (float3)(1,1,1);</pre></div>



<p class="wp-block-paragraph">This <em>should</em> produce white teapot, without any shading, and skydome pixels for all rays that do not hit the teapot. And lo and behold!:</p>


<div class="wp-block-image is-resized">
<figure class="aligncenter size-large"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/gputea-1024x576.jpg" alt="" style="width:512px"/></figure>
</div>


<h2 class="wp-block-heading">TODO</h2>



<p class="wp-block-paragraph">Now, we&#8217;re obviously not done. It&#8217;s just one teapot, it is not animated, there&#8217;s no reflection and no texture. But really, that is for another day, the article is long enough as it is. But from here things should go smooth: OpenCL is now under our command, and the data is in position. Next time we <em>really</em> complete the project, with some large-scale instanced scenery.</p>



<h2 class="wp-block-heading">Closing Remarks</h2>



<p class="wp-block-paragraph">The complete code for this project, in ten convenient incremental stages, <a href="https://github.com/jbikker/bvh_article">can be found on GitHub</a> (for Windows / Visual Studio).</p>



<p class="wp-block-paragraph">Enjoyed the article? Spotted an error?</p>



<p class="wp-block-paragraph">Ping me on Twitter (<a href="https://twitter.com/j_bikker">@j_bikker</a>), comment on this article, or send an email to <a href="mailto:bikker.j@gmail.com">bikker.j@gmail.com</a>.<br>You can also find me on Github:  <a href="https://github.com/jbikker/lighthouse2">https://github.com/jbikker</a>.</p>



<p class="wp-block-paragraph">Or read some more articles: <a href="https://jacco.ompf2.com">https://jacco.ompf2.com</a>. Some favorites:</p>



<ul class="wp-block-list">
<li><a href="https://jacco.ompf2.com/2019/07/18/wavefront-path-tracing/">Wavefront path tracing</a></li>



<li>Probability Theory for Physically Based Rendering &#8211; <a href="https://jacco.ompf2.com/2019/12/11/probability-theory-for-physically-based-rendering/">part 1</a></li>



<li>Probability Theory for Physically Based Rendering &#8211; <a href="https://jacco.ompf2.com/2019/12/13/probability-theory-for-physically-based-rendering-part-2/">part 2</a></li>



<li><a href="https://jacco.ompf2.com/2020/05/12/opt3simd-part-1-of-2/">OPT#3: SIMD</a> (part 1 of 2) &#8211; <em>also check the other optimization blog posts!</em></li>
</ul>



<p class="wp-block-paragraph"></p>
]]></content:encoded>
					
					<wfw:commentRss>https://jacco.ompf2.com/2022/06/03/how-to-build-a-bvh-part-9a-to-the-gpu/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
