<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Justin on Medium]]></title>
        <description><![CDATA[Stories by Justin on Medium]]></description>
        <link>https://medium.com/@ktstephano?source=rss-a86d528ef220------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Ot3G2_zW9ma9iJ_egZDM1A.jpeg</url>
            <title>Stories by Justin on Medium</title>
            <link>https://medium.com/@ktstephano?source=rss-a86d528ef220------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 15:14:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ktstephano/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A Look At StratusGFX: An Opensource 3D Realtime Rendering Engine]]></title>
            <link>https://medium.com/@ktstephano/a-look-at-stratusgfx-an-opensource-3d-realtime-rendering-engine-e944746d1d33?source=rss-a86d528ef220------2</link>
            <guid isPermaLink="false">https://medium.com/p/e944746d1d33</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Justin]]></dc:creator>
            <pubDate>Sun, 02 Apr 2023 09:17:57 GMT</pubDate>
            <atom:updated>2023-04-02T09:17:57.841Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pl9FP2kqfe0ZpiI6XcQgnQ.png" /><figcaption>San Miguel rendered with StratusGFX</figcaption></figure><p>A few days ago I open sourced StratusGFX. <a href="https://github.com/KTStephano/StratusGFX">It can be found here.</a></p><p>It has been a personal hobby research project for a while now. I worked on it in my free time to try and learn about low level game engine architecture and modern 3D rendering techniques. It was only recently that it reached a state where it had enough features and enough stability that I felt like it might be useful to other people to have access to. So I did some reading about some of the available open source licenses and finally settled on the Mozilla Public License 2.0 (MPL 2.0).</p><p>In this article I’ll talk about the license, who might want to use it, and go through some screenshots which showcase its current features.</p><h3>Mozilla Public License 2.0 (MPL 2.0)</h3><p>The MPL is considered a weak copyleft license that seems to sit in between the no-restriction MIT license and the strong copyleft GPLv3.</p><p>MPL has some nice advantages. It encourages collaboration by requiring that any changes to the original source either be pushed back to the main repo or made public in some other way (such as through a fork).</p><p>At the same time, it is also very attractive to both other open source and even proprietary software. It works at the individual file level and does not require projects that use it adopt the same license. As long as they make their changes to StratusGFX public, the rest of their project can use a different license or even remain closed source.</p><h3>Project Focus</h3><p>The project was designed to run on Nvidia 10-series cards such as the GTX 1050 Ti and 1060. It offers modern graphics features such as physically based rendering and global illumination. Its emphasis is on being realtime, meaning a minimum of 30 fps.</p><p>Since it’s primarily a 3D rendering engine, it only has a few features found in larger engines.</p><p><strong>What It Has</strong></p><ul><li>Compiles to libStratusEngine which can be linked against for easily setting up separate apps</li><li>Realtime 3D renderer</li><li>Resource management for textures and models</li><li>Async asset loading</li><li>Entity-Component System (ECS)</li><li>Certain utilities such as pool allocators and multi threading</li><li>A main engine class responsible for startup, main loop, shutdown</li></ul><p><strong>What It Does Not Have</strong></p><ul><li>General purpose editor</li><li>Sound engine</li><li>Physics engine</li><li>Scripting</li><li>Engine-specific file format (instead it accepts .obj, .fbx, .gltf)</li></ul><h3>Tech Stack</h3><p>It is built using C++17 and OpenGL 4.6. Future versions will likely move the backend from OpenGL to Vulkan.</p><h3>Who Should Use This Project?</h3><p>This project is still in the beta stages. There will be bugs/glitches and instability as it is still under development. It’s far from being considered battle-tested code. Right now I could see three use cases for this project:</p><ol><li>Anyone who wants to use it for educational purposes.</li><li>Anyone who is building a more general custom game engine but doesn’t want to start from nothing when building their renderer.</li><li>Integrating all (or parts of it) into other full featured engines or modeling tools.</li></ol><h3>A Look At Its Features</h3><p>&gt; See the bottom of this article for links to the 3D assets used</p><p>&gt; A video tech showcase is also available: <a href="https://www.youtube.com/watch?v=s5aIsgzwNPE">https://www.youtube.com/watch?v=s5aIsgzwNPE</a></p><h4>Realtime Global Illumination + Indirect Shadowing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k2FPJjnRDrMGOxjsue572Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k4wnE7pjD33r9vnF2O3ZIg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_dXGzCOaqTumxXNYZj_hlg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pl9FP2kqfe0ZpiI6XcQgnQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fKC6f2sTToeL8fW5JjhoOQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kFj9Hz2r0oDg7-IUPZ3H5A.png" /></figure><h4>Raymarched Volumetric Lighting</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kr0AOz4-6y2pYXLx4w0lXQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HvvixrMWz4t39SvcwpPsUg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BZqr6ESdJaZ2JkCsMlKvFQ.png" /></figure><h4>Physically Based Metallic-Roughness Pipeline</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tqKYr3yNGeW8ZQ7BqeBk3Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_mY7-zQ6eb-81ODzt9uVXw.png" /></figure><h4>Deferred Lighting + Soft Shadowing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SSGMFoxSWsAT41wq8CIM_A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hpGWYZFIAiDW29RG59AkhA.png" /></figure><h4>Filmic Tonemapping</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bozXAzJXmXb6t1dpa_jiYg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NGFKpAVS5Aj2PayBg9DGgw.png" /></figure><h4>Bloom</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NPmv46LmyLUl09sxlScsUw.png" /></figure><h4>Other Features</h4><p>Graphics</p><ul><li>Cascaded shadow mapping</li><li>Mesh LOD generation and selection</li><li>GPU Frustum Culling</li><li>Screen Space Ambient Occlusion (SSAO)</li><li>Fast Approximate Anti-Aliasing (FXAA)</li></ul><p>Engine</p><ul><li>Pool allocators</li><li>Multi threaded utilities</li><li>Concurrent hash map</li><li>Entity-Component System (ECS)</li><li>Logging</li></ul><h3>Future Of StratusGFX</h3><p>There are still a few more things that I feel are required before I would be comfortable ticking the engine version to 1.0 and saying it was ready for production use.</p><h4>Short Term</h4><p>-&gt; Improving build system and documentation to make it easier for people to get up and running with the code</p><p>-&gt; Addition of either TAA or TSSAA to help with image stability while in motion</p><p>-&gt; Animation</p><p>-&gt; Performance improvements</p><h4>Medium Term</h4><p>-&gt; Order independent transparency</p><p>-&gt; Better handling of LOD generation and transition</p><p>-&gt; Screen Space Reflections (SSR)</p><h4>Long Term</h4><p>-&gt; Switch backend to Vulkan which will enable the engine to run on MacOS and not just Windows/Linux</p><p>-&gt; Addition of baked lighting features so that weaker hardware has a fallback option</p><p>-&gt; Addition of other modern global illumination techniques to either replace or complement what is already there</p><h3>Thanks For Reading!</h3><p>If you are interested in trying the code or trying to adapt it for use in any of your projects, feel free to reach out to me with any questions you have.</p><h3>3D Assets Used</h3><ul><li><a href="https://www.intel.com/content/www/us/en/developer/topic-technology/graphics-research/samples.html">https://www.intel.com/content/www/us/en/developer/topic-technology/graphics-research/samples.html</a></li><li><a href="https://developer.nvidia.com/orca/amazon-lumberyard-bistro">https://developer.nvidia.com/orca/amazon-lumberyard-bistro</a></li><li><a href="https://sketchfab.com/3d-models/the-bathroom-free-d5e5035dda434b8d9beaa7271f1c85fc">https://sketchfab.com/3d-models/the-bathroom-free-d5e5035dda434b8d9beaa7271f1c85fc</a></li><li><a href="https://casual-effects.com/data/">https://casual-effects.com/data/</a></li><li><a href="https://sketchfab.com/3d-models/abandoned-warehouse-1e40d433ed6f48fb880a0d2172aff7ca">https://sketchfab.com/3d-models/abandoned-warehouse-1e40d433ed6f48fb880a0d2172aff7ca</a></li><li><a href="https://sketchfab.com/3d-models/interogation-room-6e9151ec29494469a74081ddc054d569">https://sketchfab.com/3d-models/interogation-room-6e9151ec29494469a74081ddc054d569</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e944746d1d33" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Modern OpenGL: Multi-Draw Indirect (MDI)]]></title>
            <link>https://medium.com/@ktstephano/advanced-modern-opengl-multi-draw-indirect-mdi-45fc2193b815?source=rss-a86d528ef220------2</link>
            <guid isPermaLink="false">https://medium.com/p/45fc2193b815</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[opengl]]></category>
            <category><![CDATA[rendering]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Justin]]></dc:creator>
            <pubDate>Thu, 16 Mar 2023 03:51:03 GMT</pubDate>
            <atom:updated>2023-03-16T03:51:03.422Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QBF_lFEbZleFpuLbSfo5Ug.png" /></figure><p>This is part of a tutorial series teaching advanced modern OpenGL. To use all features to their fullest you will need to target OpenGL 4.6. These articles assume you have familiarity with OpenGL.</p><p>With older versions of OpenGL we had access to draw commands such as glDrawArrays, glDrawElements, or glDrawElementsInstanced. Improving performance would be about doing things like maximizing the use of instancing.</p><p>With the latest versions of OpenGL the API introduced the concept of Multi-Draw Indirect (MDI). MDI opens the door to a totally new approach to generating draw commands which supports parallel command creation (either with multiple CPU cores or even on the GPU) and at the same time reduces the amount of time the CPU has to spend submitting draw calls to the driver. It also allows us to reuse draw commands from previous frames if nothing has changed.</p><h3>How Multi-Draw Indirect (MDI) Differs From Old Methods</h3><p>The primary difference is that instead of submitting each draw call manually (instanced or non-instanced, indexed or non-indexed), draw calls are instead packed into a GPU buffer which gets bound to the GL_DRAW_INDIRECT_BUFFER target before drawing. This means that instead of submitting multiple draw commands in a row, we instead submit every draw call that’s currently in the bound GPU buffer at once.</p><p>This is where the option of parallelizing the draw command generation comes into play. Since OpenGL doesn’t actually do anything with the draw command buffer until we bind it and submit it, multiple threads can write data to the buffer ahead of time before we synchronize and draw. The rendering thread will always submit the draw commands, but multiple threads can write to the draw command buffer before this happens.</p><p>Another important thing is that the GL_DRAW_INDIRECT_BUFFER is backed by GPU memory and can be used like a regular SSBO. This means you can pass it into a compute shader and have it manipulate the draw commands directly. The GPU can now generate its own work!</p><p><strong>Summary:</strong></p><ul><li>Multiple threads or the GPU can write to a draw command buffer</li><li>The rendering thread synchronizes and submits the commands in the buffer with a single API call.</li></ul><h3>A Look At The API</h3><p>There are two functions which we will be dealing with when it comes to MDI:</p><pre>void glMultiDrawArraysIndirect(<br>    GLenum mode,<br>    const void *indirect,<br>    GLsizei drawcount,<br>    GLsizei stride<br>);<br><br>void glMultiDrawElementsIndirect(<br>    GLenum mode,<br>    GLenum type,<br>    const void *indirect,<br>    GLsizei drawcount,<br>    GLsizei stride<br>);</pre><p>The difference between them is that the first performs non-indexed multi-draw while the second perforns indexed multi-draw.</p><p><strong>Parameters</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aEca2JZs_TdV2Qf7FgIFdg.png" /></figure><h3>A Look At The Draw Command Structs</h3><p>There are two draw command structs — one for MultiDrawArrays and one for MultiDrawElements.</p><pre>// Struct for MultiDrawArrays<br>typedef  struct {<br>    unsigned int  count;<br>    unsigned int  instanceCount;<br>    unsigned int  firstVertex;<br>    unsigned int  baseInstance;<br>    // Optional user-defined data goes here - if nothing, stride is 0<br>} DrawArraysIndirectCommand;<br>// sizeof(DrawArraysIndirectCommand) == 16<br><br>// Struct for MultiDrawElements<br>typedef  struct {<br>    unsigned int  count;<br>    unsigned int  instanceCount;<br>    unsigned int  firstIndex;<br>    int           baseVertex;<br>    unsigned int  baseInstance;<br>    // Optional user-defined data goes here - if nothing, stride is 0<br>} DrawElementsIndirectCommand;<br>// sizeof(DrawElementsIndirectCommand) == 20</pre><p>Below is a table detailing what each member is supposed to be interpreted as.</p><p><strong>Struct Members</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jh3OefP3s7CRAAYqamlMNw.png" /></figure><p>Here is some pseudocode for how gl_VertexID could be set by the driver.</p><pre>// When using DrawArraysIndirectCommand<br>for each (DrawArraysIndirectCommand cmd : GL_DRAW_INDIRECT_BUFFER) {<br>    for (uint i = 0; i &lt; cmd.count; ++i) {<br>        int gl_VertexID = cmd.firstVertex + i;<br>    }<br>}<br><br>// When using DrawElementsIndirectCommand when element array buffer is<br>// using unsigned ints<br>unsigned int * indices = (unsigned int *)ELEMENT_ARRAY_BUFFER;<br>for each (DrawElementsIndirectCommand cmd : GL_DRAW_INDIRECT_BUFFER) {<br>    for (uint i = 0; i &lt; cmd.count; ++i) {<br>        int gl_VertexID = indices[cmd.firstIndex + i] + cmd.baseVertex;<br>    }<br>}</pre><h3>Available Built-In Input Variables</h3><p>The following table includes the relevant built-in inputs that are available for the vertex shader stage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*io4V2bPKqvbEHju8tpLewg.png" /></figure><h3>What First Vertex/Index and Base Vertex Are Useful For</h3><p>Having these allows us to combine multiple mesh vertices and vertex indices into larger buffers that the draw commands can reference. For example, assume we have 3 meshes and we have merged their data into two large buffers (one for vertices, one for indices):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F-4pOYxY9Ivhm7I3daGp4Q.png" /><figcaption>All mesh data merged into two large arrays (vertices, indices)</figcaption></figure><p>We see here that the meshes now sit in adjacent memory and we will need to specify offsets to access the data. If using DrawArraysIndirectCommand we will specify that with the firstVertex offset so that we can correctly access the vertex data for each mesh per draw call.</p><p>Notice that the index buffer entries all reference the same indices 0 through 3, but the actual vertex buffer now goes from 0 through 9 since we put the vertices for all 3 meshes into it. If using DrawElementsIndirectCommand we specify the offset with a combination of firstIndex (where in the index buffer to start reading for the current draw call) and baseVertex (what the index should be offset by before using it to access the vertex in the vertex buffer for the current draw call).</p><p><strong>What mesh 1,2,3 draw commands would look like</strong></p><pre>DrawElementsIndirectCommand mesh1Cmd = {<br>    .count = 6,         // 6 indices total<br>    .instanceCount = 1,<br>    .firstIndex = 0,    // First in the index array<br>    .baseVertex = 0,    // First in the vertex array<br>    .baseInstance = 0<br>};<br><br>// For this command,<br>// initialIndex = indices[.firstIndex] + .baseVertex<br>//              = indices[6] + 3<br>//              = 1 + 3 = 4<br>DrawElementsIndirectCommand mesh2Cmd = {<br>    .count = 6,         // 6 indices total<br>    .instanceCount = 1,<br>    .firstIndex = 6,    // Starts at location 6 in index array<br>    .baseVertex = 3,    // Starts at location 3 in vertices array<br>    .baseInstance = 0<br>};<br><br>// For this command,<br>// initialIndex = indices[.firstIndex] + .baseVertex<br>//              = indices[12] + 6<br>//              = 0 + 6 = 6<br>DrawElementsIndirectCommand mesh3Cmd = {<br>    .count = 8,         // 8 indices total<br>    .instanceCount = 1,<br>    .firstIndex = 12,   // Starts at location 12 in index array<br>    .baseVertex = 6,    // Starts at location 6 in vertices array<br>    .baseInstance = 0<br>};</pre><h3>Creating and Using Draw Command Buffers</h3><p>This is done in the same way as an SSBO is created except now we use one of the two structs defined above. For example:</p><pre>std::vector&lt;DrawElementsIndirectCommand&gt; commands;<br><br>.. code that fills commands vector with DrawElementsIndirectCommand elements ..<br>// (for example)<br>commands.push_back(mesh1Cmd);<br>commands.push_back(mesh2Cmd);<br>commands.push_back(mesh3Cmd);<br><br>GLuint drawCmdBuffer;<br>glCreateBuffers(1, &amp;drawCmdBuffer);<br><br>glNamedBufferStorage(drawCmdBuffer, <br>                     sizeof(DrawElementsIndirectCommand) * commands.size(), <br>                     (const void *)commands.data(), <br>                     GL_DYNAMIC_STORAGE_BIT);</pre><p><strong>Binding and Drawing</strong></p><pre>glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indicesBuffer);<br>glBindBuffer(GL_DRAW_INDIRECT_BUFFER, drawCmdBuffer);<br><br>// This will submit all commands.size() draw commands in the currently<br>// bound buffer<br>glMultiDrawElementsIndirect(<br>    GL_TRIANGLES, <br>    GL_UNSIGNED_INT, // Type of data in indicesBuffer<br>    (const void *)0, // No offset into draw command buffer<br>    commands.size(),<br>    0                // No stride as data is tightly packed<br>);<br><br>glBindBuffer(GL_DRAW_INDIRECT_BUFFER, 0);<br>glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);</pre><h3>Accessing Draw Command Buffers On The GPU</h3><p>Since the draw command buffer is just a regular GPU buffer, it can be bound to both the GL_DRAW_INDIRECT_BUFFER and the GL_SHADER_STORAGE_BUFFER targets.</p><p><em>c++</em></p><pre>// 3 matches (binding = 3) in compute shader below<br>glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 3, drawCmdBuffer);<br>glUniform1ui(<br>    glGetUniformLocation(computeShader, &quot;numDrawCommands&quot;), commands.size()<br>);</pre><p><em>compute shader</em></p><pre>#version 460 core<br>layout (local_size_x = 4, local_size_y = 4, local_size_z = 1) in;<br><br>// Matches the C++ definition<br>struct DrawElementsIndirectCommand {<br>    uint  count;<br>    uint  instanceCount;<br>    uint  firstIndex;<br>    int   baseVertex;<br>    uint  baseInstance;<br>};<br><br>// Buffer for both read and write access<br>layout (std430, binding = 3) buffer ssbo1 {<br>    DrawElementsIndirectCommand drawCommands[];<br>};<br><br>uniform uint numDrawCommands;<br><br>// Now the compute shader can read and write from the buffer however<br>// way that it needs to</pre><h3>Reuse For Multiple Frames</h3><p>It is possible that a scene could have large amounts of static geometry that is set up all at once and then left alone for many frames. In a case like this you could opt to generate a draw command buffer specifically for this static geometry and then reuse it over the course of many frames to save on performance. This would mean for the static portion of the scene the CPU would just bind the static draw command buffer without regenerating it, submit draw calls, and then move on and handle the dynamic parts of the scene separately.</p><h3>Learn OpenGL Fundamentals</h3><ul><li><a href="https://learnopengl.com/">https://learnopengl.com</a></li></ul><h3>References</h3><ul><li><a href="https://registry.khronos.org/OpenGL-Refpages/gl4/html/glMultiDrawArraysIndirect.xhtml">https://registry.khronos.org/OpenGL-Refpages/gl4/html/glMultiDrawArraysIndirect.xhtml</a></li><li><a href="https://registry.khronos.org/OpenGL-Refpages/gl4/html/glMultiDrawElementsIndirect.xhtml">https://registry.khronos.org/OpenGL-Refpages/gl4/html/glMultiDrawElementsIndirect.xhtml</a></li><li><a href="https://www.khronos.org/opengl/wiki/Vertex_Shader/Defined_Inputs">https://www.khronos.org/opengl/wiki/Vertex_Shader/Defined_Inputs</a></li><li><a href="https://www.amazon.com/Graphics-Rendering-Cookbook-comprehensive-algorithms/dp/1838986197">3D Graphics Rendering Cookbook</a></li><li><a href="https://www.amazon.com/OpenGL-Superbible-Comprehensive-Tutorial-Reference/dp/0672337479">OpenGL SuperBible</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45fc2193b815" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Modern OpenGL: Bindless Textures]]></title>
            <link>https://medium.com/@ktstephano/advanced-modern-opengl-bindless-textures-e686363688c3?source=rss-a86d528ef220------2</link>
            <guid isPermaLink="false">https://medium.com/p/e686363688c3</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[graphics-programming]]></category>
            <category><![CDATA[rendering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[opengl]]></category>
            <dc:creator><![CDATA[Justin]]></dc:creator>
            <pubDate>Wed, 15 Mar 2023 00:07:18 GMT</pubDate>
            <atom:updated>2023-03-15T00:07:18.759Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QBF_lFEbZleFpuLbSfo5Ug.png" /></figure><p>This is part of a tutorial series teaching advanced modern OpenGL. To use all features to their fullest you will need to target OpenGL 4.6. These articles assume you have familiarity with OpenGL.</p><p>In this tutorial we will be looking at a method for eliminating the need to bind a texture to a uniform texture unit. If you haven’t already make sure to check out the <a href="https://medium.com/@ktstephano/advanced-modern-opengl-shader-storage-buffer-objects-ssbos-66b6414a8086?source=friends_link&amp;sk=0af28131818c5ac036c36b956d6a7d8f">Shader Storage Buffer Objects (SSBOs)</a> and <a href="https://medium.com/@ktstephano/advanced-modern-opengl-programmable-vertex-pulling-4c74c242da5e?source=friends_link&amp;sk=25cb37737fc97453fb8be873917d7016">Programmable Vertex Pulling</a> tutorials since we will use both of these here.</p><h3>What Are Bindless Textures?</h3><p>OpenGL 4.5 only requires a minimum of 16 texture units to be available to a shader for use, though many drivers support 32 or more. This is a very difficult limit to deal with if we are trying to do something like merge many different draw calls with different material textures, or access many shadow maps in a deferred lighting stage. There were two main ways to get around this in the past:</p><ul><li>Use array textures to combine multiple textures of the same dimensions</li><li>Use texture atlases to allow one large texture to represent many smaller textures</li></ul><p>Bindless textures are a 3rd alternative to this. Instead of explicitly binding a texture to a texture unit, bindless textures allow us to manually mark the texture as resident on the GPU and then pass its handle to a shader using a uniform buffer or shader storage buffer.</p><p>There is also a possible performance gain with this approach. If your renderer is currently spending a lot of time binding and unbinding textures between different draw calls, a bindless approach can reduce a lot of driver overhead. This is because your application can now figure out which textures are needed at the beginning of the frame, mark them all as resident at the sae time and then use those textures for any number of draw calls for the remainder of the frame.</p><h3>Downsides Of Bindless Textures</h3><p>There are two main downsides of bindless textures:</p><p>1) Renderdoc does not support them at the time of writing so you will need to use a graphics debugger that does such as Nvidia NSight</p><p>2) Bindless textures never made it into the core of OpenGL so it is still an extension even with 4.6. Nvidia and AMD both have a lot of hardware that is fully supportive of it, but outside of those two you will need to double check if the vendor supports it.</p><h3>A Look At The API</h3><p>For this tutorial we will be focused on 3 main API functions which we will go through now.</p><p><strong>Retrieving Texture Handles</strong></p><pre>GLuint64 glGetTextureHandleARB(GLuint texture​);</pre><p>The purpose of this function is to take a valid texture and return a 64-bit handle that represents that texture. This handle can be inserted directly into uniform buffers or shader storage buffers.</p><p>If you were to call this function multiple times with the same texture, it will always return the same handle. So what you can do is call this once after the texture is created and then use the handle for the entire lifetime of the texture without having to call this function again.</p><p><strong><em>Important!</em></strong> Khronos states the following on their wiki: <em>“Once a handle is created for a texture/sampler, none of its state can be changed. For Buffer Textures, this includes the buffer object that is currently attached to it (which also means that you cannot create a handle for a buffer texture that does not have a buffer attached). Not only that, in such cases the buffer object itself becomes immutable; it cannot be reallocated with glBufferData. Though just as with textures, its storage can still be mapped and have its data modified by other functions as normal.”</em></p><p>So the general guideline is to perform all initial setup that you will need for the texture or buffer texture, then once you are done call this. From then on you will only be able to change the texture data but no other state related to the texture.</p><p><strong>Making Texture Handles Resident</strong></p><pre>// handle is what is returned by glGetTextureHandleARB<br>void glMakeTextureHandleResidentARB(GLuint64 handle​);</pre><p>Since we won’t be binding to uniform texture units anymore, we need to be able to tell the driver which handles we plan to use before we use them. Otherwise it has no way of knowing.</p><p>Once you make a texture handle resident, it remains resident until you explicitly tell the driver to make it non-resident. This means that if you have a certain group of textures that will be around for the entire lifetime of your program, you could make them resident at the start and then leave them resident until the program is ending.</p><p><strong>Making Texture Handles Non-Resident</strong></p><pre>// handle is what is returned by glGetTextureHandleARB<br>void glMakeTextureHandleNonResidentARB(GLuint64 handle​);</pre><p>This allows you to tell the driver that the handle is no longer being used by any shaders and can be taken off the residency list.</p><h3>Example: 1600 textures in a single shader</h3><p>To show how to use this we are going to randomly generate 1600 textures (one for each of 1600 cube instances) and make them all resident for the shader to use. We will only be using a single instanced draw call to draw 1600 cubes.</p><p>First we will generate the data for the cube and insert its vertices into an SSBO.</p><pre>struct VertexData {<br>    float position[3];<br>    float uv[2];<br>    float normal[3];<br>};<br><br>// In main or some other function<br>std::vector&lt;VertexData&gt; vertices;<br><br>... code to insert a single cube data into vertices ... <br><br>const int numVertices = data.size();<br>GLuint verticesBuffer;<br><br>glCreateBuffers(1, &amp;verticesBuffer);<br>glNamedBufferStorage(<br>    verticesBuffer,<br>    sizeof(VertexData) * vertices.size(),<br>    (const void *)vertices.data(),<br>    GL_DYNAMIC_STORAGE_BIT<br>);</pre><p>Next we will create 1600 different transforms, one for each cube instance. These will also be inserted into a SSBO.</p><pre>std::vector&lt;glm::mat4&gt; instancedMatrices;<br><br>// Each one will be 5 units apart from the others in the x/y direction<br>for (size_t x = 0; x &lt; 200; x += 5) {<br>    for (size_t y = 0; y &lt; 200; y += 5) {<br>        glm::mat4 mat(1.0f);<br>        mat[3].x = float(x);<br>        mat[3].y = float(y);<br>        mat[3].z = 0.0f;<br>        instancedMatrices.push_back(std::move(mat));<br>    }<br>}<br><br>const int numInstances = instancedMatrices.size();<br>GLuint modelMatricesBuffer;<br><br>glCreateBuffers(1, &amp;modelMatricesBuffer);<br>glNamedBufferStorage(<br>    modelMatricesBuffer,<br>    sizeof(glm::mat4) * instancedMatrices.size(),<br>    (const void *)instancedMatrices.data(),<br>    GL_DYNAMIC_STORAGE_BIT<br>);</pre><p>Now we will randomly generate 1600 textures.</p><p><strong>Setting Up Vectors</strong></p><pre>std::vector&lt;GLuint&gt; textures;<br>std::vector&lt;GLuint64&gt; textureHandles;<br><br>// Each texture has a width and height of 32x32, <br>// with 3 channels of data (RGB) per pixel<br>const size_t textureSize = 32 * 32 * 3;<br>unsigned char textureData[textureSize];</pre><p>We will have a vector for the textures and for the returned handles.</p><p><strong>Generating Textures And Retrieving Handles</strong></p><pre>for (int i = 0; i &lt; numInstances; ++i) {<br>    const unsigned char limit = unsigned char(rand() % 231 + 25);<br>    // Randomly generate an unsigned char per RGB channel<br>    for (int j = 0; j &lt; textureSize; ++j) {<br>        textureData[j] = unsigned char(rand() % limit);<br>    }<br><br>    GLuint texture;<br>    glCreateTextures(GL_TEXTURE_2D, 1, &amp;texture);<br>    glTextureStorage2D(texture, 1, GL_RGB8, 32, 32);<br>    glTextureSubImage2D(<br>        texture, <br>        // level, xoffset, yoffset, width, height<br>        0, 0, 0, 32, 32, <br>        GL_RGB, GL_UNSIGNED_BYTE, <br>        (const void *)&amp;textureData[0]);<br>    glGenerateTextureMipmap(texture);<br><br>    // Retrieve the texture handle after we finish creating the texture<br>    const GLuint64 handle = glGetTextureHandleARB(texture);<br>    if (handle == 0) {<br>        std::cerr &lt;&lt; &quot;Error! Handle returned null&quot; &lt;&lt; std::endl;<br>        exit(-1);<br>    }<br><br>    textures.push_back(texture);<br>    textureHandles.push_back(handle);<br>}</pre><p>There needs to be some sort of check to make sure the handle returned actually makes sense. If something bad happened it will return 0.</p><p>Next we need to pack all the texture handles into another SSBO.</p><p><strong>Packing Handles Into SSBO</strong></p><pre>GLuint textureBuffer;<br>glCreateBuffers(1, &amp;textureBuffer);<br>glNamedBufferStorage(<br>    textureBuffer,<br>    sizeof(GLuint64) * textureHandles.size(),<br>    (const void *)textureHandles.data(),<br>    GL_DYNAMIC_STORAGE_BIT<br>);</pre><p>Once we have all this we are ready to enter the rendering loop!</p><p><strong>Making Handles Resident And Drawing</strong></p><pre>glEnable(GL_DEPTH_TEST);<br>glClearColor(0.0f, 0.0f, 0.0f, 0.0f);<br>glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);<br><br>// Mark all as resident<br>for (GLuint64 handle : textureHandles) {<br>    glMakeTextureHandleResidentARB(handle);<br>}<br><br>// Bind our shader program<br>glUseProgram(shader);<br><br>// Set up matrices<br>glUniformMatrix4fv(<br>    glGetUniformLocation(shader, &quot;projection&quot;), 1, GL_FALSE, projectionMat<br>);<br>glUniformMatrix4fv(<br>    glGetUniformLocation(shader, &quot;view&quot;), 1, GL_FALSE, viewMat<br>);<br><br>// Bind the SSBOs<br>glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, verticesBuffer);<br>glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, modelMatricesBuffer);<br>glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, textureBuffer);<br><br>glDrawArraysInstanced(GL_TRIANGLES, 0, numVertices, numInstances);<br><br>glUseProgram(0);<br><br>// Mark all as non-resident - can be skipped if you know the same textures<br>// will all be used for the next frame<br>for (GLuint64 handle : textureHandles) {<br>    glMakeTextureHandleNonResidentARB(handle);<br>}</pre><p><strong>A Look At The Shaders</strong></p><p>The vertex shader is almost identical to the one found in the Programmable Vertex Pulling tutorials except that now it writes gl_InstanceID as an output so that the fragment shader can use it. gl_InstanceID in this case will contain values from 0 to 1599 and the fragment shader will use this to determine which texture it should pull data from.</p><p>Another really important thing is to remember to use #extension GL_ARB_bindless_texture : require since the bindless textures never made it into core OpenGL. We will have to put this in both the vertex and the fragment shader.</p><p><em>shader.vs</em></p><pre>#version 460 core<br><br>#extension GL_ARB_bindless_texture : require<br><br>// This matches the C++ definition<br>struct VertexData {<br>    float position[3];<br>    float uv[2];<br>    float normal[3];<br>};<br><br>// readonly SSBO containing the data<br>layout(binding = 0, std430) readonly buffer ssbo1 {<br>    VertexData data[];<br>};<br><br>layout(binding = 1, std430) readonly buffer ssbo2 {<br>    mat4 modelTransforms[];<br>};<br><br>uniform mat4 projection;<br>uniform mat4 view;<br><br>// Helper functions to manually unpack the data into vectors given an index<br>vec3 getPosition(int index) {<br>    return vec3(<br>        data[index].position[0], <br>        data[index].position[1], <br>        data[index].position[2]<br>    );<br>}<br><br>vec2 getUV(int index) {<br>    return vec2(<br>        data[index].uv[0], <br>        data[index].uv[1]<br>    );<br>}<br><br>vec3 getNormal(int index) {<br>    return vec3(<br>        data[index].normal[0], <br>        data[index].normal[1], <br>        data[index].normal[2]<br>    );<br>}<br><br>smooth out vec2 fsUv;<br>flat out vec3 fsNormal;<br>flat out int fsInstance;<br><br>void main()<br>{<br>    mat4 vp = projection * view;<br>    vec4 position = vec4(getPosition(gl_VertexID), 1.0);<br>    gl_Position = vp * modelTransforms[gl_InstanceID] * position;<br><br>    fsUv = getUV(gl_VertexID);<br>    fsNormal = getNormal(gl_VertexID);<br>    // Fragment shader needs this to select one of the 1600 available textures<br>    fsInstance = gl_InstanceID;<br>}</pre><p>In the fragment shader below you’ll notice that the readonly SSBO has type “sampler2D” inside of it. Depending on the texture type you are using this should work with sampler2D, sampler3D, samplerCube, etc. All of them only require that you pass in the 64-bit handles as the SSBO data.</p><p><em>fragment.vs</em></p><pre>#version 460 core<br><br>#extension GL_ARB_bindless_texture : require<br><br>// SSBO containing the textures<br>layout(binding = 2, std430) readonly buffer ssbo3 {<br>    sampler2D textures[];<br>};<br><br>smooth in vec2 fsUv;<br>flat in vec3 fsNormal;<br>flat in int fsInstance;<br><br>out vec4 color;<br><br>void main() {<br>    // Select texture based on instance<br>    sampler2D tex = textures[fsInstance];<br>    // Read from the texture with the normal texture() GLSL function<br>    color = vec4(texture(tex, fsUv).rgb, 1.0);<br>}</pre><p>Running this program produces the following result on a GTX 1060:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q9QyyPenP2pcIdDZwqY-Ag.png" /></figure><h3>Conclusion</h3><p>Bindless textures are a very powerful tool to increase the number of textures that a shader can access. It supplements the old methods of using texture arrays or texture atlases, and for programs that spend large amounts of time binding/unbinding textures between draw calls it can offer a lot of performance improvements.</p><p>The main downsides relate to a) not being core in GL 4.6, b) not all graphics debuggers supporting it, and c) outside of Nvidia and AMD which have strong support for bindless, not all vendors (especially mobile) will support them.</p><h3>References</h3><ul><li><a href="https://www.khronos.org/opengl/wiki/Bindless_Texture">https://www.khronos.org/opengl/wiki/Bindless_Texture</a></li><li><a href="https://www.amazon.com/OpenGL-Superbible-Comprehensive-Tutorial-Reference/dp/0672337479">OpenGL SuperBible</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e686363688c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Modern OpenGL: Programmable Vertex Pulling]]></title>
            <link>https://medium.com/@ktstephano/advanced-modern-opengl-programmable-vertex-pulling-4c74c242da5e?source=rss-a86d528ef220------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c74c242da5e</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[graphics-programming]]></category>
            <category><![CDATA[opengl]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[rendering]]></category>
            <dc:creator><![CDATA[Justin]]></dc:creator>
            <pubDate>Tue, 14 Mar 2023 01:38:44 GMT</pubDate>
            <atom:updated>2023-03-15T02:17:36.111Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QBF_lFEbZleFpuLbSfo5Ug.png" /></figure><p>This is part of a tutorial series teaching advanced modern OpenGL. To use all features to their fullest you will need to target OpenGL 4.6. These articles assume you have familiarity with OpenGL.</p><p>With the old way of using OpenGL, it required that you send things like vertex, uv, and normal data in a format that the driver could understand and use. This meant using vertex buffer objects (VBOs) and vertex array objects (VAOs). With programmable vertex pulling we will be getting rid of VBOs and VAOs entirely and using our own data format with manual data unpacking in the shader. This gives us a lot of flexibility with how we structure our data and will be very useful in future articles that will discuss other advanced techniques.</p><p>If you haven’t already, make sure you check out the <a href="https://ktstephano.github.io/rendering/opengl/ssbos">Shader Storage Buffer Objects (SSBOs)</a> tutorial since we will be using those here.</p><h3>Old Method</h3><p>Let’s start by looking at an example of how we would pack up the vertices to send to the GPU in a stream with the old way of doing things.</p><p><em>main.cpp</em></p><pre>// Data is laid out as 3 positions, 2 uvs, 3 normals, repeat<br>std::vector&lt;float&gt; vertices;<br><br>... code to fill vertices with vertex data ...<br><br>GLuint vbo;<br>glGenBuffers(1, &amp;vbo);<br><br>// Bind and upload data<br>glBindBuffer(GL_ARRAY_BUFFER, vbo);  <br>glBufferData(<br>    GL_ARRAY_BUFFER, <br>    vertices.size(), <br>    (const void *)vertices.data(), <br>    GL_STATIC_DRAW<br>);<br><br>// Tell OpenGL how to interpret the data and where it should be linked to<br><br>// Positions<br>glVertexAttribPointer(<br>    0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0<br>);<br>glEnableVertexAttribArray(0);<br><br>// UVs<br>glVertexAttribPointer(<br>    1, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float))<br>);<br>glEnableVertexAttribArray(1);<br><br>// Normals<br>glVertexAttribPointer(<br>    2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(5 * sizeof(float))<br>);<br>glEnableVertexAttribArray(2);<br><br>// Bind program and draw<br>glUseProgram(program);<br><br>glDrawArrays(GL_TRIANGLES, 0, vertices.size());<br><br>// Unbind<br>glUseProgram(0);<br>glBindBuffer(GL_ARRAY_BUFFER, 0);</pre><p>Then the shader would look something like this:</p><p><em>shader.vs</em></p><pre>#version 330 core<br><br>layout (location = 0) in vec3 position;<br>layout (location = 1) in vec2 uv;<br>layout (location = 2) in vec3 normal;<br><br>uniform mat4 projection;<br>uniform mat4 view;<br><br>out vec2 fsUv;<br>out vec3 fsNormal;<br><br>void main()<br>{<br>    gl_Position = projection * view * vec4(position, 1.0);<br><br>    fsUv = uv;<br>    fsNormal = normal;<br>}</pre><h3>New Method — Programmable Vertex Pulling with SSBOs</h3><p>This will work for both indexed and non-indexed drawing and can be extended to further support multi-draw indirect commands. In the above example we put all the data into a vector of floats, then sent it to an OpenGL array buffer and told OpenGL how it was supposed to interpret the data and which locations it was supposed to send it to. With programmable vertex pulling we do away with that and instead manually unpack our data in the shader.</p><p>The advantage of this is that we get OpenGL out of the way when it comes to interpreting our data and instead write the code to deal with our data directly a lot like we would do with C++, but now in GLSL. This offers us a lot of flexibility both with vertex data but other with other data that will be discussed in future tutorials.</p><p><em>main.cpp</em></p><pre>// We use arrays of floats since they will be tightly packed with the<br>// layout std430 qualifier<br>struct VertexData {<br>    float position[3];<br>    float uv[2];<br>    float normal[3];<br>};<br><br>// (inside either main or a different function)<br>std::vector&lt;VertexData&gt; vertices;<br>... populate vertices with either hardcoded data or data you load from a file ...<br><br>// Create and fill the mesh data buffer<br>GLuint vertexDataBuffer;<br>glCreateBuffers(1, &amp;vertexDataBuffer);<br><br>glNamedBufferStorage(vertexDataBuffer, <br>                     sizeof(VertexData) * vertices.size(),<br>                     (const void *)vertices.data(), <br>                     GL_DYNAMIC_STORAGE_BIT);<br><br>// Bind the buffer to location 0 - matches (binding = 0) for ssbo1 in the<br>// vertex shader listed below<br>glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, vertexDataBuffer);<br><br>// Bind program and draw<br>glUseProgram(program);<br><br>glDrawArrays(GL_TRIANGLES, 0, vertices.size());<br><br>glUseProgram(0);<br><br>// Uncomment if you want to explicitly unbind the resouce<br>//glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, 0);</pre><p>Inside of the vertex shader we will be making use of a built-in input called gl_VertexID. When using non-indexed drawing such as glDrawArrays, gl_VertexID will be equal to the current vertex index. When using indexed drawing such as glDrawElements, gl_VertexID will be equal to the current index from the element array buffer.</p><p><em>shader.vs</em></p><pre>#version 460 core<br><br>// This matches the C++ definition<br>struct VertexData {<br>    float position[3];<br>    float uv[2];<br>    float normal[3];<br>};<br><br>// readonly SSBO containing the data<br>layout(binding = 0, std430) readonly buffer ssbo1 {<br>    VertexData data[];<br>};<br><br>uniform mat4 projection;<br>uniform mat4 view;<br><br>// Helper functions to manually unpack the data into vectors given an index<br>vec3 getPosition(int index) {<br>    return vec3(<br>        data[index].position[0], <br>        data[index].position[1], <br>        data[index].position[2]<br>    );<br>}<br><br>vec2 getUV(int index) {<br>    return vec2(<br>        data[index].uv[0], <br>        data[index].uv[1]<br>    );<br>}<br><br>vec3 getNormal(int index) {<br>    return vec3(<br>        data[index].normal[0], <br>        data[index].normal[1], <br>        data[index].normal[2]<br>    );<br>}<br><br>out vec2 fsUv;<br>out vec3 fsNormal;<br><br>void main()<br>{<br>    gl_Position = projection * view * vec4(getPosition(gl_VertexID), 1.0);<br><br>    fsUv = getUV(gl_VertexID);<br>    fsNormal = getNormal(gl_VertexID);<br>}</pre><p>No more VBOs or VAOs. Nice!</p><h3>Learn OpenGL Fundamentals</h3><ul><li><a href="https://learnopengl.com/">https://learnopengl.com</a></li></ul><h3>References</h3><ul><li><a href="https://registry.khronos.org/OpenGL-Refpages/gl4/html/gl_VertexID.xhtml">https://registry.khronos.org/OpenGL-Refpages/gl4/html/gl_VertexID.xhtml</a></li><li><a href="https://www.amazon.com/Graphics-Rendering-Cookbook-comprehensive-algorithms/dp/1838986197">3D Graphics Rendering Cookbook</a></li><li><a href="https://www.amazon.com/OpenGL-Superbible-Comprehensive-Tutorial-Reference/dp/0672337479">OpenGL SuperBible</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c74c242da5e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Modern OpenGL: Shader Storage Buffer Objects (SSBOs)]]></title>
            <link>https://medium.com/@ktstephano/advanced-modern-opengl-shader-storage-buffer-objects-ssbos-66b6414a8086?source=rss-a86d528ef220------2</link>
            <guid isPermaLink="false">https://medium.com/p/66b6414a8086</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[graphics-programming]]></category>
            <category><![CDATA[opengl]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[rendering]]></category>
            <dc:creator><![CDATA[Justin]]></dc:creator>
            <pubDate>Tue, 14 Mar 2023 01:30:11 GMT</pubDate>
            <atom:updated>2023-03-15T02:19:38.577Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QBF_lFEbZleFpuLbSfo5Ug.png" /></figure><p>This is part of a tutorial series teaching advanced modern OpenGL. To use all features to their fullest you will need to target OpenGL 4.6. These articles assume you have familiarity with OpenGL.</p><p>When writing graphics code that uses OpenGL, eventually we reach a stage where we want a flexible way to read from and write to GPU memory in ways that suit our application best. This is where the Shader Storage Buffer Object (SSBO) comes into play.</p><h3>What is the difference between a uniform buffer and a shader storage buffer?</h3><ol><li>A uniform buffer is read only. A shader storage buffer is both read and write. This includes <em>atomic</em>read+write operations for data synchronization between GPU cores.</li><li>Shader storage buffers can be much larger than uniform storage buffers, in practice up to the total size of all available GPU memory can be allocated for use.</li><li>Shader storage buffers have access to the std430 layout in GLSL which is an improvement over the old std140 layout.</li><li>Inside of a shader written in GLSL, an SSBO can be specified with variable length instead of having to know ahead of time what the size will be.</li><li>The spec warns that speed of accessing data in an SSBO may be lower than for a uniform buffer.</li></ol><h3>Creating and using a Shader Storage Buffer</h3><p>For this example, let’s say we are performing instanced drawing using glDrawArraysInstancedand we want to pass in all of the model matrices for each instance as a shader storage buffer.</p><p>Creating the buffer:</p><pre>GLuint modelMatricesBuffer;<br>glCreateBuffers(1, &amp;modelMatricesBuffer);</pre><p>Inserting data into the buffer using Direct State Access (DSA):</p><pre>std::vector&lt;glm::mat4&gt; instancedModelMatrices;<br>... code to insert a mat4 per instance into the vector ...<br><br>glNamedBufferStorage(modelMatricesBuffer, <br>                     sizeof(glm::mat4) * instancedModelMatrices.size(), <br>                     (const void *)instancedModelMatrices.data(), <br>                     GL_DYNAMIC_STORAGE_BIT);</pre><p>It is important to keep in mind that once glNamedBufferStorage has been used, the size of the GPU memory region for the buffer is fixed for the rest of modelMatricesBuffer&#39;s life span. We are allowed to dynamically read and write data into that region, but we can’t resize it.</p><p>The last parameter to glNamedBufferStorage is the usage flag. The following are the available options:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PtUqTgttyux1xt_3BhJ8uw.png" /></figure><p>For more information, <a href="https://registry.khronos.org/OpenGL-Refpages/gl4/html/glBufferStorage.xhtml">see this page</a>.</p><p>In order to use the buffer for instanced rendering in the vertex shader, we will set it up like this:</p><pre>#version 460 core<br><br>// Passed in like normal using a vertex array object<br>layout (location = 0) in vec3 position;<br>layout (location = 1) in vec2 texCoords;<br><br>uniform mat4 projection;<br>uniform mat4 view;<br><br>// SSBO containing the instanced model matrices<br>layout(binding = 2, std430) readonly buffer ssbo1 {<br>    mat4 modelMatrices[];<br>};<br><br>smooth out vec2 fsTexCoords;<br><br>void main() {<br>    gl_Position = <br>        projection * view * modelMatrices[gl_InstanceID] * vec4(position, 1.0);<br>    fsTexCoords = texCoords;<br>}</pre><h3>A breakdown of the vertex shader</h3><pre>layout(binding = 2, std430) readonly buffer ssbo1 {<br>    mat4 modelMatrices[];<br>};</pre><p>Here we are specifying the ssbo1 shader storage buffer binding point. We mark it as readonly so that the shader is not allowed to write to it. If we were to leave out “readonly” so that it read layout(binding = 2, std430) buffer ssbo1, the shader would be able to both read and write to the buffer (see below for more information).</p><p>We set the binding point to 2 so that when we get around to binding the buffer in C++ code, we will bind it to location 2.</p><p>We set the packing layout to std430 which determines how data is laid out in memory (see below for more information).</p><p>Finally, notice that modelMatrices[] is specified without an exact size. This is intentional since SSBOs do not require us to tell the shader the size of the array ahead of time. This means that an array of any length can be bound to binding point 2.</p><pre>void main() {<br>    gl_Position = <br>        projection * view * modelMatrices[gl_InstanceID] * vec4(position, 1.0);<br>    fsTexCoords = texCoords;<br>}</pre><p>The main thing to notice here is that we are indexing the modelMatrices by the gl_InstanceID built-in shader input. gl_InstanceID will always store the current draw instance when using a command like glDrawArraysInstanced, or will be 0 if a non-instanced draw command was used.</p><p>An SSBO can be indexed by other integer variables including uniform integers that are passed in to the shader.</p><h4>some of the available memory qualifiers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DKaT-8wcKjHKcPHsSBCnng.png" /></figure><p>For a full list of qualifiers, <a href="https://www.khronos.org/opengl/wiki/Shader_Storage_Buffer_Object">see this page</a>.</p><h4>std430 packing layout rules</h4><p>See <a href="https://www.khronos.org/opengl/wiki/Interface_Block_(GLSL)">here</a> and <a href="https://www.oreilly.com/library/view/opengl-programming-guide/9780132748445/app09lev1sec3.html">here</a> for more info.</p><p>The std430 packing layout is only available for shader storage buffers. It uses the following rules:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yC2nDNCB6deg16T0pId9jw.png" /></figure><p>From this table we can see that scalars and arrays of scalars will be tightly packed, so float array[3] on the CPU side will equal float array[3] array on the GPU side for example.</p><p>A vec3 needs to be aligned to a 16 byte boundary. A vec4 is also a 16 byte boundary. A mat3 needs to be aligned to a 48 byte boundary. A mat4 needs to be aligned to a 64 byte boundary.</p><p>To make it easier for yourself, avoid using vec3 and mat3 in shader storage buffers.</p><h3>Binding and drawing</h3><p>Now we are at the drawing stage which will look something like this:</p><pre>// Bind the storage buffer<br>// Note the 2 matches our binding = 2 in the vertex shader<br>glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, modelMatricesBuffer);<br><br>// Bind our shader program<br>glUseProgram(shader);<br><br>// Set up matrices<br>glUniformMatrix4fv(<br>    glGetUniformLocation(shader, &quot;projection&quot;), 1, GL_FALSE, projectionMat<br>);<br>glUniformMatrix4fv(<br>    glGetUniformLocation(shader, &quot;view&quot;), 1, GL_FALSE, viewMat<br>);<br><br>// Bind VAO for positions and uv coordinates<br>glBindVertexArray(vao);<br><br>// Perform instanced drawing<br>glDrawArraysInstanced(<br>    GL_TRIANGLES, 0, numVertices, instancedModelMatrices.size()<br>);<br><br>glBindVertexArray(0);<br>glUseProgram(0);<br><br>// Uncomment if you want to explicitly unbind the resouce<br>//glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, 0);</pre><h3>Unbinding? Using with multiple shaders?</h3><p>There is often not a need to explicitly unbind a buffer after using `glBindBufferBase`. You can overwrite the existing binding at any point by calling the function again with the same binding index but with a different shader storage buffer object. Explicit unbinding can be done by passing 0 as the buffer argument for a specific binding index.</p><p>If you want the same shader storage buffer to be used by multiple shaders, simply specify the exact same shader storage binding in each of those shaders. Then you can call glBindBufferBase once with the index and proceed to use it with multiple shader programs in a row.</p><h3>Can SSBOs be used to store vertex, uv, and normal data?</h3><p>Yes! See the <a href="https://medium.com/@ktstephano/advanced-modern-opengl-programmable-vertex-pulling-4c74c242da5e?source=friends_link&amp;sk=25cb37737fc97453fb8be873917d7016">Programmable Vertex Pulling</a> tutorial showing how to do this.</p><h3>Future articles</h3><p>Aside from the upcoming programmable vertex pulling article, there will also be an article dedicated to compute shaders and showing how to use SSBOs to allow the GPU to perform highly parallel work and write the results to memory that the CPU will later be able to access.</p><h3>Learn OpenGL Fundamentals</h3><ul><li><a href="https://learnopengl.com/">https://learnopengl.com</a></li></ul><h3>References</h3><ul><li><a href="https://registry.khronos.org/OpenGL-Refpages/gl4/html/glBufferStorage.xhtml">https://registry.khronos.org/OpenGL-Refpages/gl4/html/glBufferStorage.xhtml</a></li><li><a href="https://www.khronos.org/opengl/wiki/Shader_Storage_Buffer_Object">https://www.khronos.org/opengl/wiki/Shader_Storage_Buffer_Object</a></li><li><a href="https://www.oreilly.com/library/view/opengl-programming-guide/9780132748445/app09lev1sec3.html">https://www.oreilly.com/library/view/opengl-programming-guide/9780132748445/app09lev1sec3.html</a></li><li><a href="https://www.khronos.org/opengl/wiki/Direct_State_Access">https://www.khronos.org/opengl/wiki/Direct_State_Access</a></li><li><a href="https://www.amazon.com/OpenGL-Superbible-Comprehensive-Tutorial-Reference/dp/0672337479">OpenGL SuperBible</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66b6414a8086" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Modern OpenGL: Direct State Access (DSA)]]></title>
            <link>https://medium.com/@ktstephano/advanced-modern-opengl-direct-state-access-dsa-57a8c46fef23?source=rss-a86d528ef220------2</link>
            <guid isPermaLink="false">https://medium.com/p/57a8c46fef23</guid>
            <category><![CDATA[graphics-programming]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[rendering]]></category>
            <category><![CDATA[opengl]]></category>
            <dc:creator><![CDATA[Justin]]></dc:creator>
            <pubDate>Mon, 13 Mar 2023 21:42:45 GMT</pubDate>
            <atom:updated>2023-03-13T22:02:48.466Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QBF_lFEbZleFpuLbSfo5Ug.png" /></figure><p>This is part of a tutorial series teaching advanced modern OpenGL. To use all features to their fullest you will need to target OpenGL 4.6. These articles assume you have familiarity with OpenGL.</p><p>Modern OpenGL is all about improving performance and making the API much easier to use compared to older versions. This article is going to cover the simplest addition to the modern API: Direct State Access (DSA).</p><h3>What is Direct State Access (DSA)?</h3><p>DSA is a replacement of the old [bind resource –&gt; edit resource –&gt; unbind resource] model. It meant that if you wanted to update a texture, frame buffer, or storage object, you first had to bind it to a target, then perform some edit that referenced the target, then unbind. Not only was this less than ideal for ease of use and understanding, it also meant a global GL state change was needed every time a resource needed to be edited. DSA gets rid of that.</p><h3>DSA Examples</h3><p>This section will provide examples that walk through the old way of doing things, then show the new DSA way of doing things.</p><p>For example, here is the old way of copying one framebuffer to another:</p><pre>// OLD, no DSA<br><br>GLuint fboRead;<br>GLuint fboWrite;<br><br>glGenFramebuffers(1, &amp;fboRead);<br>glGenFramebuffers(1, &amp;fboWrite);<br><br>... code that populates fbo attachments ...<br><br>// Bind read+write buffers - global state change<br>glBindFramebuffer(GL_READ_FRAMEBUFFER, fboRead);<br>glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboWrite);<br><br>// Copy<br>glBlitFramebuffer(// read buffer bounds<br>                  readStartX, readStartY, readEndX, readEndY,<br>                  // write buffer bounds<br>                  writeStartX, writeStartY, writeEndX, writeEndY,<br>                  GL_COLOR_BUFFER_BIT, GL_LINEAR);<br><br>// Unbind read+write buffers - state change<br>glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);<br>glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);</pre><p>With DSA, the above code can be simplified to the following:</p><pre>// NEW, DSA<br><br>GLuint fboRead;<br>GLuint fboWrite;<br><br>glGenFramebuffers(1, &amp;fboRead);<br>glGenFramebuffers(1, &amp;fboWrite);<br><br>... code that populates fbo attachments ...<br><br>// Copy - no state change required<br>glBlitNamedFramebuffer(fboRead, fboWrite, <br>                       // read buffer bounds<br>                       readStartX, readStartY, readEndX, readEndY,<br>                       // write buffer bounds<br>                       writeStartX, writeStartY, writeEndX, writeEndY,<br>                       GL_COLOR_BUFFER_BIT, GL_LINEAR);</pre><p>Notice that glBlitNamedFramebuffer takes handles to the read and write buffers so that we don’t need to explicitly bind them to read and write points before performing the copy.</p><p>Here is an example of the old vs new method of transferring data to a shader storage buffer object (other buffer types supported as well):</p><p><strong>OLD:</strong></p><pre>GLuint buffer;<br>glCreateBuffers(1, &amp;buffer);<br>// Bind - global state change<br>glBindBuffer(GL_SHADER_STORAGE_BUFFER, buffer);<br><br>// Pass data to buffer<br>glBufferStorage(GL_SHADER_STORAGE_BUFFER, <br>                sizeof(float) * count, (const void *)floatData, <br>                GL_DYNAMIC_STORAGE_BIT);<br><br>// Unbind - global state change<br>glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);</pre><p><strong>NEW:</strong></p><pre>GLuint buffer;<br>glCreateBuffers(1, &amp;buffer);<br><br>// Pass data to buffer - no more bind + unbind!<br>glNamedBufferStorage(buffer, <br>                     sizeof(float) * count, (const void *)floatData, <br>                     GL_DYNAMIC_STORAGE_BIT);</pre><p>There are also other parts of the API that have received new DSA variants of older functions. Below are a few more examples to show the DSA pattern.</p><p><strong>OLD:</strong></p><pre>// Global state change<br>glActiveTexture(GL_TEXTURE0);<br>glBindTexture(GL_TEXTURE_2D, texture);<br><br>glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY, 16.0f);<br><br>glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);<br>glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);<br><br>// Global state change<br>glBindTexture(GL_TEXTURE_2D, 0);</pre><p><strong>NEW:</strong></p><pre>// Instead of taking a bound texture target, <br>// now it takes the texture handle directly<br>glTextureParameterf(texture, GL_TEXTURE_MAX_ANISOTROPY, 16.0f);<br><br>glTextureParameteri(texture, GL_TEXTURE_WRAP_S, GL_REPEAT);<br>glTextureParameteri(texture, GL_TEXTURE_WRAP_T, GL_REPEAT);</pre><p><strong>OLD:</strong></p><pre>// Global state change<br>glBindFramebuffer(GL_FRAMEBUFFER, fbo);<br><br>// Attach a depth texture<br>glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depthTexture, 0);<br><br>// Global state change<br>glBindFramebuffer(GL_FRAMEBUFFER, 0);</pre><p><strong>NEW:</strong></p><pre>// Now takes the framebuffer as a GLuint handle, so no need to bind+unbind<br>glNamedFramebufferTexture(fbo, GL_DEPTH_ATTACHMENT, depthTexture, 0);</pre><h3>Conclusion</h3><p>The general pattern is that anytime you find yourself using the older method of bind, edit, unbind, consider checking the documentation to see if a DSA version of the function is available so that you can avoid state changes and use the objects more directly instead.</p><h3>Learn OpenGL Fundamentals</h3><ul><li><a href="https://learnopengl.com/">https://learnopengl.com</a></li></ul><h3>References</h3><ul><li><a href="https://www.khronos.org/opengl/wiki/Direct_State_Access">https://www.khronos.org/opengl/wiki/Direct_State_Access</a></li><li><a href="https://www.amazon.com/OpenGL-Superbible-Comprehensive-Tutorial-Reference/dp/0672337479">OpenGL SuperBible</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57a8c46fef23" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[View Frustum Culling Using Axis-Aligned Bounding Boxes]]></title>
            <link>https://medium.com/@ktstephano/view-frustum-culling-using-axis-aligned-bounding-boxes-23368881ce0f?source=rss-a86d528ef220------2</link>
            <guid isPermaLink="false">https://medium.com/p/23368881ce0f</guid>
            <category><![CDATA[gpu-rendering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[gpu-computing]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[graphics-programming]]></category>
            <dc:creator><![CDATA[Justin]]></dc:creator>
            <pubDate>Mon, 13 Mar 2023 01:16:28 GMT</pubDate>
            <atom:updated>2023-03-13T04:16:31.231Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<p>Recently I was able to implement view frustum culling on both the CPU and GPU for the StratusGFX rendering engine. In this article I will walk through the process of generating and incrementally updating Axis-Aligned Bounding Boxes (AABBs) from a mesh and then extracting the view frustum planes in world space to check the AABBs against them.</p><h3>What is an AABB?</h3><p>An AABB is a rectangle that is always aligned to the world basis vectors (will never be rotated) and wraps around a mesh such that every polygon of the mesh is enclosed by the AABB. It will look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B7NUTBQA935NLrGwxgP67Q.png" /></figure><p>Here the red lines show the bounding box for the tree stump. Notice that even though the tree stump is rotated slightly, its AABB is completely aligned to the basis vectors without any rotation at all.</p><h3>Motivation</h3><p>Let’s say we have a scene that has grown in complexity to include many instanced meshes totaling tens of millions of triangles in total. These meshes are spread out so that they won’t all by visible on the screen at once.</p><p>Without some way to quickly cull objects that are currently not visible, we would be forced to send everything to the GPU and allow it to discard whatever is outside the view frustum. This results in a lot of extra work for the GPU and for complex scenes could completely destroy performance.</p><p>The benefit of wrapping all complex geometry inside of simple bounding boxes is that it enables us to perform a few very simple tests per group of geometry to answer the question “Is this object potentially visible?” Since the bounding box completely encloses the underlying mesh, if it is all or partly within the view frustum, there’s a good chance at least part of the mesh is visible. But if the bounding box is completely outside of the view frustum then we know for sure it is not visible and we don’t bother sending it to the GPU to be drawn.</p><h3>Creating AABBs</h3><p>We will be generating the bounding boxes in local (object) space for each mesh that we load from file. When generating the bounding boxes we don’t even need to pretransform the mesh relative to its parent (though it would still work if you did).</p><p>There are multiple different ways to store the bounding box information. This article stores them as min/max vertices. The algorithm is as follows:</p><pre>struct AABB {<br>    // If doing GPU frustum culling be careful of alignment. For example,<br>    // using GLSL it would be best to store these both as vec4 or an<br>    // array of 3 floats each.<br>    glm::vec3 vmin;<br>    glm::vec3 vmax;<br>};<br><br>AABB CreateBoundingBox(const std::vector&lt;glm::vec3&gt;&amp; vertices) {<br><br>    // vmin/vmax are both initialized to the first vertex<br>    glm::vec3 vmin = vertices[0];<br>    glm::vec3 vmax = vmin;<br><br>    // Start looping from vertex 1 onwards<br>    for (size_t i = 1; i &lt; vertices.size(); ++i) {<br>        const glm::vec3&amp; current = vertices[i];<br>        vmin = glm::min(vmin, current);<br>        vmax = glm::max(vmax, current);<br>    }<br><br>    AABB result;<br>    result.vmin = vmin;<br>    result.vmax = vmax;<br><br>    return result;<br>}</pre><p>Once this function returns we have a valid bounding box represented by the minimum and maximum vertices in local (object) space.</p><h3>Accounting For Transformation</h3><p>Now that we have the bounding box created in local space per mesh, what happens after we transform the mesh relative to its parent, reposition it within the world, or animate the mesh in some way? Our bounding box becomes incorrect! Since we are maintaining the property of axis alignment, we cannot just rotate the AABB.</p><p>A brute force approach would be to loop through the transformed mesh vertices and recompute the bounding box each time the mesh is changed. This would work but would be way too slow.</p><p>What we are going to do instead is to recompute the bounding box using the transformed corners of the old bounding box. This means that all we need to do is convert vmin/vmax into 8 transformed corners representing the box, then use these 8 transformed corners to compute a new vmin/vmax and this will be our new bounding box for the mesh. This is the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*tNGAbwr4SpDUDcg2EQJjBg.png" /></figure><p>Notice how after the mesh is rotated, the bounding box changes accordingly but two important properties are maintained:</p><p>1) The new bounding box still fully encloses the mesh</p><p>2) The new bounding box is axis aligned (no rotation whatsoever)</p><p>It should be noted that one important downside to this approach (and to axis aligned bounding boxes in general) is that the generated bounding box isn’t ideal in the sense that it <em>does</em> fully enclose the mesh, but it is far larger than it needs to be. If the goal is to have the most perfect fit possible while still using boxes, Oriented Bounding Boxes (OBB) should be used instead or adopt a bounding volume hierarchy (BVH) approach.</p><p>In practice AABBs not being an ideal fit for the underlying mesh means we will have false positives (it will say the mesh may be visible when it’s not leading to some amount of wasted GPU work). Luckily we will never have false negatives: if it says the mesh is not visible, it means it is definitely not visible.</p><p>Here is the algorithm for recomputing a mesh’s bounding box using the old bounding box:</p><pre>AABB RecomputeBoundingBox(const AABB&amp; old, const glm::mat4&amp; transform) {<br>    // First extract the 8 transformed corners of the box using vmin/vmax<br>    const glm::vec3&amp; vmin = old.vmin;<br>    const glm::vec3&amp; vmax = old.vmax;<br><br>    const glm::vec3 corners[8] = {<br>        glm::vec3(transform * glm::vec4(vmin.x, vmin.y, vmin.z, 1.0f)),<br>        glm::vec3(transform * glm::vec4(vmin.x, vmax.y, vmin.z, 1.0f)),<br>        glm::vec3(transform * glm::vec4(vmin.x, vmin.y, vmax.z, 1.0f)),<br>        glm::vec3(transform * glm::vec4(vmin.x, vmax.y, vmax.z, 1.0f)),<br>        glm::vec3(transform * glm::vec4(vmax.x, vmin.y, vmin.z, 1.0f)),<br>        glm::vec3(transform * glm::vec4(vmax.x, vmax.y, vmin.z, 1.0f)),<br>        glm::vec3(transform * glm::vec4(vmax.x, vmin.y, vmax.z, 1.0f)),<br>        glm::vec3(transform * glm::vec4(vmax.x, vmax.y, vmax.z, 1.0f))<br>    };<br><br>    // Now apply the min/max algorithm from before using the 8 transformed <br>    // corners<br>    glm::vec3 newVmin = corners[0];<br>    glm::vec3 newVmax = newVmin;<br><br>    // Start looping from corner 1 onwards<br>    for (size_t i = 1; i &lt; 8; ++i) {<br>        const glm::vec3&amp; current = corners[i];<br>        newVmin = glm::min(newVmin, current);<br>        newVmax = glm::max(newVmax, current);<br>    }<br><br>    // Now pack them into our new bounding box<br>    AABB result;<br>    result.vmin = newVmin;<br>    result.vmax = newVmax;<br><br>    return result;<br>}</pre><h3>Extracting View Frustum Planes In World Space</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nvM82wlvBl5_4ZDdUwn-zQ.png" /><figcaption>View Frustum</figcaption></figure><p>When using a perspective projection, the resulting view frustum looks like a pyramid with the top cut off. It is defined by 6 planes: near and far, top and bottom, left and right. For each plane its normal is pointing inward towards the center of the frustum.</p><p>What we are going to do is extract these 6 planes from the combined view-projection matrix which will give us all 6 planes in world space. This is important because our final, transformed AABB per mesh is also defined in world space, so we want to do all view frustum culling in world space as well.</p><pre>// projection        - view space to clip space<br>// view              - world space to view space<br>// projection * view - world space to clip space<br>const glm::mat4 vp  = projection * view;<br><br>// By default, glm uses a right handed coordinate space so we<br>// will first transpose the matrix so that we can easily extract the<br>// planes<br>const glm::mat4 vpt = glm::transpose(vp);<br><br>const std::vector&lt;glm::vec4&gt; frustumPlanes = {<br>    // left, right, bottom, top<br>    (vpt[3] + vpt[0]),<br>    (vpt[3] - vpt[0]),<br>    (vpt[3] + vpt[1]),<br>    (vpt[3] - vpt[1]),<br>    // near, far<br>    (vpt[3] + vpt[2]),<br>    (vpt[3] - vpt[2]),<br>};</pre><p>Now we have all 6 view frustum planes defined in world space.</p><p>Note: if for your renderer you are using a far plane defined as being infinitely far away, you could opt to only check it against 5 of the planes and skip the far plane.</p><h3>Performing View Frustum Culling</h3><p>Above I mentioned that the view frustum planes all have a normal pointing inward towards the center of the frustum. This is important to keep in mind because we can use the following properties of the dot product:</p><ul><li>Taking the dot product of a plane and a point is positive if the point is in front the plane along the direction of the plane’s normal, and</li><li>Taking the dot product of a plane and a point is 0 if the point is on the plane, and</li><li>Taking the dot product of a plane and a point is negative if the point is behind the plane</li></ul><p>So what we are going to do for each bounding box is convert it to 8 world space points, then check each point against each plane using the dot product. If the dot product returns negative for every point, we know that the bounding box is completely outside of the view frustum and therefore not visible. If even one of the dot products returns 0 or greater, we submit that mesh to the GPU to be drawn.</p><pre>bool IsAabbVisible(const AABB&amp; box, <br>                   const std::vector&lt;glm::vec4&gt;&amp; frustumPlanes) {<br><br>    const glm::vec3&amp; vmin = box.vmin;<br>    const glm::vec3&amp; vmax = box.vmax;<br><br>    for (size_t i = 0; i &lt; frustumPlanes.size(); ++i) {<br>        const glm::vec4&amp; g = frustumPlanes[i];<br>        if ((glm::dot(g, glm::vec4(vmin.x, vmin.y, vmin.z, 1.0f)) &lt; 0.0) &amp;&amp;<br>            (glm::dot(g, glm::vec4(vmax.x, vmin.y, vmin.z, 1.0f)) &lt; 0.0) &amp;&amp;<br>            (glm::dot(g, glm::vec4(vmin.x, vmax.y, vmin.z, 1.0f)) &lt; 0.0) &amp;&amp;<br>            (glm::dot(g, glm::vec4(vmax.x, vmax.y, vmin.z, 1.0f)) &lt; 0.0) &amp;&amp;<br>            (glm::dot(g, glm::vec4(vmin.x, vmin.y, vmax.z, 1.0f)) &lt; 0.0) &amp;&amp;<br>            (glm::dot(g, glm::vec4(vmax.x, vmin.y, vmax.z, 1.0f)) &lt; 0.0) &amp;&amp;<br>            (glm::dot(g, glm::vec4(vmin.x, vmax.y, vmax.z, 1.0f)) &lt; 0.0) &amp;&amp;<br>            (glm::dot(g, glm::vec4(vmax.x, vmax.y, vmax.z, 1.0f)) &lt; 0.0))<br>        {<br>            // Not visible - all returned negative<br>            return false;<br>        }<br>    }<br><br>    // Potentially visible<br>    return true;<br>}</pre><p>Now all that’s left is to loop through each transformed mesh bounding box and call IsAabbVisible. For any that return false, skip it for that frame. For any that return true, send the mesh to the GPU to be drawn.</p><h3>Converting AABB Struct To Vertices For Debugging</h3><p>If you end up wanting to render the AABBs for your scene for debugging purposes, you can create all 12 lines of the bounding box as follows:</p><pre>std::vector&lt;glm::vec3&gt; GetAABBVertices(const AABB&amp; box) {<br>    const glm::vec3&amp; vmin = box.vmin;<br>    const glm::vec3&amp; vmax = box.vmax;<br><br>    // First create the 8 corners<br>    const glm::vec3 corners[8] = {<br>        glm::vec3(vmin.x, vmin.y, vmin.z),<br>        glm::vec3(vmin.x, vmax.y, vmin.z),<br>        glm::vec3(vmin.x, vmin.y, vmax.z),<br>        glm::vec3(vmin.x, vmax.y, vmax.z),<br>        glm::vec3(vmax.x, vmin.y, vmin.z),<br>        glm::vec3(vmax.x, vmax.y, vmin.z),<br>        glm::vec3(vmax.x, vmin.y, vmax.z),<br>        glm::vec3(vmax.x, vmax.y, vmax.z)<br>    };<br><br>    // Now connect the corners to form 12 lines<br>    std::vector&lt;glm::vec3&gt; vertices = {<br>        corners[0], corners[1], // Line 1<br>        corners[2], corners[3], // Line 2<br>        corners[4], corners[5],<br>        corners[6], corners[7],<br><br>        corners[0], corners[2],<br>        corners[1], corners[3],<br>        corners[4], corners[6],<br>        corners[5], corners[7],<br><br>        corners[0], corners[4],<br>        corners[1], corners[5],<br>        corners[2], corners[6],<br>        corners[3], corners[7]  // Line 12<br>    };<br><br>    return vertices;<br>}</pre><p>Now you have access to 12 lines that you can render with something like GL_LINES. Make sure that you pass the transformed bounding box into this function and not the original bounding box. This way any time the mesh is transformed you will be able to see the latest, updated bounding box for that mesh.</p><h3>3D Model Used:</h3><ul><li><a href="https://sketchfab.com/3d-models/boubin-stump-b968b5dc462148989cb87b072885da85">https://sketchfab.com/3d-models/boubin-stump-b968b5dc462148989cb87b072885da85</a></li></ul><h3>References</h3><ul><li><a href="https://math.stackexchange.com/questions/1330210/how-to-check-if-a-point-is-in-the-direction-of-the-normal-of-a-plane">https://math.stackexchange.com/questions/1330210/how-to-check-if-a-point-is-in-the-direction-of-the-normal-of-a-plane</a></li><li><a href="https://www.amazon.com/Graphics-Rendering-Cookbook-comprehensive-algorithms/dp/1838986197">3D Graphics Rendering Cookbook</a></li><li>Foundations of Game Engine Development, Volumes 1 &amp; 2</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23368881ce0f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>