<?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[Half-edge based mesh representations: theory]]></title><type><![CDATA[link]]></type><html><![CDATA[<p><em>This post is part of the series &#8220;<a href="https://fgiesen.wordpress.com/2012/02/13/debris-opening-the-box">Debris: Opening the box</a>&#8220;.</em></p>
<p>Okay, based on my quick poll <a href="https://fgiesen.wordpress.com/2012/02/13/debris-opening-the-box">here</a>, most people would like me to write a bit about the implementations (there are two) of half-edges used in &#8220;debris&#8221;, so that&#8217;s where I&#8217;ll start. My initial plan is for this to be a three-part series (as outlined in the original post). We&#8217;ll see how that goes.</p>
<p>But first, let&#8217;s start with a tiny bit of history.</p>
<h3>Earlier mesh generators</h3>
<p>Our earlier 64ks (i.e. the stuff done with <a href="http://www.farbrausch.com/prod.py?which=117">Generator</a> or <a href="http://www.farbrausch.com/prod.py?which=99">RG2</a>) had very limited tools for mesh manipulation, most of which were a direct result of the underlying data structures: meshes were stored directly as an array of vertices plus an associated array of indices (16-bit vertex indices only, on the HW we were targeting at the time). There was exactly one vertex format used: position (3D) + normal (3D) + UV (2D), all floats, for 32 bytes/vertex. Each mesh had exactly one material (referring, at the time, mainly to the set of associated textures and render states) associated with it. This had a few advantages:</p>
<ul>
<li>The code is really simple and small. (Big advantage for 64ks)</li>
<li>The representation is directly suitable for rendering &#8211; just stuff everything into vertex/index buffers and you&#8217;re done. Exactly one D3D <code>DrawIndexedPrimitive</code> call per mesh.</li>
<li>Generating primitives and simple vertex deformations are easy in this representation.</li>
</ul>
<p>But it also had a lot of serious problems:</p>
<ul>
<li>We were limited to indexed triangle meshes.</li>
<li>Meshes with more than 65536 vertices couldn&#8217;t be correctly represented at all.</li>
<li>The &#8220;one material per mesh&#8221; limitation was quite inconvenient for our artists.</li>
<li>Similarly, &#8220;one batch per source mesh&#8221; combined with the above limitation made for quite high batch counts (for the time). This was usually resolved in a somewhat ad-hoc fashion by a special &#8220;merge&#8221; operator that could turn a scene back into a mesh, merging multiple batches into one if they shared the same material.</li>
<li>Most importantly, anything <em>but</em> the aforementioned primitive generators and simple vertex deformers was inconvenient in this representation, so we just didn&#8217;t support it at all.</li>
</ul>
<p>The original <a href="http://www.farbrausch.com/prod.py?which=113">Werkkzeug</a> added support for large meshes (&gt;65536 vertices), more general meshes (faces had to be convex polygons with &lt;=8 edges if I remember correctly), and added Extrusion and Catmull-Clark subdivision. These last two needed adjacency information; this was dealt with in the code in an ad-hoc way and had severe limitations: hard-edged meshes or discontinuous UV mappings didn&#039;t work properly.</p>
<p>Interestingly, the mesh representation we eventually ended up preferring (to be described in what will be &quot;Half-edge based mesh representations redux&quot;) was very similar to what the original Werkkzeug did, with some crucial modifications. If I had known this at the time, it would&#039;ve saved me months of my life and a lot of frustration. But I didn&#039;t, and so I wrote <code>GenMesh</code>, based on a fairly orthodox link-based half-edge representation. The first two articles in this mini-series will be about this mesh generator.</p>
<h3>Design goals</h3>
<p>For <code>GenMesh</code>, we wanted the following features:</p>
<ul>
<li>The basics we were already used to &#8211; primitives and vertex deformations.</li>
<li>Support for variable vertex formats.</li>
<li>No artificial limitations for mesh size &#8211; anything that fits into memory!</li>
<li>Multiple materials per mesh.</li>
<li>Polygon-based meshes (not just triangles) &#8211; mainly for Catmull-Clark subdivision surfaces (which was a key feature).</li>
<li>Proper support for discontinuous attributes.</li>
<li>Adjacency information is available and up-to-date all the time.</li>
</ul>
<p>That said, we still intentionally left two limitations: we disallowed meshes with boundary edges (i.e. all our meshes were topologically closed), and we required that all meshes be 2-manifold (which in this case boils down to &#8220;no more than two faces may meet at an edge&#8221;). Originally, these limitations were chosen because they make the half-edge implementation easier, and we had a small hack to support meshes with boundary from the user perspective: keep an explicit boundary face for every hole, but assign it an invisible material. A few months later, we added Shadow Volumes, which happen to have the same two limitations, and the &#8220;bug&#8221; became a feature: provided you didn&#8217;t use a few disallowed Operators (the ones that generated the &#8220;virtual holes&#8221;), you knew that your mesh was closed and 2-manifold. And it was instantly obvious where such &#8220;topological defects&#8221; were introduced into the mesh. Anyone who&#8217;s ever tried to guarantee 2-manifoldness for meshes imported from an art package knows how much of a hassle tracking down such problems is when you don&#8217;t have that level of control over how your art assets get made.</p>
<h3>Basic half-edges</h3>
<p>You can find good material on the basics online, so I&#8217;ll keep this section fairly brief. Half-edges are among the edge-centric mesh representations. The reason for focusing on edges is quite simple: Face&rarr;Edge, Face&rarr;Vertex, Vertex&rarr;Edge and Vertex&rarr;Face are all one-to-many-type relationships in a general polygon mesh, but each edge links exactly 2 vertices and lies (in a closed, 2-manifold mesh) between exactly 2 faces &#8211; a fixed number of pointers (or indices), much nicer. Half-edges make this even more uniform by using directed edges (in the direction of winding order). Each half-edge is incident to one face and one vertex, and a pair of half-edges makes up a full edge, hence the name.</p>
<p>So how does this all look? Here&#8217;s the obligatory picture:</p>
<p><img loading="lazy" data-attachment-id="610" data-permalink="https://fgiesen.wordpress.com/2012/02/21/half-edge-based-mesh-representations-theory/half_edge/" data-orig-file="https://fgiesen.files.wordpress.com/2012/02/half_edge.png" data-orig-size="499,343" 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="Half-edge links" data-image-description="" data-image-caption="" data-medium-file="https://fgiesen.files.wordpress.com/2012/02/half_edge.png?w=300" data-large-file="https://fgiesen.files.wordpress.com/2012/02/half_edge.png?w=499" src="https://fgiesen.files.wordpress.com/2012/02/half_edge1.png?w=497&#038;h=341" alt="The half-edge data structure" title="Half-edge links" width="497" height="341" class="aligncenter size-full wp-image-610" /><br />
This shows a random highlighted half-edge <code>e</code>, going from vertex <code>a</code> to vertex <code>b</code> &#8211; half-edges are directed, so order matters. The corresponding half-edge in the opposite direction is denoted by <code>opposite(e)</code>. Our edge <code>e</code> is part of face <code>f</code> (blue shaded area). The classic half-edge data structure keeps track of:</p>
<ul>
<li>Per half-edge <code>e</code>: Either its start or end vertex index (let&#8217;s pick <code>start(e)</code>, the red vertex, here), a link to the face <code>face(e)</code> it belongs to, links to the previous and next half-edges <code>prev(e)</code> and <code>next(e)</code> in the same face (in winding order), and a link to the corresponding opposite paired half-edge <code>opposite(e)</code>.</li>
<li>Per vertex: A link <code>vertEdge(v)</code> to one of the outgoing half-edges &#8211; any will do. (Equivalently, you can keep track of an incoming half-edge; again, this is equivalent)</li>
<li>Per face: A link <code>faceEdge(f)</code> to any of the half-edges that make up the face.</li>
</ul>
<p>It&#8217;s obvious that this structure lets us go from (half-)edge to (half-)edge since that&#8217;s what we store. It&#8217;s also obvious that we can enumerate all half-edges making up a face in-order just by following the <code>next</code> (or <code>prev</code>) links. And since we can get from half-edges to vertices, that means we can enumerate all vertices belonging to a face easily too. The one thing that&#8217;s not immediately obvious is that we can iterate around vertices, too: define</p>
<pre>
prevVert(e) := next(opposite(e))
nextVert(e) := opposite(prev(e))
</pre>
<p>(look at the diagram to see this does the right thing) &#8211; note these return a half-edge, not a vertex index. Again, we can use the <code>face</code> link for the corresponding half-edges to enumerate all faces that touch a given vertex.</p>
<h3>Half-edge invariants</h3>
<p>And that&#8217;s the classic half-edge data structure. Doesn&#8217;t look so bad, right? Unfortunately, there&#8217;s lots of redundancies in this representation because we keep explicit links for everything to make traversal fast. Which in turn means that there&#8217;s tons of invariants we have to maintain. Here&#8217;s the most important ones:</p>
<ul>
<li>For every half-edge <code>e</code>, <code>e = prev(next(e)) = next(prev(e)) = opposite(opposite(e))</code>, and <code>face(e) = face(next(e))</code>.</li>
<li>For every vertex <code>v</code>, <code>start(vertEdge(v)) = v</code>.</li>
<li>For every face <code>f</code>, <code>face(faceEdge(f)) = f</code>.</li>
</ul>
<p>Note that while these invariants guarantee a connectivity structure that&#8217;s free of basic self-contradictions, you need even more than that to get a meaningful polygon mesh. For example, you would probably require that faces contain at least 3 distinct edges. Another seemingly obvious invariant that I won&#8217;t require is that <code>start(next(e)) = start(opposite(e))</code> (two seemingly equivalent expressions for <code>end(e)</code> in the diagram). In fact, I&#8217;ll pick the first expression to define <code>end</code>:</p>
<pre>
end(e) := start(next(e))
</pre>
<p>and say nothing at all about the second expression for now. I also won&#8217;t require for arbitrary edges <code>e</code> that <code>start(e) = start(nextVert(e))</code>. The reasons for all this should become obvious in a minute.</p>
<p>But first, the list above should give you pause. Anyone who&#8217;s ever implemented a doubly-linked list knows that even maintaining a single invariant of the type <code>prev(next(e)) = next(prev(e))</code> above requires careful thinking (and coding) on any operation that updates the data structure. As a rule of thumb, the more invariants need to be maintained by a data structure or algorithm, the trickier it is to implement, and the more likely an implementation is to contain bugs. That&#8217;s why doubly-linked lists are harder than singly-linked lists, why binary search is harder than linear search, and why balanced search trees are harder than binary search trees, which are in turn harder to get right than sorted lists/arrays. By that metric, then, the list above suggests we&#8217;re in deep trouble. The only way I know to get this kind of data structure manipulation right and stay sane is to build it out of small, local data structure manipulations that can be understood in isolation. The actual set of operations used by the &#8220;old&#8221; mesh generator in Werkkzeug3 (used for Candytron, .kkrieger, Theta, Debris etc.) is in fact really small (and somewhat limited); I&#8217;ll go into more detail in the next post. </p>
<p>As a side note, I&#8217;ve only talked about connectivity here; if you plan to interpret this as a polygon mesh, there&#8217;s also geometric invariants you&#8217;d like to be maintained: distinct vertices are at distinct positions, all faces are planar and convex, and so forth. I&#8217;ll completely ignore this type of constraint and the fix-ups necessary to enforce them in this series to concentrate on the data structures.</p>
<h3>Attributes and discontinuities</h3>
<p>So far, I&#8217;ve described the standard half-edge data structure, as you&#8217;ll find it in Computational Geometry and Computer Graphics books (and numerous articles on the web). What it doesn&#8217;t deal with (so far) is vertices with associated attributes, such as triangle meshes with normals, UV coordinates (possibly multiple sets), vertex colors and so forth. Now, as long as these are all perfectly smooth and interpolated over the mesh, we can still use basic half-edges as discussed above. But as soon as we have sharp discontinuities, we run into an issue. Now discontinuities in normals can usually be hand-waved away by using smoothing groups, and the case you&#8217;re most likely to care about in practice are discontinuities in UV coordinates (typically seams created during unwrapping). Nevertheless, I&#8217;m going to use vertex colors for the purpose of discussion, because they&#8217;re easier to draw in a picture. So here I present, for your viewing pleasure, the Rickety Multicolored Cube&trade;:</p>
<p><a href="https://fgiesen.files.wordpress.com/2012/02/cube_part.png"><img loading="lazy" data-attachment-id="632" data-permalink="https://fgiesen.wordpress.com/2012/02/21/half-edge-based-mesh-representations-theory/cube_part/" data-orig-file="https://fgiesen.files.wordpress.com/2012/02/cube_part.png" data-orig-size="300,305" 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="Cube with discontinuous attributes" data-image-description="" data-image-caption="" data-medium-file="https://fgiesen.files.wordpress.com/2012/02/cube_part.png?w=295" data-large-file="https://fgiesen.files.wordpress.com/2012/02/cube_part.png?w=300" src="https://fgiesen.files.wordpress.com/2012/02/cube_part.png?w=300&#038;h=305" alt="Cube with discontinuous attributes" title="Cube with discontinuous attributes" width="300" height="305" class="aligncenter size-full wp-image-632" srcset="https://fgiesen.files.wordpress.com/2012/02/cube_part.png 300w, https://fgiesen.files.wordpress.com/2012/02/cube_part.png?w=148&amp;h=150 148w, https://fgiesen.files.wordpress.com/2012/02/cube_part.png?w=295&amp;h=300 295w" sizes="(max-width: 300px) 100vw, 300px" /></a></p>
<p>The funky pie charts inside our oversized vertices are made of, to borrow terminology from <a href="http://research.microsoft.com/en-us/um/people/hoppe/efficientpm.pdf">a paper by Hugues Hoppe</a>, &#8220;wedges&#8221;. A wedge is a set of attributes (normals, UV coordinates etc.) used by at least one face (but possibly more) incident to a vertex. This virtual cube has a different color on every side, which means that each of the 8 corner vertices has 3 associated wedges, one for each side. If I were to draw a tessellated cube with 2&#215;2 quads making up each face, there&#8217;d also be vertices in the middle of each cube edge that only have 2 wedges, and vertices at the center of the cube faces that only have one wedge (i.e. no discontinuities at all, which is in fact the case for most vertices in a normal mesh). You&#8217;ll have to imagine that picture, since even the simplified, incomplete, skewed version you see above took me ages to draw.</p>
<p>Now, whenever any single attribute (in this case color) varies between any of the faces incident to a vertex, we have multiple wedges. However, just because one attribute is discontinuous doesn&#8217;t mean that all of them are; for example, you might have discontinuous normals across an edge but still want to interpolate UV coordinates smoothly. To resolve this case correctly, Werkkzeug3 stores what I call &#8220;crease flags&#8221; for each edge (yes, per <em>edge</em> not <em>half-edge</em>).  This is just a single bit per attribute to denote whether this attribute has a discontinuity across the given edge or not. To visualize this, imagine that each attribute has its own set of wedges (I&#8217;ll call these &#8220;logical wedges&#8221;, and they depend on the attribute; &#8220;physical wedges&#8221;, the things we actually store, do not). The boundaries in the &#8220;pie chart&#8221; are exactly along the edges where the corresponding crease flag is set. Now, what we actually store is just the physical wedges. Whenever there&#8217;s a discontinuity in any of the attributes (i.e. whenever we cross an edge with non-zero crease flags), we store a new set of vertex attributes, but only some of them (namely the ones with their crease flags set) are allowed to change across that edge. I hope that makes sense.</p>
<h3>Dealing with wedges</h3>
<p>Hoppe maintains the distinction between wedges and vertices; vertices just store their position whereas wedges hold all interpolated attributes. As mentioned above, things get murky in the general case, where the set of seams (what I call &#8220;crease edges&#8221;) is potentially different for every single attribute, and I try to store just one set of wedges (with all &#8220;cuts&#8221; folded in) plus meta-information of which discontinuities are where. Now if I modify an attribute at a vertex that&#8217;s not discontinuous, I might need to update multiple copies &#8211; one per physical wedge. What this means is that in general, you can&#8217;t change the value of any attribute &#8220;at a vertex&#8221; &#8211; you need to know which physical wedges need updating. It also means that you can&#8217;t (in general) specify which value of an attribute you mean just by specifying the vertex: there might be multiple values at that vertex. However, while the vertex alone isn&#8217;t distinctive enough, a (vertex, face) pair is &#8211; or, more concisely, the half-edge corresponding to that (vertex, face) pair. So all vertex update operations actually need to take a half-edge reference as input, not just a vertex ID. A vertex attribute update that respects the current set of discontinuities looks like this:</p>
<p><b>Input</b>: Seed edge <code>e</code>, attribute index <code>a</code> to update, new value <code>v</code>.</p>
<ol>
<li><b>Find start of logical wedge</b>. Sweep <code>e</code> clockwise around its start vertex until you hit an edge with crease flag for <code>a</code> set or you&#8217;re back at the beginning.</li>
<li><b>Find end of logical wedge</b>. Now sweep <code>e</code> counterclockwise from the start of the logical wedge found in the previous step, again until you hit a crease for <code>a</code> or you&#8217;re back at the beginning.</li>
<li><b>Update logical wedge</b>. Loop over all physical wedges between the two extremes (if the two are equal, this reduces to just &#8220;all physical wedges&#8221;) and set their value for attribute <code>a</code> to <code>v</code>.</li>
</ol>
<p>Yes, that&#8217;s a lot of work to change a single value. What can I say, there&#8217;s a reason we later rewrote the whole thing.</p>
<p>Anyway, dealing with multiple sets of attributes means we need to deal with the case where only some of them are discontinuous anyway (hence the algorithm above). Which means there&#8217;s really no big win from keeping positions and attributes separate in the data structure; we can just treat position as an attribute that we always require to have no discontinuities (and in fact we could also theoretically represent boundary edges as &#8220;position discontinuities&#8221;, though I haven&#8217;t tried this).</p>
<p>So here&#8217;s the punchline: we don&#8217;t separate vertices and wedges. We just store an array of (physical) wedges, which also happens to be exactly what needs to go into the vertex buffer for rendering (eventually). Instead of a vertex ID, we just store the physical wedge ID as <code>start(e)</code> in the corresponding half-edges. When looping around a vertex using <code>prevVertEdge</code> and <code>nextVertEdge</code>, we end up iterating over all wedges for a vertex, so we might end up seeing multiple values of <code>start(e)</code> (that&#8217;s why I didn&#8217;t require consistent vertex numbers for this case). This should also explain why I defined <code>end(e)</code> to be <code>start(next(e))</code> &#8211; the alternative choice of <code>start(opposite(e))</code> will still return something at the same position, but potentially corresponding to a different wedge.</p>
<p>Anyway, enough for this post &#8211; I&#8217;ll let the whole &#8220;wedge&#8221; thing sink in for a while. I realize that describing this in text is terrible, but frankly, if I have to spend more time futzing around with vector drawing tools this post is never going to happen, out of sheer frustration. Besides, if you want to actually grok this, there&#8217;s just no way around filling up a lot of paper with your own diagrams; at least, that&#8217;s the way it went for me when reading papers about mesh data structures. Until next time!</p>
]]></html><thumbnail_url><![CDATA[https://fgiesen.files.wordpress.com/2012/02/half_edge1.png?fit=440%2C330]]></thumbnail_url><thumbnail_width><![CDATA[]]></thumbnail_width><thumbnail_height><![CDATA[]]></thumbnail_height></oembed>