<?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>Source Code &#8211; Jacco&#039;s Blog</title>
	<atom:link href="https://jacco.ompf2.com/category/source-code/feed/" rel="self" type="application/rss+xml" />
	<link>https://jacco.ompf2.com</link>
	<description>Links, Code &#38; Articles</description>
	<lastBuildDate>Fri, 21 Mar 2025 14:32:45 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.5</generator>

<image>
	<url>https://jacco.ompf2.com/wp-content/uploads/2019/03/cropped-robotlab-32x32.jpg</url>
	<title>Source Code &#8211; Jacco&#039;s Blog</title>
	<link>https://jacco.ompf2.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<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>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>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 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>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>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>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>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>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>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>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>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>Here, 11050 is approximately the number of vertices in the dragon mesh.</p>



<p>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>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>Time to add TLAS traversal.</p>



<h2 class="wp-block-heading">GPU TLAS</h2>



<p>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>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>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>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>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>We call two functions from <code>TLASIntersect</code> that we have not defined yet.</p>



<p>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>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>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>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>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>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>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>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>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>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>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>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>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>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>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>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>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>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>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>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>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>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>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>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>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>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>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>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>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>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>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>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>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>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>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>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>Such a scene deserves a proper view.</p>



<p>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 fetchpriority="high" 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="(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>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>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>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>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>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>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>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>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>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>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>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>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>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>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>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>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><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><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><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><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><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><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 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="(max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">Frame from the Lighthouse 2 real-time path tracing benchmark.</figcaption></figure></div>


<p>That&#8217;s just my ideas though. Let me know what your plans are, but whatever you do, keep tracing.</p>



<p>And with that, allow me to sign off for once as if it&#8217;s 1999 on Flipcode:</p>



<p>Love you all,</p>



<p>Jacco Bikker, <em>a.k.a. &#8220;The Phantom&#8221;.</em></p>



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



<p>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>Enjoyed the article? Spotted an error?</p>



<p>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>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>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>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 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 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 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>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>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>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>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>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>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>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>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 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="(max-width: 635px) 100vw, 635px" /></figure></div>


<p>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>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>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>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>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>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>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>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>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>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>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>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>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>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>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>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>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>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>The easiest way to prove that the primary rays are in fact correct is by converting the skydome functionality.</p>



<p>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>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>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>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>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>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>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>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>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>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>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>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>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>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>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>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>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>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>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>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>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>All data is in position, time to start rendering.</p>



<h2 class="wp-block-heading">Tea Time</h2>



<p>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>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>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>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>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>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>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>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>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>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>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>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>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>Enjoyed the article? Spotted an error?</p>



<p>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>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></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>
		<item>
		<title>How to build a BVH &#8211; part 8: Whitted-Style</title>
		<link>https://jacco.ompf2.com/2022/05/27/how-to-build-a-bvh-part-8-whitted-style/</link>
					<comments>https://jacco.ompf2.com/2022/05/27/how-to-build-a-bvh-part-8-whitted-style/#comments</comments>
		
		<dc:creator><![CDATA[jbikker]]></dc:creator>
		<pubDate>Fri, 27 May 2022 12:48:30 +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=1329</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>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>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><strong>Consolidating, part 2: Whitted-style ray tracing (this article).</strong></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><a href="https://jacco.ompf2.com/2022/06/15/how-to-build-a-bvh-part-9b-massive/">OpenCL: GPU ray tracing, part 2 (series finale)</a>.</li>
</ol>



<p id="block-0335045c-892a-4222-aee1-ff87a91ce61a">With a proper acceleration structure for animated scenes in place, it is time to put it to use. Last time we <a href="https://jacco.ompf2.com/2022/05/20/how-to-build-a-bvh-part-7-consolidate/">laid the groundwork</a>, with a carefully crafted 16-byte hit record for rays, a floating point image buffer (a.k.a. the accumulator) and a restructured application. Everything is now ready for the implementation of a recursive ray tracer, also known as a <em>Whitted-style</em> ray tracer, after the inventor of the algorithm, Turner Whitted.</p>



<h2 class="wp-block-heading">Previously, in this series</h2>



<p>In the previous episode we ended up with a pretty basic <code>Trace</code> function, which contains the code executed for each pixel of the rendered image:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 WhittedApp::Trace( Ray&amp; ray )
{
    tlas.Intersect( ray );
    Intersection i = ray.hit;
    if (i.t == 1e30f) return float3( 0 );
    return float3( i.u, i.v, 1 - (i.u + i.v) );
}</pre></div>



<p>This function returns an RGB color in a floating point vector. In this color representation, RGB={1,1,1} is white. Note that the more common 0..255 color component encoding, although familiar, is not any more &#8216;natural&#8217; or &#8216;logical&#8217;: the 0..255 range is simply the best we can get when we store each color component in 8 bits. Using floating point numbers, a range of 0..1 makes more sense: e.g., 0 for red means the material does not reflect any red, while 1 means that the material is a perfect reflector for red light. Any value above 1 indicates that the material emits light. A floating point color representation is the format of choice for <em>physically based rendering</em>, where reflections cannot exceed 100% of incoming light and emissive colors can be far brighter than what {255,255,255} (i.e., 0xFFFFFF in hexadecimal) in integers can represent.</p>



<p>Getting from the image that we ended up with in article 7 to something that we might consider &#8216;realistic&#8217; requires some work. In today&#8217;s article, we will cover the following ingredients:</p>



<ol class="wp-block-list">
<li><span style="color: initial;">Per-pixel material colors using barycentric coordinates and a texture map.</span></li>



<li>A proper per-pixel normal at the point of intersection.</li>



<li>Basic &#8216;Lambert&#8217; shading using the smooth normal and a point light source.</li>



<li>A skydome, represented by an HDR texture.</li>



<li>Recursive reflections using secondary rays.</li>
</ol>



<p>The primary rays, which we feed into the <code>Trace</code> function, as well as secondary rays, will use the BVH functionality we developed earlier. This means that the Whitted-style ray tracer will be able to render animated scenes, in real-time.</p>



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



<p>To keep track of progress, here&#8217;s an image of our starting point, taken from the end of article 7:</p>


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


<p>Step one is to replace the debug visualization of the barycentric coordinates by a proper texture. The texture we will be using for the teapots is this one:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/bricks.jpg" alt="" style="width:360px"/><figcaption class="wp-element-caption">assets/bricks.png, via richiepanda.ee</figcaption></figure></div>


<p>This texture was already loaded for the teapot, along with the obj file, in <code>::Init</code>:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">mesh = new Mesh( "assets/teapot.obj", "assets/bricks.png" );</pre></div>



<p>The texture is applied to the teapots by reading a color from it for each intersection of a ray and a triangle. We already have all the information to do this: </p>



<ul class="wp-block-list">
<li>the <code>Intersection</code> record contains information about which triangle we intersected;</li>



<li>the record also contains the barycentric coordinates of the hit point;</li>



<li>the <code>triEx</code> array of the <code>Mesh</code> contains the texture coordinates of the triangle vertices;</li>



<li>the <code>Mesh</code> object contains a pointer to the texture.</li>
</ul>



<p>However, the <code>Intersection</code> record does store things rather compact. Let&#8217;s unpack the information we need:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">uint triIdx = i.instPrim &amp; 0xfffff;
    uint instIdx = i.instPrim &gt;&gt; 20;</pre></div>



<p>Field <code>instPrim</code> stores the instance index and the primitive index. The primitive index can be used to access one triangle, either in the <code>Mesh::tri</code> array or in the <code>Mesh::triEx</code> array. For texturing, we need <code>TriEx</code> data, which holds texture coordinates and vertex normals.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">TriEx&amp; tri = mesh-&gt;triEx[triIdx];</pre></div>



<p>The texture can simply be obtained from the mesh. For this article we will stick to a single texture, but in case different instances use different textures, a texture can also be selected based on the instance index.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">Surface* tex = mesh-&gt;texture;</pre></div>



<p>Next, we need to calculate a position in the texture, where we will read a single pixel. By the way: pixels from a texture map are commonly referred to as <em>texels</em>. The texture coordinate of the ray/triangle intersection point is somewhere between the texture coordinates of the triangle vertices. The exact position is determined using the barycentric coordinates of the intersection test. Be careful when deciphering the following snippet: convention says that both barycentric coordinates and texture coordinates are referred to as u,v&#8230; The calculated vector <code>uv</code> thus denotes a texture coordinate, while <code>i.u</code> and <code>i.v</code> hold the barycentric coordinates at the intersection point.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float2 uv = i.u * tri.uv1 + i.v * tri.uv2 + (1 - (i.u + i.v)) * tri.uv0;</pre></div>



<p>Here, <code>i.u</code> and <code>i.v</code> are two of the three barycentric coordinates of the intersection point on the triangle. The third barycentric coordinate is <code>1-(i.u+i.v)</code>. Using these we obtain a coordinate on the texture, which we store in the 2D vector <code>uv</code>. Note that the three vertices of the triangle have been reordered, from <span class="wp-katex-eq" data-display="false">{0,1,2}</span> to <span class="wp-katex-eq" data-display="false">{1,2,0}</span>: this has to do with the ordering used in the triangle intersection code.</p>



<p>At this point another convention needs to be mentioned: Texture coordinates are decoupled from texture resolution. The top-left corner of a texture is (0,0), while the bottom-right corner is (1,1) rather than e.g. (511,511) for a 512&#215;512 texture. To actually read data from the bitmap, we thus need to multiply <code>uv</code> by the size of the texture. The benefit of this approach is that we can replace textures by images of different dimensions, without consequences for the uv-coordinates.</p>



<p>To complicate things further: although the coordinates typically range from (0,0) to (1,1), we may still encounter coordinates outside this range. This happens for instance when the texture is repeated over the object. E.g., to apply the texture on a single triangle in a 2&#215;2 tile pattern, we would use the range (0,0) to (2,2).</p>



<p>The following code applies the proper scale, and uses a modulo to ensure that tiled textures still yield integer pixel positions within the bitmap:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">int iu = (int)(uv.x * tex-&gt;width) % tex-&gt;width;
    int iv = (int)(uv.y * tex-&gt;height) % tex-&gt;height;
    uint texel = tex-&gt;pixels[iu + iv * tex-&gt;width];</pre></div>



<p>We&#8217;re almost done. Variable <code>texel</code> contains an integer color, while the Trace function expects (and returns) floating point colors. Converting from 8-bit integer RGB to 32-bit floating point RGB is done with a small helper function:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">inline float3 RGB8toRGB32F( uint c )
{
    float s = 1 / 256.0f;
    int r = (c &gt;&gt; 16) &amp; 255;  // extract the red byte
    int g = (c &gt;&gt; 8) &amp; 255;   // extract the green byte
    int b = c &amp; 255;          // extract the blue byte
    return float3( r * s, g * s, b * s );
}</pre></div>



<p>We now have a material color, obtained from the texture. This material color, or better: <em>material reflectivity</em>, is in physics referred to as <em>albedo</em>. For now, we simply return this as the end result of the Trace function, which, in its entirety, now looks as follows:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 WhittedApp::Trace( Ray&amp; ray )
{
    tlas.Intersect( ray );
    Intersection i = ray.hit;
    if (i.t == 1e30f) return float3( 0 );
    // calculate texture uv based on barycentrics
    uint triIdx = i.instPrim &amp; 0xfffff;
    uint instIdx = i.instPrim &gt;&gt; 20;
    TriEx&amp; tri = mesh-&gt;triEx[triIdx];
    Surface* tex = mesh-&gt;texture;
    float2 uv = i.u * tri.uv1 + i.v * tri.uv2 + (1 - (i.u + i.v)) * tri.uv0;
    int iu = (int)(uv.x * tex-&gt;width) % tex-&gt;width;
    int iv = (int)(uv.y * tex-&gt;height) % tex-&gt;height;
    uint texel = tex-&gt;pixels[iu + iv * tex-&gt;width];
    float3 albedo = RGB8toRGB32F( texel );
    return albedo;
}</pre></div>



<p>The result of this step:</p>


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


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



<p>Now that textures are working, normals are simple. Or at least, at first they appear to be. The addition is trivial:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">// calculate the normal for the intersection
    float3 N = i.u * tri.N1 + i.v * tri.N2 + (1 - (i.u + i.v)) * tri.N0;</pre></div>



<p>We use the same barycentric coordinates, but instead of interpolating between the uv-coordinates of the vertices, we now interpolate between the vertex normals. </p>



<p>To visualize and inspect the normals we can use a small trick. Normals are vectors with a length of 1; their x, y and z coordinates are guaranteed to be in the range -1..1. We can map this range to colors. For this, we add 1 to x, y and z &#8211; this brings them in the range 0..2. Then, we halve the vector, to reduce it to the range 0..1. Three components in the range 0..1: that is a color! The teapots, with their normals, look like this:</p>


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


<p>At first sight, that&#8217;s not bad. The lid of the teapot is green, which is color (0,1,0). That makes sense: the normal of the lid has to be pointing up along the y-axis. Likewise, a red color on the right side of the teapots is to be expected: Red is (1,0,0), which is indeed a vector to the right.</p>



<p>But, when we look closer:</p>


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


<p>There&#8217;s seams where we expected smooth normals; the top of the lid looks completely wrong, and, when we look at the spinning teapots: the red side happily rotates to the left and back, instead of staying in place.</p>



<p>To understand the seams, we open the teapot in Visual Studio. Simply drag and drop the teapot.obj file onto the application, and it will be displayed for you in 3D:</p>



<figure class="wp-block-image size-large"><img decoding="async" src="https://www.cs.uu.nl/docs/vakken/magr/ompf2/vsobj-1024x614.jpg" alt=""/></figure>



<p>It turns out that the artifacts are not caused by the ray tracing code: The model is simply broken, somewhat. This is not uncommon; when you obtain your models for free from the internet, this is sometimes a consequence. Let&#8217;s accept the imperfections in this world and move on. </p>



<p>There is still another problem: the rotating normals.</p>



<p>The rotating normals are caused by the transforms that we apply to the scene objects. Vertex normals are specified in object space; they should thus be transformed with the matrix that we applied to the object. A small extension of the normal calculation code takes care of this:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">// calculate the normal for the intersection
    float3 N = i.u * tri.N1 + i.v * tri.N2 + (1 - (i.u + i.v)) * tri.N0;
    N = normalize( TransformVector( N, bvhInstance[instIdx].GetTransform() ) );
    return (N + float3( 1 )) * 0.5f;</pre></div>



<p>The transform that we need is obtained from the <code>bvhInstance</code>, indexed by <code>instIdx</code>, which we got from the <code>Intersection</code> record. Note that the resulting normal must be re-normalized. There are two reasons for this: first of all, the matrix may include a scale, and secondly: interpolation does not guarantee preservation of the vector length. By the way, if the matrix contains a shear or a non-uniform scale, simple re-normalization doesn&#8217;t solve the issue. Let&#8217;s ignore that for now: It is somewhat uncommon and the solution is quite involved.</p>



<p>With these fixes in place, the normals properly stay in place. The final result of this step:</p>


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


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



<p>In the next step we add illumination to the scene. In nature, light transport starts with light sources; without lights everything should thus be black. A simple light source type to start with is a <em>point light</em>. A point light has two properties: a <em>position</em> and a <em>color</em>. Since we are working with floating point colors, we can now specify pretty bright lights, which is a good thing: the light from any source quickly diminishes with distance. The precise relation is quadratic: at a distance <span class="wp-katex-eq" data-display="false">r</span>, only <span class="wp-katex-eq" data-display="false">1/r^2</span> of the emitted intensity remains.</p>



<p>We start with the definition of the light source:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">// illuminate the intersection point
    float3 lightPos( 3, 10, 2 );
    float3 lightColor( 150, 150, 120 );</pre></div>



<p>To calculate the distance from the light to the point we&#8217;re illuminating (the intersection point <span class="wp-katex-eq" data-display="false">I</span>), we of course need to know where this point is. The intersection of the ray and the triangle is along the ray, obviously. It is also at a distance <code>i.t</code> from the ray origin. The point is thus:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 I = ray.O + i.t * ray.D;</pre></div>



<p>We can now calculate the distance from point <span class="wp-katex-eq" data-display="false">I</span> to the light:</p>



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



<p>Apart from distance, we also need to take into account the angle of the triangle towards the light source. For a perfect diffuse material (a.k.a. a Lambert BRDF), the correct attenuation factor is the cosine of the angle between the normal and a normalized vector to the light source. Conveniently, this cosine is calculated using a simple dot product. </p>



<p>We start the calculation by normalizing the <span class="wp-katex-eq" data-display="false">L</span> vector that we used before to calculate the distance to the light source:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">L *= 1.0f / dist;</pre></div>



<p>A call to a &#8216;normalize&#8217; function would also have worked, but the multiplication by <span class="wp-katex-eq" data-display="false">1/dist</span> is faster: we already calculated the distance (which required a square root!), so we can save ourselves another square root. The cosine calculation now becomes:</p>



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



<p>The <code>max( 0, ... )</code> part clamps negative values to zero; this happens for triangles that do not face the light source. Finally, we put everything together:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">return albedo * (
    ambient + 
    max( 0.0f, dot( N, L ) ) * 
    lightColor * 
    (1.0f / (dist * dist))
);</pre></div>



<p>The formula accounts for the cosine of <span class="wp-katex-eq" data-display="false">N</span> and <span class="wp-katex-eq" data-display="false">L</span>, the color of the light source, the RGB albedo of the material, and the distance attenuation. The final factor, &#8216;ambient&#8217;, is a fixed amount of light we add to account for indirect light. Without this, points in the scene that cannot see the light would be pitch black, which looks unnatural.</p>



<p>The result of this step:</p>


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


<p>On my screen, the shading looks a bit off. </p>



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



<p>The next ingredient on our list is a <em>skydome</em>. Right now, when a ray doesn&#8217;t encounter any geometry, the <code>::Trace</code> function returns black. We could replace this by a more interesting color, but a much prettier solution is the use of a textured sphere that encloses the entire scene. The texture for this sphere should be an <em>HDR texture</em>, with floating point pixel values, so that bright parts of the sky can actually be bright. For this step we will use the following texture, of which an HDR version has been added to the assets folder of the <a href="https://github.com/jbikker/bvh_article">project on Github</a>:</p>


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


<p>We can load the HDR bitmap in the <code>::Init</code> function:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">// load HDR sky
    int bpp = 0;
    skyPixels = stbi_loadf( "assets/sky_19.hdr", &amp;skyWidth, &amp;skyHeight, &amp;skyBpp, 0 );
    for (int i = 0; i &lt; skyWidth * skyHeight * 3; i++) skyPixels[i] = sqrtf( skyPixels[i] );</pre></div>



<p>This code uses the <a href="https://github.com/nothings/stb/blob/master/stb_image.h">stb_image</a> image loader library, which is already included with the template used for this series. The <code>stbi_loadf</code> function loads an image to float values, and returns a pointer to the result. In the above snippet, the end result is gamma-adjusted (using the square roots) to reduce the HDR range somewhat; this looks nicer for this particular image. </p>



<p>The loaded texture is a so-called <em>equirectangular panorama</em>. To sample this texture we use the ray direction, and the ray direction alone. This is a bit surprising, but when we consider that for all intends and purposes the skydome has a very large (let&#8217;s say: infinite) radius, a position inside this dome becomes irrelevant.</p>



<p>The formulas for the u and v coordinates in the panorama are:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">uint u = skyWidth * atan2f( ray.D.z, ray.D.x ) * INV2PI - 0.5f;
uint v = skyHeight * acosf( ray.D.y ) * INVPI - 0.5f;</pre></div>



<p>Here, constant <code>INVPI</code> is simply <span class="wp-katex-eq" data-display="false">1/\pi</span>, and <code>INV2PI</code> is <span class="wp-katex-eq" data-display="false">1/2\pi</span>. As usual, I try to prevent actual divisions by multiplying by the reciprocal, for performance reasons.</p>



<p>Handling rays that miss geometry, in its entirety:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">if (i.t == 1e30f) 
   {
       // sample sky
       uint u = skyWidth * atan2f( ray.D.z, ray.D.x ) * INV2PI - 0.5f;
       uint v = skyHeight * acosf( ray.D.y ) * INVPI - 0.5f;
       uint skyIdx = (u + v * skyWidth) % (skyWidth * skyHeight);		
       return 0.65f * float3( skyPixels[skyIdx * 3], skyPixels[skyIdx * 3 + 1], skyPixels[skyIdx * 3 + 2] );
   }</pre></div>



<p>We need to improve camera movement to appreciate the new functionality. For that, we move the camera setup back to <code>::Tick</code>, and tweak it a bit with some matrix magic:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">// render the scene: multithreaded tiles
    static float angle = 0; angle += 0.01f;
    mat4 M1 = mat4::RotateY( angle ), M2 = M1 * mat4::RotateX( -0.65f );
    // setup screen plane in world space
    p0 = TransformPosition( float3( -1, 1, 1.5f ), M2 );
    p1 = TransformPosition( float3( 1, 1, 1.5f ), M2 );
    p2 = TransformPosition( float3( -1, -1, 1.5f ), M2 );
    float3 camPos = TransformPosition( float3( 0, -2, -8.5f ), M1 );</pre></div>



<p>Don&#8217;t forget to store the moving camera position in <code>ray.O</code> inside the main loop. With that in place, the output becomes:</p>


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


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



<p>The shading model we have been using so far is the &#8216;pure diffuse&#8217; BRDF (Bidirectional Reflection Distribution Function, which models the ratio between incoming irradiance and outgoing radiance), also known as the Lambert BRDF. This is simple to model, and, in a Whitted-style ray tracer, non-recursive. Whitted-style ray tracing also can support &#8216;pure specular&#8217; reflections, which lets us model mirrors, and really shiny teapots.</p>



<p>When a ray with direction <span class="wp-katex-eq" data-display="false">D</span> arrives at a mirror with normal <span class="wp-katex-eq" data-display="false">N</span>, the ray should bounce into a new direction <span class="wp-katex-eq" data-display="false">R</span>, which is calculated as</p>



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



<p>The origin of the bounced ray is of course the intersection point where the incoming ray hit the triangle.</p>



<p>The light that travels back via the mirror towards the camera is simply the light that the reflected ray finds.</p>



<p>Let&#8217;s put this in code:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">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;</pre></div>



<p>When the primary ray encounters a reflective triangle (we&#8217;ll see how we determine this in a minute) we create a new ray, called <code>secondary</code>. The secondary ray uses the reflection formula to fill the <code>D</code> field. The origin is the intersection point <code>I</code>, with a small twist: We don&#8217;t want the secondary ray to start exactly <em>on</em> the triangle, because in that case, we may very well find an intersection between the secondary ray and that same triangle, at distance 0. So, we offset the ray slightly: 0.001 in the direction of the reflection. The 0.001 value works well for this particular scene; in general it should be chosen carefully: make it too small and the CPU can&#8217;t distinguish it from 0; make it too large and reflections may miss details near the reflective surface.</p>



<p>The purpose of the secondary ray is to find light energy in a new direction. We have a function for that, and it&#8217;s called ::Trace. The secondary ray will thus call ::Trace recursively:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">return Trace( secondary, rayDepth + 1 );</pre></div>



<p>There&#8217;s a problem with that. If we have multiple shiny teapots, reflections may theoretically bounce forever. We need to put a cap on that. The function definition of Trace is changed to:</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 )</pre></div>



<p>The primary ray will call this with a value of 0. Then, just before we recurse, we do a safety check:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">if (rayDepth &gt;= 10) return float3( 0 );</pre></div>



<p>In other words: Don&#8217;t bounce more than 10 times. If you do, return black. To see if 10 is a reasonable number, just change &#8216;black&#8217; to &#8216;bright purple&#8217; and see if it ever happens.</p>



<p>One final detail remains: How do we determine if a teapot is reflective or not? Let&#8217;s hack it: if the <code>instanceIdx</code>, multiplied by a small prime number, is odd, we&#8217;ll make the teapot reflective, otherwise, we use the Lambert material. Like so: </p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">// shading
    bool mirror = (instIdx * 17) &amp; 1;
    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>That completes the implementation of reflections. The result of this step:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img decoding="async" src="https://ics.uu.nl/docs/vakken/magr/ompf2/shiny.jpg" alt=""/></figure></div>


<p>The reflections do emphasize one shortcoming of the ray tracer: There is no anti-aliasing. Luckily, that is easily fixed. We can simply shoot multiple rays through each pixel, and average what they bring back. The multiple rays can go to fixed locations on each pixel, or we can simply pick random positions. Like so:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">...
    for (int v = 0; v &lt; 8; v++) for (int u = 0; u &lt; 8; u++)
    {
        uint pixelAddress = x * 8 + u + (y * 8 + v) * 640;
        accumulator[pixelAddress] = float3( 0 );
        for( int s = 0; s &lt; 4; s++ )
        {
            // setup a primary ray
            float3 pixelPos = ray.O + p0 +
                (p1 - p0) * ((x * 8 + u + RandomFloat()) / 640.0f) +
                (p2 - p0) * ((y * 8 + v + RandomFloat()) / 640.0f);
            ray.D = normalize( pixelPos - ray.O );
            ray.hit.t = 1e30f; // 1e30f denotes 'no hit'
            accumulator[pixelAddress] += 0.25f * Trace( ray );
        }
    }
    ...</pre></div>



<p>With 16 samples per pixel, this yields a pretty crisp picture, albeit at a terrible framerate. Also notice what this does to the textured teapots!</p>


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


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



<p>Adding anti-aliasing made one thing painfully clear: in terms of performance, we may have work to do. It is definitely possible to improve performance on the CPU, but a real boost will be possible when we switch from CPU to GPU. This is the topic of the next article.</p>



<p>Apart from that, some other things are missing:</p>



<ul class="wp-block-list">
<li>Glass, water and other <em>dielectrics</em></li>



<li>Shadows!</li>



<li>Depth of field, soft shadows, motion blur and other <em>distribution effects</em></li>



<li>Diffuse reflections</li>
</ul>



<p>Many of these would justify an entirely new series however.</p>



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



<p>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>Enjoyed the article? Spotted an error?</p>



<p>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>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><br></p>
]]></content:encoded>
					
					<wfw:commentRss>https://jacco.ompf2.com/2022/05/27/how-to-build-a-bvh-part-8-whitted-style/feed/</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>How to build a BVH – part 7: Consolidate</title>
		<link>https://jacco.ompf2.com/2022/05/20/how-to-build-a-bvh-part-7-consolidate/</link>
					<comments>https://jacco.ompf2.com/2022/05/20/how-to-build-a-bvh-part-7-consolidate/#comments</comments>
		
		<dc:creator><![CDATA[jbikker]]></dc:creator>
		<pubDate>Fri, 20 May 2022 14:19:31 +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=1273</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 id="block-a48dbb6f-9984-4794-9a4a-d69171c15330">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>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><strong>Consolidating, part 1: ray tracing textured and shaded meshes (this article).</strong></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><a href="https://jacco.ompf2.com/2022/06/15/how-to-build-a-bvh-part-9b-massive/">OpenCL: GPU ray tracing, part 2 (series finale)</a>.</li>
</ol>



<p id="block-0335045c-892a-4222-aee1-ff87a91ce61a">With a proper acceleration structure for animated scenes in place, it is time to put it to use. In this article we discuss how to use a BVH for rendering a scene with textured and shaded objects. The concepts introduced in this article will also be useful when we take the BVH to the GPU in article 9.</p>



<p>This is part one of two: shading, including full Whitted-style (recursive) ray tracing is postponed to the next article.</p>



<h2 class="wp-block-heading">Preparations &amp; Recap</h2>



<p>Until now, all source code was stored in just two files. Now that BVH construction is &#8216;done&#8217; <em>(it never is!)</em> it is finally time to put the construction and traversal functionality in proper, separate files. On <a href="https://github.com/jbikker">Github</a> you&#8217;ll find that project #7 contains a <code>bvh.cpp</code> and <code>bvh.h</code> file. The header file contains the class and struct definitions:</p>



<ul class="wp-block-list">
<li><code>aabb</code>, which lets us conveniently maintain axis-aligned bounding boxes, with functionality to initialize them as &#8216;infinitely inverted boxes&#8217;, and functions to grow them using positions or other AABBs.</li>



<li><code>Ray</code>, which stores everything we need for a ray: an origin and direction, as well as the distance from the origin to the nearest intersection. <code>Struct Ray</code> also contains reciprocals of the ray direction, to speed up AABB intersection. The data is &#8216;unioned&#8217; with <code>__m128</code> (&#8216;quadfloat&#8217;) values, to facilitate SIMD AABB intersection (<a href="https://jacco.ompf2.com/2022/04/18/how-to-build-a-bvh-part-2-faster-rays/">see article #2</a>).</li>



<li><code>BVHNode</code>, which defines a node for a &#8216;bottom level acceleration structure&#8217; or BLAS, i.e. a BVH over triangles. It is carefully tuned to fit in 32 bytes (discussed at the end of <a href="https://jacco.ompf2.com/2022/04/13/how-to-build-a-bvh-part-1-basics/">article #1</a>).</li>



<li><code>BVH</code>, which implements BVH construction and traversal. It &#8216;owns&#8217; a pool of <code>BVHNode</code> objects; the <code>BVHNode</code> with index 0 is always the root of the BVH. <a href="https://jacco.ompf2.com/2022/04/21/how-to-build-a-bvh-part-3-quick-builds/">Article #3</a> discussed efficient binned construction of the BVH.</li>



<li><code>BVHInstance</code>, which adds a 4&#215;4 matrix transform to the BVH, so we can intersect a single BVH multiple times using transformed rays. This allows for instancing, as well as free &#8216;rigid motion&#8217;. Details in <a href="https://jacco.ompf2.com/2022/05/07/how-to-build-a-bvh-part-5-tlas-blas/">article 5</a>.</li>



<li><code>TLASNode</code>, which defines a node for the &#8216;top level acceleration structure&#8217; or TLAS, i.e. a BVH over BVHs. Each leaf node of the TLAS contains exactly one BLAS. Details 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>.</li>



<li>And finally, class <code>TLAS</code>, which implements agglomerative clustering of TLASNodes to build the final TLAS structure, with its root node in <code>tlasNode[0]</code>.</li>
</ul>



<p>The .cpp file contains the implementation of these classes and structs, as well as functionality to intersect a ray with a triangle, and with an AABB, with or without SIMD code.</p>



<p>The separation yields a rather brief application in pretty.cpp: just an <code>::Init</code> function and a <code>::Tick</code> function. That&#8217;s nice: we can now focus on code that uses rays in the application files, while the BVH logic is isolated in its own files.</p>



<h2 class="wp-block-heading">Textures and Normals</h2>



<p>To render scenes with textures and lighting we are going to need more information than just the current set of three vertices per triangle.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/bunnies-2-1024x346.jpg" alt="" style="width:640px"/><figcaption class="wp-element-caption">Triangle bunny + texture = textured bunny. Texture by Bruno Levy, used with permission.</figcaption></figure></div>


<p>The first additional piece of information is obviously a <em>texture</em>, which is typically specified per mesh. The texture is connected to individual triangles using a uv-coordinate for each vertex. For lighting, we also need triangle <em>normals</em>. We can specify one normal for a triangle, or one normal per triangle vertex, which lets us interpolate the normal over the triangle, for a smoothly shaded mesh.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/cow-1024x377.jpg" alt="" style="width:600px"/><figcaption class="wp-element-caption">Left: per-triangle normals for lighting; right: per-vertex normals, interpolated over the triangles.</figcaption></figure></div>


<p>Previously, we defined a triangle as follows:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">// minimalist triangle struct
struct Tri { float3 vertex0, vertex1, vertex2; float3 centroid; };</pre></div>



<p>The new data could simply be added to this triangle:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">// minimalist triangle struct
struct Tri 
{ 
    float3 vertex0, vertex1, vertex2; 
    float3 centroid; 
    float2 uv0, uv1, uv2;
    float3 N0, N1, N2;
};</pre></div>



<p>It turns out that this is not a very good idea. We don&#8217;t need the extra data during ray/scene intersection, but it <em>will</em> be read into the caches. Smaller data leaves more room for other data, and therefore we split the triangle data. We keep the original Tri struct, and add another one, just for texturing and shading:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">// additional triangle data, for texturing and shading
struct TriEx { float2 uv0, uv1, uv2; float3 N0, N1, N2; float dummy; };</pre></div>



<p>We will thus store arrays of <code>Tri</code> and <code>TriEx</code> objects for each mesh, were each element in the <code>Tri</code> array has a matching <code>TriEx</code> element, with the same index.</p>



<p>Adding the texture also requires some careful consideration. So far we stored triangle data in a BVH object. That doesn&#8217;t make sense anymore now that we have texture, normal and uv data: This data has nothing to do with ray/scene intersections and really should be stored elsewhere. The new fundamental geometry class is the Mesh class:</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 );
    BVH* bvh;
    Tri tri[1024];	  // triangle data for intersection
    TriEx triEx[1024];	  // triangle data for shading
    int triCount = 0;
    Surface* texture;
};</pre></div>



<p>Instead of storing triangles in a BVH, we now assign a BVH to a mesh, which makes more sense. The mesh also stores the new <code>triEx</code> array, as well as a texture. To keep things as simple as possible we limit meshes to 1024 triangles; this is a limitation you should of course lift as soon as possible when you adapt this code to your own project. The constructor now takes a basic obj file, as well as a texture file. The Alias Wavefront OBJ file format is chosen here because it supports uv- and normal data, which is precisely what we need.</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[1024];
    float3 N[1024], P[1024];
    int UVs = 0, Ns = 0, Ps = 0, a, b, c, d, e, f, g, h, i;
    FILE* file = fopen( objFile, "r" );
    while (!feof( file ))
    {
        char line[256] = { 0 };
        fgets( line, 1023, file );
        if (line == strstr( line, "vt " )) UVs++,
            sscanf( line + 3, "%f %f", &amp;UV[UVs].x, &amp;UV[UVs].y );
        else if (line == strstr( line, "vn " )) Ns++,
            sscanf( line + 3, "%f %f %f", &amp;N[Ns].x, &amp;N[Ns].y, &amp;N[Ns].z );
        else if (line[0] == 'v') Ps++,
            sscanf( line + 2, "%f %f %f", &amp;P[Ps].x, &amp;P[Ps].y, &amp;P[Ps].z );
        if (line[0] != 'f') continue; else
        sscanf( line + 2, "%i/%i/%i %i/%i/%i %i/%i/%i",
            &amp;a, &amp;b, &amp;c, &amp;d, &amp;e, &amp;f, &amp;g, &amp;h, &amp;i );
        tri[triCount].vertex0 = P[a], triEx[triCount].N0 = N[b];
        tri[triCount].vertex1 = P[d], triEx[triCount].N1 = N[e];
        tri[triCount].vertex2 = P[g], triEx[triCount].N2 = N[h];
        triEx[triCount].uv0 = UV[c], triEx[triCount].uv1 = UV[f];
        triEx[triCount++].uv2 = UV[i];
    }
    fclose( file );
    bvh = new BVH( this );
}</pre></div>



<p>Again, in a more serious project this needs to be replaced, but for now, it will do.</p>



<p>Moving the triangle data to the mesh has some consequences for the BVH class as well, although the required changes are minor. We store a pointer to the <code>Mesh</code> in the <code>BVH</code> class, so we can access the data easily. The BVH constructor then becomes:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">BVH::BVH( Mesh* triMesh )
{
    mesh = triMesh;
    bvhNode = (BVHNode*)_aligned_malloc( sizeof( BVHNode ) * mesh-&gt;triCount * 2, 64 );
    triIdx = new uint[mesh-&gt;triCount];
    Build();
}</pre></div>



<p>Now that we have properly stored the additional data, it is time to actually use it.</p>



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



<p>When a ray hits a triangle, all it stores is the hit distance, if it is smaller than <code>ray.t</code>. This was sufficient for the greyscale images we produced so far. However, now that we have textures and normals, we need some additional data:</p>



<ul class="wp-block-list">
<li>The normal at the intersection point</li>



<li>The texture color at the intersection point</li>
</ul>



<p>Before we discuss what actually needs to be stored, let&#8217;s first see how to obtain an interpolated normal and a texture color in a ray tracer. For that, we need to review the ray/triangle intersection code from article #1:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void IntersectTri( Ray&amp; ray, const Tri&amp; tri )
{
    const float3 edge1 = tri.vertex1 - tri.vertex0;
    const float3 edge2 = tri.vertex2 - tri.vertex0;
    const float3 h = cross( ray.D, edge2 );
    const float a = dot( edge1, h );
    if (a &gt; -0.0001f &amp;&amp; a &lt; 0.0001f) return; // ray parallel to triangle
    const float f = 1 / a;
    const float3 s = ray.O - tri.vertex0;
    const float u = f * dot( s, h );
    if (u &lt; 0 || u &gt; 1) return;
    const float3 q = cross( s, edge1 );
    const float v = f * dot( ray.D, q );
    if (v &lt; 0 || u + v &gt; 1) return;
    const float t = f * dot( edge2, q );
    if (t &gt; 0.0001f) ray.t = min( ray.t, t );
}</pre></div>



<p>On the highlighted lines variables <code>u</code> and <code>v</code> are calculated and evaluated. Here, u and v are <em>not </em>texture uv-coordinates: they are <em>barycentric coordinates</em>, and they are extremely useful. It works like this: Given a triangle with vertices A, B, and C, any point P on the triangle can be reached by combining A, B and C using weights. Let&#8217;s call the weights <em>u</em>, <em>v</em> and <em>w</em>. Now, <span class="wp-katex-eq" data-display="false">P=uA+vB+wC</span>. In a diagram:</p>


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


<p>At the vertices the weights are pretty simple: e.g., A is just A, so v and w are 0. Between A and B we know that u is decreasing from 1 to 0, while v increases from 0 to 1. We can conclude a few additional things:</p>



<ol class="wp-block-list">
<li>The sum of u, v and w must be 1 everywhere on the triangle.</li>



<li>The weights u, v and w must all be between 0 and 1.</li>



<li>Weight w must be 1 &#8211; (u + v) and is thus redundant.</li>
</ol>



<p>The triangle intersection code uses the concept of barycentric coordinates: on line 11, u and w are tested against the valid range, and on line 14, the sum of u and v is tested: this cannot exceed 1.</p>



<p>The triangle intersection code thus gets us u and v, and by extension, w. This is rather useful. The barycentric coordinates do not just let us find points on the triangle, we can also use them to interpolate other values than vertex positions. Given <em>u</em>, <em>v</em> and <em>w</em>, we can combine vertex normals <span class="wp-katex-eq" data-display="false">N_0</span>, <span class="wp-katex-eq" data-display="false">N_1</span> and <span class="wp-katex-eq" data-display="false">N_2</span> into interpolated normal <span class="wp-katex-eq" data-display="false">N_i</span> and likewise, we can interpolate the uv-coordinates of the vertices to find the uv-coordinate at the point of intersection (be careful not to confuse the barycentric coordinates <em>u </em>and <em>v</em> with texture uv-coordinates &#8211; industry standard is sadly to use the letters u and v in both cases&#8230;)</p>



<p>Back to the original problem: what do we store at the intersection point? It turns out we need five values:</p>



<ul class="wp-block-list">
<li>t, i.e. the distance along the ray</li>



<li>the triangle index</li>



<li>u and v, i.e. the barycentric coordinates on the triangle (<span style="text-decoration: underline;">not</span> the texture coordinates!).</li>
</ul>



<p>The fifth value is the index of the instance, which we will need to find the transform. Without this, the normals will be in the untransformed space of the object.</p>



<p>With these five values we can reconstruct everything, regardless of how much data we store per vertex. Perhaps we also stored vertex colors, or a second set of uv-coordinates (e.g. for detail textures or a normal map); all of these can be interpolated at a later time using the stored barycentric coordinates.</p>



<p>Postponing the actual interpolation also helps when a ray intersects multiple triangles along its path through the BVHs. Each time we find a closer intersection, we overwrite earlier results; we need to make sure that storing hit information is efficient.</p>



<p>Let&#8217;s define a compact intersection record:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">// intersection record, carefully tuned to be 16 bytes in size
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)
};</pre></div>



<p>The five fields are squeezed into 16 bytes here. This will be particularly relevant on the GPU later, where a 16-byte read is a single memory operation, while most other sizes require multiple transactions.</p>



<p>The new hit record is filled with a slightly modified <code>IntersectTri</code> function:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void IntersectTri( Ray&amp; ray, const Tri&amp; tri, const uint instPrim )
{
    // Moeller-Trumbore ray/triangle intersection algorithm
    ...
    const float t = f * dot( edge2, q );
    if (t &gt; 0.0001f &amp;&amp; t &lt; ray.hit.t) 
        ray.hit.t = t, 
        ray.hit.u = u,
        ray.hit.v = v, 
        ray.hit.instPrim = instPrim;
}</pre></div>



<p>The <code>instPrim</code> value that is passed to <code>IntersectTri</code> contains the instance index and the primitive index, packed together in a single 32-bit unsigned int. This value is passed all the way from <code>BVHInstance::Intersect</code>, via <code>BVH::Intersect to IntersectTri</code>.</p>



<h2 class="wp-block-heading">The Other End</h2>



<p>Intersecting the ray with the scene now yields quite a bit more info than just an intersection distance. The place to use this data is the application: in this case, in <code>pretty.cpp</code> and <code>pretty.h</code>.</p>



<p>Let&#8217;s make some quick preparations. First thing: the integer pixel buffer. It is pretty much inevitable that our final colors are 32-bit unsigned ints, but for proper rendering, this is not a great choice. Let&#8217;s define a proper floating point frame buffer, called the accumulator:</p>



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



<p>This array stores a 3-component vector per pixel, where x, y and z store red, green and blue color components. The floating point storage is more accurate, but more important: it doesn&#8217;t clamp intensities at 255.</p>



<p>We write to this buffer by calling a <code>::Trace</code> function for each pixel:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 PrettyApp::Trace( Ray&amp; ray )
{
    tlas.Intersect( ray );
    Intersection i = ray.hit;
    if (i.t == 1e30f) return float3( 0 );
    return float3( i.u, i.v, 1 - (i.u + i.v) );
}</pre></div>



<p>This function is called from the multi-threaded tile renderer, with a single ray per pixel. We call this ray the <em>primary ray</em>, to distinguish it from the rays that we use for shadows, reflections and refractions.</p>



<p>The rudimentary trace function shown here stores the barycentric coordinates <em>u</em>, <em>v</em> and <em>w</em> in the red, green and blue components of the returned color. The result:</p>


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


<p>Note how the three corners of each triangle indeed turn red, green and blue, while these primary colors smoothly interpolate over the primitive. The data was received!</p>



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



<p>By now the article got a lot longer than I anticipated; that means that another article needs to be inserted here. Next time we will talk about Whitted-style ray tracing, for which we will use the new intersection information.</p>



<p>The complete code for this project (for Windows / Visual Studio) <a href="https://github.com/jbikker/bvh_article">can be found on GitHub</a>, as usual.</p>



<p>Enjoyed the article? Spotted an error?</p>



<p>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>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/05/20/how-to-build-a-bvh-part-7-consolidate/feed/</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
		<item>
		<title>How to build a BVH &#8211; part 6: All Together Now</title>
		<link>https://jacco.ompf2.com/2022/05/13/how-to-build-a-bvh-part-6-all-together-now/</link>
					<comments>https://jacco.ompf2.com/2022/05/13/how-to-build-a-bvh-part-6-all-together-now/#comments</comments>
		
		<dc:creator><![CDATA[jbikker]]></dc:creator>
		<pubDate>Fri, 13 May 2022 18:46:54 +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=1201</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 id="block-a48dbb6f-9984-4794-9a4a-d69171c15330">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>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><strong>TLAS &amp; BLAS part 2 – all together now (this article).</strong></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><a href="https://jacco.ompf2.com/2022/06/15/how-to-build-a-bvh-part-9b-massive/">OpenCL: GPU ray tracing, part 2 (series finale)</a>.</li>
</ol>



<p id="block-0335045c-892a-4222-aee1-ff87a91ce61a">In this article we finalize the construction of the two-level acceleration structure for animated scenes.</p>



<h2 class="wp-block-heading">Half Baked</h2>



<p>The conclusion of article 5 probably felt a bit underwhelming. The code handles no less than <em>two </em> armadillos, which get intersected using a <em>single call</em> to the Intersect method of TLAS, even if they <em>both</em> get a new transformation matrix each frame. True, but&#8230; that&#8217;s not the kind of performance and versatility you may have been hoping for. It&#8217;s time to fulfill some promises.</p>



<p>Let&#8217;s formulate a target for this article, and then see how we can get there. The goal for today is to have 256 armadillos floating through space, while rotating, and bouncing off the walls of a virtual cube. For this, we will build a top-level structure over 256 bottom-level acceleration structures, in real-time. The total polygon count will be 30,000 times 256, so well over 7 million triangles. Once we reach this goal, it&#8217;s play time; we&#8217;ll be able to ray trace virtually anything &#8211; although a scene that can be intersected efficiently by rays must have certain characteristics. More on that at the end of the article.</p>



<h2 class="wp-block-heading">Proper TLAS Construction</h2>



<p>Last time we built a TLAS over two BVHs. We did this by storing the two BVHs in TLAS leaf nodes; the two leaf nodes then became child nodes of a single TLAS root node.</p>



<p>For a larger number of BVHs we can use a similar technique. In short, we will combine pairs of nodes using a parent node; the parent node will then be paired with other leaf nodes or interior nodes, until we have just a single node left. This is then the root node.</p>



<p>To build an <em>optimal</em> TLAS, the pairs that we create must be carefully chosen. It turns out that we should be pairing nodes that form small boxes &#8211; where &#8216;small&#8217; actually means: having a small surface area. So, given 256 BVHs, we are looking for the two BVHs that, when put into a single AABB, have the smallest AABB. A simple algorithm will get the job done:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">for each BVH A
    find BVH B for which AABB(A,B) is smallest</pre></div>



<p id="block-0335045c-892a-4222-aee1-ff87a91ce61a">This is an <span class="wp-katex-eq" data-display="false">O(N^2)</span> algorithm. However, we&#8217;re overlooking something: the algorithm gets us <em>one</em> pair, which brings the number of nodes down to 255 (one is now an interior node). We need to do this 255 more times to get to a single root node. By then, the algorithm is <span class="wp-katex-eq" data-display="false">O(N^3)</span>, which is bad, even on a fast machine and at a pretty low number of BVHs (such as 256).</p>



<p>Luckily, something better exists. For this, we need to look at a 2008 paper by Walter et al., titled <em>Fast Agglomerative Clustering for Rendering</em>. The term agglomerative clustering refers to the bottom-up process we&#8217;re using when we combine pairs of nodes; the alternative is the top-down process we used for  constructing a BLAS over a group of triangles. The algorithm from the paper, in pseudo-code:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">TLASNode A = list.GetFirst();
TLASNode B = list.FindBestMatch( A );
while (list.size() &gt; 1)
{
   TLASNode C = list.FindBestMatch( B );
   if (A == C)
   {
      list.Remove( A );
      list.Remove( B );
      A = new Node( A, B );
      list.Add( A );
      B = list.FindBestMatch( A );
   }
   else A = B, B = C;
}</pre></div>



<p>If you try this out on a piece of paper you&#8217;ll see that this actually works. Performance is pretty good as well: we get close to <span class="wp-katex-eq" data-display="false">O(N^2)</span> in practice, which is quite acceptable for 256 armadillos.</p>



<p>Before we turn this into practical code we need to make a change to the <code>TLASNode</code> struct that was proposed in <a href="https://jacco.ompf2.com/2022/05/07/how-to-build-a-bvh-part-5-tlas-blas/">article 5</a>. The struct stores only the index of the left child, assuming that the right child can be derived from that. Using agglomerative clustering, this is no longer the case. Luckily, the required change is not too complex:</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;
    bool isLeaf() { return leftRight == 0; }
};</pre></div>



<p>The 32-bit field <code>leftRight</code> now stores two numbers, in 2&#215;16 bits. For leaf nodes, field <code>BLAS</code> stores the index of a BLAS, otherwise it is unused. We identify leaves by looking at <code>leftRight</code>: for interior nodes one of the child indices must be greater than zero, so only if we set <code>leftRight</code> to 0, we have a leaf node.</p>



<p>Back to TLAS construction. Construction starts with the 256 leaf nodes:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void TLAS::Build()
{
    // assign a TLASleaf node to each BLAS
    nodesUsed = 1;
    for (uint i = 0; i &lt; blasCount; i++)
    {
        tlasNode[nodesUsed].aabbMin = blas[i].bounds.bmin;
        tlasNode[nodesUsed].aabbMax = blas[i].bounds.bmax;
        tlasNode[nodesUsed].BLAS = i;
        tlasNode[nodesUsed++].leftRight = 0; // makes it a leaf
    }
    ...</pre></div>



<p>As with a regular BVH, <code>tlasNode[0]</code> will contain the root. We create the root last, so we reserve space for it; the first node we will use as a leaf node is thus <code>tlasNode[1]</code> (indexed by <code>nodesUsed</code>). The AABB we use for each TLAS leaf node is obtained from the BVHs and is in world space. </p>



<p>Now that we have the leaf nodes, we can create the work list for the agglomerative clustering algorithm:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">int nodeIdx[256], nodeIndices = blasCount;</pre></div>



<p>Rather than directly storing the <code>TLASNode</code> instances, we store indices of elements of the <code>tlasNode</code> array. The number of nodes that still need to be paired is obtained from <code>blasCount</code>; for 256 armadillos this will simply be 256, and after each generated pair, it will decrement by 1 until only one node is left: this will be our root node.</p>



<p>The array can be initialized in the loop that creates the TLAS leaf nodes:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void TLAS::Build()
{
    // assign a TLASleaf node to each BLAS
    int nodeIdx[256], nodeIndices = blasCount;
    nodesUsed = 1;
    for (uint i = 0; i &lt; blasCount; i++)
    {
        nodeIdx[i] = nodesUsed;
        tlasNode[nodesUsed].aabbMin = blas[i].bounds.bmin;
        tlasNode[nodesUsed].aabbMax = blas[i].bounds.bmax;
        tlasNode[nodesUsed].BLAS = i;
        tlasNode[nodesUsed++].leftRight = 0; // makes it a leaf
    }</pre></div>



<p>Everything is now ready for the actual clustering. The algorithm calls &#8216;FindBestMatch&#8217; three times. This is the function that, given a TLASNode A, finds the node B (where B != A) that forms the smallest AABB with A. It is implemented as follows:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">int TLAS::FindBestMatch( int* list, int N, int A )
{
    float smallest = 1e30f;
    int bestB = -1;
    for (int B = 0; B &lt; N; B++) if (B != A)
    {
        float3 bmax = fmaxf( tlasNode[list[A]].aabbMax, tlasNode[list[B]].aabbMax );
        float3 bmin = fminf( tlasNode[list[A]].aabbMin, tlasNode[list[B]].aabbMin );
        float3 e = bmax - bmin;
        float surfaceArea = e.x * e.y + e.y * e.z + e.z * e.x;
        if (surfaceArea &lt; smallest) smallest = surfaceArea, bestB = B;
    }
    return bestB;
}</pre></div>



<p>This function simply checks all remaining nodes in the list. For each node, the combined AABB is determined. If the area of this AABB (skipping the factor 2, as usual) is smaller than what we found before, we take note of that. After checking all nodes we return our best find.</p>



<p>Note the tricky addressing of the <code>tlasNode</code> array: since the work list contains <code>tlasNode</code> array indices, we need this complex indirection to query the correct nodes.</p>



<p>With the FindBestMatch function properly implemented, we can now finalize the agglomerative clustering algorithm.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void TLAS::Build()
{
    // assign a TLASleaf node to each BLAS
    ...
    // use agglomerative clustering to build the TLAS
    int A = 0, B = FindBestMatch( nodeIdx, nodeIndices, A );
    while (nodeIndices &gt; 1)
    {
        int C = FindBestMatch( nodeIdx, nodeIndices, B );
        if (A == C)
        {
            int nodeIdxA = nodeIdx[A], nodeIdxB = nodeIdx[B];
            TLASNode&amp; nodeA = tlasNode[nodeIdxA];
            TLASNode&amp; nodeB = tlasNode[nodeIdxB];
            TLASNode&amp; newNode = tlasNode[nodesUsed];
            newNode.leftRight = nodeIdxA + (nodeIdxB &lt;&lt; 16);
            newNode.aabbMin = fminf( nodeA.aabbMin, nodeB.aabbMin );
            newNode.aabbMax = fmaxf( nodeA.aabbMax, nodeB.aabbMax );
            nodeIdx[A] = nodesUsed++;
            nodeIdx[B] = nodeIdx[nodeIndices - 1];
            B = FindBestMatch( nodeIdx, --nodeIndices, A );
        }
        else A = B, B = C;
    }
    tlasNode[0] = tlasNode[nodeIdx[A]];
}</pre></div>



<p>This code closely follows the pseudo-code. When two nodes are paired, a new interior node is created (line 15), which points to existing nodes with indices <code>nodeIdxA</code> and <code>nodeIdxB</code> (line 16). The AABB of the new interior node is the union of the AABBs of the child nodes (lines 17 and 18). Now that the two nodes are paired, work item A (in the <code>nodeIdx</code> array) gets replaced by the index of a newly created TLAS interior node (line 19). Work item B, which is to be removed, gets replaced by the last element in the list (line 20), and the list is shortened by 1 (on line 21, as part of the function call).</p>



<p>And with that, we can suddenly handle far more than a pair of armadillos. Play time!</p>



<h2 class="wp-block-heading">Move it</h2>



<p>Let&#8217;s load a few more armadillos. For starters, 16 of them:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void AllTogetherApp::Init()
{
    for (int i = 0; i &lt; 16; i++) bvh[i] = BVH( "assets/armadillo.tri", 30000 );
    tlas = TLAS( bvh, 16 );
}</pre></div>



<p>Loading 16 armadillos happens in a flash, but building a BVH for each of them causes a bit of a delay. We want 256 armadillos ultimately, so we&#8217;ll need to look into that later.</p>



<p>With 16 objects in memory we need some basic animation to make them move. How about this:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void AllTogetherApp::Tick( float deltaTime )
{
    // animate the scene
    static float a[16] = { 0 }, h[16] = { 5, 4, 3, 2, 1, 5, 4, 3 }, s[16] = { 0 };
    for (int i = 0, x = 0; x &lt; 4; x++) for (int y = 0; y &lt; 4; y++, i++)
    {
        mat4 R, T = mat4::Translate( (x - 1.5f) * 2.5f, 0, (y - 1.5f) * 2.5f );
        if ((x + y) &amp; 1) R = mat4::RotateX( a[i] ) * mat4::RotateZ( a[i] );
        else R = mat4::Translate( 0, h[i / 2], 0 );
        if ((a[i] += (((i * 13) &amp; 7) + 2) * 0.005f) &gt; 2 * PI) a[i] -= 2 * PI;
        if ((s[i] -= 0.01f, h[i] += s[i]) &lt; 0) s[i] = 0.2f;
        bvh[i].SetTransform( T * R * mat4::Scale( 0.75f ) );
    }
    ...</pre></div>



<p>This super-ugly code makes half of the armadillos bounce, while the other half rotates. It&#8217;s all pretty chaotic. The code does however show how flexible things are now: objects are scaled, translated and rotated without any difficulty, using pretty basic matrix math. This will combine quite nicely with a typical scene graph.</p>



<p>Changing the transforms of the BLAS BVHs updates their world space bounds, and so we need to build a new TLAS. We do this each frame:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">tlas.Build();</pre></div>



<p>That&#8217;s all! This will invoke the agglomerative builder, which executes in a flash for the 16 armadillos that we have right now. Let&#8217;s tilt and move the camera a bit to take it all in:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">...
    float3 p0 = TransformPosition( float3( -1, 1, 2 ), mat4::RotateX( 0.5f ) );
    float3 p1 = TransformPosition( float3( 1, 1, 2 ), mat4::RotateX( 0.5f ) );
    float3 p2 = TransformPosition( float3( -1, -1, 2 ), mat4::RotateX( 0.5f ) );
#pragma omp parallel for schedule(dynamic)
    for (int tile = 0; tile &lt; 6400; tile++)
    {
        int x = tile % 80, y = tile / 80;
        Ray ray;
        ray.O = float3( 0, 4.5f, -8.5f );
        ...</pre></div>



<p>The result is glorious.</p>


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


<h2 class="wp-block-heading">Après Nous le Déluge</h2>



<p>It is time for the final step: 256 armadillos. For that we only really need one new ingredient: <em>instancing</em>.</p>



<p>Instancing is very commonly used in games:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/lumberyard-meadow-1024x567.jpg" alt="" style="width:640px"/></figure></div>


<p>Here, just a few trees are carbon-copied all over the rolling hills, with a slightly different scale and orientation applied to prevent that we notice the repetition. In a regular 3D engine, instancing helps to reduce memory use and bandwidth between CPU and GPU. In a ray tracer we get essentially the same benefits, plus one more: we can reuse a BLAS if the only difference between two objects can be expressed in a 4&#215;4 matrix: rotation, translation and scale. On a race track that means: one car gets multiplied to form a grid; add a track and you&#8217;re done. You could even apply different textures to each car: materials do not affect the BVH, after all.</p>



<p>Let&#8217;s make the necessary changes. We start with a <code>BVHInstance</code> class, which takes over the matrix transform functionality from the BVH class.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">// instance of a BVH, with transform and world bounds
class BVHInstance
{
public:
    BVHInstance() = default;
    BVHInstance( BVH* blas ) : bvh( blas ) { SetTransform( mat4() ); }
    void SetTransform( mat4&amp; transform );
    void Intersect( Ray&amp; ray );
private:
    BVH* bvh = 0;
    mat4 invTransform; // inverse transform
public:
    aabb bounds; // in world space
};</pre></div>



<p>This leads to a cleaner BVH class: the inverse transform and world space bounds are now gone, as well as the <code>SetTransform(...)</code> method. Even the <code>BVH::Intersect(...)</code> is simpler now; the ray transform is handled by a short method of <code>BVHInstance</code>, which forwards the work, with an already transformed ray, to the BVH.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void BVHInstance::Intersect( Ray&amp; ray )
{
    // backup ray and transform original
    Ray backupRay = ray;
    ray.O = TransformPosition( ray.O, invTransform );
    ray.D = TransformVector( ray.D, invTransform );
    ray.rD = float3( 1 / ray.D.x, 1 / ray.D.y, 1 / ray.D.z );
    // trace ray through BVH
    bvh-&gt;Intersect( ray );
    // restore ray origin and direction
    backupRay.t = ray.t;
    ray = backupRay;
}</pre></div>



<p>From now on, when we would normally process a <code>BVH</code>, we now operate on a<code> BVHInstance</code>. The TLAS constructor takes a <code>BVHInstance</code> array, for instance:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">TLAS::TLAS( BVHInstance* bvhList, int N )
{
    // copy a pointer to the array of bottom level accstruc instances
    blas = bvhList;
    blasCount = N;
    // allocate TLAS nodes
    tlasNode = (TLASNode*)_aligned_malloc( sizeof( TLASNode ) * 2 * N, 64 );
    nodesUsed = 2;
}</pre></div>



<p>That also means that member variable <code>blas</code> is now a <code>BVHInstance*</code> rather than a <code>BVH*</code>. Apart from this, surprisingly few changes are needed; we can simply point to the same BVH now with different transforms, which is exactly what we need. This has a great effect on the scene construction:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void AllTogetherApp::Init()
{
    BVH* bvh = new BVH( "assets/armadillo.tri", 30000 );
    for (int i = 0; i &lt; 16; i++)
        bvhInstance[i] = BVHInstance( bvh );
    tlas = TLAS( bvhInstance, 16 );
}</pre></div>



<p>A mesh is now loaded once, and a BVH is constructed for it, also once. The only thing that we get 16 of is BVHInstances &#8211; but creating these is, well, instantaneous.</p>



<p>Let&#8217;s bring in an army of armadillos!</p>



<h2 class="wp-block-heading">We&#8217;re in the Army Now</h2>



<p>Recall the goal of this article: to have 256 armadillos float around in a cubical section of space, rotating and bouncing off the walls. For that, we need some additional data in the <code>AllTogetherApp</code> class.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3* position, *direction, *orientation;</pre></div>



<p>Each of these will become arrays when we initialize the scene.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void AllTogetherApp::Init()
{
    ...
    // set up spacy armadillo army
    position = new float3[256];
    direction = new float3[256];
    orientation = new float3[256];
    for( int i = 0; i &lt; 256; i++ )
    {
        position[i] = float3( RandomFloat(), RandomFloat(), RandomFloat() ) - 0.5f;
        position[i] *= 4;
        direction[i] = normalize( position[i] ) * 0.05f;
        orientation[i] = float3( RandomFloat(), RandomFloat(), RandomFloat() ) * 2.5f;
    }
}</pre></div>



<p>Finally, we use this data to actually update the transforms of 256 <code>BVHInstance</code> objects:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void AllTogetherApp::Tick( float deltaTime )
{
    // animate the scene
    for( int i = 0; i &lt; 256; i++ )
    {
        mat4 R = mat4::RotateX( orientation[i].x ) * 
            mat4::RotateY( orientation[i].y ) *
            mat4::RotateZ( orientation[i].z ) * mat4::Scale( 0.2f );
        bvhInstance[i].SetTransform( mat4::Translate( position[i] ) * R );
        position[i] += direction[i], orientation[i] += direction[i];
        if (position[i].x &lt; -3 || position[i].x &gt; 3) direction[i].x *= -1;
        if (position[i].y &lt; -3 || position[i].y &gt; 3) direction[i].y *= -1;
        if (position[i].z &lt; -3 || position[i].z &gt; 3) direction[i].z *= -1;
    }
    ...</pre></div>



<p>And that is all. On my machine, about 8.5 million rays per second are traced through this scene, which now consists of 7.68 million triangles. Updating the TLAS only takes half a millisecond.</p>



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



<p>From here, the sky is the limit. In terms of BVH maintenance, we can add all kinds of functionality:</p>



<ul class="wp-block-list">
<li>Add refitting for meshes that deform. We can still instance them, complete with animation. </li>



<li>Add rebuilding for meshes that undergo more structural changes.</li>



<li>Move large static meshes by changing their transforms alone.</li>



<li>Add all this in a single framework that intelligently divides work over frames for an optimal balance between ray tracing speed and BVH maintenance time.</li>
</ul>



<p>In terms of performance, we&#8217;ve only scratched the surface. We can for example trace bundles of rays to greatly speed up the kind of ray distributions we use in these demos, exploiting the fact that rays for nearby pixels tend to travel the same route through a BVH. We can also build a BVH with more than 2 child nodes per level, to reduce the number of traversal steps. This is beneficial for rays that go all over the place, like those for path tracing.</p>



<p>And then there is the actual using of the rays. We&#8217;ve done greyscale images so far. Some cleverly aimed rays can yield photo-realistic images. Doing that for animated scenes is the holy grail &#8211; and it&#8217;s happening in games right now.</p>



<p>But all that is for another day.</p>


<div class="wp-block-image is-resized">
<figure class="aligncenter size-large"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/arm.jpg" alt="" style="width:512px"/><figcaption class="wp-element-caption">Armadillo signing off.</figcaption></figure></div>


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



<p>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>Enjoyed the article? Spotted an error?</p>



<p>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>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/05/13/how-to-build-a-bvh-part-6-all-together-now/feed/</wfw:commentRss>
			<slash:comments>13</slash:comments>
		
		
			</item>
		<item>
		<title>How to build a BVH &#8211; part 5: TLAS &#038; BLAS</title>
		<link>https://jacco.ompf2.com/2022/05/07/how-to-build-a-bvh-part-5-tlas-blas/</link>
					<comments>https://jacco.ompf2.com/2022/05/07/how-to-build-a-bvh-part-5-tlas-blas/#comments</comments>
		
		<dc:creator><![CDATA[jbikker]]></dc:creator>
		<pubDate>Sat, 07 May 2022 18:14:16 +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=1130</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>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>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><strong>BVHs for animated scenes: the top-level BVH (this article).</strong></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><a href="https://jacco.ompf2.com/2022/06/15/how-to-build-a-bvh-part-9b-massive/">OpenCL: GPU ray tracing, part 2 (series finale)</a>.</li>
</ol>



<p>In the final two articles we explore how to build a BVH for a fully dynamic scene, using the same techniques employed by modern games: the <em>top level acceleration structure</em> and the <em>bottom level acceleration structure.</em></p>



<h2 class="wp-block-heading">Mise en Place</h2>



<p>As usual we&#8217;ll start with some preparations &#8211; an approach, I recently learned, called &#8216;mise en place&#8217; in the French cuisine, which apparently <a href="https://buttondown.email/hillelwayne/archive/software-mise-en-place/">also works for programming</a>. For today&#8217;s main dish we will need multiple BVHs, so it is time to bring a tiny bit of OOP to the code (just a pinch should do). Let&#8217;s add a proper BVH class to encapsulate the <code>BVHNode</code> pool, triangle indices and a triangle list:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">class BVH
{
public:
    BVH() = default;
    BVH( char* triFile, int N );
    void Build();
    void Refit();
    void Intersect( Ray&amp; ray );
private:
    void Subdivide( uint nodeIdx );
    void UpdateNodeBounds( uint nodeIdx );
    float FindBestSplitPlane( BVHNode&amp; node, int&amp; axis, float&amp; splitPos );
    BVHNode* bvhNode = 0;
    Tri* tri = 0;
    uint* triIdx = 0;
    uint nodesUsed, triCount;
};</pre></div>



<p>A lot of functionality we implemented before is moved to this class, in general without (much) modifications. I made some changes to the names of the methods: <code>BuildBVH()</code> is now <code>BVH::Build()</code>, <code>RefitBVH()</code> is now <code>BVH::Refit()</code>, and <code>IntersectBVH(...)</code> is now <code>BVH::Intersect(...)</code>. Methods that are not to be called outside the BVH class are declared private. The data is also private. Loading the scene is now handled by the constructor of the BVH class:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">BVH::BVH( char* triFile, int N )
{
    FILE* file = fopen( triFile, "r" );
    triCount = N;
    tri = new Tri[N];
    for (int t = 0; t &lt; N; t++) fscanf( file, "%f %f %f %f %f %f %f %f %f\n",
        &amp;tri[t].vertex0.x, &amp;tri[t].vertex0.y, &amp;tri[t].vertex0.z,
        &amp;tri[t].vertex1.x, &amp;tri[t].vertex1.y, &amp;tri[t].vertex1.z,
        &amp;tri[t].vertex2.x, &amp;tri[t].vertex2.y, &amp;tri[t].vertex2.z );
    bvhNode = (BVHNode*)_aligned_malloc( sizeof( BVHNode ) * N * 2, 64 );
    triIdx = new uint[N];
    Build();
}</pre></div>



<p>The global scope definition of <code>N</code> (the number of triangles in the mesh) is now passed to the constructor, because I insist on keeping file loading as basic as possible.</p>



<p>With the newly created BVH class, we can now reduce the global application data to:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">// application data
BVH bvh;</pre></div>



<p>&#8230;which we initialize in the <code>TopLevelApp::Init()</code> function:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void TopLevelApp::Init()
{
    bvh = BVH( "assets/armadillo.tri", 30000 );
}</pre></div>



<p>OOP has its merits; this is tidy. Plus, we are now ready to add more meshes. Intersecting these efficiently is going to be the first step; after that, we will also animate them efficiently, all using some quite beautiful constructs, commonly referred to as the TLAS and BLAS.</p>



<h2 class="wp-block-heading">Two Armadillos</h2>



<p>Now that the BVH data and logic is properly stored in a class, we can easily add a second mesh:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void TopLevelApp::Init()
{
    bvh[0] = BVH( "assets/armadillo.tri", 30000 );
    bvh[1] = BVH( "assets/armadillo.tri", 30000 );
}</pre></div>



<p>This is not terribly useful: both armadillos will be at the same location. We could solve this by adding an offset to the vertices of each armadillo. The next issue is the calculation of an intersection. This is not too hard either: calling <code>BVH::Intersect()</code> with a ray updates the intersection <code>t</code> for that ray; we can thus call this function once for each armadillo. That does work, but it seems impractical for a scene with more than a couple armadillos&#8230; And while we are pointing out problems with the current plan: why do we store the armadillo twice, while all the polygons are the same?</p>



<p>Let&#8217;s start with that last question. To move an armadillo, we can add a translation to every vertex of the mesh. Or, and that is a tantalizing alternative: we can move the <em>camera</em> with the <em>inverse</em> of the same translation.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/scenery.jpg" alt="" style="width:512px"/><figcaption class="wp-element-caption">Is the train moving to the left, or is the landscape moving to the right? Doesn&#8217;t matter, it&#8217;s all the same. </figcaption></figure></div>


<p>So instead of loading the armadillo twice, and moving one of them, and intersecting them one at a time, we can do something clever:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void TopLevelApp::Tick( float deltaTime )
{
    float3 p0( -1, 1, 2 ), p1( 1, 1, 2 ), p2( -1, -1, 2 );
    for (int tile = 0; tile &lt; 6400; tile++)
    {
        int x = tile % 80, y = tile / 80;
        Ray ray;
        for (int v = 0; v &lt; 8; v++) for (int u = 0; u &lt; 8; u++)
        {
            float3 pixelPos = ray.O + p0 +
                (p1 - p0) * ((x * 8 + u) / 640.0f) +
                (p2 - p0) * ((y * 8 + v) / 640.0f);
            ray.D = normalize( pixelPos - ray.O ), ray.t = 1e30f;
            ray.rD = float3( 1 / ray.D.x, 1 / ray.D.y, 1 / ray.D.z );
            ray.O = float3( -1, 0.5f, -4.5f );
            bvh.Intersect( ray );
            ray.O = float3( 1, 0.5f, -4.5f );
            bvh.Intersect( ray );
            uint c = ray.t &lt; 1e30f ? (255 - (int)((ray.t - 3) * 80)) : 0;
            screen-&gt;Plot( x * 8 + u, y * 8 + v, c * 0x10101 );
       }
    }
}</pre></div>



<p>Here, the <em>same </em>BVH is intersected <em>twice</em>, with the same ray even, but between invocations of <code>bvh.Intersect(ray)</code>, we <em>change</em> the ray. By moving the ray a bit to the left, we effectively move the scene to the right. Then, by moving the ray to the right, we move the scene to the left. The result is a scene with two armadillos.</p>


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


<p>We can take this one step further. Moving the ray in the opposite direction of a mesh can be applied to translations as well as orientations. Concrete and formal: </p>



<p><strong><em>Given a mesh with a BVH built in object space and 4&#215;4 matrix that stores orientation and translation for the mesh, we can intersect its BVH in world space by applying the inverse transform to the rays. </em></strong> </p>


<div class="wp-block-image is-resized">
<figure class="aligncenter size-large"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/racinggame.jpg" alt="" style="width:600px"/><figcaption class="wp-element-caption">Recall the race game scenario. The track is stationary (it uses the identity matrix), but the cars use matrices to zip around. And the car tires use matrices relative to the car. </figcaption></figure></div>


<p>This may sound complex, but it is very powerful. In any 3D engine, the meshes of the scene hierarchy come with their own 4&#215;4 matrix. To ray trace these meshes, we simply transform rays using the inverse matrix. This still works if the matrix changes from one frame to another: mesh motion defined by a matrix does not require a rebuild or refit, and is essentially free.</p>



<h2 class="wp-block-heading">Spinning Armadillos</h2>



<p>It is time to add this functionality to the BVH class. We will need a few things:</p>



<ul class="wp-block-list">
<li>Storage for the transformation matrix (4&#215;4, so it includes rotation and translation, potentially also scaling and shearing).</li>



<li>Storage for the bounds of the BVH in world space. This will be important for constructing the TLAS later.</li>
</ul>



<p>The new fields are named <code>invTransform</code> and <code>bounds</code>:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">mat4 invTransform; // inverse transform
   aabb bounds; // in world space</pre></div>



<p>Note that we don&#8217;t actually store the transformation matrix: we store its inverse. Inverting a matrix is somewhat costly, so we don&#8217;t want to do this for every ray.</p>



<p>The new fields are filled using a new method:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void BVH::SetTransform( mat4&amp; transform )
{
    invTransform = transform.Inverted();
    // calculate world-space bounds using the new matrix
    float3 bmin = bvhNode[0].aabbMin, bmax = bvhNode[0].aabbMax;
    bounds = aabb();
    for( int i = 0; i &lt; 8; i++ ) 
        bounds.grow( TransformPosition( float3( i &amp; 1 ? bmax.x : bmin.x,
            i &amp; 2 ? bmax.y : bmin.y, i &amp; 4 ? bmax.z : bmin.z ), transform ) );
}</pre></div>



<p>This is some pretty dense code, so allow me to explain. First, as promised, the <code>invTransform</code> field is set using the inverted 4&#215;4 matrix. After this we calculate the bounding box for the transformed bounding box of the object. This sounds strange, but it is quite useful: The only way to detect if a ray misses a BVH is by checking its root node against the ray. In the case of a transformed BVH, this already requires transformation of the ray. Storing (the AABB of) the transformed bounds of the BVH root node allows us to do an early &#8216;hit/miss&#8217; test using the original ray. The AABB is likely going to be too large, but that&#8217;s OK: at least it lets us efficiently ignore BVHs that a ray does not even get close to. In the actual code, the <code>for</code> loop calculates the 8 unique combinations of x, y and z from <code>aabbMin</code> and <code>aabbMax</code> of the root node; these combinations represent the 8 corners of the root AABB.</p>



<p>Using the inverted transform we can now make the required modifications to BVH::Traverse.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void BVH::Intersect( Ray&amp; ray )
{
    // backup ray and transform original
    Ray backupRay = ray;
    ray.O = TransformPosition( ray.O, invTransform );
    ray.D = TransformVector( ray.D, invTransform );
    ray.rD = float3( 1 / ray.D.x, 1 / ray.D.y, 1 / ray.D.z );
    // trace transformed ray

    ....

    // restore ray origin and direction
    backupRay.t = ray.t;
    ray = backupRay;
}</pre></div>



<p>The ray that is about to intersect the BVH first gets copied, so we can restore it later: we may wish to intersect the same ray with another BVH. After that we transform the ray origin and direction, and recalculate the reciprocals of the direction. With the transformed ray we then traverse the BVH in the usual manner.</p>



<p>Maths note: the ray origin is a position; to transform it using a matrix we should apply rotation and translation. We thus use a homogeneous coordinate with 1 for the w component. The ray direction on the  other hand should be rotated but not translated; it is thus turned into a homogeneous coordinate with 0 for the w component. The <code>TransformPosition</code> and <code>TransformVector</code> functions reflect this difference.</p>



<p>At the end of the code we restore the original ray, except for one field: the t value, which represents the nearest intersection distance.</p>



<p>With the proposed modifications, the <code>Tick</code> function now becomes quite a bit more elegant:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void TopLevelApp::Tick( float deltaTime )
{
    float3 p0( -1, 1, 2 ), p1( 1, 1, 2 ), p2( -1, -1, 2 );
    static float angle = 0;
    angle += 0.01f; if (angle &gt; 2 * PI) angle -= 2 * PI;
    bvh[0].SetTransform( mat4::Translate( float3( -1.3f, 0, 0 ) ) );
    bvh[1].SetTransform( mat4::Translate( float3( 1.3f, 0, 0 ) ) 
                       * mat4::RotateY( angle ) );
#pragma omp parallel for schedule(dynamic)
    for (int tile = 0; tile &lt; 6400; tile++)
    {
        int x = tile % 80, y = tile / 80;
        Ray ray;
        ray.O = float3( 0, 0.5f, -4.5f );
        for (int v = 0; v &lt; 8; v++) for (int u = 0; u &lt; 8; u++)
        {
            float3 pixelPos = ray.O + p0 +
                (p1 - p0) * ((x * 8 + u) / 640.0f) +
                (p2 - p0) * ((y * 8 + v) / 640.0f);
            ray.D = normalize( pixelPos - ray.O ), ray.t = 1e30f;
            ray.rD = float3( 1 / ray.D.x, 1 / ray.D.y, 1 / ray.D.z );
            bvh[0].Intersect( ray );
            bvh[1].Intersect( ray );
            uint c = ray.t &lt; 1e30f ? (255 - (int)((ray.t - 3) * 80)) : 0;
            screen-&gt;Plot( x * 8 + u, y * 8 + v, c * 0x10101 );
        }
    }
}</pre></div>



<p>Note how <code>bvh[0]</code> is transformed to the left using a translation matrix. For <code>bvh[1]</code> we use a concatenated matrix, consisting of a rotation around the y-axis followed by a translation to the right.</p>



<h2 class="wp-block-heading">Many Armadillos</h2>



<p>With the code we have so far we can conveniently spin and move models, without rebuilding or refitting their BVHs. But what if we have <em>a lot of</em> Armadillos? This is where the top level acceleration structure comes in.</p>



<p>It starts with the notion that a pair of BVHs can be combined into a single BVH, by simply adding one new node, that has the pair of BVHs as child nodes. We now have a new, valid BVH that we can traverse as if it were a regular BVH. If we combine this with the concept of transformed BVHs, we get something very powerful. The nodes that we use to combine a set of BVHs into a single BVH are referred to as the top level acceleration structure, or TLAS. It effectively helps us to hierarchically cull groups of objects, just like we culled groups of triangles using the BVH.</p>



<p>Let&#8217;s start with the definition of a TLAS node:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">struct TLASNode
{
    float3 aabbMin;
    uint leftBLAS;
    float3 aabbMax;
    uint isLeaf;
};</pre></div>



<p>This looks like a regular BVH node. The <code>leftFirst</code> field, which originally stored either the index of the left node, or the &#8216;index of the index&#8217; of the first triangle, now stores a BLAS index: in our simple case with two BVHs, this would be either 0 or 1. In the TLAS, we will never have more than one BLAS in a leaf node, so indirection is not needed here. The <code>triCount</code> field is also not needed. Since we still need to know if this is a leaf node or not, we now simply use a boolean, encoded as a uint.</p>



<p>Also analogous to the original BVH we get a TLAS, which stores data related to the top level acceleration structure:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">class TLAS
{
public:
    TLAS() = default;
    TLAS( BVH* bvhList, int N );
    void Build();
    void Intersect( Ray&amp; ray );
private:
    TLASNode* tlasNode = 0;
    BVH* blas = 0;
    uint nodesUsed, blasCount;
};</pre></div>



<p>The <code>tlasNode</code> field is a pool of nodes, analogous to the <code>bvhNode</code> array we used for constructing a BVH. The triangle array of the BVH is replaced by a BVH array. Each BVH is a bottom level acceleration structure, so we name this array <code>blas</code>.</p>



<p>Let&#8217;s build a minimal TLAS, before we get to more complex scenes.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">TLAS::TLAS( BVH* bvhList, int N )
{
    // copy a pointer to the array of bottom level accstructs
    blas = bvhList;
    blasCount = N;
    // allocate TLAS nodes
    tlasNode = (TLASNode*)_aligned_malloc( sizeof( TLASNode ) * 2 * N, 64 );
    nodesUsed = 2;
}</pre></div>



<p>This is the constructor for the TLAS. It takes an array of BVHs (and since I stubbornly evade the use of a convenient vector here, <code>N</code> stores the BVH count), which we store in the TLAS object. A TLAS over <code>N</code> BVHs will consist of <code>2N-1</code> nodes, so we pre-allocate this set of nodes. And as usual, for cache alignment reasons, we skip <code>tlasNode[1]</code>, so the actual array has <code>2N</code> elements. Element 0 is, as usual, reserved for the root.</p>



<p>For just two BVHs we can build the TLAS manually.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void TLAS::Build()
{
    // assign a TLASleaf node to each BLAS
    tlasNode[2].leftBLAS = 0;
    tlasNode[2].aabbMin = float3( -100 );
    tlasNode[2].aabbMax = float3( 100 );
    tlasNode[2].isLeaf = true;
    tlasNode[3].leftBLAS = 1;
    tlasNode[3].aabbMin = float3( -100 );
    tlasNode[3].aabbMax = float3( 100 );
    tlasNode[3].isLeaf = true;
    // create a root node over the two leaf nodes
    tlasNode[0].leftBLAS = 2;
    tlasNode[0].aabbMin = float3( -100 );
    tlasNode[0].aabbMax = float3( 100 );
    tlasNode[0].isLeaf = false;
}</pre></div>



<p>Here, two TLAS leaf nodes are created, which reference BVH 0 and 1. The nodes have massive AABBs, to ensure that a ray will always intersect them. We&#8217;ll need to refine that later. The root node of the TLAS references child node 2 (and thus also 3), which we just created. The root also has a massive AABB, for now.</p>



<p>The TLAS is traversed like a regular BVH:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void TLAS::Intersect( Ray&amp; ray )
{
    TLASNode* node = &amp;tlasNode[0], *stack[64];
    uint stackPtr = 0;
    while (1)
    {
        if (node-&gt;isLeaf)
        {
            blas[node-&gt;leftBLAS].Intersect( ray );
            if (stackPtr == 0) break; else node = stack[--stackPtr];
            continue;
        }
        TLASNode* child1 = &amp;tlasNode[node-&gt;leftBLAS];
        TLASNode* child2 = &amp;tlasNode[node-&gt;leftBLAS + 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>The difference between TLAS traversal and BLAS traversal is in the leaf nodes. For the TLAS, a leaf contains a single BLAS, which we must intersect. After intersecting the BLAS, we still may need to intersect other BVHs (if they are closer than the nearest intersection so far), so the functionality that restores the ray after traversing a BVH comes in handy now.</p>



<p>Let&#8217;s put the TLAS/BLAS to the test. First, we create the TLAS in the <code>::Init</code> function:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void TopLevelApp::Init()
{
    bvh[0] = BVH( "assets/armadillo.tri", 30000 );
    bvh[1] = BVH( "assets/armadillo.tri", 30000 );
    tlas = TLAS( bvh, 2 );
    tlas.Build();
}</pre></div>



<p>Then, in the <code>::Tick</code> function, we replace the two calls to <code>BVH::Intersect(...)</code> by a single call to <code>TLAS::Intersect(...)</code>:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">tlas.Intersect( ray );</pre></div>


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


<p>And that is all. We now have two BVHs, nicely tucked away into a single structure, which we can intersect with a single call. We can still change the transforms for the BVHs, per frame if we wish, without any cost.</p>



<h2 class="wp-block-heading">Loose Ends</h2>



<p>A lot remains to be done, but this is already a pretty long article. Next time we will fill in the details:</p>



<ul class="wp-block-list">
<li>Rebuilding the TLAS per frame</li>



<li>Building a TLAS for lots of armadillos</li>



<li>Proper AABBs in the TLAS</li>



<li>Instancing, so we don&#8217;t have to load the armadillo twice</li>



<li>Combining TLAS/BLAS with refitting and rebuilding</li>
</ul>



<p>In short: <a href="https://jacco.ompf2.com/2022/05/13/how-to-build-a-bvh-part-6-all-together-now/">everything will come together</a>. </p>



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



<p>The complete code for this project (for Windows / Visual Studio) <a href="https://github.com/jbikker/bvh_article">can be found on GitHub</a>.</p>



<p>Enjoyed the article? Spotted an error?</p>



<p>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>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/05/07/how-to-build-a-bvh-part-5-tlas-blas/feed/</wfw:commentRss>
			<slash:comments>14</slash:comments>
		
		
			</item>
		<item>
		<title>How to build a BVH &#8211; part 4: Animation</title>
		<link>https://jacco.ompf2.com/2022/04/26/how-to-build-a-bvh-part-4-animation/</link>
					<comments>https://jacco.ompf2.com/2022/04/26/how-to-build-a-bvh-part-4-animation/#comments</comments>
		
		<dc:creator><![CDATA[jbikker]]></dc:creator>
		<pubDate>Tue, 26 Apr 2022 08:24:50 +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=1091</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>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>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><strong>.</strong></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><strong>BVHs for animated models: refitting and rebuilding (this article).</strong></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><a href="https://jacco.ompf2.com/2022/06/15/how-to-build-a-bvh-part-9b-massive/">OpenCL: GPU ray tracing, part 2 (series finale)</a>.</li>
</ol>



<p>In this fourth article we make a start with rendering animated scenes. For a single mesh we have two options: rebuilding and <em>refitting</em>. Once we have these at our disposal we can go for the Holy Grail: animating scenes with multiple objects.</p>



<h2 class="wp-block-heading">Needful Things</h2>



<p>As usual, we&#8217;ll start with some modifications to the code to facilitate the introduction of some new concepts. We will need a new model, for which I picked London&#8217;s Westminster clock tower from <a href="https://sketchfab.com/">Sketchfab</a>:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/bigben.jpg" alt=""/><figcaption class="wp-element-caption">Just the tower though. Without textures. In greyscale. Sorry.</figcaption></figure></div>


<p>The 3D rendition of the tower has 20944 triangles, which will tax the BVH builder a bit more than the Unity vehicle. Rendering the slender object on the other hand is faster, as it occupies less pixels. This lets us focus on BVH maintenance for this article without worrying too much about rendering performance. Speaking of rendering performance: here is a new <code>Tick</code> function, with an adjusted camera and somewhat fine-tuned OpenMP multithreading:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void AnimationApp::Tick( float deltaTime )
{
    float3 p0( -1, 1, 2 ), p1( 1, 1, 2 ), p2( -1, -1, 2 );
    #pragma omp parallel for schedule(dynamic)
    for (int tile = 0; tile &lt; 6400; tile++)
    {
        int x = tile % 80, y = tile / 80;
        Ray ray;
        ray.O = float3( 0, 3.5f, -4.5f );
        for (int v = 0; v &lt; 8; v++) for (int u = 0; u &lt; 8; u++)
        {
            float3 pixelPos = ray.O + p0 + 
                (p1 - p0) * ((x * 8 + u) / 640.0f) + 
                (p2 - p0) * ((y * 8 + v) / 640.0f);
            ray.D = normalize( pixelPos - ray.O ), ray.t = 1e30f;
            ray.rD = float3( 1 / ray.D.x, 1 / ray.D.y, 1 / ray.D.z );
            IntersectBVH( ray );
            uint c = ray.t &lt; 1e30f ? (255 - (int)((ray.t - 4) * 180)) : 0;
            screen-&gt;Plot( x * 8 + u, y * 8 + v, c * 0x10101 );
        }
    }
}</pre></div>



<p>On my machine, this renders one frame in less than 4 milliseconds. Building the BVH using the 8-plane binned builder takes about 30 milliseconds. The rendered image looks like this:</p>


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


<p>Not as shiny as the photo of the original, but it will have to do. Time to add some movement!</p>



<h2 class="wp-block-heading">Being Flexible</h2>



<p>Let&#8217;s add a bit of a swing to Big Ben&#8217;s tower:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void Animate()
{
    static float r = 0;
    if ((r += 0.05f) &gt; 2 * PI) r -= 2 * PI;
    float a = sinf( r ) * 0.5f;
    for( int i = 0; i &lt; N; i++ ) for( int j = 0; j &lt; 3; j++ )
    {
        float3 o = (&amp;original[i].vertex0)[j];
        float s = a * (o.y - 0.2f) * 0.2f;
        float x = o.x * cosf( s ) - o.y * sinf( s );
        float y = o.x * sinf( s ) + o.y * cosf( s );
        (&amp;tri[i].vertex0)[j] = float3( x, y, o.z );
    }
}</pre></div>



<p>This code applies a 2D rotation to each triangle vertex, with a sine-wave angle scaled by the y-position of the vertex. Whatever; the result looks like a stiff breeze is bothering the tower:</p>


<div class="wp-block-image is-resized">
<figure class="aligncenter size-large"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/swing.jpg" alt="" style="width:480px"/><figcaption class="wp-element-caption">Two frames of the animation sequence.</figcaption></figure></div>


<p>The animation code requires a copy of the unmodified triangles. So, we create room for two copies of the triangle set:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">Tri tri[N], original[N];</pre></div>



<p>Array <code>tri</code> contains the input for the BVH builder; array <code>original</code> stores the unmodified data. The ::Init function now thus reads to the <code>original</code> array:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void AnimationApp::Init()
{
    FILE* file = fopen( "assets/bigben.tri", "r" );
    for (int t = 0; t &lt; N; t++) fscanf( file, "%f %f %f %f %f %f %f %f %f\n",
        &amp;original[t].vertex0.x, &amp;original[t].vertex0.y, &amp;original[t].vertex0.z,
        &amp;original[t].vertex1.x, &amp;original[t].vertex1.y, &amp;original[t].vertex1.z,
        &amp;original[t].vertex2.x, &amp;original[t].vertex2.y, &amp;original[t].vertex2.z );
}</pre></div>



<p>Since we are now changing the mesh each frame, we should build the BVH each frame as well. This requires a few small changes to the <code>BuildBVH()</code> function. First of all, it should not allocate the <code>bvhNode</code> array each time we build a BVH, so this needs to be allocated elsewhere. Second, we need to reset the pointer to the next free node in the <code>bvhNode</code> array, by resetting <code>nodesUsed</code> to 2: Recall that <code>bvhNode[0]</code> is the BVH root node, and <code>bvhNode[1]</code> is skipped to ensure that subsequent pairs of nodes reside in the same cache line.</p>



<p>With these changes made, we can call the new <code>Animate()</code> function and the updated <code>BuildBVH()</code> function once per frame, in the <code>::Tick</code> function, to obtain the desired ray traced animated scene.</p>



<h2 class="wp-block-heading">If It Fits</h2>



<p>The animated flexible Big Ben is now being ray traced in real-time &#8211; if your system is fast enough. On my machine I get almost 30fps. If the total frame time, about 30ms is spent on building the BVH each frame, while rendering takes 4 milliseconds.</p>



<p>It seems like we may have a problem for a more complex scene, or a mesh that covers more pixels. We may have to come up with a smarter solution to stay real-time under those circumstances.</p>



<p>Let&#8217;s take a look at a very simple animation, one in which the clock tower takes off for a trip to the moon:</p>


<div class="wp-block-image is-resized">
<figure class="aligncenter size-large"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/takeoff-1.jpg" alt="" style="width:512px"/><figcaption class="wp-element-caption">Boldly going where no Big Ben has gone before.</figcaption></figure></div>


<p>The three frames have something in common: their BVH. For the construction of each of the three BVHs, <em>exactly the same</em> decisions are made. We will have the same number of nodes and the same number of triangles in each leaf node. The only difference is in the <em>bounds</em> that we store in every node: these will have a vertical offset. </p>



<p>Obviously there is a better and faster way to handle this type of animation. Instead of moving the missile <em>up</em>, we can move the camera <em>down</em> to obtain the same result &#8211; without ever rebuilding the BVH. But what if the animation is a little different?</p>


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


<p>This time moving the camera isn&#8217;t going to work. And we can also not simply assume that the BVHs differ only in their bounds. They <em>are</em> going to be rather similar though. What if we <em>would </em>in fact use the same tree, with updated bounds only? It certainly would save a lot of time in construction work.  </p>



<p>The technique where we reuse a BVH for an animated mesh is called <em>refitting</em>. The process starts at the leaf nodes, which contain the (now changed) triangles. Each leaf node gets an updated bounding box. The update may have consequences for the parent nodes of the leaf nodes, so we adjust their bounds as well, by making them tightly fit their child nodes. We proceed this way until we reach the root of the tree.</p>



<p>This sounds like a recursive process, but in practice, a simpler approach can be used.</p>



<p>When we created the BVH, we used node 0 for the root. After that, every child node got allocated after its parent; we thus know that the index of a child is <em>always</em> greater than the index of its parent. We can exploit this by visiting all nodes starting at the end of the list, working our way back to the first element. This reverse order guarantees that we never visit an interior node with outdated child nodes.</p>



<p>With this trick, the refit functionality becomes rather simple:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void RefitBVH()
{
    for (int i = nodesUsed - 1; i &gt;= 0; i--) if (i != 1)
    { 
        BVHNode&amp; node = bvhNode[i];
        if (node.isLeaf())  
        {
            // leaf node: adjust bounds to contained triangles
            UpdateNodeBounds( i );
            continue;
        }
        // interior node: adjust bounds to child node bounds
        BVHNode&amp; leftChild = bvhNode[node.leftFirst];
        BVHNode&amp; rightChild = bvhNode[node.leftFirst + 1];
        node.aabbMin = fminf( leftChild.aabbMin, rightChild.aabbMin );
        node.aabbMax = fmaxf( leftChild.aabbMax, rightChild.aabbMax );
    }
}</pre></div>



<p>In words: we visit all the allocated nodes, starting at the last and skipping node 1. If the node is a leaf, we recalculate its bounds using the triangles it contains. For interior nodes, we adjust the bounds so they enclose the two child nodes. The whole procedure is pretty simple, and completes in half a millisecond. That means that the flexible tower now gets updated <em>and </em>rendered in less than 5 milliseconds: we are actually ray tracing a dynamic scene at 200fps, unoptimized and all.</p>



<h2 class="wp-block-heading">Bad News</h2>



<p>Based on the findings so far it would seem that BVH refitting is a golden bullet to handle all animation. This is sadly not the case. For starters, refitting requires that animation frames have the same number of triangles. It also requires that the structure of the animation frames is roughly equal. 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/smallchange-1024x433.jpg" alt="" style="width:600px"/></figure></div>


<p>Here, the large triangle moved a bit, invalidating the right bounding box. This is not a big deal; refitting is quite effective here:</p>



<ul class="wp-block-list">
<li>we adjust the right box to tightly fit the new set of primitives</li>



<li>we adjust the root box: it becomes a bit smaller at the right side and the bottom.</li>
</ul>



<p>But now consider a different 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/bigchange-1024x433.jpg" alt="" style="width:600px"/></figure></div>


<p>This time, one of the small objects from the top-left node moved all the way to the bottom right of the scene. If we update the top-left box to include the moved object, the resulting box will be massive; it will almost entirely overlap the right box. Quite obviously the resulting tree is rather bad. A much better choice would be to include the moved object in the right node &#8211; but that&#8217;s not what refitting does.</p>



<p>In general, refitting is applied when we have subtle animation: trees waving in the wind, objects changing position, perhaps in some cases a walking character. In those cases, we get the BVH update almost for free, often at the expense of (some) tree quality. In other cases, a rebuild will be the better option. We can also combine rebuilding and refitting: in that case, we refit some subsequent frames, and after a few refits, we rebuild, to ensure that the BVH doesn&#8217;t deteriorate too much. A well-designed ray tracing engine will strive to rebuild a few meshes per frame, while refitting the others.</p>



<h2 class="wp-block-heading">On Track</h2>



<p>Finally, have a look at this scene from a racing game:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/racinggame.jpg" alt="" style="aspect-ratio:1;object-fit:cover;width:600px"/></figure></div>


<p>How should we build a BVH for this animation? We have a few different situations:</p>



<ul class="wp-block-list">
<li>The track is large and static: we should build a high-quality BVH once for this.</li>



<li>The race cars move, but do not deform; so they could be refitted.</li>



<li>The audience next to the track goes through a simple animation sequence: we could precalculate a small set of BVHs for this.</li>
</ul>



<p>The challenge is of course in the combination. How to handle that is the topic of the <a href="https://jacco.ompf2.com/2022/05/07/how-to-build-a-bvh-part-5-tlas-blas/">next article</a>.</p>



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



<p>The complete code for this project (for Windows / Visual Studio) <a href="https://github.com/jbikker/bvh_article">can be found on GitHub</a>.</p>



<p>Enjoyed the article? Spotted an error?</p>



<p>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>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/04/26/how-to-build-a-bvh-part-4-animation/feed/</wfw:commentRss>
			<slash:comments>9</slash:comments>
		
		
			</item>
		<item>
		<title>How to build a BVH &#8211; part 3: Quick Builds</title>
		<link>https://jacco.ompf2.com/2022/04/21/how-to-build-a-bvh-part-3-quick-builds/</link>
					<comments>https://jacco.ompf2.com/2022/04/21/how-to-build-a-bvh-part-3-quick-builds/#comments</comments>
		
		<dc:creator><![CDATA[jbikker]]></dc:creator>
		<pubDate>Thu, 21 Apr 2022 18:30:23 +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=1078</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>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>This series consist of <s>six</s> eight 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><strong>Faster construction: binned BVH building (this article).</strong></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><a href="https://jacco.ompf2.com/2022/06/15/how-to-build-a-bvh-part-9b-massive/">OpenCL: GPU ray tracing, part 2 (series finale)</a>.</li></ol>



<p>In this third article we discuss how to reduce the time it takes to build a good BVH. This will be an important ingredient for the ultimate goal: building a BVH for a large scale dynamic environment, which is the topic of a later article.</p>



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



<p>In the <a href="https://jacco.ompf2.com/2022/04/18/how-to-build-a-bvh-part-2-faster-rays/">previous article</a> the Surface Area Heuristic was introduced to improve the quality of the BVH. Here, a &#8216;high quality tree&#8217; is one that can be used to quickly find the intersection between a ray and the scene. The SAH works wonders, and when combined with ordered traversal, the naïve BVH from the <a href="https://jacco.ompf2.com/2022/04/13/how-to-build-a-bvh-part-1-basics/">first article</a>  is outperformed by a factor 3.</p>



<p>There is a catch however. Where the basic BVH builder needed mere milliseconds to build the tree, the SAH builder needs multiple seconds &#8211; and we&#8217;re not exactly using a very complex mesh. The reason is simple: For <em>N</em> polygons, we evaluate <em>N</em> split plane candidates on each axis &#8211; but split plane evaluation involves visiting all primitives. The algorithmic complexity is thus <em>O(N²)</em> for one split; not great if we hoped to build BVHs for much larger scenes, and also not something we can solve with low-level optimizations or parallel code.</p>



<p>For the new concepts introduced in this article we will need to clean up the <code>Subdivide</code> function somewhat. Let&#8217;s start with splitting of the code that finds the optimal split plane position and axis to a function:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float FindBestSplitPlane( BVHNode&amp; node, int&amp; axis, float&amp; splitPos )
{
    float bestCost = 1e30f;
    for (int a = 0; a &lt; 3; a++) for (uint i = 0; i &lt; node.triCount; i++)
    {
        Tri&amp; triangle = tri[triIdx[node.leftFirst + i]];
        float candidatePos = triangle.centroid[a];
        float cost = EvaluateSAH( node, a, candidatePos );
        if (cost &lt; bestCost) splitPos = candidatePos, axis = a, bestCost = cost;
    }
    return bestCost;
}</pre></div>



<p> This simplifies the relevant section in <code>Subdivide</code> to</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">// determine split axis using SAH
    int axis;
    float splitPos;
    float splitCost = FindBestSplitPlane( node, axis, splitPos );</pre></div>



<p>Next, <code>Subdivide</code> checks if the best split cost is actually an improvement over not splitting. We can make that a bit more clear using a function that calculates the cost of an unsplit node:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float CalculateNodeCost( BVHNode&amp; node )
{
    float3 e = node.aabbMax - node.aabbMin; // extent of the node
    float surfaceArea = e.x * e.y + e.y * e.z + e.z * e.x;
    return node.triCount * surfaceArea;
}</pre></div>



<p>Back in <code>Subdivide</code>, we call <code>CalculateNodeCost</code> after finding the best split plane, and terminate if it isn&#8217;t worth it:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float nosplitCost = CalculateNodeCost( node );
    if (splitCost &gt;= nosplitCost) return;</pre></div>



<p>Now that everything is nice and tidy we can focus on the isolated logic in <code>FindBestSplitPlane</code>.</p>



<h2 class="wp-block-heading">From <em>O(N²)</em> to <em>O(N)</em></h2>



<p>A straightforward way to reduce the time complexity to O(N) is to use the midpoint algorithm. However, we have very good reasons for not using that: the resulting tree is a rather poor one. But what would happen if we did not just consider <em>one</em> position, but several, or many? Intuitively, there shouldn&#8217;t be too much of a difference between these two situations: </p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="530" src="https://jacco.ompf2.com/wp-content/uploads/2022/04/towardsbins-1024x530.jpg" alt="" class="wp-image-1080" srcset="https://jacco.ompf2.com/wp-content/uploads/2022/04/towardsbins-1024x530.jpg 1024w, https://jacco.ompf2.com/wp-content/uploads/2022/04/towardsbins-300x155.jpg 300w, https://jacco.ompf2.com/wp-content/uploads/2022/04/towardsbins-768x398.jpg 768w, https://jacco.ompf2.com/wp-content/uploads/2022/04/towardsbins-1536x795.jpg 1536w, https://jacco.ompf2.com/wp-content/uploads/2022/04/towardsbins-1222x633.jpg 1222w, https://jacco.ompf2.com/wp-content/uploads/2022/04/towardsbins-897x465.jpg 897w, https://jacco.ompf2.com/wp-content/uploads/2022/04/towardsbins-360x186.jpg 360w, https://jacco.ompf2.com/wp-content/uploads/2022/04/towardsbins.jpg 1734w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><figcaption>Left: split plane candidates through the primitive centroids. Right: uniformly spaced split plane candidates.</figcaption></figure>



<p>In fact, if we use a high enough number of uniformly spaced planes, the solution should converge to the same answer as the full SAH sweep. And, once this works, we can start experimenting: At which number of planes do we still get a reasonable tree?</p>



<p>The initial code for this is simple enough:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float FindBestSplitPlane( BVHNode&amp; node, int&amp; axis, float&amp; splitPos )
{
    float bestCost = 1e30f;
    for (int a = 0; a &lt; 3; a++) 
    {
        float boundsMin = node.aabbMin[a];
        float boundsMax = node.aabbMax[a];
        if (boundsMin == boundsMax) continue;
        float scale = (boundsMax - boundsMin) / 100;
        for (uint i = 1; i &lt; 100; i++)
        {
            float candidatePos = boundsMin + i * scale;
            float cost = EvaluateSAH( node, a, candidatePos );
            if (cost &lt; bestCost)
                splitPos = candidatePos, axis = a, bestCost = cost;
        }
    }
    return bestCost;
}</pre></div>



<p>Here, 100 is hardcoded as the number of intervals; these are separated by 99 planes, which will be the split plane candidates. The planes are a fixed distance apart: to prevent a repeated division by 100, this distance is calculated once as <em>(boundsMax &#8211; boundsMin) / 100</em>.</p>



<p>Running the code gets us our first results. Building the BVH is now considerably faster, because 100 is far smaller than <em>N</em>: on my machine it now takes about 350ms. The other result is that the BVH is not bad at all: where the full sweep results in a frame time of 106ms, the 100 planes yield a tree that renders in 109ms; a rather modest reduction in performance considering the much faster build.</p>



<p>It turns out that a smaller number of planes still gets us a pretty decent tree. At only 16 planes, rendering takes 110ms &#8211; but the build completes in a mere 60ms. And at just 8 planes, rendering takes 111ms, while the tree now builds in 30ms. Even 4 planes seem reasonable: 113ms for rendering, 15ms for building the tree. Note that this is still far better than the midpoint split.</p>



<p>We can now balance tree quality and build speed. This is very useful, especially once we start rendering animated scenes: a model that occupies just a few pixels and changes every frame justifies a quick and dirty tree, but full-screen static scenery should use a tree that is high quality &#8211; no matter the cost. We can control this now, especially when we realize that we left one trick unused: limiting the SAH sweep to the longest axis, like we did with the midpoint split. This comes at a minor degradation of tree quality, but it cuts build time down to 5ms for our scene. </p>



<p>In short, we have options.</p>



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



<p>In the initial code for the uniformly spaced planes I assumed that we should subdivide the full extent of the AABB of a node. This is strictly not necessary. In the SAH sweep, the first split plane candidate is on the first centroid; the last one on the last centroid. A better range of values to cut up is thus the AABB over the centroids of the primitives. It turns out that this matters.</p>



<div class="wp-block-image"><figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" src="https://jacco.ompf2.com/wp-content/uploads/2022/04/cbounds.jpg" alt="" class="wp-image-1081" width="591" height="591" srcset="https://jacco.ompf2.com/wp-content/uploads/2022/04/cbounds.jpg 788w, https://jacco.ompf2.com/wp-content/uploads/2022/04/cbounds-300x300.jpg 300w, https://jacco.ompf2.com/wp-content/uploads/2022/04/cbounds-150x150.jpg 150w, https://jacco.ompf2.com/wp-content/uploads/2022/04/cbounds-768x768.jpg 768w, https://jacco.ompf2.com/wp-content/uploads/2022/04/cbounds-360x360.jpg 360w" sizes="auto, (max-width: 591px) 100vw, 591px" /><figcaption>Bounds over the primitives (blue) versus bounds over the primitive centroids (yellow).</figcaption></figure></div>



<p>The centroid bounds are quickly found using a loop over the primitives:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float boundsMin = 1e30f, boundsMax = -1e30f;
    for (int i = 0; i &lt; node.triCount; i++)
    {
        Tri&amp; triangle = tri[triIdx[node.leftFirst + i]];
        boundsMin = min( boundsMin, triangle.centroid[a] );
        boundsMax = max( boundsMax, triangle.centroid[a] );
    }</pre></div>



<p>This replaces the two lines that read <code>boundsMin</code> and <code>boundsMax</code> directly from the node AABB. At 4 and 8 planes per dimension, this slightly improves the resulting tree, at negligible cost.</p>



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



<p>The Unity vehicle mesh consists of about 12k triangles. Using the fixed planes, this now builds in mere milliseconds. But: it turns out that we can do much better than what we have so far.</p>



<p>Let&#8217;s have another look at the diagram with the evenly spaced planes:</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="538" src="https://jacco.ompf2.com/wp-content/uploads/2022/04/bins-1024x538.jpg" alt="" class="wp-image-1082" srcset="https://jacco.ompf2.com/wp-content/uploads/2022/04/bins-1024x538.jpg 1024w, https://jacco.ompf2.com/wp-content/uploads/2022/04/bins-300x158.jpg 300w, https://jacco.ompf2.com/wp-content/uploads/2022/04/bins-768x403.jpg 768w, https://jacco.ompf2.com/wp-content/uploads/2022/04/bins-1536x807.jpg 1536w, https://jacco.ompf2.com/wp-content/uploads/2022/04/bins-1222x642.jpg 1222w, https://jacco.ompf2.com/wp-content/uploads/2022/04/bins-897x471.jpg 897w, https://jacco.ompf2.com/wp-content/uploads/2022/04/bins-360x189.jpg 360w, https://jacco.ompf2.com/wp-content/uploads/2022/04/bins.jpg 1710w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>Here, seven planes separate 8 intervals. Each of the primitive centroids projects to one of these intervals. We can now calculate the <em>bounds </em>of each interval, and the <em>primitive count </em>for each interval. Once we have this data for each interval, we can efficiently determine the union of the bounds of a range of intervals, as well as the sum of the primitive counts of a range of intervals. And this in turn is exactly what we need to evaluate the SAH; this time without visiting every primitive multiple times.</p>



<p>Let&#8217;s start with the definition of a <em>bin</em>, which will store an AABB and a primitive count:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">struct Bin { aabb bounds; int triCount = 0; };</pre></div>



<p>Next, we populate the bins by visiting the primitives once (per axis):</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">Bin bin[BINS];
float scale = BINS / (boundsMax - boundsMin);
for (uint i = 0; i &lt; node.triCount; i++)
{
    Tri&amp; triangle = tri[triIdx[node.leftFirst + i]];
    int binIdx = min( BINS - 1, 
        (int)((triangle.centroid[a] - boundsMin) * scale) ); 
    bin[binIdx].triCount++;
    bin[binIdx].bounds.grow( triangle.vertex0 );
    bin[binIdx].bounds.grow( triangle.vertex1 );
    bin[binIdx].bounds.grow( triangle.vertex2 );
}</pre></div>



<p>Here, <code>BINS</code> is the number of intervals.</p>



<p>The bin index for a primitive centroid is calculated as:</p>



<span class="wp-katex-eq" data-display="false">binIdx=(centroid[a] - boundsMin) * 8 / (boundsMax - boundsMin)</span>



<p>To prevent the division per primitive, variable scale stores the non-varying part of this equation.</p>



<p>Once we have determined bounds and primitive counts for the bins, we can use this information to calculate the info we need at each plane. Our final goal is to evaluate the SAH at each plane. For this, we need the following information:</p>



<ul class="wp-block-list"><li>The number of primitives to the left of the plane</li><li>The number of primitives to the right of the plane</li><li>The bounding box over the primitives to the left of the plane</li><li>The bounding box over the primitives to the right of the plane.</li></ul>



<p>We need this data per plane, so we store it in some arrays:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float leftArea[BINS - 1], rightArea[BINS - 1];
int leftCount[BINS - 1], rightCount[BINS - 1];</pre></div>



<p>We can fill these arrays with a sweep over the bins. We will do a sweep from the left to the right to populate the <code>leftArea</code> and <code>leftCount</code> arrays, and a sweep from the right to the left to populate the <code>rightArea</code> and <code>rightCount</code> arrays. </p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">aabb leftBox, rightBox;
int leftSum = 0, rightSum = 0;
for (int i = 0; i &lt; BINS - 1; i++)
{
    leftSum += bin[i].triCount;
    leftCount[i] = leftSum;
    leftBox.grow( bin[i].bounds );
    leftArea[i] = leftBox.area();
    rightSum += bin[BINS - 1 - i].triCount;
    rightCount[BINS - 2 - i] = rightSum;
    rightBox.grow( bin[BINS - 1 - i].bounds );
    rightArea[BINS - 2 - i] = rightBox.area();
}</pre></div>



<p>Note that the sweep from left to right and from right to left happen simultaneously. Variable <code>leftBox</code> starts as an empty AABB. At each bin it is extended with the bounds of that bin. Likewise, <code>leftSum</code> (used for the summed triangle count) starts at zero and increases with the counts stored for each bin. The variables for the right side are updated in the same manner.</p>



<p>After the arrays have been filled we can evaluate the SAH for each plane:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">scale = (boundsMax - boundsMin) / BINS;
for (int i = 0; i &lt; BINS - 1; i++)
{
    float planeCost = leftCount[i] * leftArea[i] + rightCount[i] * rightArea[i];
    if (planeCost &lt; bestCost)
        axis = a, splitPos = boundsMin + scale * (i + 1), bestCost = planeCost;
}</pre></div>



<p>Once again, scale is used to prevent the repeated division.</p>



<p>The full Subdivide function is now a somewhat large chunk of code:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float FindBestSplitPlane( BVHNode&amp; node, int&amp; axis, float&amp; splitPos )
{
   float bestCost = 1e30f;
   for (int a = 0; a &lt; 3; a++)
   {
      float boundsMin = 1e30f, boundsMax = -1e30f;
      for (int i = 0; i &lt; node.triCount; i++)
      {
         Tri&amp; triangle = tri[triIdx[node.leftFirst + i]];
         boundsMin = min( boundsMin, triangle.centroid[a] );
         boundsMax = max( boundsMax, triangle.centroid[a] );
      }
      if (boundsMin == boundsMax) continue;
      // populate the bins
      Bin bin[BINS];
      float scale = BINS / (boundsMax - boundsMin);
      for (uint i = 0; i &lt; node.triCount; i++)
      {
         Tri&amp; triangle = tri[triIdx[node.leftFirst + i]];
         int binIdx = min( BINS - 1, 
            (int)((triangle.centroid[a] - boundsMin) * scale) );
         bin[binIdx].triCount++;
         bin[binIdx].bounds.grow( triangle.vertex0 );
         bin[binIdx].bounds.grow( triangle.vertex1 );
         bin[binIdx].bounds.grow( triangle.vertex2 );
      }
      // gather data for the 7 planes between the 8 bins
      float leftArea[BINS - 1], rightArea[BINS - 1];
      int leftCount[BINS - 1], rightCount[BINS - 1];
      aabb leftBox, rightBox;
      int leftSum = 0, rightSum = 0;
      for (int i = 0; i &lt; BINS - 1; i++)
      {
         leftSum += bin[i].triCount;
         leftCount[i] = leftSum;
         leftBox.grow( bin[i].bounds );
         leftArea[i] = leftBox.area();
         rightSum += bin[BINS - 1 - i].triCount;
         rightCount[BINS - 2 - i] = rightSum;
         rightBox.grow( bin[BINS - 1 - i].bounds );
         rightArea[BINS - 2 - i] = rightBox.area();
      }
      // calculate SAH cost for the 7 planes
      scale = (boundsMax - boundsMin) / BINS;
      for (int i = 0; i &lt; BINS - 1; i++)
      {
        float planeCost = 
           leftCount[i] * leftArea[i] + rightCount[i] * rightArea[i];
        if (planeCost &lt; bestCost)
           axis = a, splitPos = boundsMin + scale * (i + 1), 
           bestCost = planeCost;
      }
   }
   return bestCost;
}</pre></div>



<p>But, it is worth it. Using eight bins the BVH now builds in just 11ms: almost three times faster than before. I did not time the version that considers only the longest axis of the node bounds, but that should take us close to 3ms for this mesh. And that is without any low-level optimizations and SIMD; there is still a lot of room for improvement if we go that route.</p>



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



<p>Now that we can build a BVH this rapidly we are ready to consider animated scenes. Before we go there, two more ingredients are needed: refitting and rigid motion for BVHs using ray transforms. Combined with fast rebuilds, these ingredients unlock the full potential of the top-level BVH, which will finally let us ray trace massive scenes with large moving objects in real-time, even on a CPU. But that&#8217;s material for another day.</p>



<p>Continue reading in <a href="https://jacco.ompf2.com/2022/04/26/how-to-build-a-bvh-part-4-animation/">article 4: rebuilding and refitting</a>.</p>



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



<p>The complete code for this project (for Windows / Visual Studio) <a href="https://github.com/jbikker/bvh_article">can be found on GitHub</a>.</p>



<p>Enjoyed the article? Spotted an error?</p>



<p>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>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/04/21/how-to-build-a-bvh-part-3-quick-builds/feed/</wfw:commentRss>
			<slash:comments>15</slash:comments>
		
		
			</item>
		<item>
		<title>How to build a BVH &#8211; part 2: Faster Rays</title>
		<link>https://jacco.ompf2.com/2022/04/18/how-to-build-a-bvh-part-2-faster-rays/</link>
					<comments>https://jacco.ompf2.com/2022/04/18/how-to-build-a-bvh-part-2-faster-rays/#comments</comments>
		
		<dc:creator><![CDATA[jbikker]]></dc:creator>
		<pubDate>Mon, 18 Apr 2022 19:00:11 +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=1041</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>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>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><strong>Faster rays: the Surface Area Heuristic and ordered traversal (this article).</strong></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><a href="https://jacco.ompf2.com/2022/06/15/how-to-build-a-bvh-part-9b-massive/">OpenCL: GPU ray tracing, part 2 (series finale)</a>.</li>
</ol>



<p>In this second article we explore several approaches to substantially speed up ray traversal. For a static scene, this means faster rendering. However, some of the presented techniques do make BVH construction more costly. How to fix this is a topic for a later article.</p>



<h2 class="wp-block-heading">Setting up Shop</h2>



<p>In the first article the scene consisted of a list of random triangles. For today&#8217;s experiments we will need something fancier. We&#8217;ll use a model from the Unity RobotLab scene:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" src="https://jacco.ompf2.com/wp-content/uploads/2022/04/backside.jpg" alt="" class="wp-image-1066" width="479" height="476" srcset="https://jacco.ompf2.com/wp-content/uploads/2022/04/backside.jpg 638w, https://jacco.ompf2.com/wp-content/uploads/2022/04/backside-300x298.jpg 300w, https://jacco.ompf2.com/wp-content/uploads/2022/04/backside-150x150.jpg 150w, https://jacco.ompf2.com/wp-content/uploads/2022/04/backside-360x358.jpg 360w" sizes="auto, (max-width: 479px) 100vw, 479px" /></figure></div>


<p>The model used here (<a href="https://github.com/jbikker/bvh_article/raw/main/assets/unity.tri">click</a> to download it) consists of exactly 12582 triangles. For the purpose of this article the file was converted to a simplistic format, which can be loaded with just a few lines of code.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void FasterRaysApp::Init()
{
    FILE* file = fopen( "assets/unity.tri", "r" );
    float a, b, c, d, e, f, g, h, i;
    for (int t = 0; t &lt; N; t++) 
    {
        fscanf( file, "%f %f %f %f %f %f %f %f %f\n", 
            &amp;a, &amp;b, &amp;c, &amp;d, &amp;e, &amp;f, &amp;g, &amp;h, &amp;i );
        tri[t].vertex0 = float3( a, b, c );
        tri[t].vertex1 = float3( d, e, f );
        tri[t].vertex2 = float3( g, h, i );
    }
    fclose( file );
    // construct the BVH
    BuildBVH();
}</pre></div>



<p>The second change to the code is in the visualization: a bit of depth visualization is obtained by plotting greyscale pixels based on the ray distance.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">// draw the scene
screen-&gt;Clear( 0 );
float3 p0( -2.5f, 0.8f, -0.5f );
float3 p1( -0.5f, 0.8f, -0.5f );
float3 p2( -2.5f, -1.2f, -0.5f );
Ray ray;
for (int y = 0; y &lt; 640; y++) for (int x = 0; x &lt; 640; x++)
{
    ray.O = float3( -1.5f, -0.2f, -2.5f );
    float3 pixelPos = p0 + 
        (p1 - p0) * (x / 640.0f) + 
        (p2 - p0) * (y / 640.0f);
    ray.D = normalize( pixelPos - ray.O ), ray.t = 1e30f;
    IntersectBVH( ray, rootNodeIdx );
    uint c = 500 - (int)(ray.t * 42);
    if (ray.t &lt; 1e30f) screen-&gt;Plot( x, y, c * 0x10101 );
}</pre></div>



<p>For this camera view, the scene renders in 300 milliseconds on my machine, which corresponds to about 1.3MRays/s, still on a single core.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" src="https://jacco.ompf2.com/wp-content/uploads/2022/04/frontside.jpg" alt="" class="wp-image-1067" width="477" height="476" srcset="https://jacco.ompf2.com/wp-content/uploads/2022/04/frontside.jpg 636w, https://jacco.ompf2.com/wp-content/uploads/2022/04/frontside-300x300.jpg 300w, https://jacco.ompf2.com/wp-content/uploads/2022/04/frontside-150x150.jpg 150w, https://jacco.ompf2.com/wp-content/uploads/2022/04/frontside-360x359.jpg 360w" sizes="auto, (max-width: 477px) 100vw, 477px" /></figure></div>


<p>Something interesting happens when we observe the bunny from the opposite side. When we place the camera at (-1.5f, -0.2f, -2.5) and flip the relative position of the screen plane accordingly by changing -2 to 2 for p0, p1 and p2, we get a different image, but also different performance: suddenly one frame only takes 183 milliseconds, for a ray throughput of more than 2.1MRays/s.</p>



<p>Once we see what causes this, we have the means to always achieve the higher performance level. In this article we will combine this with several other things to greatly improve overall performance.</p>



<h2 class="wp-block-heading">Raison d&#8217;Être</h2>



<p>Before we get to the cause of the puzzling difference between the two camera viewpoints I would like to introduce you to the <em>Surface Area Heuristic</em>.</p>



<p>Last time we chose the split plane position and axis in a rather simplistic manner: halfway along the longest axis and perpendicular to that axis, a technique known as the <em>midpoint split</em>. It is not hard to come up with scenes where this is not a great idea:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" src="https://jacco.ompf2.com/wp-content/uploads/2022/04/badmidpoint.jpg" alt="" class="wp-image-1047" width="619" height="347" srcset="https://jacco.ompf2.com/wp-content/uploads/2022/04/badmidpoint.jpg 825w, https://jacco.ompf2.com/wp-content/uploads/2022/04/badmidpoint-300x168.jpg 300w, https://jacco.ompf2.com/wp-content/uploads/2022/04/badmidpoint-768x430.jpg 768w, https://jacco.ompf2.com/wp-content/uploads/2022/04/badmidpoint-360x202.jpg 360w" sizes="auto, (max-width: 619px) 100vw, 619px" /></figure></div>


<p>A midpoint split in this case yields two large overlapping boxes. A subtle nudge of the plane to the right, so it includes the disc at the bottom of the image, would be much better: the left box would be only slightly bigger, but the box on the right would be tiny. On the other hand, a nudge to the left might also be a good idea: the midpoint split hardly yields a balanced tree, while including the tree discs near the split plane seems far better in that regard.</p>



<p>This raises the question: <em>what makes a good BVH?</em> Should it be balanced, should it quickly isolate empty space, or is there something else?</p>



<p>Let&#8217;s take a step back, and think about what the BVH is trying to solve. Without a BVH, we brute-force intersect <em>N</em> triangles. With the BVH, we intersect a small number of triangles, plus a number of bounding boxes. An optimal BVH <em>minimizes the total number of intersections</em>. Applied to the local problem of picking a good split plane: since the number of bounding boxes after the split is constant (i.e., two), the optimal split plane is the one that minimizes the number of intersections between a ray and the primitives in both child nodes. <em>&#8216;A ray&#8217;</em>, without further context, is a <em>random ray</em>, unless we specifically construct the BVH for a particular ray &#8211; which we don&#8217;t.</p>



<p>The word &#8216;random&#8217; provides an important clue. How many intersections with a random ray need to be evaluated for a bounding box containing <em>N</em> triangles? That depends: if the ray hits the box, the answer is <em>N</em>; otherwise it is zero. The cost is thus proportional to <em>N</em>, but also proportional to the <em>probability</em> that the ray hits the box.</p>



<p>So, what is the probability of a random ray hitting a random box? Obviously, we can&#8217;t calculate this. But we can do something else. Consider these two triangles: </p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" src="https://jacco.ompf2.com/wp-content/uploads/2022/04/triprob.jpg" alt="" class="wp-image-1052" width="537" height="290" srcset="https://jacco.ompf2.com/wp-content/uploads/2022/04/triprob.jpg 716w, https://jacco.ompf2.com/wp-content/uploads/2022/04/triprob-300x162.jpg 300w, https://jacco.ompf2.com/wp-content/uploads/2022/04/triprob-360x195.jpg 360w" sizes="auto, (max-width: 537px) 100vw, 537px" /></figure></div>


<p>Which of these has a higher probability of being struck by a random ray? Obviously, the larger one. So, although we cannot calculate the probability itself, we do know that it is <em>proportional to surface area</em>, and that turns out to be enough. Applying this to boxes, the same principle holds: the chance that a random ray hits a random box is proportional to the surface area of the box. Note: not its volume! This is easy to see when you imagine a box with a height of zero: although it now has a volume of zero, it can still be hit by a ray.</p>



<p>This leads to the formulation of the Surface Area Heuristic:</p>



<span class="wp-katex-eq katex-display" data-display="true">C_{SAH}=N_{left} A_{left} + N_{right} A_{right}</span>



<p>In words: the &#8216;cost&#8217; of a split is proportional to the summed cost of intersecting the two resulting boxes, including the triangles they store. The cost of a box with triangles is proportional to the number or triangles, times the surface area of the box.</p>



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



<p>The SAH allows us to estimate the cost of a split. But, for what splits do we evaluate this cost? The answer is: <em>all of them</em>. There are infinitely many ways to split a bounding box along one axis, and three times more if we consider x, y and z instead of just the longest axis. Fortunately, the <em>cost function</em> is constant between two primitive centroids. This means that we only evaluate it at those locations: </p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" src="https://jacco.ompf2.com/wp-content/uploads/2022/04/candidates.jpg" alt="" class="wp-image-1055" width="539" height="483" srcset="https://jacco.ompf2.com/wp-content/uploads/2022/04/candidates.jpg 718w, https://jacco.ompf2.com/wp-content/uploads/2022/04/candidates-300x269.jpg 300w, https://jacco.ompf2.com/wp-content/uploads/2022/04/candidates-360x323.jpg 360w" sizes="auto, (max-width: 539px) 100vw, 539px" /></figure></div>


<p>Only after evaluating all of them we know which position (on which axis) is best; this position then replaces the midpoint split position.</p>



<p>We thus replace the midpoint split by a search for the lowest cost. For this, we use candidate split planes through the centroids of all triangles in the node, and for each axis:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">// determine split axis using SAH
int bestAxis = -1;
float bestPos = 0, bestCost = 1e30f;
for( int axis = 0; axis &lt; 3; axis++ ) for( uint i = 0; i &lt; node.triCount; i++ )
{
    Tri&amp; triangle = tri[triIdx[node.leftFirst + i]];
    float candidatePos = triangle.centroid[axis];
    float cost = EvaluateSAH( node, axis, candidatePos );
    if (cost &lt; bestCost) 
        bestPos = candidatePos, bestAxis = axis, bestCost = cost;
}
int axis = bestAxis;
float splitPos = bestPos;</pre></div>



<p>The search yields a <code>bestPos</code> and a <code>bestAxis</code>, which we then use instead of the midpoint split position.</p>



<p>The above code uses function EvaluateSAH to calculate the cost for one potential split. This function needs to determine the bounding boxes that would result from the split, as well as the number of triangles in each of the boxes. Based on this information, the SAH cost function can be evaluated.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float EvaluateSAH( BVHNode&amp; node, int axis, float pos )
{
    // determine triangle counts and bounds for this split candidate
    aabb leftBox, rightBox;
    int leftCount = 0, rightCount = 0;
    for( uint i = 0; i &lt; node.triCount; i++ )
    {
        Tri&amp; triangle = tri[triIdx[node.leftFirst + i]];
        if (triangle.centroid[axis] &lt; pos)
        {
            leftCount++;
            leftBox.grow( triangle.vertex0 );
            leftBox.grow( triangle.vertex1 );
            leftBox.grow( triangle.vertex2 );
        }
        else
        {
            rightCount++;
            rightBox.grow( triangle.vertex0 );
            rightBox.grow( triangle.vertex1 );
            rightBox.grow( triangle.vertex2 );
        }
    }
    float cost = leftCount * leftBox.area() + rightCount * rightBox.area();
    return cost &gt; 0 ? cost : 1e30f;
}</pre></div>



<p>A new struct <code>aabb</code> is used here, which is straightforward but makes the <code>EvaluateSAH</code> function a lot more concise:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">struct aabb 
{ 
    float3 bmin = 1e30f, bmax = -1e30f;
    void grow( float3 p ) { bmin = fminf( bmin, p ), bmax = fmaxf( bmax, p ); }
    float area() 
    { 
        float3 e = bmax - bmin; // box extent
        return e.x * e.y + e.y * e.z + e.z * e.x; 
    }
};</pre></div>



<p>There is one thing that remains, and that may come as a bit of a surprise. In the initial version of the Subdivide function, recursion was terminated when a certain triangle count was reached (we used 2). Using the SAH, we can do better. Splitting a node in two new nodes is supposed to reduce the cost function. This is however not always the case. Take the example used in the first article: two triangles may form an axis-aligned quad, which cannot be split into two boxes, unless these two boxes fully overlap. The SAH can be used to easily detect this. We calculate the SAH cost of the parent:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 e = node.aabbMax - node.aabbMin; // extent of parent
float parentArea = e.x * e.y + e.y * e.z + e.z * e.x;
float parentCost = node.triCount * parentArea;</pre></div>



<p>Before splitting, the parent is one box with triangles, so the cost is based on this single box. Now, splitting is supposed to help. If it doesn&#8217;t, we should abort the attempt to split.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">if (bestCost &gt;= parentCost) return;</pre></div>



<p>This test replaces the old test.</p>



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



<p>Before applying the surface area heuristic, it took 183 milliseconds to render the scene. With the SAH, this is reduced to 128 milliseconds: a 43% speedup.</p>



<p>There is a problem however. Without SAH, the BVH is constructed rapidly: it only takes 2.5 milliseconds on my machine. <em>With</em> SAH, this increases to 7.4 <em>seconds</em>. The reason is obvious: we simply do a lot more work to determine the split plane position. </p>



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



<p>Back to that weird thing with speed being influenced by camera angle. Consider the following two scenarios:</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="643" src="https://jacco.ompf2.com/wp-content/uploads/2022/04/order-1024x643.jpg" alt="" class="wp-image-1061" srcset="https://jacco.ompf2.com/wp-content/uploads/2022/04/order-1024x643.jpg 1024w, https://jacco.ompf2.com/wp-content/uploads/2022/04/order-300x188.jpg 300w, https://jacco.ompf2.com/wp-content/uploads/2022/04/order-768x482.jpg 768w, https://jacco.ompf2.com/wp-content/uploads/2022/04/order-1222x767.jpg 1222w, https://jacco.ompf2.com/wp-content/uploads/2022/04/order-897x563.jpg 897w, https://jacco.ompf2.com/wp-content/uploads/2022/04/order-360x226.jpg 360w, https://jacco.ompf2.com/wp-content/uploads/2022/04/order.jpg 1468w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>In the left scenario, the ray travels to the south. It intersects the top and bottom node, but depending on the order, it needs to visit both, or only one. This is because an intersection <em>shortens</em> the ray: hitting the first disc along the ray makes the ray short enough to <em>not</em> intersect the bottom node. If on the other hand the ray travelling south visits the <em>bottom</em> node first, it also gets shorter, but not short enough to skip the top node. In the right scenario the ideal order is reversed: this time we will save time if we visit the bottom node first.</p>



<p>It is now clear what happened to the bunny cam: since we visit the nodes in a fixed order, some views are faster than others. We can fix this by visiting the nodes front to back. There are several ways to do this. One way requires a reformulation of the traversal algorithm:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void IntersectBVH( Ray&amp; ray )
{
    BVHNode* node = &amp;bvhNode[rootNodeIdx], *stack[64];
    uint stackPtr = 0;
    while (1)
    {
        if (node-&gt;isLeaf())
        {
            for (uint i = 0; i &lt; node-&gt;triCount; i++)
                IntersectTri( ray, tri[triIdx[node-&gt;leftFirst + i]] );
            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>The traversal looks quite different from what we had before. For starters, the code is no longer recursive. An infinite loop is used instead, and whenever two child nodes require a visit, one of them is pushed on a small stack. The loop completes when we try to pop from an empty stack.</p>



<p>Secondly, the test to check if we intersect a node is removed; this time we check if the child nodes intersect the ray. The answer from the <code>IntersectAABB</code> function is also no longer a boolean, but a float: 1e30f denotes &#8216;miss&#8217;, while any other value is a hit at the reported distance:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float IntersectAABB( const Ray&amp; ray, const float3 bmin, const float3 bmax )
{
    float tx1 = (bmin.x - ray.O.x) / ray.D.x, tx2 = (bmax.x - ray.O.x) / ray.D.x;
    float tmin = min( tx1, tx2 ), tmax = max( tx1, tx2 );
    float ty1 = (bmin.y - ray.O.y) / ray.D.y, ty2 = (bmax.y - ray.O.y) / ray.D.y;
    tmin = max( tmin, min( ty1, ty2 ) ), tmax = min( tmax, max( ty1, ty2 ) );
    float tz1 = (bmin.z - ray.O.z) / ray.D.z, tz2 = (bmax.z - ray.O.z) / ray.D.z;
    tmin = max( tmin, min( tz1, tz2 ) ), tmax = min( tmax, max( tz1, tz2 ) );
    if (tmax &gt;= tmin &amp;&amp; tmin &lt; ray.t &amp;&amp; tmax &gt; 0) return tmin; else return 1e30f;
}</pre></div>



<p>Using the distances to both child nodes, we can sort them: now, if the nearest child is at distance 1e30f, we know we must have missed them both, in which case we proceed with a node from the stack. Otherwise, we proceed with the nearest child. If the far child also requires visitation, we push this one on the stack.</p>



<p>The resulting traversal is faster for both camera views. The front-side view drops from 128 to 107 milliseconds. The back-side view improves from 300 to 91 milliseconds: more than 3 times faster than without ordering.</p>



<h2 class="wp-block-heading">Low Hanging Fruit</h2>



<p>Let&#8217;s finish this article with some quick and dirty optimizations. For this, we visit the <code>IntersectAABB</code> function once more. It contains no less than six divisions, which are notoriously expensive for processors. In this case, they are easy to get rid of.</p>



<p>A division by <em>x</em> can be replaced by a multiplication by <em>1/x</em>. In this case, that doesn&#8217;t look particularly useful, because <em>1/x</em> itself contains a division. However, one ray gets intersected with many boxes; that means that  the cost of calculating <em>1/ray.D.x</em>yz can be cached. This requires a modification to the ray struct:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">struct Ray { float3 O, D, rD; float t = 1e30f; };</pre></div>



<p>Member variable rD will contain the reciprocals of the direction components, which we can set right after constructing the ray:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">ray.rD = float3( 1 / ray.D.x, 1 / ray.D.y, 1 / ray.D.z );</pre></div>



<p>From here on, <code>IntersectAABB</code> operates without divisions:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">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.t &amp;&amp; tmax &gt; 0) return tmin; else return 1e30f;
}</pre></div>



<p>On my machine this optimization has limited effect, which indicates that the performance problem may lie elsewhere. Perhaps the traversal code is memory bound (which causes the divisions to be hidden behind memory latencies) or perhaps we suffer from branch mispredictions in the conditional code in <code>IntersectAABB</code>. A definitive diagnosis requires a proper profiling session with a specialized tool such as Intel&#8217;s VTune. Instead of that, I am going to propose two optimizations: one that aims to improve cache utilization, and one that reduces the amount of conditional code.</p>



<p><strong>1. Improving data locality:</strong> To make better use of the caches, we should ensure that data that we use is similar to data we have recently seen. This is known as <em>temporal data locality</em>. In a ray tracer this can be achieved by rendering the image in tiles. The pixels in a tile of e.g. 4&#215;4 pixels often find the same triangles, typically after traversing the same BVH nodes. For this, we change the pixel plotting loops as follows:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">for (int y = 0; y &lt; 640; y+=4) for (int x = 0; x &lt; 640; x+=4)
{
    for( int v = 0; v &lt; 4; v++ ) for( int u = 0; u &lt; 4; u++ )
    {
        // ray.O = float3( -1.5f, -0.2f, -2.5f );
        ray.O = float3( -1.5f, 0, 2.5f );
        float3 pixelPos = ray.O + p0 + 
            (p1 - p0) * ((x + u) / 640.0f) + 
            (p2 - p0) * ((y + v) / 640.0f);
        ray.D = normalize( pixelPos - ray.O ), ray.t = 1e30f;
        ray.rD = float3( 1 / ray.D.x, 1 / ray.D.y, 1 / ray.D.z );
        IntersectBVH( ray );
        uint c = 500 - (int)(ray.t * 42);
        if (ray.t &lt; 1e30f) screen-&gt;Plot( x + u, y + v, c * 0x10101 );
    }
}</pre></div>



<p><strong>2. Reducing conditional code:</strong> We can change <code>IntersectAABB</code> to a version that is mostly devoid of conditional code. This version does however require an Intel compatible CPU, so the following is very platform dependent.</p>



<p>We start with a modification of the BVHNode:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">struct BVHNode
{
    union 
    { 
        struct { float3 aabbMin; uint leftFirst; };
        __m128 aabbMin4;
    };
    union
    {
        struct { float3 aabbMax; uint triCount; };
        __m128 aabbMax4;
    };
    bool isLeaf() { return triCount &gt; 0; }
};</pre></div>



<p>This rather horrible data structure uses an unnamed union to overlap the two <code>float3</code> + <code>uint</code> structs with a <code>__m128</code> (pronounced as &#8216;quadfloat&#8217;) value, which is a 128-bit vector variable that stores four floats. The <code>__m128</code> data type is supported in hardware on pretty much any processor. The union lets us access the original data without changes. At the same time, we can now read the bounding box information into two SSE registers, which lets us use a rather cryptic piece of intersection logic. Before we get to that, we need to make a similar change to the ray struct:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">struct Ray 
{ 
    Ray() { O4 = D4 = rD4 = _mm_set1_ps( 1 ); }
    union { struct { float3 O; float dummy1; }; __m128 O4; };
    union { struct { float3 D; float dummy2; }; __m128 D4; };
    union { struct { float3 rD; float dummy3; }; __m128 rD4; };
    float t = 1e30f; 
};</pre></div>



<p>The constructor makes sure that the three dummy values that pad the 12-bute float3 values to 16 bytes are initialized to valid floats. The SIMD AABB intersection code now becomes:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float IntersectAABB_SSE( const Ray&amp; ray, const __m128 bmin4, const __m128 bmax4 )
{
    static __m128 mask4 = _mm_cmpeq_ps(_mm_setzero_ps(),_mm_set_ps(1,0,0,0));
    __m128 t1 = _mm_mul_ps(_mm_sub_ps(_mm_and_ps(bmin4,mask4),ray.O4),ray.rD4 );
    __m128 t2 = _mm_mul_ps(_mm_sub_ps(_mm_and_ps(bmax4,mask4),ray.O4),ray.rD4 );
    __m128 vmax4 = _mm_max_ps(t1,t2), vmin4 = _mm_min_ps(t1,t2);
    float tmax = min(vmax4.m128_f32[0],min(vmax4.m128_f32[1],vmax4.m128_f32[2]));
    float tmin = max(vmin4.m128_f32[0],max(vmin4.m128_f32[1],vmin4.m128_f32[2]));
    if (tmax &gt;= tmin &amp;&amp; tmin &lt; ray.t &amp;&amp; tmax &gt; 0) return tmin; else return 1e30f;
}</pre></div>



<p>On my Ryzen processor this yields a modest speed boost compared to the original code. That same Ryzen also made clear to me that doing calculations on numbers that are not floats (in this case: the fourth component in <code>aabbMin4</code> and <code>aabbMax4</code>, which really are ints) is exceedingly slow. The SSE intersection code counters this by masking these values out.</p>



<p>With the improved data locality and SIMD code we reach the final performance level for this article. For the backside view we end up with 86ms per frame, which means we are blasting the scene with 4.5MRays/s. The frontside view is a little bit slower at 103ms, but that is still 3.8MRays/s, on a single core.</p>



<p>If you are interested in trying out multi-core performance: OpenMP lets you start with this with relative ease. You will have to play a bit with the tile size to optimize performance. Also make sure to use the dynamic scheduler: each tile has a different workload. As a target, know that good parallel ray tracing should scale linearly in the number of cores, although OpenMP alone may not completely get you there.</p>



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



<p>The next article in this series discusses <a href="https://jacco.ompf2.com/2022/04/21/how-to-build-a-bvh-part-3-quick-builds/">binned BVH building for rapid construction</a>. Check it out now.</p>



<p>The complete code for this project (for Windows / Visual Studio) <a href="https://github.com/jbikker/bvh_article">can be found on GitHub</a>.</p>



<p>Enjoyed the article? Spotted an error?</p>



<p>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>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>
</ul>
]]></content:encoded>
					
					<wfw:commentRss>https://jacco.ompf2.com/2022/04/18/how-to-build-a-bvh-part-2-faster-rays/feed/</wfw:commentRss>
			<slash:comments>22</slash:comments>
		
		
			</item>
		<item>
		<title>How to build a BVH &#8211; Part 1: Basics</title>
		<link>https://jacco.ompf2.com/2022/04/13/how-to-build-a-bvh-part-1-basics/</link>
					<comments>https://jacco.ompf2.com/2022/04/13/how-to-build-a-bvh-part-1-basics/#comments</comments>
		
		<dc:creator><![CDATA[jbikker]]></dc:creator>
		<pubDate>Wed, 13 Apr 2022 16:23:11 +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=999</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>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>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><strong>Basics: data structure, simple construction and ray traversal (this article).</strong></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><a href="https://jacco.ompf2.com/2022/06/15/how-to-build-a-bvh-part-9b-massive/">OpenCL: GPU ray tracing, part 2 (series finale)</a>.</li></ol>



<p>In this first article we discuss the bare basics: what the BVH is used for, and how a basic BVH is constructed and traversed with a ray. The end product is a simple but reasonably efficient CPU ray tracer, which we will further improve upon in subsequent articles.</p>



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



<p>The BVH is an <em>acceleration structure</em>. It serves to reduce a pretty fundamental problem in ray tracing: the sheer cost of finding the nearest intersection of a ray and a scene consisting of (potentially) millions of polygons. The basic principle is easy to understand: if we have 64 polygons, we could split them into two groups of 32 polygons, each group enclosed by a <em>bounding volume</em> such as a box or a sphere. When intersecting the scene, we can skip 32 polygons if the ray does not intersect the enclosing volume, nearly halving the processing time. Next, we do the same to each of the two groups: split in two halves, encapsulate, recurse. The resulting bounding volume <em>hierarchy</em> brings down processing time to manageable levels: with each level, we halve the number of polygons. Starting with 64 polygons, we traverse a tree in six steps to arrive at a single polygon.</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="548" src="https://jacco.ompf2.com/wp-content/uploads/2022/04/whittedbvh-1024x548.jpg" alt="" class="wp-image-1033" srcset="https://jacco.ompf2.com/wp-content/uploads/2022/04/whittedbvh-1024x548.jpg 1024w, https://jacco.ompf2.com/wp-content/uploads/2022/04/whittedbvh-300x160.jpg 300w, https://jacco.ompf2.com/wp-content/uploads/2022/04/whittedbvh-768x411.jpg 768w, https://jacco.ompf2.com/wp-content/uploads/2022/04/whittedbvh-897x480.jpg 897w, https://jacco.ompf2.com/wp-content/uploads/2022/04/whittedbvh-360x193.jpg 360w, https://jacco.ompf2.com/wp-content/uploads/2022/04/whittedbvh.jpg 1208w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><figcaption>BVH: a hierarchy of bounding volumes. We can skip any volume that the ray doesn&#8217;t intersect. Image based on <em>A 3-Dimensional Representation for Fast Rendering of Complex Scenes</em>, by Rubin and Whitted.</figcaption></figure>



<p>That&#8217;s the global idea, but let&#8217;s make things practical. I will be using a <a href="https://github.com/jbikker/advgrtmpl8">minimalistic template</a> from one of my courses for these experiments, but the code is designed to be generic. Feel free to use something else.</p>



<p>We start with the definition of a triangle:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">struct Tri { float3 vertex0, vertex1, vertex2; float3 centroid; };</pre></div>



<p>Your triangle may need more properties for rendering, but for building a BVH and intersecting the triangle with a ray, this is all we need. Speaking of rays:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">struct Ray { float3 O, D; float t = 1e30f; };</pre></div>



<p>Here, <code>O</code> is the ray origin, <code>D</code> is the (typically normalized) ray direction. Scalar <code>t</code> is the distance at which we found an intersection, which gets initialized to &#8216;infinity&#8217; (well, almost) here.</p>



<p>Let&#8217;s construct some random triangles to play with:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">// triangle count
#define N 64
Tri tri[N];
// application init; gets called once at startup
void BasicBVHApp::Init()
{
    for (int i = 0; i &lt; N; i++)
    {
        float3 r0( RandomFloat(), RandomFloat(), RandomFloat() );
        float3 r1( RandomFloat(), RandomFloat(), RandomFloat() );
        float3 r2( RandomFloat(), RandomFloat(), RandomFloat() );
        tri[i].vertex0 = r0 * 9 - float3( 5 );
        tri[i].vertex1 = tri[i].vertex0 + r1;
        tri[i].vertex2 = tri[i].vertex0 + r2;
    }
}</pre></div>



<p>Here, <code>RandomFloat()</code> yields a uniform random number in the range 0..1. I used <a href="https://www.researchgate.net/publication/5142825_Xorshift_RNGs">Marsaglia&#8217;s Xor32 RNG</a>, but anything will do. Given three vectors with random components, a triangle is then produced within a 10x10x10 cube centered around the origin. Not pretty, but good enough for now. Feel free to replace this with a proper model, e.g. imported using <a href="https://github.com/assimp/assimp">assimp</a> or <a href="https://github.com/tinyobjloader/tinyobjloader">TinyOBJ</a>.</p>



<p>Next, we need a way to intersect a triangle with a ray:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void IntersectTri( Ray&amp; ray, const Tri&amp; tri )
{
    const float3 edge1 = tri.vertex1 - tri.vertex0;
    const float3 edge2 = tri.vertex2 - tri.vertex0;
    const float3 h = cross( ray.D, edge2 );
    const float a = dot( edge1, h );
    if (a &gt; -0.0001f &amp;&amp; a &lt; 0.0001f) return; // ray parallel to triangle
    const float f = 1 / a;
    const float3 s = ray.O - tri.vertex0;
    const float u = f * dot( s, h );
    if (u &lt; 0 || u &gt; 1) return;
    const float3 q = cross( s, edge1 );
    const float v = f * dot( ray.D, q );
    if (v &lt; 0 || u + v &gt; 1) return;
    const float t = f * dot( edge2, q );
    if (t &gt; 0.0001f) ray.t = min( ray.t, t );
}</pre></div>



<p>This is the famous <a href="https://en.wikipedia.org/wiki/M%C3%B6ller%E2%80%93Trumbore_intersection_algorithm">Möller–Trumbore intersection algorithm</a>, which is still pretty close to &#8216;as fast as possible&#8217;. There exist <a href="http://www.sven-woop.de/papers/2004-Diplom-Sven-Woop.pdf">slightly faster approaches</a> (see Chapter 5 of Sven&#8217;s thesis), but these need more (or rather, different) data than just the three vertices. </p>



<p>The <code>IntersectTri</code> function determines if there is an intersection between the ray and the triangle. If this is the case, we check if the found intersection distance is closer than what the ray encountered before. If so, the <code>t</code> value for the ray is updated. For a given ray, we can now simply check all triangles; after doing so, the ray &#8216;knows&#8217; the shortest distance to a surface in the scene.</p>



<p>So, let&#8217;s generate some rays. For e.g. a 640 x 640 image, we do this by firing rays from a camera position to a virtual screen plane:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 camPos( 0, 0, -18 );
float3 p0( -1, 1, -15 ), p1( 1, 1, -15 ), p2( -1, -1, -15 );
Ray ray;
for (int y = 0; y &lt; 640; y++) for (int x = 0; x &lt; 640; x++)
{
    float3 pixelPos = p0 + (p1 - p0) * (x / 640.0f) + (p2 - p0) * (y / 640.0f);
    ray.O = camPos;
    ray.D = normalize( pixelPos - ray.O );
    ray.t = 1e30f;</pre></div>



<p>Here, the camera is placed at position (0,0,-18), so: well outside the cube that contains the triangles. Virtual screen corners are located at (-1, 1, -15), (1,1,-15) and (-1,-1,-15), so 3 units in front of the camera. For each of the pixels we can now calculate a position on this square. The ray is then initialized with the camera position as origin, and a normalized vector from the ray origin to the pixel position as a direction.</p>



<div class="wp-block-image"><figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" src="https://jacco.ompf2.com/wp-content/uploads/2022/04/primrays-1024x568.jpg" alt="" class="wp-image-1034" width="634" height="351" srcset="https://jacco.ompf2.com/wp-content/uploads/2022/04/primrays-1024x568.jpg 1024w, https://jacco.ompf2.com/wp-content/uploads/2022/04/primrays-300x167.jpg 300w, https://jacco.ompf2.com/wp-content/uploads/2022/04/primrays-768x426.jpg 768w, https://jacco.ompf2.com/wp-content/uploads/2022/04/primrays-1222x678.jpg 1222w, https://jacco.ompf2.com/wp-content/uploads/2022/04/primrays-897x498.jpg 897w, https://jacco.ompf2.com/wp-content/uploads/2022/04/primrays-360x200.jpg 360w, https://jacco.ompf2.com/wp-content/uploads/2022/04/primrays.jpg 1344w" sizes="auto, (max-width: 634px) 100vw, 634px" /><figcaption>Generating primary rays: pixelPos is obtained by interpolating over the rectangle defined by p0, p1 and p2.</figcaption></figure></div>



<p>With a properly initialized primary ray we can now get our first ray traced view of the test scene, by &#8216;brute force&#8217; checking the ray against every triangle. The result is a <code>t</code> value in the ray for each pixel. This value is 1e30f if we hit nothing, or the actual distance to a triangle otherwise.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">for( int i = 0; i &lt; N; i++ ) IntersectTri( ray, tri[i] );</pre></div>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="620" height="308" src="https://jacco.ompf2.com/wp-content/uploads/2022/04/result.png" alt="" class="wp-image-1008" srcset="https://jacco.ompf2.com/wp-content/uploads/2022/04/result.png 620w, https://jacco.ompf2.com/wp-content/uploads/2022/04/result-300x149.png 300w, https://jacco.ompf2.com/wp-content/uploads/2022/04/result-360x179.png 360w" sizes="auto, (max-width: 620px) 100vw, 620px" /><figcaption>Result of ray tracing 64 triangles.</figcaption></figure></div>



<p>The result is underwhelming, but hey, it shows that the basic setup works. I&#8217;ll leave the explanation of proper Whitted-style ray tracing to <a href="https://raytracing.github.io/books/RayTracingInOneWeekend.html">Peter Shirley</a>&#8216;s amazing book and focus on the efficiency of those rays instead.</p>



<h2 class="wp-block-heading">Concepts and Ingredients</h2>



<p>On my machine, it takes about 140 milliseconds to construct the 640 x 640 rays and intersect them with the 64 triangles. That&#8217;s not bad by the way: we trace almost 3 million rays per second, and that&#8217;s not even using multithreading or the GPU. Thing is, however: computation scales linearly in the number of triangles&#8230; Tracing 256 triangles takes 540 milliseconds; 1024 triangles bring this to 2250 milliseconds.</p>



<p>Time to introduce the BVH.</p>



<p>When Rubin &amp; Whitted first described the bounding volume hierarchy, they assumed the bounding volumes would be placed manually. This is not something artists will enjoy, so let&#8217;s see how a BVH can be constructed automatically.</p>



<div class="wp-block-image"><figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" src="https://jacco.ompf2.com/wp-content/uploads/2022/04/bvhroot-1024x805.jpg" alt="" class="wp-image-1036" width="512" height="403" srcset="https://jacco.ompf2.com/wp-content/uploads/2022/04/bvhroot-1024x805.jpg 1024w, https://jacco.ompf2.com/wp-content/uploads/2022/04/bvhroot-300x236.jpg 300w, https://jacco.ompf2.com/wp-content/uploads/2022/04/bvhroot-768x603.jpg 768w, https://jacco.ompf2.com/wp-content/uploads/2022/04/bvhroot-897x705.jpg 897w, https://jacco.ompf2.com/wp-content/uploads/2022/04/bvhroot-360x283.jpg 360w, https://jacco.ompf2.com/wp-content/uploads/2022/04/bvhroot.jpg 1176w" sizes="auto, (max-width: 512px) 100vw, 512px" /></figure></div>



<p>We start with the scene and its bounding box. This is going to be the root node for the hierarchy. We then recursively subdivide this node. A <em>split plane</em> partitions the primitives in two sets. Note that we do not split <em>space</em>: this might lead to primitives being split and/or assigned to both sides. In a BVH this never happens. The partitioning is what we need the primitive <em>centroids</em> for: each triangle (or disc, in the figure above) is either to the left of the split plane, or <em>not</em> to the left (which includes the situation where the primitive is <em>on</em> the split plane &#8211; we need to be precise!).</p>



<p>After the split we have two (now independent) groups of objects, with their updated group bounds:</p>



<div class="wp-block-image"><figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" src="https://jacco.ompf2.com/wp-content/uploads/2022/04/childs-1024x835.jpg" alt="" class="wp-image-1037" width="512" height="418" srcset="https://jacco.ompf2.com/wp-content/uploads/2022/04/childs-1024x835.jpg 1024w, https://jacco.ompf2.com/wp-content/uploads/2022/04/childs-300x245.jpg 300w, https://jacco.ompf2.com/wp-content/uploads/2022/04/childs-768x626.jpg 768w, https://jacco.ompf2.com/wp-content/uploads/2022/04/childs-897x732.jpg 897w, https://jacco.ompf2.com/wp-content/uploads/2022/04/childs-360x294.jpg 360w, https://jacco.ompf2.com/wp-content/uploads/2022/04/childs.jpg 1128w" sizes="auto, (max-width: 512px) 100vw, 512px" /></figure></div>



<p>Note that the bounding volumes of the two groups may overlap. This actually happens when we split the right group vertically:</p>



<div class="wp-block-image"><figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" src="https://jacco.ompf2.com/wp-content/uploads/2022/04/overlap-1024x822.jpg" alt="" class="wp-image-1038" width="512" height="411" srcset="https://jacco.ompf2.com/wp-content/uploads/2022/04/overlap-1024x822.jpg 1024w, https://jacco.ompf2.com/wp-content/uploads/2022/04/overlap-300x241.jpg 300w, https://jacco.ompf2.com/wp-content/uploads/2022/04/overlap-768x617.jpg 768w, https://jacco.ompf2.com/wp-content/uploads/2022/04/overlap-897x720.jpg 897w, https://jacco.ompf2.com/wp-content/uploads/2022/04/overlap-360x289.jpg 360w, https://jacco.ompf2.com/wp-content/uploads/2022/04/overlap.jpg 1138w" sizes="auto, (max-width: 512px) 100vw, 512px" /></figure></div>



<p>Splitting the left group also leads to an interesting situation: the group of discs at the top and the single disc at the bottom have bounds that are pretty far apart. A ray that does intersect the left group may thus miss both of its child nodes, avoiding intersection tests with seven discs.</p>



<p>For a BVH node we need the following data:</p>



<ol class="wp-block-list"><li>The bounds. In our case: an <em>axis-aligned bounding box</em> (AABB), which is easy to calculate and cheap to store: just 6 floats define the AABB in 3D space. Note: a sphere would be even cheaper to store, but it is not as convenient to work with in practice.</li><li>References to the two child nodes, if the node is not a leaf node.</li><li>References to primitives, if the node is a leaf node.</li></ol>



<p>A naïve BVH node layout would look something like:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">struct BVHNode
{
    aabb nodeBounds;
    BVHNode* left, *right;
    bool isLeaf;
    vector&lt;Tri*&gt; primitives;
};</pre></div>



<p>However, this struct has many problems. It is rather large, but also somewhat unpredictable in size due to the vector and the pointers, which take up 4 bytes on a 32-bit OS, but 8 on a 64-bit OS. </p>



<p>The first improvement is switching from pointers to <em>indices</em>. For triangles we use their indices in the triangle array; for child node pointers we can do something similar if we pre-allocate all nodes that we ever need in a <code>BVHNode</code> pool. We can do this, because the size of the BVH for <em>N</em> triangles has an upper limit: we can never have more than <em>2N-1</em> nodes, since <em>N</em> primitives in <em>N</em> leaves have no more than <em>N/2</em> parents, <em>N/4</em> grandparents and so on.</p>



<p>With primitive pointers and <code>BVHNode</code> pointers replaced by indices the <code>BVHNode</code> struct reduces to:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">struct
{
    float3 aabbMin, aabbMax;     // 24 bytes
    uint leftChild, rightChild;  // 8 bytes
    bool isLeaf;                 // 4 bytes
    uint firstPrim, primCount;   // 8 bytes; total: 44 bytes
};</pre></div>



<p>Note how we cleverly store a list of primitives using just two numbers: we simply store the index of the first primitive, and the number of primitives. This way, any number of primitives can be specified in just eight bytes, as long as they are stored consecutively in the primitive array. It turns out that we can enforce this elegantly.</p>



<p>We can make several improvements; most of these I will mention later but one is useful now: boolean <code>isLeaf</code> is redundant once we realize that for a leaf the <code>primCount</code> cannot be zero, while for all other nodes <code>leftChild</code> and <code>rightChild</code> cannot be zero. This yields (for now) the final structure with a size of 40 bytes.</p>



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



<p>We can now start the actual construction of the hierarchy. The first step is the creation of the root node, which we will then recursively subdivide.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">BVHNode bvhNode[N * 2 - 1];
uint rootNodeIdx = 0, nodesUsed = 1;

void BuildBVH()
{
    for (int i = 0; i &lt; N; i++) tri[i].centroid = 
        (tri[i].vertex0 + tri[i].vertex1 + tri[i].vertex2) * 0.3333f;
    // assign all triangles to root node
    BVHNode&amp; root = bvhNode[rootNodeIdx];
    root.leftChild = root.rightChild = 0;
    root.firstPrim = 0, root.primCount = N;
    UpdateNodeBounds( rootNodeIdx );
    // subdivide recursively
    Subdivide( rootNodeIdx );
}</pre></div>



<p>The first lines of this function initialize the centroids for the triangles, which are needed for the subdivision process. After that, we claim one node from the bvhNode array. The root node is initialized: the child references are zeroed, and all primitives are added to it.</p>



<p>Updating the AABB for the root node is straightforward:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void UpdateNodeBounds( uint nodeIdx )
{
    BVHNode&amp; node = bvhNode[nodeIdx];
    node.aabbMin = float3( 1e30f );
    node.aabbMax = float3( -1e30f );
    for (uint first = node.firstPrim, i = 0; i &lt; node.primCount; i++)
    {
        Tri&amp; leafTri = tri[first + i];
        node.aabbMin = fminf( node.aabbMin, leafTri.vertex0 );
        node.aabbMin = fminf( node.aabbMin, leafTri.vertex1 );
        node.aabbMin = fminf( node.aabbMin, leafTri.vertex2 );
        node.aabbMax = fmaxf( node.aabbMax, leafTri.vertex0 );
        node.aabbMax = fmaxf( node.aabbMax, leafTri.vertex1 );
        node.aabbMax = fmaxf( node.aabbMax, leafTri.vertex2 );
    }
}</pre></div>



<p>Note: The <code>fminf</code> and <code>fmaxf</code> functions used here return the minimum and maximum x, y and z for pairs of <code>float3</code>&#8216;s. Each vertex of each triangle in the <code>BVHNode</code> is visited to find the lowest and highest x, y and z: the resulting set of six values is the AABB we are looking for.</p>



<p>Finally, we recursively subdivide the root node. A few steps are required:</p>



<ol class="wp-block-list"><li>Determine the axis and position of the split plane</li><li>Split the group of primitives in two halves using the split plane</li><li>Create child nodes for each half</li><li>Recurse into each of the child nodes.</li></ol>



<p><strong>1. Split plane axis and position:</strong> for now, we will split the AABB along its longest axis. Later we will discuss better ways, but for now this is fine. Code:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 extent = node.aabbMax - node.aabbMin;
int axis = 0;
if (extent.y &gt; extent.x) axis = 1;
if (extent.z &gt; extent[axis]) axis = 2;
float splitPos = node.aabbMin[axis] + extent[axis] * 0.5f;</pre></div>



<p><strong>2. Split the group in two halves:</strong> this sounds like a complicated thing to do, but in BVH construction this is surprisingly simple. Because we are not splitting any triangles, the combined size of the list of triangles in both halves is exactly the size of the unsplit list. That means the split can be done <em>in place</em>. For this, we walk the list of primitives, and swap each primitive that is not on the left of the plane with a primitive at the end of the list. This is functionally equivalent to a QuickSort partition.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">int i = node.firstPrim;
int j = i + node.primCount - 1;
while (i &lt;= j)
{
    if (tri[i].centroid[axis] &lt; splitPos)
        i++;
    else
        swap( tri[i], tri[j--] );
}</pre></div>



<p>Note that the triangles do not need to be sorted; it is sufficient that the two groups of triangles on both sides of the split plane are stored consecutively.</p>



<p><strong>3. Creating child nodes for each half: </strong>Using the outcome of the partition loop we construct two child nodes. The first child node contains the primitives at the start of the array; the second child node contains the primitives starting at <code>i</code>. The number of primitives on the left is thus <code>i - node.firstPrim</code>; the right child has the remaining primitives. In code:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">int leftCount = i - node.firstPrim;
if (leftCount == 0 || leftCount == node.primCount) return;
// create child nodes
int leftChildIdx = nodesUsed++;
int rightChildIdx = nodesUsed++;
node.leftNode = leftChildIdx;
bvhNode[leftChildIdx].firstPrim = node.firstPrim;
bvhNode[leftChildIdx].primCount = leftCount;
bvhNode[rightChildIdx].firstPrim = i;
bvhNode[rightChildIdx].primCount = node.primCount - leftCount;
node.primCount = 0;</pre></div>



<p>Some details to point out here: </p>



<ul class="wp-block-list"><li>Theoretically, the split in the middle can yield an empty box on the left or the right side. Not easy to come up with such a situation though! Left as an exercise for the reader. <img src="https://s.w.org/images/core/emoji/16.0.1/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" />  </li><li>We should not forget to set the primitive count of the node we just split to zero. Since we do not store the <code>isLeaf</code> boolean anymore, we rely on the <code>primCount</code> to identify leaves and interior nodes.</li><li>Since we increment the &#8216;next free bvh node counter&#8217; <code>nodesUsed</code> twice on consecutive lines, it is obvious that <code>rightChildIdx</code> is always equal to <code>leftChildIdx + 1</code>. This of course should have consequences for the <code>BVHNode</code> struct, which gets reduced to 36 bytes.</li></ul>



<p>We&#8217;re almost done with the subdivide functionality. One we have generated the left and right child nodes, we update their bounds (using a call to <code>UpdateNodeBounds</code>, which we created earlier), and we recurse into the child nodes (using a call to the <code>Subdivide</code> function we&#8217;re currently writing). Leaves us with one question: when does the recursion end? One would say: once there is one primitive left. This is sadly not true. The point is, two triangles quite often form a quad in real-world scenes. If this quad is axis-aligned, there is no way we can split it (with an axis-aligned plane) into two non-empty halves. For this reason, we typically terminate when we have 2 or less primitives in a leaf. Even this is not completely safe &#8211; but for a solution we need a seemingly unrelated technique, which will be discussed in the next article.</p>



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



<p>There is one nagging oversight in the partition code that we need to fix. I am talking about this line:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">swap( tri[i], tri[j--] );</pre></div>



<p>This line has two issues. First, we are changing the original list of triangles. This may be fine if it is owned by the BVH builder, but not so great if it is shared with e.g. the animation system of an engine. Secondly, we are swapping <em>whole triangles</em> by value. Their size is somewhat limited in this case, but what if a triangle has uv-coordinates, material ids, a name and so on?</p>



<p>We can resolve these issues by using an intermediate array with triangle indices. It contains simple unsigned integers and gets initialized with the numbers <em>0..N-1</em>. From then on, we swap entries in this array, rather than the triangles themselves. A <code>BVHNode</code> leaf now references a slice of indices, rather than a set of consecutive triangles. It is an extra step of indirection, but it proves to be quite practical.</p>



<p>We make a few small changes to facilitate this new data structure:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">Tri tri[N];
uint triIdx[N];</pre></div>



<p>At the start of <code>BuildBVH</code> we initialize this array:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void BuildBVH()
{
    // populate triangle index array
    for (int i = 0; i &lt; N; i++) triIdx[i] = i;
    ....</pre></div>



<p>The <code>BVHNode</code> struct needs some updates to member variable names, and now also incorporates some of the other changes we discussed:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">struct BVHNode
{
    float3 aabbMin, aabbMax;
    uint leftNode, firstTriIdx, triCount;
    bool isLeaf() { return triCount &gt; 0; }
};</pre></div>



<p><code>UpdateBounds</code> now uses the new indirection:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void UpdateNodeBounds( uint nodeIdx )
{
    BVHNode&amp; node = bvhNode[nodeIdx];
    node.aabbMin = float3( 1e30f );
    node.aabbMax = float3( -1e30f );
    for (uint first = node.firstTriIdx, i = 0; i &lt; node.triCount; i++)
    {
        uint leafTriIdx = triIdx[first + i];
        Tri&amp; leafTri = tri[leafTriIdx];
        node.aabbMin = fminf( node.aabbMin, leafTri.vertex0 ),
        node.aabbMin = fminf( node.aabbMin, leafTri.vertex1 ),
        node.aabbMin = fminf( node.aabbMin, leafTri.vertex2 ),
        node.aabbMax = fmaxf( node.aabbMax, leafTri.vertex0 ),
        node.aabbMax = fmaxf( node.aabbMax, leafTri.vertex1 ),
        node.aabbMax = fmaxf( node.aabbMax, leafTri.vertex2 );
    }
}</pre></div>



<p>The full <code>Subdivide</code> function, of which we have seen bits and pieces so far, in its full glory:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void Subdivide( uint nodeIdx )
{
    // terminate recursion
    BVHNode&amp; node = bvhNode[nodeIdx];
    if (node.triCount &lt;= 2) return;
    // determine split axis and position
    float3 extent = node.aabbMax - node.aabbMin;
    int axis = 0;
    if (extent.y &gt; extent.x) axis = 1;
    if (extent.z &gt; extent[axis]) axis = 2;
    float splitPos = node.aabbMin[axis] + extent[axis] * 0.5f;
    // in-place partition
    int i = node.firstTriIdx;
    int j = i + node.triCount - 1;
    while (i &lt;= j)
    {
        if (tri[triIdx[i]].centroid[axis] &lt; splitPos)
            i++;
        else
            swap( triIdx[i], triIdx[j--] );
    }
    // abort split if one of the sides is empty
    int leftCount = i - node.firstTriIdx;
    if (leftCount == 0 || leftCount == node.triCount) return;
    // create child nodes
    int leftChildIdx = nodesUsed++;
    int rightChildIdx = nodesUsed++;
    bvhNode[leftChildIdx].firstTriIdx = node.firstTriIdx;
    bvhNode[leftChildIdx].triCount = leftCount;
    bvhNode[rightChildIdx].firstTriIdx = i;
    bvhNode[rightChildIdx].triCount = node.triCount - leftCount;
    node.leftNode = leftChildIdx;
    node.triCount = 0;
    UpdateNodeBounds( leftChildIdx );
    UpdateNodeBounds( rightChildIdx );
    // recurse
    Subdivide( leftChildIdx );
    Subdivide( rightChildIdx );
}</pre></div>



<p>And there you have it: one valid BVH constructed from a polygon soup, in a (perhaps) surprisingly short snippet of code.</p>



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



<p>Time to put the BVH to work. Traversing it is of course a recursive process, starting at the root node:</p>



<ol class="wp-block-list"><li>Terminate if the ray misses the AABB <span style="color: initial;">of this node.</span></li><li>If the node is a leaf: intersect the ray with the triangles in the leaf.</li><li>Otherwise: recurse into the left and right child.</li></ol>



<p>That doesn&#8217;t sound too complex, and indeed: it is implemented in just a few lines of code.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void IntersectBVH( Ray&amp; ray, const uint nodeIdx )
{
    BVHNode&amp; node = bvhNode[nodeIdx];
    if (!IntersectAABB( ray, node.aabbMin, node.aabbMax )) return;
    if (node.isLeaf())
    {
        for (uint i = 0; i &lt; node.triCount; i++ )
            IntersectTri( ray, tri[triIdx[node.firstTriIdx + i]] );
    }
    else
    {
        IntersectBVH( ray, node.leftNode );
        IntersectBVH( ray, node.leftNode + 1 );
    }
}</pre></div>



<p>The <code>IntersectAABB</code> function is one function we did not implement yet. To detect if a ray intersects an AABB we use the <em>slab test</em>. Note that we don&#8217;t care <em>where</em> we hit the box; the only info we need is a yes/no answer. Without further explanation:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">bool IntersectAABB( const Ray&amp; ray, const float3 bmin, const float3 bmax )
{
    float tx1 = (bmin.x - ray.O.x) / ray.D.x, tx2 = (bmax.x - ray.O.x) / ray.D.x;
    float tmin = min( tx1, tx2 ), tmax = max( tx1, tx2 );
    float ty1 = (bmin.y - ray.O.y) / ray.D.y, ty2 = (bmax.y - ray.O.y) / ray.D.y;
    tmin = max( tmin, min( ty1, ty2 ) ), tmax = min( tmax, max( ty1, ty2 ) );
    float tz1 = (bmin.z - ray.O.z) / ray.D.z, tz2 = (bmax.z - ray.O.z) / ray.D.z;
    tmin = max( tmin, min( tz1, tz2 ) ), tmax = min( tmax, max( tz1, tz2 ) );
    return tmax &gt;= tmin &amp;&amp; tmin &lt; ray.t &amp;&amp; tmax &gt; 0;
}</pre></div>



<p>The IntersectBVH function now does the work we previously did with the loop over all the triangles. That means that this loop now simply gets replaced by a single function call:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">#if 0
    for( int i = 0; i &lt; N; i++ ) IntersectTri( ray, tri[i] );
#else
    IntersectBVH( ray, rootNodeIdx );
#endif</pre></div>



<p>Question is: is it any faster?</p>



<p>Well, on my machine I got 140 milliseconds for brute-force intersecting 64 triangles. With the BVH, this drops to (drumroll&#8230;) 32 milliseconds; a 4.4x speedup. Things get more interesting at 1024 triangles. At this scene size, frame time without BVH is 2250 milliseconds; with BVH this drops to 112 milliseconds. That is 20x faster. For larger scenes, the brute force approach becomes infeasible. And we&#8217;re only getting started: better BVHs will yield faster rays.</p>



<h2 class="wp-block-heading">Dangling Pointers</h2>



<p>In this article I postponed a lot of things. For instance: how can we make the <code>BVHNode</code> structure even smaller, and why should we do this? And what about the &#8216;ideal&#8217; split plane axis and position? How do we safely terminate recursion in Subdivide? And what about multithreading construction?</p>



<p>Most of these topics are for another day, but let&#8217;s end this article with a better <code>BVHNode</code> structure. We currently have:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">struct BVHNode
{
    float3 aabbMin, aabbMax;
    uint leftNode, firstTriIdx, triCount;
};</pre></div>



<p>This takes 36 bytes. That means that, on a modern GPU, one node fits in a 64-byte cache line, but quite frequently a node will in fact be partially in one cache line and partially in the next. This is a pretty severe performance issue. If we can reduce the <code>BVHNode</code> to 32 bytes, and if we align the array of nodes that we pre-allocate to a 64-byte boundary in memory (e.g. using <a href="https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/aligned-malloc?view=msvc-170">_aligned_malloc</a>), then <em>every</em> node always uses exactly half of a cache line. Even better: if we are careful, the two children of a node will be in the <em>same</em> cache line <em>(for the inpatient: skip one node after the root to achieve this).</em></p>



<p>We can reach the 32-byte node size when we realize that a node that has triangles <em>must</em> be a leaf. It thus has no child nodes. And the other way round: if there are child nodes, there are no triangles. We thus need to store a child node index <strong>or</strong> the index of the first triangle. That means these can be stored in one and the same variable:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">struct BVHNode
{
    float3 aabbMin, aabbMax;
    uint leftFirst, triCount;
};</pre></div>



<p>How we interpret this mysterious &#8216;leftFirst&#8217; variable depends on <code>triCount</code>. If it is 0, <code>leftFirst</code> contains the index of the left child node. Otherwise, it contains the index of the first triangle index.</p>



<p>There you have it: 32 bytes for one BVH node. It doesn&#8217;t get any better. Or perhaps it does. We&#8217;ll see, in a later article.</p>



<p><a href="https://jacco.ompf2.com/2022/04/18/how-to-build-a-bvh-part-2-faster-rays/">Continue reading in article 2</a>, in which we explore how to trace rays more quickly.</p>



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



<p>This article now has a small but important fix in the ray traversal code, as suggested by Daniel Moore. Thanks!</p>



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



<p>The complete code for this project (for Windows / Visual Studio) <a href="https://github.com/jbikker/bvh_article">can be found on GitHub</a>.</p>



<p>Enjoyed the article? Spotted an error?</p>



<p>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>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>The <a href="https://jacco.ompf2.com/2022/04/18/how-to-build-a-bvh-part-2-faster-rays/">next article in this series</a>, on faster ray traversal.</li><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></ul>
]]></content:encoded>
					
					<wfw:commentRss>https://jacco.ompf2.com/2022/04/13/how-to-build-a-bvh-part-1-basics/feed/</wfw:commentRss>
			<slash:comments>22</slash:comments>
		
		
			</item>
	</channel>
</rss>
