<?xml version="1.0" encoding="UTF-8" standalone="yes"?><oembed><version><![CDATA[1.0]]></version><provider_name><![CDATA[The ryg blog]]></provider_name><provider_url><![CDATA[https://fgiesen.wordpress.com]]></provider_url><author_name><![CDATA[fgiesen]]></author_name><author_url><![CDATA[https://fgiesen.wordpress.com/author/fgiesen/]]></author_url><title><![CDATA[Simple lossless(*) index buffer&nbsp;compression]]></title><type><![CDATA[link]]></type><html><![CDATA[<p>(Almost) everyone uses indexed primitives. At this point, the primary choice is between indexed triangle lists, which are flexible but always take 3 indices per triangle, and indexed triangle strips; since your meshes are unlikely to be one big tri strip, that&#8217;s gonna involve primitive restarts of some kind. So for a strip with N triangles, you&#8217;re generally gonna spend 3+N indices &#8211; 2 indices to &#8220;prime the pump&#8221;, after which every new index will emit a new triangle, and finally a single primitive restart index at the end (supposing your HW target does have primitive restarts, that is).</p>
<p>Indexed triangle strips are nice because they&#8217;re smaller, but finding triangle strips is a bit of a pain, and more importantly, long triangle strips actually aren&#8217;t ideal because they tend to &#8220;wander away&#8221; from the origin triangle, which means they&#8217;re not getting very good mileage out of the vertex cache (see, for example, <a href="http://home.comcast.net/~tom_forsyth/papers/fast_vert_cache_opt.html">Tom Forsyth&#8217;s old article</a> on vertex cache optimization).</p>
<p>So here&#8217;s the thing: we&#8217;d like our index buffers for indexed tri lists to be smaller, but we&#8217;d also like to do our other processing (like vertex cache optimization) and then not mess with the results &#8211; not too much anyway. Can we do that?</p>
<h3>The plan</h3>
<p>Yes we can (I had this idea a while back, but never bothered to work out the details). The key insight is that, in a normal mesh, <a href="http://realtimecollisiondetection.net/blog/?p=12">almost all triangles share an edge with another triangle</a>. And if you&#8217;ve vertex-cache optimized your index buffer, two triangles that are adjacent in the index buffer are also quite likely to be adjacent in the geometric sense, i.e. share an edge.</p>
<p>So, here&#8217;s the idea: loop over the index buffer. For each triangle, check if it shares an edge with its immediate successor. If so, the two triangles can (in theory anyway) be described with four indices, rather than the usual six (since two vertices appear in both triangles).</p>
<p>But how do we encode this? We could try to steal a bit somewhere, but in fact there&#8217;s no need &#8211; we can do better than that.</p>
<p>Suppose you have a triangle with vertex indices (A, B, C). The choice of which vertex is first is somewhat arbitrary: the other two even cycles (B, C, A) and (C, A, B) describe the same triangle with the same winding order (and the odd cycles describe the same triangle with opposite winding order, but let&#8217;s leave that alone). We can use this choice to encode a bit of information: say if A&ge;B, we are indeed coding a triangle &#8211; otherwise (A&lt;B), what follows will be two triangles sharing a common edge (namely, the edge AB). We can always pick an even permutation of triangle indices such that A&ge;B, since for <em>any</em> integer A, B, C we have</p>
<p><img src="https://s0.wp.com/latex.php?latex=0+%3D+%28A+-+A%29+%2B+%28B+-+B%29+%2B+%28C+-+C%29+%3D+%28A+-+B%29+%2B+%28B+-+C%29+%2B+%28C+-+A%29&#038;bg=ffffff&#038;fg=000&#038;s=0&#038;c=20201002" srcset="https://s0.wp.com/latex.php?latex=0+%3D+%28A+-+A%29+%2B+%28B+-+B%29+%2B+%28C+-+C%29+%3D+%28A+-+B%29+%2B+%28B+-+C%29+%2B+%28C+-+A%29&#038;bg=ffffff&#038;fg=000&#038;s=0&#038;c=20201002 1x, https://s0.wp.com/latex.php?latex=0+%3D+%28A+-+A%29+%2B+%28B+-+B%29+%2B+%28C+-+C%29+%3D+%28A+-+B%29+%2B+%28B+-+C%29+%2B+%28C+-+A%29&#038;bg=ffffff&#038;fg=000&#038;s=0&#038;c=20201002&#038;zoom=4.5 4x" alt="0 = (A - A) + (B - B) + (C - C) = (A - B) + (B - C) + (C - A)" class="latex" /></p>
<p>Because the sum is 0, not all three terms can be negative, which in turn means that at least one of A&ge;B, B&ge;C or C&ge;A must be true. Furthermore, if A, B, and C are all distinct (i.e. the triangle is non-degenerate), all three terms are nonzero, and hence we must have both negative and positive terms for the sum to come out as 0.</p>
<h3>Paired triangles</h3>
<p>Okay, so if the triangle <em>wasn&#8217;t</em> paired up, we can always cyclically permute the vertices such that A&ge;B. What do we do when we have two triangles sharing an edge, say AB?</p>
<div data-shortcode="caption" id="attachment_2297" style="width: 182px" class="wp-caption aligncenter"><a href="https://fgiesen.files.wordpress.com/2013/12/two_tri.png"><img loading="lazy" aria-describedby="caption-attachment-2297" data-attachment-id="2297" data-permalink="https://fgiesen.wordpress.com/2013/12/14/simple-lossless-index-buffer-compression/two_tri/" data-orig-file="https://fgiesen.files.wordpress.com/2013/12/two_tri.png" data-orig-size="172,213" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;}" data-image-title="Two triangles" data-image-description="" data-image-caption="&lt;p&gt;Two triangle sharing edge AB.&lt;/p&gt;
" data-medium-file="https://fgiesen.files.wordpress.com/2013/12/two_tri.png?w=172" data-large-file="https://fgiesen.files.wordpress.com/2013/12/two_tri.png?w=172" src="https://fgiesen.files.wordpress.com/2013/12/two_tri.png?w=172&#038;h=213" alt="Two triangles sharing edge AB." width="172" height="213" class="size-full wp-image-2297" srcset="https://fgiesen.files.wordpress.com/2013/12/two_tri.png 172w, https://fgiesen.files.wordpress.com/2013/12/two_tri.png?w=121&amp;h=150 121w" sizes="(max-width: 172px) 100vw, 172px" /></a><p id="caption-attachment-2297" class="wp-caption-text">Two triangles sharing edge AB.</p></div>
<p>For this configuration, we need to send the 4 indices A, B, C, D, which encode the two triangles (A, B, C) and (A, D, B).</p>
<p>If A&lt;B, we can just send the 4 indices directly, leading to this very simple decoding algorithm that unpacks our mixed triangle/double-triangle indexed buffer back to a regular triangle list:</p>
<ol>
<li>Read 3 indices A, B, C.</li>
<li>Output triangle (A, B, C).</li>
<li>If A&lt;B, read another index D and output triangle (A, D, B).</li>
</ol>
<p>Okay, so this works out really nicely if A&lt;B. But what if it&#8217;s not? Well, there&#8217;s just two cases left. If A=B, the shared edge is a degenerate edge and both triangles are degenerate triangles; not exactly common, so the pragmatic solution is to say &#8220;if either triangle is degenerate, you have to send them un-paired&#8221;. That leaves the case A&gt;B; but that means B&lt;A, and BA is also a shared edge! In fact, we can simply rotate the diagram by 180 degrees; this swaps the position of (B,A) and (C,D) but corresponds to the same triangles. With the algorithm above, (B, A, D, C) will decode as the two triangles (B, A, D), (B, C, A) &#8211; same two triangles as before, just in a different order. So we&#8217;re good.</p>
<h3>Why this is cool</h3>
<p>What this means is that, under fairly mild assumptions (but see &#8220;limitations&#8221; section below), we can have a representation of index buffers that mixes triangles and pairs of adjacent triangles, with no need for any special flag bits (as recommended in Christer&#8217;s article) or other hackery to distinguish the two.</p>
<p>In most closed meshes, every triangle has at least one adjacent neighbor (usually several); isolated triangles are very rare. We can store such meshes using 4 indices for every pair of triangles, instead of 6, for about a 33% reduction. Furthermore, most meshes in fact contain a significant number of quadriliterals (quads), and this representation supports quads directly (stored with 4 indices). 33% reduction for index buffers isn&#8217;t a huge deal if you have &#8220;fat&#8221; vertex formats, but for relatively small vertices (as you have in collision detection, among other things), indices can actually end up being a significant part of your overall mesh data.</p>
<p>Finally, this is simple enough to decode that it would probably be viable in GPU hardware. I wouldn&#8217;t hold my breath for that one, just thought I might point it out. 🙂</p>
<h3>Implementation</h3>
<p>I wrote up a quick test for this and put it on <a href="https://github.com/rygorous/simple-ib-compress">Github</a>, as usual. This code loads a mesh, vertex-cache optimizes the index buffer (using Tom&#8217;s algorithm), then checks for each triangle whether it shares an edge with its immediate successor and if so, sends them as a pair &#8211; otherwise, send the triangle alone. That&#8217;s it. No attempt is made to be more thorough than that; I just wanted to be as faithful to the original index buffer as possible.</p>
<p>On the &#8220;Armadillo&#8221; mesh from the <a href="http://graphics.stanford.edu/data/3Dscanrep/">Stanford 3D scanning repository</a>, the program outputs this: (<b>UPDATE</b>: I added some more features to the sample program and updated the results here accordingly)</p>
<pre>
172974 verts, 1037832 inds.
before:
ACMR: 2.617 (16-entry FIFO)
62558 paired tris, 283386 single
IB inds: list=1037832, fancy=975274 (-6.03%)
after:
ACMR: 0.814 (16-entry FIFO)
292458 paired tris, 53486 single
IB inds: list=1037832, fancy=745374 (-28.18%)
745374 inds packed
1037832 inds unpacked
index buffers match.
ACMR: 0.815 (16-entry FIFO)
</pre>
<p>&#8220;Before&#8221; is the average cache miss rate (vertex cache misses/triangle) assuming a 16-entry FIFO cache for the original Armadillo mesh (not optimized). As you can see, it&#8217;s pretty bad.</p>
<p>I then run the simple pairing algorithm (&#8220;fancy&#8221;) on that, which (surprisingly enough) manages to reduce the index list size by about 6%.</p>
<p>&#8220;After&#8221; is after vertex cache optimization. Note that Tom&#8217;s algorithm is cache size agnostic; it does not assume any particular vertex cache size, and the only reason I&#8217;m dumping stats for a 16-entry FIFO is because I had to pick a number and wanted to pick a relatively conservative estimate. As expected, ACMR is much better; and the index buffer packing algorithm reduces the IB size by about 28%. Considering that the best possible case is a reduction of 33%, this is quite good. Finally, I verify that packing and unpacking the index buffer gives back the expected results (it does), and then re-compute the ACMR on the unpacked index buffer (which has vertices and triangles in a slightly different order, after all).</p>
<p>Long story short: it works, even the basic &#8220;only look 1 triangle ahead&#8221; algorithm gives good results on vertex cache optimized meshes, and the slight reordering performed by the algorithm does not seem to harm vertex cache hit rate much (on this test mesh anyway). Apologies for only testing on one 3D-scanned mesh, but I don&#8217;t actually have any realistic art assets lying around at home, and even if I did, loading them would&#8217;ve probably taken me more time than writing the entire rest of this program did.</p>
<h3>UPDATE: Some more results</h3>
<p>The original program was missing one more step that is normally done after vertex cache optimization: reordering the vertex buffer so that vertices appear in the order they&#8217;re referenced from the index buffer. This usually improves the efficiency of the <em>pre</em>-transform cache (as opposed to the <em>post</em>-transform cache that the vertex cache optimization algorithm takes care of) because it gives better locality of reference, and has the added side effect of also making the index data more compressible for general purpose lossless compression algorithms like Deflate or LZMA.</p>
<p>Anyway, here&#8217;s the results for taking the entire Armadillo mesh &#8211; vertices, which just store X/Y/Z position as floats, and 32-bit indices both &#8211; and processing it with some standard general-purpose compressors at various stages of the optimization process: (all sizes in binary kilobytes, KiB)</p>
<table>
<tr>
<th>Stage</th>
<th>Size</th>
<th>.zip size</th>
<th>.7z size</th>
</tr>
<tr>
<td>Original mesh</td>
<td>6082k</td>
<td>3312k</td>
<td>2682k</td>
</tr>
<tr>
<td>Vertex cache optimized</td>
<td>6082k</td>
<td>2084k</td>
<td>1504k</td>
</tr>
<tr>
<td>Postprocessed</td>
<td>4939k (-18.8%)</td>
<td>1830k (-12.2%)</td>
<td>1340k (-10.9%)</td>
</tr>
</table>
<p>So the post-process yields a good 10% reduction in the compressed size for what would be the final packaged assets here. This value is to be taken with a grain of salt: &#8220;real&#8221; art assets have other per-vertex data besides just 12 bytes for the 3D position, and nothing I described here does anything about vertex data. In other words, this comparison is on data that favors the algorithm in the sense that roughly half of the mesh file is indices, so keep that in mind. Still, 10% reduction post-LZMA is quite good for such a simple algorithm, especially compared to the effort it takes to get the same level of reduction on, say, <a href="https://fgiesen.wordpress.com/2011/01/24/x86-code-compression-in-kkrunchy/">x86 code</a>.</p>
<p>Also note that the vertex cache optimization by itself <em>massively</em> helps the compressors here; the index list for this mesh comes from a 3D reconstruction of range-scanned data and is pathologically bad (the vertex order is really quite random), but the data you get out of a regular 3D mesh export is quite crappy too. So if you&#8217;re not doing any optimization on your mesh data yet, you should really consider doing so &#8211; it will reduce both your frame timings and your asset sizes.</p>
<h3>Limitations</h3>
<p>This is where the (*) from the title comes in. While I think this is fairly nice, there&#8217;s two cases where you can&#8217;t use this scheme, at least not always:</p>
<ol>
<li>When the order of vertices within a triangle matters. An example would be meshes using flat attribute interpolation, where the value chosen for a primitive depends on the &#8220;provoking vertex&#8221;. And I remember some fairly old graphics hardware where the Z interpolation depended on vertex specification order, so you could get Z-fighting between the passes in multi-pass rendering if they used different subsets of triangles.</li>
<li>When the order of triangles within a mesh matters (remember that we in the two-tris case, we might end up swapping them to make the encoding work). Having the triangles in a particular order in the index buffer can be very useful with alpha blending, for example. That said, the typical case for this application is that the index buffer partitions into several chunks that should be drawn in order, but with no particular ordering requirements within that chunk, which is easy to do &#8211; just prohibit merging tris across chunk boundaries.</li>
</ol>
<p>That said, it seems to me that it really should be useful in every case where you&#8217;d use a vertex cache optimizer (which messes with the order anyway). So it&#8217;s probably fine.</p>
<p>Anyway, that&#8217;s it. No idea whether it&#8217;s useful to anyone, but I think it&#8217;s fairly cute, and it definitely seemed worth writing up.</p>
]]></html><thumbnail_url><![CDATA[https://fgiesen.files.wordpress.com/2013/12/two_tri.png?fit=440%2C330]]></thumbnail_url><thumbnail_width><![CDATA[]]></thumbnail_width><thumbnail_height><![CDATA[]]></thumbnail_height></oembed>